Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 5.5 57a30979a7 fix(ci): prune keeps newest 2 ACTIVE runner images; docs: executable swap commands + final results
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 16:26:31 -04:00
Andrew BeveridgeandClaude Opus 5.5 70dd49da4a chore(infra): encoding-worker disk cost cut + fix runner image pruning
- Encoding-worker boot disks 100 -> 50 GB (DiskSizes.ENCODING_WORKER); Packer
  image disk_size 100 -> 30 so the image no longer forces a 100 GB floor.
  Test enforces image size <= worker disk size.
- build-runner-images.yml: prune step used an invalid gcloud filter and
  silently pruned nothing (31 images accumulated). Now deletes images beyond
  the newest 2 per family, matches the family exactly (gcloud family= also
  matched gpu-windows), and never deletes a disk's source image.
- Docs: rollout procedure (stockout-safe in-place boot-disk swap), lessons,
  cost doc, packer README.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 16:12:25 -04:00
Andrew BeveridgeandClaude Opus 5.5 f26fb3fd85 chore(infra): shrink encoding-worker boot disks 100->50 GB, Packer image 100->30 GB
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 16:12:25 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 e9465c73d4 chore: gemini-3.8-flash everywhere + auto-correct on Opus 5.5 (cost) (#1054)
## Why
GCP credits expired 2026-09-19; Vertex Gemini 3.1 Pro spend had grown $9
→ $37 → $105/30d. `gemini-3.8-flash` is $0.75/$3.75 per 1M (vs $2/$12
for 3.1 Pro; rises to $1.50/$7.50 on 2027-01-01). Opus 5.5 is $4/$20 (vs
$5/$25 for 4.8).

## Changes
- All Gemini defaults → `gemini-3.8-flash`: credit eval, custom lyrics,
auto-correct (default + compare leg), match judge, parse titles, tenant
bulk analyze, agentic AI router, error-monitor LLM analysis (also
`us-central1` → `global`, required for Gemini 3.x), frontend
`translate.py`.
- Auto-correct Claude leg `claude-opus-4-8` → `claude-opus-5-5` (ci.yml
env), with `effort: "high"` pinned (5.5 defaults to medium). Pricing
table gains both new models.
- Docs updated; version 0.241.1.

## Evidence (12 recent prod jobs, pre-review lyrics scored against the
human-reviewed final)
| Model | Precision | Word-level recall | $/job |
|---|---|---|---|
| gemini-3.1-pro-preview | 91% | 74% | $0.067 |
| gemini-3.8-flash | 98% | 38–41% | $0.020 |
| gemini-3.8-flash @ high thinking | 97% | 60% (4/12 timed out, 504) |
$0.041 |
| claude-opus-4-8 | 94% | 33% | $0.080 |
| claude-opus-5-5 (effort high) | 93% | 58% | $0.048 |

Flash for the Gemini leg is a deliberate cost/recall trade-off (Andrew
chose it); Opus 5.5 more than compensates. Also verified:
`gemini-3.8-flash` works on Vertex `global` (rejects
`thinking_level=minimal`; nothing here uses it), match-judge latency
median 3.3s / max 6.2s (< 12s timeout), Japanese translation smoke test
preserves ICU placeholders. Translation cache is keyed on English text +
locale, so no re-translation churn.

Tests: auto_correct, credit eval, custom lyrics, parse_titles,
error_monitor, agentic router suites pass locally.

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

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

* **New Features**
* AI-powered correction, translation, matching, title parsing, and
evaluation now use updated models, including Gemini 3.8 Flash and Claude
Opus 5.5.
* **Updates**
* AI service pricing reflects scheduled rate changes, including a Gemini
3.8 Flash rate change beginning January 1, 2027.
  * Application version updated to 0.241.1.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 14:53:04 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 b177c36641 feat(kjbox): free-text song resolve for singer search auto-correct (v0.241.0) (#1053)
## Summary
Andrew wants the kjbox singer song search to auto-correct like gen's job
creation does, e.g. "the strokes max picu" → The Strokes — Machu Picchu,
with Undo. gen's match-judge only takes a separate artist and title, and
its catalog stage only fixes formatting, not typos. So this adds:

- **`POST /api/kjbox/catalog/resolve`** (`X-Kjbox-Secret`) `{query}` →
match-judge verdict shape (`kind` cosmetic/content/ambiguous/none,
`confident`, `canonical_*`, `alternatives`) plus
`typed_artist`/`typed_title`.
- **`backend/services/match_judge/free_text.py`**: one small Gemini call
(the match judge's model and settings) that splits and corrects
together. Bad or incomplete model output, or any model failure, degrades
to `kind: "none"`, never a 5xx.
- **Cost and abuse controls:**
- Results are cached per case-folded query (in-process, 2000 entries);
transient failures are not cached.
- A partner-wide cap of 120 AI calls/min per instance (429
`rate_limited`); cache hits are free.
- kjbox only calls this after its own catalogue search came back empty.
- Docs: `docs/API.md` § kjbox Partner API.

## Testing
- `test_match_judge_free_text.py` (8)
- `TestCatalogResolve` (4)
- Full backend suite passes (emulator tests excluded)

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

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

* **New Features**
* Added free-text song search resolution that identifies artist and
title, corrects typos, and can suggest alternatives when a match is
ambiguous.
* Repeated searches can use cached results. If resolution is
unavailable, the request returns without an error; uncached requests may
be rate-limited.
* **Documentation**
* Documented the song-resolution API, including its response behavior
and request limits.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 13:09:27 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 36e95c7fe9 feat(kjbox): on-demand review sign-in link + record who started the review (v0.240.0) (#1052)
## Summary
Backs Andrew's feedback on the kjbox singer make-it flow (kjbox
companion PR to follow):

- **`POST /api/kjbox/jobs/{job_id}/review-link`** (partner secret +
singer Bearer session): mints the same one-click `job_review:<id>`
sign-in link the kjbox review email carries, on demand. This powers
"**Tap here** to review it yourself" on the singer's My songs. It is
owner-only (404 otherwise, including unknown ids) and only while
`awaiting_review`/`in_review` (409 `not_in_review`). It also returns
`review_started_by`.
- **`state_data.review_started_by` / `review_started_at`** are recorded
on the first `AWAITING_REVIEW → IN_REVIEW` transition. The value is
`"admin"` when an admin other than the owner (the KJ) opened it, and
`"owner"` otherwise (review-token links count as owner). It is wired
into `GET /api/review/{id}/correction-data` (`require_review_auth` now
stashes the reviewer on `request.state`) and into the legacy
`start-review` / `corrections` routes. kjbox reads it through its admin
job poll to show "Andrew has already started reviewing".
- Docs: `docs/API.md` § kjbox Partner API.

## Testing
- New `TestReviewLink` (6 tests) in `test_kjbox_partner_api.py`
- New `test_review_started_by.py` (7 tests)
- New route-level `TestCorrectionDataRecordsReviewStarter` (2 tests)
- Full backend suite: 4671 passed (excluding emulator tests)

CodeRabbit CLI has no seat on this org, so this PR is opened without the
ignore line and the GitHub bot will review it.

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

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

* **New Features**
* Added a partner API endpoint for job owners to request a localized
sign-in link for jobs awaiting or undergoing review.
* Review details now indicate whether the owner or an administrator
started the review.
* **Documentation**
* Updated the API documentation with the required partner secret header
for review-link requests.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 03:28:22 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 d570b1f139 feat(kjbox): partner API for singer email-code sign-in + show credits (v0.239.0) (#1051)
## Summary
Partner API so the kjbox singer UI (live karaoke nights) can turn
patrons into real karaoke-gen customers: the singer verifies their email
with a 6-digit code typed into the kjbox page, and kjbox then searches
audio / creates the job **as that user** (normal gen delivery emails).

All under `/api/kjbox`, gated by `X-Kjbox-Secret` (Secret Manager
`kjbox-partner-secret`, wired in ci.yml; 503 when unset):
- `POST /auth/send-code` — emails a 6-digit code (hashed at rest, 10-min
expiry, new code supersedes old). Exempt from the 2-signups-per-IP cap
(a venue shares one IP) — replaced by a partner-wide 100 new accounts /
24h cap + 5 codes / email / hour. New users tagged `signup_source=kjbox`
(+ venue).
- `POST /auth/verify-code` — 5 attempts then burned, single-use; shares
the post-login path with magic-link verify (refactored into
`complete_verified_login`: welcome credit w/ AI eval, locale, referral,
session, welcome email).
- `POST /credits/show-credit` (+ user Bearer) — +1 credit, no email
("free at Andrew's shows"), idempotent per key, 5 / user / 24h.
- Review-needed + 24h reminder emails for `X-Client-Id: kjbox*` jobs
carry a one-click sign-in link to the review page (singers never signed
in on gen's site).

Paired kjbox PR: nomadkaraoke/kjbox (singer make-it flow, v0.116.0).
Plan: kjbox `docs/archive/2026-09-24-singer-make-it-auto-flow-plan.md`.

## Testing
- New: `backend/tests/test_kjbox_partner_api.py`,
`backend/tests/emulator/test_kjbox_partner_service.py` (+ additions to
existing tests for the verify refactor, review-email links, X-Client-Id
on create-from-search)
- Backend unit suite: 4644 passed; emulator suite passed.

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

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

* **New Features**
* Added partner sign-in with one-time email codes and show-credit
claiming, with limits on code requests and credit grants to prevent
repeated or duplicate claims.
* Added localized sign-in emails and single-use review links for
eligible reminders.
  * Sign-in supports welcome-credit evaluation and referral attribution.
* **Improvements**
* Review reminders can use custom links, and new accounts can record
signup source and venue.
  * Credential-like request headers are redacted from stored metadata.
* **Documentation**
  * Added partner API usage and behavior details.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 00:03:10 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 5d56ee9069 fix(frontend): stop reporting opaque cross-origin "Script error." (v0.238.6) (#1050)
## Summary
The error monitor keeps alerting on a frontend pattern
`@https://gen.nomadkaraoke.com/` with sample `Error: Script error.` (iOS
Safari, 4 occurrences since June). That's the browser's opaque
cross-origin error: a script from another origin (a third-party tag,
in-app browser or extension injection) threw. The browser hides
everything, so there's no error object, filename or line. Our
`window.onerror` handler wrapped it in `new Error(event.message)`, so
the only "stack" frame (`63bfc60a…js:6:874`) is our own handler. There's
nothing actionable in these reports.

## Changes
- `frontend/lib/client-error-setup.ts`: new exported
`isOpaqueCrossOriginError(event)`. The window `error` listener returns
early when `event.error == null` and the message is `Script error.`.
- `backend/services/error_monitor/frontend_ingestion.py` +
`backend/api/routes/client_errors.py`: `is_opaque_script_error()` drops
bare `Script error.` / `Error: Script error.` reports at ingestion.
They're accepted (202) but not persisted, the same way the bot filter
works. This also stops older cached bundles from alerting.
- `docs/ARCHITECTURE.md`: a note on the crash-report noise filters.
- Version 0.238.5 → 0.238.6.

## Testing
- New Jest `lib/__tests__/client-error-setup.test.ts`: tests the
predicate; an opaque event is not reported; a real error is still
reported. Full Jest: 1342 passed.
- Backend: parametrized API tests (dropped vs "Script error in …" still
persisted) and unit tests for the predicate. `tests/unit` passed (1834),
and `backend/tests` without the emulator passed (4591). Emulator tests
are left to CI.

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

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

* **Bug Fixes**
* Opaque cross-origin “Script error” events without an error object and
location details are no longer recorded. Other client errors, including
script errors with location details or different messages, continue
through the reporting flow.
* Matching is case- and whitespace-tolerant and allows an optional
trailing period.
* **Documentation**
* Updated Error Monitor guidance to describe which browser and
server-side errors are ignored.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:58:03 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 bcdfd6b6bb fix(jobs): unstick audio-edit jobs — waveform OOM, retry skip, screens handoff (#1049)
## Summary
Job `2c1b922e` (Dave Matthews Band – Why I Am, 24-bit/96kHz FLAC, audio
edit requested) stalled twice in prod. Three bugs:

1. **Waveform OOM** — `WaveformGenerator.generate_data_only` decoded the
full source at native resolution through pydub. For a 6-min hi-res FLAC
that peaked at ~1 GB RSS and OOM-killed the 1 GiB `audio-download-job`
while pre-generating editor assets. It now decodes straight to 16 kHz
mono PCM via ffmpeg and computes the envelope with numpy: **156 MB vs
1.07 GB peak** on the real file, amplitudes within 0.003 of the old
output. The same function backs the editor's on-demand waveform in the
API.
2. **Retry skipped unfinished audio-edit prep** — the Cloud Run
auto-retry saw `downloading`, treated the download as done and exited 0,
leaving the job at `downloading` forever. A retry that finds an
audio-edit job still at `downloading` now resumes the editor prep. That
path triggers nothing downstream, so it's safe. Non-edit jobs keep the
existing skip (downstream may already be triggered).
3. **Screens handoff ignored `audio_edit_complete`** —
`advance_to_screens_if_ready` (added in #1002) and the
`recover-stuck-jobs` lost-screens sweep only accepted `downloading`.
Audio-edited jobs prep at `audio_edit_complete`, so **every audio-edited
job since Sept 15 stalled** after lyrics and separation finished (log:
`screens not (re)triggered — status=audio_edit_complete`). Both now use
a shared `PREP_PHASE_STATUSES`.

2c1b922e was unstuck manually (admin reset → `awaiting_audio_edit`, then
a direct `/api/internal/workers/screens` dispatch). Added a
TROUBLESHOOTING entry covering both signatures and the manual fixes.

## Testing
- New tests: hi-res 96k/24-bit decode path (low-rate mono args, envelope
matches pydub reference, silent → 0, undecodable → error);
download-worker resume vs skip; handoff at `audio_edit_complete`;
watchdog recovers `audio_edit_complete` and queries both statuses.
- `pytest tests/unit/` → 1824 passed, 8 skipped
- `pytest backend/tests/ --ignore=backend/tests/emulator` → 4586 passed,
36 skipped
- Version 0.238.4 → 0.238.5

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

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

* **Bug Fixes**
* Audio-edit jobs can resume preparation after an interruption without
redownloading existing audio.
* Screen generation can proceed after audio editing is complete, and
stalled screen-generation triggers can be recovered.
* Waveform previews are more reliable for high-resolution and silent
audio. Invalid audio and decoding timeouts now produce clear errors.
* **Documentation**
* Added troubleshooting guidance for jobs stuck during audio editing or
before screen generation.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 23:39:25 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 daa46347f7 docs: KaraokeHunt outreach handoffs + session record (#1048)
Docs-only. Brings the KaraokeHunt outreach handoff docs (2026-09-13,
09-19, 09-24 final phase) and the 09-19 session record onto main before
the outreach worktree is cleaned up. Covers Segments A/B/C being sent
(87 + 238 + 35) and the Postmark outbound-stream sending method.

This is a public repo, so customer emails and handles are redacted to
`<user>`. The unredacted working copies stay in the local PII directory.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 19:37:12 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 6c28a8cc3c fix: /karaokehuntnews wording - original song, not a cover band (v0.238.4) (#1047)
Wording change requested by Andrew for the Segment C / Frog #1 launch
letter, to match the email as sent: "(the vocals are genuinely gone, not
just quieter)" -> "(original song, not a cover band)". en + 32 locales
retranslated.

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

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

* **Documentation**
* Updated the karaoke generator description across supported languages
to clarify that instrumental separation uses the original song, not a
cover band. The description also highlights word-by-word synced lyrics,
an estimated half-hour turnaround, and support for 33 languages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:53:52 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 20f9334995 feat: /karaokehuntnews letter for KaraokeHunt mailing-list subscribers (v0.238.3) (#1046)
## Summary
Localized letter page for the launch email to KaraokeHunt **mailing-list
subscribers who never used the app** (outreach Segment C, folded into
Frog #1). Linked from that email's PS, same pattern as `/karaokehunt`
and `/karaokehuntlist`.

## Changes
- `KaraokeHuntLetter`: optional `link` for the credits paragraph
(defaults to gen) + `hasCreditsAfter` toggle
- `/[locale]/karaokehuntnews` + bare `/karaokehuntnews` locale redirect
(no-JS fallback)
- `karaokehuntNewsLetter` strings, 33 locales; CTA link =
`nomadkaraoke.com/r/thankyou50` (50%-off vanity referral link, created
via admin API)
- Version 0.238.3

## Testing
- Jest: new case for the news letter (custom link, no trailing text);
full frontend suite 1337/1337

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 10:36:10 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 c8bd29654b feat: /karaokehuntlist letter for KaraokeHunt app users (v0.238.2) (#1045)
## Summary
Localized letter page for **Segment B** of the KaraokeHunt outreach (app
users who signed up but never requested a song). The existing
`/karaokehunt` page opens with "you requested a song", which is wrong
for these users, so the Segment B email's PS links here instead.

## Changes
- `components/karaokehunt/KaraokeHuntLetter.tsx`: shared letter layout
extracted from `/karaokehunt` (namespace + ordered paragraph keys)
- `/[locale]/karaokehunt`: now uses the shared component (rendering
unchanged)
- `/[locale]/karaokehuntlist` + bare `/karaokehuntlist` locale redirect
(with no-JS fallback, same as `/karaokehunt`)
- `karaokehuntListLetter` strings in all 33 locales
- Version 0.238.2

## Testing
- New Jest tests for the shared letter (both variants + credits link);
full frontend suite 1336/1336 passing
- Visually verified locally: `/karaokehuntlist` (en, he RTL) and
`/karaokehunt` unchanged

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

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

* **New Features**
* Added a localized note for former KaraokeHunt users who signed up but
never requested a song, available in 33 languages.
* The note introduces Nomad Karaoke, explains how to sign in using the
email associated with KaraokeHunt, and offers three free credits.
* **Updates**
* Refreshed the existing KaraokeHunt letter page with a shared,
language-aware layout.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 09:50:32 -04:00
150 changed files with 5353 additions and 263 deletions

No files matched your search

+41 -16
View File
@@ -14,7 +14,7 @@ name: Build GHA Runner Images
# 3. Stop the VM, snapshot its boot disk to a new image in the `gha-runner-<variant>`
# image family with name gha-runner-<variant>-<timestamp>.
# 4. Delete the build VM (boot disk auto-deletes).
# 5. Deprecate older images in the family, keeping the newest 3 ACTIVE.
# 5. Delete older images in the family, keeping the newest 2 (rollback = previous month).
on:
workflow_dispatch:
@@ -24,7 +24,7 @@ on:
required: false
default: 'all'
skip_prune:
description: 'Skip deprecation of old images (debugging)'
description: 'Skip pruning (deletion) of old images (debugging)'
type: boolean
required: false
default: false
@@ -41,7 +41,7 @@ env:
BUILD_REGION: us-central1
BUILD_ZONE: us-central1-a
BASE_IMAGE: projects/debian-cloud/global/images/family/debian-12
KEEP_IMAGES_PER_FAMILY: 3
KEEP_IMAGES_PER_FAMILY: 2
jobs:
resolve-matrix:
@@ -271,7 +271,7 @@ jobs:
run: |
gcloud compute instances delete "$VM" --zone="$ZONE" --project="$PROJECT" --quiet || true
- name: Deprecate old images (keep newest ${{ env.KEEP_IMAGES_PER_FAMILY }})
- name: Prune old images (keep newest ${{ env.KEEP_IMAGES_PER_FAMILY }})
if: ${{ github.event.inputs.skip_prune != 'true' }}
env:
PROJECT: ${{ env.GCP_PROJECT }}
@@ -279,20 +279,45 @@ jobs:
KEEP: ${{ env.KEEP_IMAGES_PER_FAMILY }}
run: |
set -euo pipefail
# List ACTIVE images in this family, newest first, skip the top $KEEP.
to_deprecate=$(gcloud compute images list \
# DELETE (not deprecate — deprecated images still bill for storage)
# every image in this family beyond the newest $KEEP. The dispatcher
# boots from the family URL, which always resolves to the newest image,
# so older ones are only rollback insurance (~$0.05/GB-mo; gpu images
# are ~21 GB each). Previously this step used an invalid
# `-deprecated.state:*` filter: gcloud errored to stderr, stdout was
# empty, and it silently reported "Nothing to deprecate" every month
# while images piled up (31 runner images, ~$18/mo, by 2026-09).
# Match the family EXACTLY client-side: a gcloud `family=gha-runner-gpu`
# filter is a word-boundary regex that ALSO matches gha-runner-gpu-windows.
# Rank by ACTIVE (non-deprecated) images: the family URL skips deprecated
# images, so the newest $KEEP active ones are the real rollback path.
# Deprecated images never count toward $KEEP.
rows=$(gcloud compute images list \
--project="$PROJECT" \
--filter="family=$FAMILY AND status=READY AND -deprecated.state:*" \
--no-standard-images \
--show-deprecated \
--sort-by='~creationTimestamp' \
--format='value(name)' | tail -n +$((KEEP+1)))
if [[ -z "$to_deprecate" ]]; then
echo "Nothing to deprecate."
--format='value(name,family,deprecated.state)' | awk -v f="$FAMILY" '$2==f')
active=$(echo "$rows" | awk 'NF==2 {print $1}')
if [[ -z "$active" ]]; then
echo "::error::No active images found in family $FAMILY (list failed?) — refusing to prune."
exit 1
fi
keep=$(echo "$active" | head -n "$KEEP")
to_delete=$(echo "$rows" | awk '{print $1}' | grep -vxF "$keep" || true)
if [[ -z "$to_delete" ]]; then
echo "Nothing to prune (<= $KEEP images in $FAMILY)."
exit 0
fi
for img in $to_deprecate; do
echo "Deprecating $img"
gcloud compute images deprecate "$img" \
--project="$PROJECT" \
--state=DEPRECATED \
--replacement="projects/$PROJECT/global/images/family/$FAMILY"
# Never delete an image some existing disk was created from (e.g. a
# long-lived VM still on an older image).
in_use=$(gcloud compute disks list --project="$PROJECT" \
--format='value(sourceImage.basename())' | sort -u)
for img in $to_delete; do
if grep -qx "$img" <<<"$in_use"; then
echo "Keeping $img (source image of an existing disk)"
continue
fi
echo "Deleting $img"
gcloud compute images delete "$img" --project="$PROJECT" --quiet
done
+2 -2
View File
@@ -2025,8 +2025,8 @@ jobs:
--min-instances 2 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-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"
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
- name: Smoke candidate revision
+1 -1
View File
@@ -112,7 +112,7 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
- Only `/admin/*` is English-only — it has no `[locale]/admin` counterpart and inherits `DefaultIntlProvider` from the root layout
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
- Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
- Translation uses Gemini 3.8 Flash via Vertex AI with GCS cache for efficiency
- CI validates all locale files have matching keys — **PR will fail if translations are missing**
- Pre-commit hook auto-translates when en.json changes (enable: `git config core.hooksPath .githooks`)
- Don't hardcode user-facing strings — add to `messages/en.json` and use `t('key')`
+4
View File
@@ -311,6 +311,10 @@ def require_review_auth_factory(job_id_param: str = "job_id"):
)
logger.info(f"Review access granted via full auth ({auth_result.user_type}) for job {job_id}")
# Who is reviewing — handlers record it on first open
# (state_data.review_started_by, see JobManager.record_review_started).
request.state.review_auth_email = auth_result.user_email
request.state.review_auth_is_admin = bool(auth_result.is_admin)
return job_id, "full"
# Try review token
+3 -4
View File
@@ -310,10 +310,9 @@ def extract_request_metadata(request: Request, created_from: str = "audio_search
environment = headers.get('x-environment', '')
client_id = headers.get('x-client-id', '')
custom_headers = {}
for key, value in headers.items():
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
custom_headers[key] = value
# Secret-bearing headers are redacted: custom_headers is visible to the job owner.
from backend.utils.request_helpers import collect_custom_headers
custom_headers = collect_custom_headers(headers)
metadata = {
'client_ip': client_ip,
+10
View File
@@ -19,6 +19,7 @@ from backend.services.error_monitor.frontend_ingestion import (
RateLimiter,
build_pattern_data,
is_bot_user_agent,
is_opaque_script_error,
sanitize_url,
)
@@ -80,6 +81,15 @@ def report_client_error(payload: ClientErrorPayload, request: Request) -> Client
)
return ClientErrorResponse(pattern_id="bot-ignored", is_new=False)
# Opaque cross-origin "Script error." — no file/line, not our code.
if is_opaque_script_error(payload.message, payload.source, payload.extra):
logger.info(
"frontend_crash_ignored_opaque_script_error url=%s source=%s",
sanitize_url(payload.url),
payload.source,
)
return ClientErrorResponse(pattern_id="opaque-script-error-ignored", is_new=False)
report = FrontendErrorReport(
message=payload.message,
stack=payload.stack,
+3 -5
View File
@@ -343,11 +343,9 @@ def extract_request_metadata(request: Request, created_from: str = "upload", aut
client_id = headers.get('x-client-id', '') # Customer/user identifier
# Collect all X-* custom headers (excluding standard ones we already captured)
custom_headers = {}
for key, value in headers.items():
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
# Normalize header name to original casing if possible
custom_headers[key] = value
# Secret-bearing headers are redacted: custom_headers is visible to the job owner.
from backend.utils.request_helpers import collect_custom_headers
custom_headers = collect_custom_headers(headers)
metadata = {
'client_ip': client_ip,
+8 -6
View File
@@ -27,7 +27,7 @@ from backend.workers.video_worker import generate_video
from backend.workers.render_video_worker import process_render_video
from backend.api.dependencies import require_admin
from backend.services.auth_service import AuthResult, UserType
from backend.services.job_manager import JobManager
from backend.services.job_manager import JobManager, PREP_PHASE_STATUSES
from backend.services.tracing import (
extract_trace_context,
start_span_with_context,
@@ -516,6 +516,7 @@ async def check_idle_reminder(
audio_hash=job.audio_hash,
review_token=job.review_token,
instrumental_token=job.instrumental_token,
request_metadata=getattr(job, 'request_metadata', None),
)
if success:
@@ -1078,11 +1079,12 @@ async def recover_stuck_jobs(
except Exception as e:
logger.warning(f"[job:{job_id}] render re-trigger failed: {e}")
# --- DOWNLOADING with lyrics done but screens never triggered: lost screens trigger ---
# --- Prep phase with lyrics done but screens never triggered: lost screens trigger ---
# The lyrics worker triggers screen generation once transcription completes
# (audio separation is decoupled). If that dispatch is lost — historically a
# fire-and-forget task cancelled on Cloud Run Job loop teardown, now awaited,
# but a Cloud Tasks enqueue can still fail — the job sits at `downloading` with
# but a Cloud Tasks enqueue can still fail — the job sits in its prep status
# (`downloading`, or `audio_edit_complete` for audio-edited jobs) with
# lyrics_complete=True and never advances, with no error. Re-trigger is
# idempotent (advance_to_screens_if_ready status-guards + the screens worker
# no-ops a duplicate). Mirrors the REVIEW_COMPLETE lost-render recovery above.
@@ -1092,7 +1094,7 @@ async def recover_stuck_jobs(
# in. DOWNLOADING is a transient processing state (jobs move through in
# minutes), so this ceiling is far above any realistic concurrent population.
dl_query = jobs_ref.where(
filter=FieldFilter("status", "==", JobStatus.DOWNLOADING.value)
filter=FieldFilter("status", "in", sorted(s.value for s in PREP_PHASE_STATUSES))
).limit(SCREENS_RECOVERY_SCAN_LIMIT).stream()
for doc in dl_query:
if len(screens_retriggered) >= SCREENS_RETRIGGERS_PER_TICK:
@@ -1104,7 +1106,7 @@ async def recover_stuck_jobs(
if not _prep_screens_stalled(job):
continue
logger.warning(
f"[job:{job_id}] DOWNLOADING stalled >10 min with lyrics complete but "
f"[job:{job_id}] {job.status} stalled >10 min with lyrics complete but "
"no screens — re-triggering"
)
try:
@@ -1167,7 +1169,7 @@ def _job_updated_age_seconds(job):
def _prep_screens_stalled(job) -> bool:
"""True when a DOWNLOADING job has lyrics complete but has sat >10 min without
"""True when a prep-phase job has lyrics complete but has sat >10 min without
advancing to screen generation — i.e. the screens trigger was lost.
While audio separation is still running it keeps ``updated_at`` fresh, so this
+10 -2
View File
@@ -1080,6 +1080,7 @@ async def start_review(
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
was_awaiting = job.status == JobStatus.AWAITING_REVIEW
success = job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.IN_REVIEW,
@@ -1088,6 +1089,10 @@ async def start_review(
if not success:
raise HTTPException(status_code=400, detail=t(locale, "jobs.reviewCannotStart"))
if 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"}
@@ -1152,11 +1157,14 @@ async def submit_corrections(
# Transition to IN_REVIEW if not already
if job.status == JobStatus.AWAITING_REVIEW:
job_manager.transition_to_state(
if job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.IN_REVIEW,
message="User is reviewing lyrics"
)
):
job_manager.record_review_started(
job_id, getattr(job, "user_email", None), auth_result.user_email, auth_result.is_admin
)
# Save updated corrections to GCS for the render worker
from backend.services.storage_service import StorageService
+473
View File
@@ -0,0 +1,473 @@
"""kjbox partner API — singer email-code sign-in + "free at the show" credits.
kjbox (the KJ device app at live karaoke nights) lets a patron verify their
email inside the kjbox singer web page, then creates gen jobs AS that real gen
user (with the returned session token) so they get normal gen delivery emails.
Every endpoint requires ``X-Kjbox-Secret`` (503 until ``KJBOX_PARTNER_SECRET``
is configured — deploys dark; 403 if wrong). Contract:
- POST /api/kjbox/auth/send-code {email, locale?, venue?} → {"status": "sent"}
- POST /api/kjbox/auth/verify-code {email, code} → {session_token, user,
credits_granted, credit_status}
- POST /api/kjbox/credits/show-credit (+ Authorization: Bearer <session>)
{idempotency_key, venue?, only_if_empty?}
→ {granted, credits}
A venue is many singers behind one IP, so gen's 2-signups-per-IP cap does NOT
apply here; instead a partner-wide rolling-24h cap on new VERIFIED accounts
(accounts are only created at verify-code), a per-email code throttle, and a
per-user daily show-credit cap bound abuse.
"""
from __future__ import annotations
import asyncio
import hmac
import logging
import threading
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, Header, HTTPException, Request
from pydantic import BaseModel, Field
from backend.api.routes.users import (
_build_user_public,
_mask_email,
_precompute_credit_eval,
complete_verified_login,
)
from backend.config import get_settings, is_production
from backend.i18n import SUPPORTED_LOCALES, t
from backend.services.email_service import EmailService, get_email_service
from backend.services.email_validation_service import get_email_validation_service
from backend.services.kjbox_partner_service import (
CODE_EXPIRY_MINUTES,
LOGIN_CODES_COLLECTION,
KjboxPartnerService,
CodeThrottled,
ShowCreditCapReached,
TransactionContention,
VerifyOutcome,
)
from backend.services.user_service import UserService, get_user_service
from backend.utils.request_helpers import get_client_ip
from backend.utils.test_data import is_test_email
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/kjbox", tags=["kjbox"])
SIGNUP_SOURCE = "kjbox"
_MAX_EMAIL_LEN = 254
_MAX_VENUE_LEN = 200
# ------------------------------------------------------------------ auth gate
def require_kjbox_partner(x_kjbox_secret: Optional[str] = Header(default=None)) -> str:
"""Shared-secret gate. Returns the secret (also used as the code-hash pepper)."""
secret = get_settings().kjbox_partner_secret
if not secret:
raise HTTPException(status_code=503, detail="not configured")
if not hmac.compare_digest((x_kjbox_secret or "").encode(), secret.encode()):
raise HTTPException(status_code=403, detail="forbidden")
return secret
def get_kjbox_service(
secret: str = Depends(require_kjbox_partner),
user_service: UserService = Depends(get_user_service),
) -> KjboxPartnerService:
return KjboxPartnerService(user_service.db, pepper=secret)
# --------------------------------------------------------------------- models
class SendCodeRequest(BaseModel):
email: str
locale: Optional[str] = None
venue: Optional[str] = Field(default=None, max_length=_MAX_VENUE_LEN)
class SendCodeResponse(BaseModel):
status: str
class VerifyCodeRequest(BaseModel):
email: str
code: str = Field(max_length=32)
class VerifyCodeResponse(BaseModel):
session_token: str
user: dict
credits_granted: int
credit_status: str
class ShowCreditRequest(BaseModel):
idempotency_key: str = Field(min_length=1, max_length=128)
venue: Optional[str] = Field(default=None, max_length=_MAX_VENUE_LEN)
# Grant only if the singer currently has no credits (< 1). The key is claimed
# only when a credit is actually granted, so a later call with the same key
# and only_if_empty=false grants iff this one didn't.
only_if_empty: bool = False
class ShowCreditResponse(BaseModel):
granted: bool
credits: int
# -------------------------------------------------------------------- helpers
def _normalize_email(raw: str) -> str:
email = (raw or "").strip().lower()
local, _, domain = email.partition("@")
if (not local or "." not in domain or len(email) > _MAX_EMAIL_LEN
or any(c.isspace() for c in email) or email.count("@") != 1):
raise HTTPException(status_code=422, detail="invalid_email")
return email
def _split_locale(raw: Optional[str]) -> tuple[Optional[str], Optional[str]]:
"""Return (email_locale in en/es/de or None, ui_locale primary subtag or None)."""
if not raw:
return None, None
primary = raw.strip().replace("_", "-").split("-")[0].lower()
if not primary.isalpha() or len(primary) < 2:
return None, None
return (primary if primary in SUPPORTED_LOCALES else None), primary
def _pretend_sent() -> SendCodeResponse:
return SendCodeResponse(status="sent")
# ------------------------------------------------------------------ endpoints
@router.post("/auth/send-code", response_model=SendCodeResponse)
async def send_code(
body: SendCodeRequest,
http_request: Request,
svc: KjboxPartnerService = Depends(get_kjbox_service),
user_service: UserService = Depends(get_user_service),
email_service: EmailService = Depends(get_email_service),
):
settings = get_settings()
email = _normalize_email(body.email)
email_locale, ui_locale = _split_locale(body.locale)
locale = email_locale or "en"
venue = (body.venue or "").strip() or None
email_validation = get_email_validation_service()
if email_validation.is_disposable_domain(email):
logger.warning(f"kjbox: blocked disposable email {_mask_email(email)}")
raise HTTPException(status_code=422, detail=t(locale, "users.disposableEmailBlocked"))
if email_validation.is_email_blocked(email):
logger.warning(f"kjbox: blocked email {_mask_email(email)} — pretending success")
return _pretend_sent()
ip_address = get_client_ip(http_request)
if ip_address and email_validation.is_ip_blocked(ip_address):
logger.warning(f"kjbox: blocked IP {ip_address} — pretending success")
return _pretend_sent()
if not email_service.is_configured() and is_production():
logger.error("kjbox: email service not configured - cannot send codes")
raise HTTPException(status_code=503, detail="email not configured")
# No account is created here — only once the email is verified (verify-code),
# so unverified addresses can neither burn the signup cap nor create accounts
# for other people's emails. Venue/locale ride on the code record until then.
user = user_service.get_user(email)
try:
issued = svc.issue_code(
email,
max_per_hour=settings.kjbox_codes_per_email_per_hour,
needs_credit_eval=(
not (user and getattr(user, "welcome_credits_granted", False))
and not is_test_email(email)
),
locale=email_locale,
ui_locale=ui_locale,
venue=venue,
ip_address=ip_address,
user_agent=http_request.headers.get("user-agent"),
)
except (CodeThrottled, TransactionContention):
# Contention on one email's code doc = a burst of parallel sends to the
# same address, which is exactly what the throttle exists to stop.
raise HTTPException(status_code=429, detail="too_many_codes")
sent = email_service.send_kjbox_login_code(
email, issued.code, expiry_minutes=CODE_EXPIRY_MINUTES, locale=locale,
)
if not sent:
if getattr(email_service, "last_send_suppressed", False):
logger.info(f"kjbox: code recipient {_mask_email(email)} is Postmark-suppressed")
else:
logger.error(f"kjbox: failed to send code email to {_mask_email(email)}")
# Warm the welcome-credit AI evaluation while the singer reads their email,
# so verify-code is instant (same optimisation as magic links).
if issued.needs_credit_eval:
threading.Thread(
target=_precompute_credit_eval,
args=(issued.doc_id, email, LOGIN_CODES_COLLECTION),
daemon=True,
).start()
return SendCodeResponse(status="sent")
@router.post("/auth/verify-code", response_model=VerifyCodeResponse)
async def verify_code(
body: VerifyCodeRequest,
http_request: Request,
svc: KjboxPartnerService = Depends(get_kjbox_service),
user_service: UserService = Depends(get_user_service),
email_service: EmailService = Depends(get_email_service),
):
settings = get_settings()
email = _normalize_email(body.email)
# New accounts are created (and counted against the partner-wide cap) only
# here, after the email is proven. Check the cap BEFORE consuming the code so
# a capped singer can retry the same code later.
existing = user_service.get_user(email)
if existing is None and svc.count_recent_signups() >= settings.kjbox_signup_cap_per_24h:
logger.warning("kjbox: partner-wide verified-signup cap reached")
raise HTTPException(status_code=429, detail="signup_cap")
outcome, record = svc.verify_code(email, body.code)
if outcome == VerifyOutcome.TOO_MANY_ATTEMPTS:
raise HTTPException(status_code=429, detail="too_many_attempts")
if outcome == VerifyOutcome.INVALID:
raise HTTPException(status_code=401, detail="invalid_code")
if outcome != VerifyOutcome.OK or record is None:
raise HTTPException(status_code=401, detail="expired")
user = user_service.get_user(email)
if user is None:
# No signup_ip: the caller is the kjbox box, whose IP is the whole
# venue's — recording it would trip gen's per-IP cap for everyone there.
user = user_service.get_or_create_user(
email, signup_source=SIGNUP_SOURCE, signup_venue=record.get("venue"),
)
svc.record_signup(email, record.get("venue"))
logger.info(f"kjbox: created verified gen user {_mask_email(email)} (venue={record.get('venue')!r})")
# Same first-login definition as magic-link verify (checked before last_login_at is set).
is_first_login = user.total_jobs_created == 0 and not user.last_login_at
user = user_service.update_user(
email, email_verified=True, last_login_at=datetime.utcnow(),
) or user
precomputed_eval = {
k: record.get(k)
for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error")
if record.get(k) is not None
} or None
email_locale = record.get("locale")
result = complete_verified_login(
user,
user_service=user_service,
email_service=email_service,
is_first_login=is_first_login,
precomputed_eval=precomputed_eval,
grant_welcome_credit=True,
referral_code=None,
locale=email_locale,
ui_locale=record.get("ui_locale"),
ip_address=get_client_ip(http_request),
user_agent=http_request.headers.get("user-agent"),
tenant_id=None,
device_fingerprint=None,
email_locale=email_locale or user.locale or "en",
)
logger.info(f"kjbox: verified {_mask_email(email)} (credit_status={result.credit_status})")
return VerifyCodeResponse(
session_token=result.session.token,
user=_build_user_public(result.user).model_dump(mode="json"),
credits_granted=result.credits_granted,
credit_status=result.credit_status,
)
@router.post("/credits/show-credit", response_model=ShowCreditResponse)
async def show_credit(
body: ShowCreditRequest,
svc: KjboxPartnerService = Depends(get_kjbox_service),
user_service: UserService = Depends(get_user_service),
authorization: Optional[str] = Header(default=None),
):
"""Quietly grant +1 credit so a singer's make-it job is free at the show.
No "credits added" email. Idempotent per ``idempotency_key`` (claimed only
when a credit is granted); ``only_if_empty`` grants only at a 0 balance;
capped per user per rolling 24h. All decisions + the increment are one
Firestore transaction.
"""
settings = get_settings()
scheme, _, token = (authorization or "").partition(" ")
token = token.strip()
if scheme.lower() != "bearer" or not token:
raise HTTPException(status_code=401, detail="invalid_session")
valid, user, _msg = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail="invalid_session")
email = user.email.lower()
venue = (body.venue or "").strip() or None
user_ref = user_service.get_user_doc_ref(email)
if user_ref is None:
raise HTTPException(status_code=401, detail="invalid_session")
try:
result = svc.grant_show_credit(
user_ref,
email,
body.idempotency_key,
venue=venue,
only_if_empty=body.only_if_empty,
max_per_24h=settings.kjbox_show_credits_per_user_per_24h,
)
except ShowCreditCapReached:
raise HTTPException(status_code=429, detail="show_credit_cap")
except LookupError:
raise HTTPException(status_code=401, detail="invalid_session")
except TransactionContention:
# Nothing was written; kjbox retries with the same idempotency key.
raise HTTPException(status_code=409, detail="busy_retry")
if result.granted:
logger.info(f"kjbox: show credit granted to {_mask_email(email)} (venue={venue!r}) → {result.credits}")
return ShowCreditResponse(granted=result.granted, credits=result.credits)
# ------------------------------------------------------------- review link
class ReviewLinkRequest(BaseModel):
locale: Optional[str] = None
class ReviewLinkResponse(BaseModel):
url: str
status: str
# "admin" = the KJ / support already opened the review; "owner" = the
# singer did; None = nobody has opened it yet.
review_started_by: Optional[str] = None
_REVIEW_LINK_STATUSES = ("awaiting_review", "in_review")
@router.post("/jobs/{job_id}/review-link", response_model=ReviewLinkResponse)
async def review_link(
job_id: str,
body: ReviewLinkRequest,
_secret: str = Depends(require_kjbox_partner),
user_service: UserService = Depends(get_user_service),
authorization: Optional[str] = Header(default=None),
):
"""One-click sign-in link straight to the singer's own job's lyrics review.
Backs the "Tap here to review it yourself" link on the kjbox singer page:
the same single-use ``job_review:<id>`` magic link the kjbox review email
carries, minted on demand. Only the job's owner (the Bearer session) may
get one, and only while the job is in review (409 ``not_in_review``).
"""
scheme, _, token = (authorization or "").partition(" ")
token = token.strip()
if scheme.lower() != "bearer" or not token:
raise HTTPException(status_code=401, detail="invalid_session")
locale = body.locale if body.locale in SUPPORTED_LOCALES else "en"
# Session check, job read and token mint are blocking Firestore calls —
# keep them off the event loop (it serves every in-flight request).
url, status, started_by = await asyncio.to_thread(
_mint_review_link, user_service, token, job_id, locale)
return ReviewLinkResponse(url=url, status=status, review_started_by=started_by)
def _mint_review_link(user_service: UserService, token: str, job_id: str, locale: str):
"""Blocking half of ``review_link`` → (url, status, review_started_by)."""
from backend.services.job_manager import JobManager
from backend.services.job_notification_service import build_review_login_url
valid, user, _msg = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail="invalid_session")
job = JobManager().get_job(job_id)
# Same 404 for "missing" and "not yours" — don't confirm other users' job ids.
if not job or (job.user_email or "").lower() != user.email.lower():
raise HTTPException(status_code=404, detail="not_found")
status = str(getattr(job.status, "value", job.status))
if status not in _REVIEW_LINK_STATUSES:
raise HTTPException(status_code=409, detail="not_in_review")
url = build_review_login_url(job.job_id, job.user_email, locale=locale)
if not url:
raise HTTPException(status_code=502, detail="link_unavailable")
started_by = (job.state_data or {}).get("review_started_by") if status == "in_review" else None
return url, status, started_by
# ---------------------------------------------------------- search resolve
class ResolveRequest(BaseModel):
query: str = Field(min_length=1, max_length=200)
_RESOLVE_CACHE_MAX = 2000
_RESOLVE_PER_MINUTE = 120
_resolve_cache: "dict[str, dict]" = {}
_resolve_calls: "list[float]" = []
_resolve_lock = threading.Lock()
def _resolve_budget_ok() -> bool:
"""Partner-wide in-process cap on AI calls (cache hits are free)."""
import time
now = time.monotonic()
with _resolve_lock:
while _resolve_calls and _resolve_calls[0] < now - 60:
_resolve_calls.pop(0)
if len(_resolve_calls) >= _RESOLVE_PER_MINUTE:
return False
_resolve_calls.append(now)
return True
@router.post("/catalog/resolve")
async def catalog_resolve(body: ResolveRequest, _secret: str = Depends(require_kjbox_partner)):
"""Split + auto-correct a singer's free-text song search.
kjbox calls this only when its own catalogue search found nothing, then
re-searches with the canonical artist/title and shows "Corrected to … —
you typed … Undo" (gen's AudioSourceStep correction, for the singer
search box). Response = the match judge verdict shape + typed_artist /
typed_title. Never 5xx on model trouble: kind "none".
"""
from backend.services.match_judge.free_text import _none, resolve_free_text
query = " ".join(body.query.split())
if not query:
raise HTTPException(status_code=422, detail="empty_query")
key = query.casefold()
with _resolve_lock:
hit = _resolve_cache.get(key)
if hit is not None:
# Same query modulo case/spacing: the verdict applies, but echo THIS
# request's text where the verdict fell back to the typed query.
if not hit.get("typed_artist"):
hit = {**hit, "typed_title": query}
return hit
if not _resolve_budget_ok():
raise HTTPException(status_code=429, detail="rate_limited")
verdict = await resolve_free_text(query)
if verdict.get("reason") != "unavailable": # don't cache transient failures
with _resolve_lock:
if len(_resolve_cache) >= _RESOLVE_CACHE_MAX:
_resolve_cache.pop(next(iter(_resolve_cache)))
_resolve_cache[key] = verdict
return verdict or _none(query)
+11 -1
View File
@@ -901,12 +901,22 @@ 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:
await asyncio.to_thread(
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",
)
if started:
# Set by require_review_auth (absent for review-token links).
auth_state = getattr(request, "state", None)
await asyncio.to_thread(
job_manager.record_review_started,
job_id,
getattr(job, "user_email", None),
getattr(auth_state, "review_auth_email", None),
getattr(auth_state, "review_auth_is_admin", False),
)
# Replay: attach the reviewer's ordered edit_log so the UI can show the
# sequence of actions (AI-accept/reject/manual/timing) beside the final state.
+133 -65
View File
@@ -12,6 +12,7 @@ import hashlib
import html
import logging
import threading
from dataclasses import dataclass
from datetime import datetime
from typing import Optional, Tuple
@@ -187,12 +188,13 @@ class LogoutResponse(BaseModel):
# =============================================================================
def _precompute_credit_eval(token: str, email: str) -> None:
"""Run credit evaluation in background and store result on magic link doc.
def _precompute_credit_eval(token: str, email: str, collection: Optional[str] = None) -> None:
"""Run credit evaluation in background and store result on the sign-in doc.
Called in a background thread after sending a magic link for new users.
If the user clicks the link before this finishes, verify_magic_link falls
back to inline evaluation (same as before this optimization).
Called in a background thread after sending a magic link (or a kjbox emailed
code — pass ``collection`` + that doc's id as ``token``) for new users. If the
user verifies before this finishes, verification falls back to inline
evaluation (same as before this optimization).
"""
try:
from backend.services.credit_evaluation_service import get_credit_evaluation_service
@@ -202,7 +204,7 @@ def _precompute_credit_eval(token: str, email: str) -> None:
evaluation = eval_service.evaluate(email, "welcome")
user_service = get_user_service()
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
user_service.db.collection(collection or MAGIC_LINKS_COLLECTION).document(token).update({
"credit_eval_decision": evaluation.decision,
"credit_eval_reasoning": evaluation.reasoning,
"credit_eval_error": evaluation.error,
@@ -386,6 +388,111 @@ def _magic_link_redirect_path(purpose) -> "Optional[str]":
return None
@dataclass
class VerifiedLogin:
"""Outcome of the shared post-verification login steps."""
user: object
session: object
credits_granted: int = 0
credit_status: str = "not_applicable"
def complete_verified_login(
user,
*,
user_service: UserService,
email_service: EmailService,
is_first_login: bool,
precomputed_eval: Optional[dict],
grant_welcome_credit: bool,
referral_code: Optional[str],
locale: Optional[str],
ui_locale: Optional[str],
ip_address: Optional[str],
user_agent: Optional[str],
tenant_id: Optional[str],
device_fingerprint: Optional[str],
email_locale: str = "en",
) -> VerifiedLogin:
"""Everything that happens after an identity proof (magic link click or kjbox
emailed code) succeeds: welcome-credit grant (with the precomputed AI eval),
referral attribution, locale persistence, session creation and the first-login
welcome email.
``user`` must already be marked verified (email_verified / last_login_at) by
the caller's verification step.
Args:
locale: Narrowed email locale (en/es/de) to persist on the user, or None
to leave the stored value untouched (e.g. no Accept-Language header).
ui_locale: Full UI language subtag to persist, or None.
email_locale: Locale used to render the welcome email.
"""
credits_granted = 0
credit_status = "not_applicable" # returning user, not first login
granted = False
if grant_welcome_credit:
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
user.email, precomputed_eval=precomputed_eval,
)
if granted:
credits_granted = user_service.NEW_USER_FREE_CREDITS
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
# Refresh user to get updated credit balance
user = user_service.get_user(user.email)
elif credit_status == "denied":
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
if referral_code and not user.referred_by_code:
try:
from backend.services.referral_service import get_referral_service
referral_svc = get_referral_service()
attr_success, attr_msg = referral_svc.attribute_referral(
referred_email=user.email,
referral_code=referral_code,
)
if attr_success:
attr_data = referral_svc.get_attribution_data(referral_code)
if attr_data:
user_service.update_user(user.email, **attr_data)
user = user_service.get_user(user.email) # Refresh to include referral data
logger.info(f"Referral attributed for {_mask_email(user.email)} via code '{referral_code}'")
except Exception as ref_err:
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
# `locale` is narrowed to en/es/de for email rendering; `ui_locale` is the
# full UI language (any of 33) so admins know what language to communicate in.
locale_updates = {}
if locale and locale != (user.locale or "en"):
locale_updates["locale"] = locale
if ui_locale and ui_locale != user.ui_locale:
locale_updates["ui_locale"] = ui_locale
if locale_updates:
try:
user_service.update_user(user.email, **locale_updates)
except Exception:
pass # Non-critical — don't block login
session = user_service.create_session(
user.email,
ip_address=ip_address,
user_agent=user_agent,
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
)
# Send welcome email to first-time users (not when the welcome credit is
# skipped, e.g. board sign-in — the credit-centric copy would be confusing
# with a 0 balance).
if is_first_login and grant_welcome_credit:
email_service.send_welcome_email(user.email, user.credits, locale=email_locale)
return VerifiedLogin(
user=user, session=session,
credits_granted=credits_granted, credit_status=credit_status,
)
@router.get("/auth/verify", response_model=VerifyMagicLinkResponse)
async def verify_magic_link(
token: str,
@@ -431,7 +538,6 @@ async def verify_magic_link(
if not success or not user:
raise HTTPException(status_code=401, detail=t(locale, "users.verifyError", message=message))
# Grant welcome credits on first verification (with AI abuse evaluation)
# Use pre-computed evaluation from magic link if available (computed at send time)
precomputed_eval = None
if magic_link_doc.exists:
@@ -441,80 +547,42 @@ async def verify_magic_link(
if magic_link_data.get(k) is not None
} or None
credits_granted = 0
credit_status = "not_applicable" # returning user, not first login
# Board sign-in grants NO welcome credit — it's identity only. The credit is granted
# later, when the user converts via the "make it yourself now" flow (claim endpoint),
# or when their requested track gets picked (Phase 2).
is_board_signin = magic_link_purpose == "requests_board"
granted = False
if not is_board_signin:
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
user.email, precomputed_eval=precomputed_eval,
)
if granted:
credits_granted = user_service.NEW_USER_FREE_CREDITS
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
# Refresh user to get updated credit balance
user = user_service.get_user(user.email)
elif credit_status == "denied":
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
# Referral attribution: try header first (cookie path), then magic link token (email path), then URL param
# Referral attribution: try header first (cookie path), then magic link token (email path)
referral_code = (
http_request.headers.get("x-referral-code")
or (magic_link_data.get("referral_code") if magic_link_doc.exists else None)
)
if referral_code and not user.referred_by_code:
try:
from backend.services.referral_service import get_referral_service
referral_svc = get_referral_service()
attr_success, attr_msg = referral_svc.attribute_referral(
referred_email=user.email,
referral_code=referral_code,
)
if attr_success:
attr_data = referral_svc.get_attribution_data(referral_code)
if attr_data:
user_service.update_user(user.email, **attr_data)
user = user_service.get_user(user.email) # Refresh to include referral data
logger.info(f"Referral attributed for {_mask_email(user.email)} via code '{referral_code}'")
except Exception as ref_err:
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
# Persist user's locale preference (from Accept-Language header).
# `locale` is narrowed to en/es/de for email rendering; `ui_locale` is the
# full UI language (any of 33) so admins know what language to communicate in.
ui_locale = get_full_locale_from_request(http_request)
has_accept_language = bool(http_request.headers.get("accept-language"))
locale_updates = {}
# Only touch locale when the client actually sent an Accept-Language header —
# otherwise get_locale_from_request()'s "en" default would clobber a user's
# real stored locale on token-only logins (e.g. magic-link scanners).
if has_accept_language and locale and locale != (user.locale or "en"):
locale_updates["locale"] = locale
if ui_locale and ui_locale != user.ui_locale:
locale_updates["ui_locale"] = ui_locale
if locale_updates:
try:
user_service.update_user(user.email, **locale_updates)
except Exception:
pass # Non-critical — don't block login
has_accept_language = bool(http_request.headers.get("accept-language"))
# Create session with tenant context and device fingerprint from the magic link
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
session = user_service.create_session(
user.email,
# Board sign-in grants NO welcome credit — it's identity only. The credit is granted
# later, when the user converts via the "make it yourself now" flow (claim endpoint),
# or when their requested track gets picked (Phase 2).
result = complete_verified_login(
user,
user_service=user_service,
email_service=email_service,
is_first_login=is_first_login,
precomputed_eval=precomputed_eval,
grant_welcome_credit=magic_link_purpose != "requests_board",
referral_code=referral_code,
locale=locale if has_accept_language else None,
ui_locale=get_full_locale_from_request(http_request),
ip_address=ip_address,
user_agent=user_agent,
tenant_id=magic_link_tenant_id,
device_fingerprint=magic_link_fingerprint,
email_locale=locale,
)
# Send welcome email to first-time users (not for board sign-in — no credit granted,
# and the credit-centric welcome copy would be confusing with a 0 balance).
if is_first_login and not is_board_signin:
email_service.send_welcome_email(user.email, user.credits, locale=locale)
user = result.user
session = result.session
credits_granted = result.credits_granted
credit_status = result.credit_status
# Return user info with tenant_id
user_public = _build_user_public(user)
+18 -6
View File
@@ -84,7 +84,7 @@ class Settings(BaseSettings):
# Only used when skip_correction=false
# When enabled, uses Gemini via Vertex AI for intelligent lyrics correction
use_agentic_ai: bool = os.getenv("USE_AGENTIC_AI", "true").lower() in ("true", "1", "yes")
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "vertexai/gemini-3-flash-preview")
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "vertexai/gemini-3.8-flash")
# Timeout for agentic correction in seconds. If correction takes longer, abort and
# use uncorrected transcription - human review will fix any issues.
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
@@ -105,12 +105,12 @@ class Settings(BaseSettings):
# before granting. Fail-CLOSED: if evaluation fails, the decision becomes
# "pending_review" (no auto-grant; an admin is notified to decide).
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.8-flash")
# Custom Lyrics (LLM-powered) — used by the Custom Lyrics mode in the
# Edit All Lyrics modal. Stateless service: takes operator-provided
# custom-lyrics text/file and returns transformed lyric lines.
custom_lyrics_model: str = os.getenv("CUSTOM_LYRICS_MODEL", "gemini-3.1-pro-preview")
custom_lyrics_model: str = os.getenv("CUSTOM_LYRICS_MODEL", "gemini-3.8-flash")
custom_lyrics_max_file_mb: int = int(os.getenv("CUSTOM_LYRICS_MAX_FILE_MB", "5"))
custom_lyrics_max_input_lines: int = int(os.getenv("CUSTOM_LYRICS_MAX_INPUT_LINES", "500"))
custom_lyrics_max_iterations: int = int(os.getenv("CUSTOM_LYRICS_MAX_ITERATIONS", "4"))
@@ -120,7 +120,7 @@ class Settings(BaseSettings):
# AI auto-correct suggestions — opt-in, user-triggered from the lyrics
# review UI. Stateless: one whole-song LLM call returning word-level
# suggestions the reviewer accepts/rejects individually.
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.1-pro-preview")
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.8-flash")
# Models used by the multi-model "compare" mode (semicolon-separated —
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
@@ -175,7 +175,7 @@ class Settings(BaseSettings):
match_judge_enabled: bool = os.getenv("MATCH_JUDGE_ENABLED", "true").lower() in (
"true", "1", "yes",
)
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.5-flash")
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.8-flash")
# Bounds the AI call so a hung model never strands the submission UI. Kept
# generous because Vertex returns 504 DEADLINE_EXCEEDED if generation can't
# finish within this deadline (3s was too tight for gemini-3.5-flash); the
@@ -187,7 +187,7 @@ class Settings(BaseSettings):
parse_titles_enabled: bool = os.getenv("PARSE_TITLES_ENABLED", "true").lower() in (
"1", "true", "yes",
)
parse_titles_model: str = os.getenv("PARSE_TITLES_MODEL", "gemini-3.5-flash")
parse_titles_model: str = os.getenv("PARSE_TITLES_MODEL", "gemini-3.8-flash")
parse_titles_timeout_ms: int = int(os.getenv("PARSE_TITLES_TIMEOUT_MS", "20000"))
parse_titles_max_items: int = int(os.getenv("PARSE_TITLES_MAX_ITEMS", "200"))
# Items per Gemini call: large client batches are split into concurrent
@@ -310,6 +310,18 @@ class Settings(BaseSettings):
# over-cap requests fall through to the free community requests board.
karaokehunt_daily_job_cap: int = int(os.getenv("KARAOKEHUNT_DAILY_JOB_CAP", "3"))
# kjbox partner API (/api/kjbox/*): singer email-code sign-in + show credits
# 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", "")
# 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"))
# Max emailed sign-in codes per address per rolling hour.
kjbox_codes_per_email_per_hour: int = int(os.getenv("KJBOX_CODES_PER_EMAIL_PER_HOUR", "5"))
# Max "free at the show" credits kjbox may grant one user per rolling 24h.
kjbox_show_credits_per_user_per_24h: int = int(os.getenv("KJBOX_SHOW_CREDITS_PER_USER_PER_24H", "5"))
# Private (non-published) track distribution settings
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")
+2
View File
@@ -240,6 +240,8 @@ app.include_router(client_errors.router, prefix="/api") # Frontend crash report
app.include_router(client_events.router, prefix="/api") # Frontend degradation telemetry (banner/unavailable/waveform events)
from backend.api.routes import karaokehunt
app.include_router(karaokehunt.router, prefix="/api") # Retired KaraokeHunt app request interceptor
from backend.api.routes import kjbox
app.include_router(kjbox.router, prefix="/api") # kjbox partner API: singer email-code sign-in + show credits
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
app.include_router(tenant_admin.router) # Admin tenant provisioning (router has /api prefix)
app.include_router(tenant_bulk.router) # Tenant bulk-upload filename analysis (router has /api prefix)
+6
View File
@@ -115,6 +115,12 @@ class User(BaseModel):
# Flag to prevent duplicate welcome credit grants (idempotency)
welcome_credits_granted: bool = False
# Acquisition channel for accounts created outside the gen website, e.g.
# "kjbox" (signed up via an emailed code on a karaoke-night singer page).
# None = normal gen website signup (all pre-existing docs).
signup_source: Optional[str] = None
signup_venue: Optional[str] = None # Venue name reported by the partner (kjbox)
# Referral system
referral_code: Optional[str] = None # User's own referral code
referred_by_code: Optional[str] = None # Code used when this user signed up
+25 -4
View File
@@ -22,6 +22,7 @@ logged tokens rather than trusting the historical USD value.
"""
from __future__ import annotations
from datetime import date, datetime, timezone
from typing import Optional, TypedDict
@@ -49,27 +50,47 @@ class _Rate(TypedDict):
MODEL_PRICING: dict[str, _Rate] = {
# --- Anthropic (authoritative) ---
"claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0},
"claude-opus-5-5": {"input": 4.0, "output": 20.0, "cache_read": 0.2},
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
# tier; confirm against current Google pricing before trusting USD) ---
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
# Promo rate through 2026-12-31; see _RATE_CHANGES for the standard rate.
"gemini-3.8-flash": {"input": 0.75, "output": 3.75, "cache_read": 0.075},
}
# Scheduled price changes: model -> [(effective_date, rate)], oldest first.
# The latest entry whose date has arrived overrides MODEL_PRICING.
_RATE_CHANGES: dict[str, list[tuple[date, _Rate]]] = {
"gemini-3.8-flash": [
(date(2027, 1, 1), {"input": 1.5, "output": 7.5, "cache_read": 0.15}),
],
}
def get_rate(model: str) -> Optional[_Rate]:
def _effective(model: str, rate: _Rate, on: Optional[date]) -> _Rate:
on = on or datetime.now(timezone.utc).date()
for effective, changed in _RATE_CHANGES.get(model, []):
if on >= effective:
rate = changed
return rate
def get_rate(model: str, on: Optional[date] = None) -> Optional[_Rate]:
"""Return the rate card for ``model``, or None if we have no pricing.
Falls back to a prefix match on the model family (e.g. a dated
``claude-fable-5-2026...`` snapshot still resolves to ``claude-fable-5``)
so a minor model-id change doesn't silently drop cost tracking.
so a minor model-id change doesn't silently drop cost tracking. ``on``
(default: today, UTC) selects any scheduled price change.
"""
if model in MODEL_PRICING:
return MODEL_PRICING[model]
return _effective(model, MODEL_PRICING[model], on)
for known, rate in MODEL_PRICING.items():
if model.startswith(known):
return rate
return _effective(known, rate, on)
return None
+5 -1
View File
@@ -674,7 +674,11 @@ class AutoCorrectService:
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
thinking={"type": "adaptive"},
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
# Pin effort: Opus 5.5 defaults to "medium" (4.8 defaulted to "high").
output_config={
"effort": "high",
"format": {"type": "json_schema", "schema": strict_schema},
},
)
except Exception as exc:
if _is_transient_model_error(exc):
+75 -1
View File
@@ -608,6 +608,76 @@ class EmailService:
email, subject, html_content, text_content, from_email_override=sender_email
)
def send_kjbox_login_code(
self,
email: str,
code: str,
expiry_minutes: int,
locale: str = "en",
) -> bool:
"""
Send a 6-digit sign-in code for the kjbox karaoke-night singer page.
The singer types the code into the venue's singer page (they never visit
the gen website), so the email carries no link — just the code.
Returns:
True if email was sent successfully
"""
subject = t(locale, "emails.kjboxLoginCode.subject", code=code)
safe_code = html.escape(code)
extra_styles = f"""
.code-box {{
background-color: #fdf2f8;
border: 2px solid {self.BRAND_PRIMARY};
border-radius: 12px;
padding: 20px;
text-align: center;
margin: 24px 0;
}}
.code {{
font-size: 40px;
font-weight: 700;
letter-spacing: 10px;
font-family: 'SF Mono', Menlo, Consolas, monospace;
color: #111827;
}}
"""
content = f"""
<p>{t(locale, "emails.kjboxLoginCode.greeting")}</p>
<p>{t(locale, "emails.kjboxLoginCode.intro")}</p>
<div class="code-box">
<div class="code">{safe_code}</div>
</div>
<p>{t(locale, "emails.kjboxLoginCode.expiry", minutes=expiry_minutes)}</p>
<p>{t(locale, "emails.kjboxLoginCode.ignoreNote")}</p>
"""
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = f"""
{t(locale, "emails.kjboxLoginCode.greeting")}
{t(locale, "emails.kjboxLoginCode.intro")}
{code}
{t(locale, "emails.kjboxLoginCode.expiry", minutes=expiry_minutes)}
{t(locale, "emails.kjboxLoginCode.ignoreNote")}
---
© {self._get_year()} Nomad Karaoke
"""
return self._log_and_send(email, subject, html_content, text_content)
def send_credits_added(self, email: str, credits: int, total_credits: int, locale: str = "en") -> bool:
"""
Send notification when credits are added to account.
@@ -1455,6 +1525,7 @@ class EmailService:
title: Optional[str] = None,
job_id: Optional[str] = None,
locale: str = "en",
review_url: Optional[str] = None,
) -> bool:
"""
Send 24h review reminder email with expiry warning.
@@ -1467,6 +1538,8 @@ class EmailService:
artist: Artist name for subject line
title: Song title for subject line
job_id: Job ID for constructing the review link
review_url: Override link (e.g. a one-click sign-in link to the review
for kjbox jobs); defaults to the bare review URL
Returns:
True if email was sent successfully
@@ -1477,7 +1550,8 @@ class EmailService:
subject = t(locale, "emails.reviewReminder.subjectFallback")
locale_prefix = get_locale_prefix(locale)
review_url = f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}{locale_prefix}/app"
if not review_url:
review_url = f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}{locale_prefix}/app"
extra_styles = """
.alert {
+2 -2
View File
@@ -98,8 +98,8 @@ Shared infrastructure:
# LLM analysis settings
# ---------------------------------------------------------------------------
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-2.0-flash-001")
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "us-central1")
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-3.8-flash")
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "global")
#: Minimum number of active error patterns required before triggering LLM analysis.
MIN_PATTERNS_FOR_ANALYSIS: int = 3
@@ -50,6 +50,26 @@ def is_bot_user_agent(user_agent: str | None) -> bool:
return bool(_BOT_UA_RE.search(user_agent))
# Browsers mask errors from cross-origin scripts (third-party tags, in-app
# browser/extension injections) as a bare "Script error." with no error object,
# file or line — nothing actionable. The frontend drops these at the source; this
# also covers older cached bundles that still report them (as "Error: Script
# error." whose stack is only our own window.onerror handler's frame, so the stack
# can't be used to tell them apart). The discriminator is the ErrorEvent's own
# filename/lineno, which browsers blank for opaque errors — a genuine
# `throw new Error("Script error.")` from our code keeps its file/line and is kept.
_OPAQUE_SCRIPT_ERROR_RE = re.compile(r"^(?:Error:\s*)?Script error\.?$", re.IGNORECASE)
def is_opaque_script_error(message: str | None, source: str | None = None, extra: dict | None = None) -> bool:
"""Return True for the browser's opaque cross-origin "Script error." report."""
if not message or not _OPAQUE_SCRIPT_ERROR_RE.match(message.strip()):
return False
if source != "window.onerror" or not isinstance(extra, dict):
return False
return not extra.get("filename") and not extra.get("lineno")
@dataclass
class FrontendErrorReport:
"""In-memory representation of an inbound crash report."""
+43 -3
View File
@@ -25,6 +25,17 @@ from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
# Statuses a job sits in while its prep workers (audio separation + lyrics) run,
# i.e. the states from which the lyrics→screens handoff may fire. Normal jobs
# prep at DOWNLOADING; jobs that went through the audio editor prep at
# AUDIO_EDIT_COMPLETE (the edit-submit endpoint triggers the workers without
# passing back through DOWNLOADING).
PREP_PHASE_STATUSES = frozenset({
JobStatus.DOWNLOADING,
JobStatus.AUDIO_EDIT_COMPLETE,
})
def _mask_email(email: str) -> str:
"""Mask email for logging to protect PII. Shows first char + domain."""
if not email or "@" not in email:
@@ -778,6 +789,34 @@ class JobManager:
except Exception as e:
logger.error(f"Failed to send push notification for job {job.job_id}: {e}")
def record_review_started(
self,
job_id: str,
job_user_email: Optional[str],
reviewer_email: Optional[str],
is_admin: bool,
) -> str:
"""Record who opened the lyrics review first (AWAITING_REVIEW → IN_REVIEW).
``state_data.review_started_by`` is "admin" when someone other than the
owner (the KJ / support) opened it, else "owner" (incl. review-token
links, which only the owner is sent). kjbox shows singers "the host has
already started reviewing" from it. Best-effort; returns the value.
"""
is_owner = bool(
reviewer_email and job_user_email
and reviewer_email.lower() == job_user_email.lower()
)
by = "admin" if (is_admin and not is_owner) else "owner"
try:
self.update_job(job_id, {
"state_data.review_started_by": by,
"state_data.review_started_at": datetime.now(timezone.utc).isoformat(),
})
except Exception as e:
logger.warning(f"Job {job_id}: could not record review_started_by: {e}")
return by
def update_state_data(self, job_id: str, key: str, value: Any) -> None:
"""
Update a specific key in the job's state_data field.
@@ -1160,7 +1199,8 @@ class JobManager:
Screen generation is gated on LYRICS only (audio separation is decoupled
so reviewers can start while it finishes), so this no-ops until lyrics are
done, and only fires while the job is still at ``downloading``.
done, and only fires while the job is still in its prep phase
(``downloading``, or ``audio_edit_complete`` for audio-edited jobs).
Returns:
True iff a screens dispatch was issued.
@@ -1171,13 +1211,13 @@ class JobManager:
if not job.state_data.get('lyrics_complete', False):
# Lyrics not finished yet — whichever worker finishes lyrics triggers.
return False
if job.status != JobStatus.DOWNLOADING:
if job.status not in PREP_PHASE_STATUSES:
# Already advanced past prep (or parked in a special state). Keeps the
# audio-worker fallback from re-triggering a job that already reached
# screens/review.
logger.info(
f"Job {job_id}: screens not (re)triggered — status={job.status} "
"(expected downloading)"
"(expected downloading or audio_edit_complete)"
)
return False
from backend.services.worker_service import get_worker_service
+61 -1
View File
@@ -24,6 +24,10 @@ logger = logging.getLogger(__name__)
# Environment variable to enable/disable auto emails
ENABLE_AUTO_EMAILS = os.getenv("ENABLE_AUTO_EMAILS", "true").lower() == "true"
# One-click review sign-in links in kjbox jobs' review emails stay valid this long
# (single-use; an expired/used link offers a fresh one on the verify page).
KJBOX_REVIEW_LOGIN_LINK_EXPIRY_HOURS = 72
# Feedback form URL (configured per environment, empty by default to avoid placeholder in emails)
FEEDBACK_FORM_URL = os.getenv("FEEDBACK_FORM_URL", "")
@@ -38,6 +42,48 @@ def _mask_email(email: str) -> str:
return f"{local[0]}***@{domain}"
def is_kjbox_job(request_metadata: Optional[Dict[str, Any]]) -> bool:
"""Jobs created by kjbox (``X-Client-Id: kjbox…``) on behalf of a singer."""
client_id = str((request_metadata or {}).get("client_id") or "")
return client_id.lower().startswith("kjbox")
def build_review_login_url(
job_id: str,
user_email: str,
locale: str = "en",
frontend_url: Optional[str] = None,
) -> Optional[str]:
"""One-click sign-in link that lands on the job's lyrics review.
kjbox singers verified their email on the karaoke-night page and have never
signed in on the gen website, so a bare review URL would dead-end at a login
wall. The magic-link token's ``job_review:<id>`` purpose makes /auth/verify
redirect straight to the review. Returns None on failure (callers fall back
to the bare review URL).
"""
base = frontend_url or os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
try:
token = get_user_service().create_admin_login_token(
email=user_email,
expiry_hours=KJBOX_REVIEW_LOGIN_LINK_EXPIRY_HOURS,
purpose=f"job_review:{job_id}",
)
return f"{base}{get_locale_prefix(locale)}/auth/verify?token={token.token}"
except Exception:
logger.exception(f"Failed to mint review login link for job {job_id}; using bare review URL")
return None
def review_login_url_for_job(job, locale: str = "en") -> Optional[str]:
"""Sign-in review link for kjbox jobs; None for every other job."""
if not job or not getattr(job, "user_email", None):
return None
if not is_kjbox_job(getattr(job, "request_metadata", None)):
return None
return build_review_login_url(job.job_id, job.user_email, locale=locale)
class JobNotificationService:
"""
Service for sending job-related email notifications.
@@ -69,6 +115,13 @@ class JobNotificationService:
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/review"
@staticmethod
def _is_kjbox_job(request_metadata: Optional[Dict[str, Any]]) -> bool:
return is_kjbox_job(request_metadata)
def _build_review_login_url(self, job_id: str, user_email: str, locale: str = "en") -> Optional[str]:
return build_review_login_url(job_id, user_email, locale=locale, frontend_url=self.frontend_url)
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None, locale: str = "en") -> str:
"""Build the instrumental selection URL for a job."""
# Use hash-based routing for static hosting compatibility
@@ -287,6 +340,7 @@ class JobNotificationService:
audio_hash: Optional[str] = None,
review_token: Optional[str] = None,
instrumental_token: Optional[str] = None,
request_metadata: Optional[Dict[str, Any]] = None,
) -> bool:
"""
Send action-needed reminder email to user.
@@ -304,6 +358,8 @@ class JobNotificationService:
audio_hash: Audio hash for review URL (unused, kept for compatibility)
review_token: Review token for URL (unused, kept for compatibility)
instrumental_token: Instrumental token for URL (unused, kept for compatibility)
request_metadata: Job request metadata; kjbox jobs (client_id "kjbox…")
get a one-click sign-in link to the review instead of the bare URL
Returns:
True if email was sent successfully
@@ -322,7 +378,11 @@ class JobNotificationService:
# Render the appropriate template
if action_type == "lyrics":
review_url = self._build_review_url(job_id, audio_hash, review_token, locale=user_locale)
review_url = None
if self._is_kjbox_job(request_metadata):
review_url = self._build_review_login_url(job_id, user_email, locale=user_locale)
if not review_url:
review_url = self._build_review_url(job_id, audio_hash, review_token, locale=user_locale)
message_content = self.template_service.render_action_needed_lyrics(
name=user_name,
artist=artist,
+354
View File
@@ -0,0 +1,354 @@
"""Firestore state for the kjbox partner API (``/api/kjbox/*``).
kjbox (the KJ device app at live karaoke nights) signs singers in to gen with a
6-digit emailed code and tops up one "free at the show" credit per make-it job.
This module owns the persistence + policy for that; the HTTP layer lives in
``backend/api/routes/kjbox.py``.
Collections:
- ``kjbox_login_codes`` one doc per email (id = sha256(email)); holds only an
HMAC of the current code, its expiry + attempt counter,
the recent send timestamps (per-email throttle) and the
precomputed welcome-credit evaluation.
- ``kjbox_login_code_uses`` create()-only markers keyed by code_id — makes a code
strictly single-use even under concurrent verifies.
- ``kjbox_signups`` one doc per NEW gen account created via kjbox — written
only once the email is VERIFIED (the partner-wide
rolling-24h signup cap counts these).
- ``kjbox_show_credits`` one doc per idempotency key that actually GRANTED a
credit (id = sha256(key)).
- ``kjbox_show_credit_users`` per-user doc (id = sha256(email)) with recent grant
timestamps; read+written in the grant transaction so
the per-user rolling-24h cap can't be raced.
Throttle/cap/idempotency decisions run inside Firestore transactions so
concurrent requests can't slip past them.
"""
from __future__ import annotations
import hashlib
import hmac
import logging
import secrets
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from google.api_core import exceptions as google_exceptions
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter, Increment
from backend.models.user import CreditTransaction
logger = logging.getLogger(__name__)
LOGIN_CODES_COLLECTION = "kjbox_login_codes"
LOGIN_CODE_USES_COLLECTION = "kjbox_login_code_uses"
SIGNUPS_COLLECTION = "kjbox_signups"
SHOW_CREDITS_COLLECTION = "kjbox_show_credits"
SHOW_CREDIT_USERS_COLLECTION = "kjbox_show_credit_users"
CODE_LENGTH = 6
CODE_EXPIRY_MINUTES = 10
MAX_VERIFY_ATTEMPTS = 5
SHOW_CREDIT_REASON = "kjbox show credit"
TRANSACTION_MAX_ATTEMPTS = 10
_THROTTLE_WINDOW = timedelta(hours=1)
_DAY = timedelta(hours=24)
def _now() -> datetime:
return datetime.now(timezone.utc)
def _aware(dt: Any) -> Optional[datetime]:
"""Normalize Firestore/ISO timestamps to tz-aware UTC datetimes."""
if dt is None:
return None
if isinstance(dt, str):
try:
dt = datetime.fromisoformat(dt)
except ValueError:
return None
if not isinstance(dt, datetime):
return None
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
def _sha256(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def code_doc_id(email: str) -> str:
return _sha256(email.strip().lower())
@dataclass
class IssuedCode:
code: str
doc_id: str
needs_credit_eval: bool
class TransactionContention(Exception):
"""A Firestore transaction gave up after repeated contention (nothing written)."""
class CodeThrottled(Exception):
"""Per-email code throttle hit (raised out of the issue transaction)."""
class ShowCreditCapReached(Exception):
"""Per-user rolling-24h show-credit cap hit."""
@dataclass
class ShowCreditResult:
granted: bool
credits: int
class VerifyOutcome:
OK = "ok"
EXPIRED = "expired"
INVALID = "invalid_code"
TOO_MANY_ATTEMPTS = "too_many_attempts"
class KjboxPartnerService:
"""Code issuance/verification, signup cap, and show-credit bookkeeping."""
def __init__(self, db, pepper: str, transaction_runner=None):
self.db = db
# The partner secret doubles as the HMAC pepper: a Firestore read alone
# (backups, exports) can't brute-force the 10^6 code space offline.
self._pepper = pepper.encode("utf-8")
# Injectable for unit tests (in-memory Firestore fake); production runs
# ``fn(transaction)`` under @firestore.transactional (retried on contention).
self._transaction_runner = transaction_runner
def _run_transaction(self, fn):
if self._transaction_runner is not None:
return self._transaction_runner(fn)
try:
return firestore.transactional(fn)(self.db.transaction(max_attempts=TRANSACTION_MAX_ATTEMPTS))
except ValueError as exc:
# google-cloud-firestore gives up with ValueError("Failed to commit
# transaction in N attempts.") under heavy contention. Nothing was
# written, so callers can safely treat it as "busy, retry".
if "Failed to commit transaction" in str(exc):
raise TransactionContention() from exc
raise
# ------------------------------------------------------------------ codes
def _hash_code(self, code_id: str, code: str) -> str:
return hmac.new(self._pepper, f"{code_id}:{code}".encode("utf-8"), hashlib.sha256).hexdigest()
def _code_ref(self, email: str):
return self.db.collection(LOGIN_CODES_COLLECTION).document(code_doc_id(email))
def get_code_record(self, email: str) -> Optional[dict]:
snap = self._code_ref(email).get()
return snap.to_dict() if snap.exists else None
def recent_send_times(self, record: Optional[dict], now: Optional[datetime] = None) -> list:
now = now or _now()
times = [_aware(t) for t in (record or {}).get("send_times") or []]
return [t for t in times if t and now - t < _THROTTLE_WINDOW]
def issue_code(
self,
email: str,
*,
max_per_hour: int,
needs_credit_eval: bool,
locale: Optional[str],
ui_locale: Optional[str],
venue: Optional[str],
ip_address: Optional[str],
user_agent: Optional[str],
) -> IssuedCode:
"""Mint a fresh code for ``email``, replacing (invalidating) any prior one.
The throttle check, the send_times append and the code write happen in ONE
transaction, so parallel requests can't exceed ``max_per_hour`` sends
(raises :class:`CodeThrottled`). Only an HMAC of the code is stored.
``merge=True`` keeps any precomputed welcome-credit evaluation across
re-sends. Venue/locale are kept for attribution when the email verifies.
"""
email = email.strip().lower()
ref = self._code_ref(email)
def _txn(transaction):
now = _now()
snap = ref.get(transaction=transaction)
record = snap.to_dict() if snap.exists else None
recent = self.recent_send_times(record, now)
if len(recent) >= max_per_hour:
raise CodeThrottled()
code = f"{secrets.randbelow(10 ** CODE_LENGTH):0{CODE_LENGTH}d}"
code_id = secrets.token_urlsafe(16)
transaction.set(
ref,
{
"email": email,
"code_id": code_id,
"code_hash": self._hash_code(code_id, code),
"created_at": now,
"expires_at": now + timedelta(minutes=CODE_EXPIRY_MINUTES),
"attempts": 0,
"send_times": recent + [now],
"locale": locale,
"ui_locale": ui_locale,
"venue": venue,
"ip_address": ip_address,
"user_agent": user_agent,
},
merge=True,
)
has_eval = bool((record or {}).get("credit_eval_decision"))
return IssuedCode(
code=code,
doc_id=code_doc_id(email),
needs_credit_eval=needs_credit_eval and not has_eval,
)
return self._run_transaction(_txn)
def verify_code(self, email: str, code: str) -> tuple[str, Optional[dict]]:
"""Check ``code`` for ``email``. Returns (outcome, code_record).
Attempts are counted with an atomic server-side increment BEFORE the
comparison, so parallel guesses can't exceed MAX_VERIFY_ATTEMPTS. A
success is claimed via a create()-only marker so a code works once.
"""
email = email.strip().lower()
ref = self._code_ref(email)
snap = ref.get()
record = snap.to_dict() if snap.exists else None
if not record or not record.get("code_hash") or not record.get("code_id"):
return VerifyOutcome.EXPIRED, None
expires_at = _aware(record.get("expires_at"))
if not expires_at or _now() > expires_at:
ref.update({"code_hash": None})
return VerifyOutcome.EXPIRED, None
ref.update({"attempts": Increment(1)})
after = ref.get().to_dict() or {}
if after.get("code_id") != record["code_id"] or not after.get("code_hash"):
# Superseded or burned between our read and the increment.
return VerifyOutcome.EXPIRED, None
if int(after.get("attempts") or 0) > MAX_VERIFY_ATTEMPTS:
ref.update({"code_hash": None})
return VerifyOutcome.TOO_MANY_ATTEMPTS, None
candidate = (code or "").strip()
expected = record["code_hash"]
provided = self._hash_code(record["code_id"], candidate)
if not (candidate.isdigit() and len(candidate) == CODE_LENGTH
and hmac.compare_digest(provided, expected)):
return VerifyOutcome.INVALID, None
try:
self.db.collection(LOGIN_CODE_USES_COLLECTION).document(record["code_id"]).create(
{"email": email, "used_at": _now()}
)
except google_exceptions.AlreadyExists:
return VerifyOutcome.EXPIRED, None
ref.update({"code_hash": None, "used_at": _now()})
return VerifyOutcome.OK, after
# ----------------------------------------------------------- signup cap
def count_recent_signups(self) -> int:
cutoff = _now() - _DAY
query = self.db.collection(SIGNUPS_COLLECTION).where(
filter=FieldFilter("created_at", ">=", cutoff)
)
return sum(1 for _ in query.stream())
def record_signup(self, email: str, venue: Optional[str]) -> None:
self.db.collection(SIGNUPS_COLLECTION).document().set(
{"email": email.strip().lower(), "venue": venue, "created_at": _now()}
)
# --------------------------------------------------------- show credits
def _show_credit_ref(self, idempotency_key: str):
return self.db.collection(SHOW_CREDITS_COLLECTION).document(_sha256(idempotency_key))
def _show_credit_user_ref(self, email: str):
return self.db.collection(SHOW_CREDIT_USERS_COLLECTION).document(_sha256(email.strip().lower()))
def grant_show_credit(
self,
user_ref,
email: str,
idempotency_key: str,
*,
venue: Optional[str],
only_if_empty: bool,
max_per_24h: int,
reason: str = SHOW_CREDIT_REASON,
max_transactions: int = 100,
) -> ShowCreditResult:
"""Atomically: idempotency check, only-if-empty check, per-user cap, key
claim, and the +1 credit (with its transaction-history entry).
The key is claimed ONLY when a credit is actually granted, so kjbox can
call with ``only_if_empty=True`` early and again with the same key and
``only_if_empty=False`` later — the second call grants only if the first
didn't. Raises :class:`ShowCreditCapReached` at the cap.
"""
email = email.strip().lower()
key_ref = self._show_credit_ref(idempotency_key)
counter_ref = self._show_credit_user_ref(email)
def _txn(transaction):
now = _now()
key_snap = key_ref.get(transaction=transaction)
user_snap = user_ref.get(transaction=transaction)
counter_snap = counter_ref.get(transaction=transaction)
user_data = user_snap.to_dict() if user_snap.exists else None
if user_data is None:
raise LookupError("user not found")
credits = int(user_data.get("credits") or 0)
if key_snap.exists:
return ShowCreditResult(granted=False, credits=credits)
if only_if_empty and credits >= 1:
return ShowCreditResult(granted=False, credits=credits)
counter = counter_snap.to_dict() if counter_snap.exists else {}
recent = [t for t in (_aware(x) for x in counter.get("grant_times") or [])
if t and now - t < _DAY]
if len(recent) >= max_per_24h:
raise ShowCreditCapReached()
entry = CreditTransaction(
id=str(uuid.uuid4()), amount=1, reason=reason,
).model_dump(mode="json")
history = list(user_data.get("credit_transactions") or [])
history = history[-(max_transactions - 1):] + [entry]
transaction.create(key_ref, {
"idempotency_key": idempotency_key,
"email": email,
"venue": venue,
"created_at": now,
})
transaction.set(counter_ref, {"email": email, "grant_times": recent + [now]})
transaction.update(user_ref, {
"credits": credits + 1,
"credit_transactions": history,
"updated_at": datetime.utcnow(),
})
return ShowCreditResult(granted=True, credits=credits + 1)
return self._run_transaction(_txn)
+2 -2
View File
@@ -70,9 +70,9 @@ RESPONSE_SCHEMA = {
def _model() -> str:
try:
from backend.config import settings
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
return getattr(settings, "match_judge_model", "gemini-3.8-flash")
except Exception: # pragma: no cover - config import guard
return "gemini-3.5-flash"
return "gemini-3.8-flash"
def build_prompts(
+156
View File
@@ -0,0 +1,156 @@
"""Free-text song resolution for the kjbox singer search box.
gen's match judge takes a separate artist + title; a karaoke singer types one
line ("the strokes max picu"). One small Gemini call splits the query into
artist/title AND corrects typos in the same step, returning the match judge's
verdict shape (kind cosmetic/content/ambiguous/none) plus the typed split, so
kjbox can show gen's "Corrected to X — you typed Y. Undo".
"""
from __future__ import annotations
import asyncio
import copy
import json
import logging
from typing import Awaitable, Callable, Optional
from backend.services.match_judge.ai import _model
from backend.services.match_judge.verdict import KIND_NONE
logger = logging.getLogger(__name__)
Generate = Callable[[str, str, str], Awaitable[dict]]
_VALID_KINDS = {"cosmetic", "content", "ambiguous"}
_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 "
"misspelled (e.g. 'the strokes max picu' = The Strokes — Machu Picchu).\n"
"Return JSON with: kind, confident, typed_artist, typed_title, canonical_artist, "
"canonical_title, alternatives, reason.\n"
"typed_artist/typed_title: how the query splits as typed (either may be empty).\n"
"kind:\n"
" 'cosmetic' – the query already names one real song; only casing/punctuation "
"differ.\n"
" 'content' – the query names one real song but with typos or a wrong/variant "
"title; canonical_* is the song meant.\n"
" 'ambiguous' – several real songs are plausible; list them in alternatives.\n"
" 'none' – not a recognisable song, or you are not sure.\n"
"confident: true only when you are sure which released song is meant. Never "
"invent songs; prefer kind='none' when unsure. canonical_artist/canonical_title "
"must use official formatting. alternatives is a list of {artist,title} (max 4)."
)
RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"kind": {"type": "string", "enum": ["cosmetic", "content", "ambiguous", "none"]},
"confident": {"type": "boolean"},
"typed_artist": {"type": "string"},
"typed_title": {"type": "string"},
"canonical_artist": {"type": "string"},
"canonical_title": {"type": "string"},
"alternatives": {
"type": "array",
"items": {
"type": "object",
"properties": {"artist": {"type": "string"}, "title": {"type": "string"}},
},
},
"reason": {"type": "string"},
},
"required": ["kind", "confident"],
}
def _none(query: str, reason: str = "no suggestion") -> dict:
return {
"kind": KIND_NONE, "confident": False, "typed_artist": "", "typed_title": query,
"canonical_artist": "", "canonical_title": "", "alternatives": [],
"engine": "ai", "reason": reason,
}
def verdict_from_response(data: object, query: str) -> dict:
"""Validate/normalise the model's JSON into the resolve response shape.
Anything malformed (wrong kinds or field types) → kind 'none'."""
try:
return _verdict_from_response(data, query)
except (TypeError, ValueError, AttributeError):
return _none(query, "malformed response")
def _verdict_from_response(data: object, query: str) -> dict:
if not isinstance(data, dict) or data.get("kind") not in _VALID_KINDS:
return _none(query)
for key in ("typed_artist", "typed_title", "canonical_artist", "canonical_title", "reason"):
if data.get(key) is not None and not isinstance(data[key], str):
return _none(query, "malformed response")
if data.get("alternatives") is not None and not isinstance(data["alternatives"], list):
return _none(query, "malformed response")
s = lambda k: str(data.get(k) or "").strip() # noqa: E731
alternatives = [
{"artist": str(a["artist"]).strip(), "title": str(a["title"]).strip()}
for a in (data.get("alternatives") or [])
if isinstance(a, dict) and isinstance(a.get("artist"), str) and isinstance(a.get("title"), str)
and a["artist"].strip() and a["title"].strip()
][:4]
canonical_artist, canonical_title = s("canonical_artist"), s("canonical_title")
kind = data["kind"]
if kind in ("cosmetic", "content") and not (canonical_artist and canonical_title):
return _none(query, "incomplete suggestion")
if kind == "ambiguous" and not alternatives:
return _none(query, "ambiguous without alternatives")
return {
"kind": kind,
"confident": bool(data.get("confident", False)),
"typed_artist": s("typed_artist"),
"typed_title": s("typed_title") or (query if not s("typed_artist") else ""),
"canonical_artist": canonical_artist,
"canonical_title": canonical_title,
"alternatives": alternatives,
"engine": "ai",
"reason": s("reason"),
}
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:
logger.warning(f"resolve_free_text failed: {e}")
return _none(query, "unavailable")
return verdict_from_response(data, query)
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
from google import genai
from google.genai import types
from backend.config import settings
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=int(getattr(settings, "match_judge_timeout_ms", 12000))),
)
response = client.models.generate_content(
model=model,
contents=[user_prompt],
config=types.GenerateContentConfig(
system_instruction=system_prompt,
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
),
)
return json.loads(response.text)
+2 -2
View File
@@ -59,9 +59,9 @@ RESPONSE_SCHEMA = {
def _model() -> str:
try:
from backend.config import settings
return getattr(settings, "parse_titles_model", "gemini-3.5-flash")
return getattr(settings, "parse_titles_model", "gemini-3.8-flash")
except Exception: # pragma: no cover - config guard
return "gemini-3.5-flash"
return "gemini-3.8-flash"
def build_prompts(items: list[dict]) -> tuple[str, str]:
+2 -2
View File
@@ -445,9 +445,9 @@ def _default_model() -> str:
try:
from backend.config import settings
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
return getattr(settings, "match_judge_model", "gemini-3.8-flash")
except Exception: # pragma: no cover - config import guard
return "gemini-3.5-flash"
return "gemini-3.8-flash"
def default_generate(system_prompt: str, user_prompt: str) -> dict:
+7
View File
@@ -128,6 +128,8 @@ class UserService:
tenant_id: Optional[str] = None,
signup_ip: Optional[str] = None,
device_fingerprint: Optional[str] = None,
signup_source: Optional[str] = None,
signup_venue: Optional[str] = None,
) -> User:
"""
Get existing user or create a new one.
@@ -139,6 +141,9 @@ class UserService:
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
signup_ip: Client IP address at signup (for rate limiting)
device_fingerprint: Browser fingerprint at signup (for rate limiting)
signup_source: Acquisition channel for partner signups (e.g. "kjbox");
only recorded when the user is created here
signup_venue: Partner-reported venue for the signup (kjbox)
Note: If user exists but has a different tenant_id, the existing user is returned.
Users are uniquely identified by email, not email+tenant.
@@ -160,6 +165,8 @@ class UserService:
tenant_id=tenant_id, # Associate with tenant on creation
signup_ip=signup_ip,
device_fingerprint=device_fingerprint,
signup_source=signup_source,
signup_venue=signup_venue,
)
self._save_user(user)
logger.info(f"Created new user: {email} (tenant: {tenant_id or 'default'}) — credits pending verification")
+40
View File
@@ -67,6 +67,46 @@ def test_bot_report_is_accepted_but_not_persisted(client):
client.fake_adapter.upsert_pattern.assert_not_called()
@pytest.mark.parametrize("message", ["Script error.", "Error: Script error.", "script error"])
def test_opaque_script_error_is_accepted_but_not_persisted(client, message):
# Opaque cross-origin error (older cached bundles still report it) — the
# "stack" is only our own handler's frame, so it's pure alert noise.
resp = client.post(
"/api/client-errors",
json=_payload(
message=message,
stack=f"Error: {message}\n@https://gen.nomadkaraoke.com/_next/static/chunks/x.js:6:874",
source="window.onerror",
extra={"filename": "", "lineno": 0, "colno": 0},
),
)
assert resp.status_code == 202
assert resp.json()["is_new"] is False
client.fake_adapter.upsert_pattern.assert_not_called()
def test_located_script_error_message_is_persisted(client):
# A genuine `throw new Error("Script error.")` from our own code has a real
# file/line on the ErrorEvent — actionable, so it must still be recorded.
resp = client.post(
"/api/client-errors",
json=_payload(
message="Error: Script error.",
stack="Error: Script error.\n at foo (https://gen.nomadkaraoke.com/_next/static/chunks/y.js:3:120)",
source="window.onerror",
extra={"filename": "https://gen.nomadkaraoke.com/_next/static/chunks/y.js", "lineno": 3, "colno": 120},
),
)
assert resp.status_code == 202
client.fake_adapter.upsert_pattern.assert_called_once()
def test_message_merely_mentioning_script_error_is_persisted(client):
resp = client.post("/api/client-errors", json=_payload(message="Script error in chunk loader"))
assert resp.status_code == 202
client.fake_adapter.upsert_pattern.assert_called_once()
def test_rejects_missing_message(client):
resp = client.post("/api/client-errors", json=_payload(message=""))
assert resp.status_code == 422
@@ -0,0 +1,181 @@
"""
Emulator integration tests for the kjbox partner service.
Runs KjboxPartnerService against a REAL Firestore emulator so the primitives
the security properties rest on are verified for real, not faked: the atomic
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 uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
import pytest
from google.cloud import firestore
from backend.services import kjbox_partner_service as kps
from .conftest import emulators_running
pytestmark = pytest.mark.skipif(
not emulators_running(),
reason="GCP emulators not running. Start with: scripts/start-emulators.sh",
)
@pytest.fixture
def svc():
return kps.KjboxPartnerService(firestore.Client(), pepper="emulator-pepper")
def _email():
return f"kj-{uuid.uuid4().hex[:8]}@example.com"
def _issue(svc, email, **over):
kwargs = dict(max_per_hour=5, needs_credit_eval=True, locale="en", ui_locale="en",
venue="Dive", ip_address=None, user_agent=None)
kwargs.update(over)
return svc.issue_code(email, **kwargs)
def _wrong(code):
return f"{(int(code) + 1) % 1_000_000:06d}"
class TestCodes:
def test_round_trip_and_single_use(self, svc):
email = _email()
issued = _issue(svc, email)
assert svc.verify_code(email, _wrong(issued.code))[0] == kps.VerifyOutcome.INVALID
outcome, record = svc.verify_code(email, issued.code)
assert outcome == kps.VerifyOutcome.OK and record["email"] == email
assert svc.verify_code(email, issued.code)[0] == kps.VerifyOutcome.EXPIRED
def test_attempt_cap_uses_atomic_increment(self, svc):
email = _email()
issued = _issue(svc, email)
for _ in range(kps.MAX_VERIFY_ATTEMPTS):
assert svc.verify_code(email, _wrong(issued.code))[0] == kps.VerifyOutcome.INVALID
assert svc.verify_code(email, issued.code)[0] == kps.VerifyOutcome.TOO_MANY_ATTEMPTS
assert svc.get_code_record(email)["code_hash"] is None
def test_resend_keeps_eval_and_throttle_history(self, svc):
email = _email()
first = _issue(svc, email)
ref = svc.db.collection(kps.LOGIN_CODES_COLLECTION).document(first.doc_id)
ref.update({"credit_eval_decision": "grant"})
second = _issue(svc, email)
record = svc.get_code_record(email)
assert record["credit_eval_decision"] == "grant"
assert second.needs_credit_eval is False # eval already stored
assert len(record["send_times"]) == 2
with pytest.raises(kps.CodeThrottled):
_issue(svc, email, max_per_hour=2)
assert svc.verify_code(email, second.code)[0] == kps.VerifyOutcome.OK
def test_throttle_holds_under_concurrency(self, svc):
"""Throttle check + send_times append + code write are one transaction."""
email = _email()
def attempt(_):
try:
_issue(svc, email, max_per_hour=5)
return True
except (kps.CodeThrottled, kps.TransactionContention):
return False
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(attempt, range(12)))
# Never more than the cap, and every success is recorded exactly once
assert 1 <= sum(results) <= 5
assert len(svc.get_code_record(email)["send_times"]) == sum(results)
# Sequential top-up reaches exactly the cap, then throttles
while len(svc.get_code_record(email)["send_times"]) < 5:
_issue(svc, email, max_per_hour=5)
with pytest.raises(kps.CodeThrottled):
_issue(svc, email, max_per_hour=5)
def test_expired(self, svc):
email = _email()
issued = _issue(svc, email)
svc.db.collection(kps.LOGIN_CODES_COLLECTION).document(issued.doc_id).update(
{"expires_at": datetime.now(timezone.utc) - timedelta(seconds=1)}
)
assert svc.verify_code(email, issued.code)[0] == kps.VerifyOutcome.EXPIRED
class TestCaps:
def test_signup_count_window(self, svc):
before = svc.count_recent_signups()
svc.record_signup(_email(), "Dive")
svc.db.collection(kps.SIGNUPS_COLLECTION).document().set(
{"email": _email(), "created_at": datetime.now(timezone.utc) - timedelta(hours=25)}
)
assert svc.count_recent_signups() == before + 1
def _seed_user(svc, credits=0):
email = _email()
ref = svc.db.collection("gen_users").document(email)
ref.set({"email": email, "credits": credits, "credit_transactions": []})
return email, ref
def _grant(svc, ref, email, key, **over):
kwargs = dict(venue="Dive", only_if_empty=False, max_per_24h=5)
kwargs.update(over)
return svc.grant_show_credit(ref, email, key, **kwargs)
class TestShowCredit:
def test_grant_idempotent_and_recorded(self, svc):
email, ref = _seed_user(svc, credits=0)
key = uuid.uuid4().hex
assert _grant(svc, ref, email, key) == kps.ShowCreditResult(granted=True, credits=1)
assert _grant(svc, ref, email, key) == kps.ShowCreditResult(granted=False, credits=1)
data = ref.get().to_dict()
assert data["credits"] == 1
assert data["credit_transactions"][-1]["reason"] == "kjbox show credit"
def test_only_if_empty_does_not_claim_key(self, svc):
email, ref = _seed_user(svc, credits=1)
key = uuid.uuid4().hex
assert _grant(svc, ref, email, key, only_if_empty=True).granted is False
assert _grant(svc, ref, email, key).granted is True
assert ref.get().to_dict()["credits"] == 2
def test_cap_and_credits_hold_under_concurrency(self, svc):
email, ref = _seed_user(svc, credits=0)
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
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(attempt, range(8)))
granted = sum(results)
assert 1 <= granted <= 3
# Credits exactly match grants (no lost updates, no over-grant)
assert ref.get().to_dict()["credits"] == granted
def test_same_key_concurrently_grants_once(self, svc):
email, ref = _seed_user(svc, credits=0)
with ThreadPoolExecutor(max_workers=6) as pool:
key = uuid.uuid4().hex
def attempt(_):
try:
return _grant(svc, ref, email, key).granted
except kps.TransactionContention:
return False
results = list(pool.map(attempt, range(6)))
assert sum(results) == 1
assert ref.get().to_dict()["credits"] == 1
@@ -171,3 +171,15 @@ def test_suggest_logs_unavailable_usage_without_crashing(caplog) -> None:
)
assert "auto-correct usage job=job-2 model=claude-fable-5 tokens=unavailable" in caplog.text
assert "total_est_cost_usd=unknown" in caplog.text
def test_gemini_38_flash_rate_switches_to_standard_on_2027_01_01() -> None:
from datetime import date
from backend.services.auto_correct.pricing import get_rate
assert get_rate("gemini-3.8-flash", on=date(2026, 12, 31))["output"] == 3.75
assert get_rate("gemini-3.8-flash", on=date(2027, 1, 1))["output"] == 7.5
assert get_rate("gemini-3.8-flash", on=date(2027, 1, 1))["input"] == 1.5
# Models without scheduled changes are unaffected.
assert get_rate("claude-opus-5-5", on=date(2027, 6, 1))["output"] == 20.0
@@ -375,6 +375,43 @@ class TestIdleReminderEndpoint:
assert data["status"] == "sent"
assert data["job_id"] == "test-job-123"
def test_forwards_request_metadata_for_kjbox_login_links(self, mock_job):
"""The idle review email needs the job's request_metadata so kjbox jobs
(client_id "kjbox") get a one-click sign-in link instead of a bare URL."""
from backend.api.routes.internal import router as internal_router
from backend.api.dependencies import require_admin
test_app = FastAPI()
test_app.include_router(internal_router, prefix="/api")
test_app.dependency_overrides[require_admin] = get_mock_admin
mock_job.status = JobStatus.AWAITING_REVIEW.value
mock_job.request_metadata = {"client_id": "kjbox"}
mock_job.state_data = {
"blocking_state_entered_at": "2024-01-01T00:00:00",
"blocking_action_type": "lyrics",
"reminder_sent": False,
}
with patch('backend.api.routes.internal.JobManager') as mock_jm_class, \
patch('backend.services.job_notification_service.get_job_notification_service') as mock_get_ns:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.firestore = Mock()
mock_jm_class.return_value = mock_jm
mock_ns = Mock()
mock_ns.send_action_reminder_email = AsyncMock(return_value=True)
mock_get_ns.return_value = mock_ns
response = TestClient(test_app).post(
"/api/internal/jobs/test-job-123/check-idle-reminder",
headers={"Authorization": "Bearer admin-token"}
)
assert response.status_code == 200
kwargs = mock_ns.send_action_reminder_email.call_args.kwargs
assert kwargs["request_metadata"] == {"client_id": "kjbox"}
def test_skips_reminder_when_already_sent(self, mock_job):
"""Test that reminder is skipped if already sent."""
from backend.api.routes.internal import router as internal_router
@@ -547,6 +547,100 @@ class TestAudioEditPreGeneration:
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
class TestAudioEditPrepResume:
"""A retry that finds an audio-edit job stuck at DOWNLOADING must finish the
editor prep instead of skipping (job 2c1b922e: first run OOM-killed while
generating the waveform, retry skipped, job orphaned at `downloading`)."""
@pytest.mark.asyncio
async def test_retry_resumes_unfinished_audio_edit_prep(self):
job = _make_job(
status=JobStatus.DOWNLOADING,
state_data={'requires_audio_edit': True},
input_media_gcs_path="uploads/test-job-123/audio/song.flac",
)
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory, \
patch("backend.services.audio_transcoding_service.AudioTranscodingService") as MockTS, \
patch("backend.services.audio_analysis_service.AudioAnalysisService") as MockAS:
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm.transition_to_state.return_value = True
mock_jm_cls.return_value = mock_jm
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
MockAS.return_value.cache_waveform_data.return_value = ([0.1], 1.0)
result = await process_audio_download("test-job-123")
assert result is True
mock_dl.assert_not_awaited()
MockTS.return_value.transcode_if_needed.assert_called_once_with(
"uploads/test-job-123/audio/song.flac"
)
mock_jm.transition_to_state.assert_called_once()
assert mock_jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.AWAITING_AUDIO_EDIT
mock_ws.trigger_audio_worker.assert_not_awaited()
mock_ws.trigger_lyrics_worker.assert_not_awaited()
mock_jm.fail_job.assert_not_called()
@pytest.mark.asyncio
async def test_concurrent_run_already_in_editor_is_success(self):
"""If another run moved the job to AWAITING_AUDIO_EDIT first, the losing
transition must not fail the job."""
stuck = _make_job(
status=JobStatus.DOWNLOADING,
state_data={'requires_audio_edit': True},
input_media_gcs_path="uploads/test-job-123/audio/song.flac",
)
advanced = _make_job(status=JobStatus.AWAITING_AUDIO_EDIT)
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.services.audio_transcoding_service.AudioTranscodingService"), \
patch("backend.services.audio_analysis_service.AudioAnalysisService"):
mock_jm = MagicMock()
mock_jm.get_job.side_effect = [stuck, advanced]
mock_jm.transition_to_state.return_value = False
mock_jm_cls.return_value = mock_jm
result = await process_audio_download("test-job-123")
assert result is True
assert mock_jm.transition_to_state.call_args.kwargs["raise_on_invalid"] is False
mock_jm.fail_job.assert_not_called()
@pytest.mark.asyncio
async def test_retry_without_audio_edit_still_skips(self):
"""Non-edit jobs at DOWNLOADING may already have downstream workers
triggered — keep skipping to avoid double-triggering."""
job = _make_job(
status=JobStatus.DOWNLOADING,
input_media_gcs_path="uploads/test-job-123/audio/song.flac",
)
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._enter_audio_edit") as mock_enter:
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm_cls.return_value = mock_jm
result = await process_audio_download("test-job-123")
assert result is True
mock_dl.assert_not_awaited()
mock_enter.assert_not_called()
mock_jm.transition_to_state.assert_not_called()
class TestFfprobeSeconds:
"""Tests for the _ffprobe_seconds helper in duration_reconciliation."""
@@ -425,3 +425,48 @@ class TestCompleteReviewSkipsEmptyCorrections:
bad_updated_data = {"some_key": "value"}
has_valid_corrections = bad_updated_data and "corrections" in bad_updated_data
assert not has_valid_corrections, "Dict without corrections key should not be valid"
class TestCorrectionDataRecordsReviewStarter:
"""First open of the review (AWAITING_REVIEW → IN_REVIEW) records who opened
it — kjbox tells a singer "the host has already started reviewing"."""
def _open(self, request_state, user_email="singer@example.com"):
from types import SimpleNamespace
from backend.api.routes.review import get_correction_data
import asyncio
job = Mock(spec=Job)
job.job_id = "job-1"
job.status = JobStatus.AWAITING_REVIEW
job.user_email = user_email
job.artist, job.title = "A", "T"
job.input_media_gcs_path = "jobs/job-1/input/audio.flac"
job.file_urls = {"lyrics": {"corrections": "jobs/job-1/lyrics/corrections.json"},
"stems": {}, "analysis": {}}
job.state_data = {}
job.style_params_gcs_path = None
job.style_assets = {}
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
patch("backend.api.routes.review.StorageService") as MockStorage:
jm = MockJobManager.return_value
jm.get_job.return_value = job
jm.transition_to_state.return_value = True
storage = MockStorage.return_value
storage.file_exists.return_value = False
storage.download_json.return_value = {"corrected_segments": [], "corrections": []}
request = SimpleNamespace(state=SimpleNamespace(**request_state))
try:
asyncio.run(get_correction_data("job-1", request=request, auth_info=("job-1", "full")))
except Exception:
pass # payload assembly isn't under test; the transition runs first
return jm
def test_admin_opening_records_admin(self):
jm = self._open({"review_auth_email": "andrew@nomadkaraoke.com", "review_auth_is_admin": True})
jm.record_review_started.assert_called_once_with(
"job-1", "singer@example.com", "andrew@nomadkaraoke.com", True)
def test_review_token_link_has_no_auth_state(self):
jm = self._open({})
jm.record_review_started.assert_called_once_with("job-1", "singer@example.com", None, False)
+29
View File
@@ -295,6 +295,35 @@ class TestEmailServiceProviderSelection:
assert svc.last_send_suppressed is True
class TestEmailServiceKjboxLoginCode:
"""The kjbox karaoke-night sign-in code email."""
def _send(self, locale="en"):
service = EmailService()
service.provider = Mock()
service.provider.send_email.return_value = True
result = service.send_kjbox_login_code("singer@example.com", "042917", expiry_minutes=10, locale=locale)
return result, service.provider.send_email.call_args.kwargs
def test_subject_and_body_show_code_and_expiry(self):
result, kwargs = self._send()
assert result is True
assert kwargs["to_email"] == "singer@example.com"
assert kwargs["subject"] == "Your Nomad Karaoke code: 042917"
for body in (kwargs["html_content"], kwargs["text_content"]):
assert "042917" in body
assert "10 minutes" in body
assert "ignore" in body.lower()
# Code-only email: nothing to click
assert "/auth/verify" not in kwargs["html_content"]
def test_localised(self):
_, kwargs = self._send(locale="es")
from backend.i18n import t
assert kwargs["subject"] == t("es", "emails.kjboxLoginCode.subject", code="042917")
assert "042917" in kwargs["subject"]
class TestEmailServiceJobCompletion:
"""Tests for job completion email method."""
@@ -314,6 +314,76 @@ class TestActionReminderEmail:
review_url = call_kwargs.get('review_url')
assert review_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
def _lyrics_service(self):
service = JobNotificationService()
service.frontend_url = "https://gen.nomadkaraoke.com"
service.email_service = Mock()
service.email_service.send_action_reminder.return_value = True
service.template_service = Mock()
service.template_service.render_action_needed_lyrics.return_value = "Review"
return service
@pytest.mark.asyncio
async def test_kjbox_job_review_email_uses_one_click_login_link(self):
"""kjbox jobs: the review link signs the singer in and lands on the review."""
service = self._lyrics_service()
login_svc = Mock()
login_svc.create_admin_login_token.return_value = Mock(token="tok-abc")
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True), \
patch('backend.services.job_notification_service.get_user_service', return_value=login_svc):
await service.send_action_reminder_email(
job_id="job-123",
user_email="singer@example.com",
action_type="lyrics",
request_metadata={"client_id": "kjbox"},
)
review_url = service.template_service.render_action_needed_lyrics.call_args.kwargs["review_url"]
assert review_url == "https://gen.nomadkaraoke.com/en/auth/verify?token=tok-abc"
kwargs = login_svc.create_admin_login_token.call_args.kwargs
assert kwargs["email"] == "singer@example.com"
assert kwargs["purpose"] == "job_review:job-123"
assert 1 <= kwargs["expiry_hours"] <= 168
@pytest.mark.asyncio
@pytest.mark.parametrize("metadata", [None, {}, {"client_id": ""}, {"client_id": "test-runner"}])
async def test_non_kjbox_job_review_email_uses_bare_url(self, metadata):
service = self._lyrics_service()
login_svc = Mock()
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True), \
patch('backend.services.job_notification_service.get_user_service', return_value=login_svc):
await service.send_action_reminder_email(
job_id="job-123",
user_email="user@example.com",
action_type="lyrics",
request_metadata=metadata,
)
review_url = service.template_service.render_action_needed_lyrics.call_args.kwargs["review_url"]
assert review_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
login_svc.create_admin_login_token.assert_not_called()
@pytest.mark.asyncio
async def test_kjbox_login_link_failure_falls_back_to_bare_url(self):
service = self._lyrics_service()
login_svc = Mock()
login_svc.create_admin_login_token.side_effect = RuntimeError("firestore down")
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True), \
patch('backend.services.job_notification_service.get_user_service', return_value=login_svc):
sent = await service.send_action_reminder_email(
job_id="job-123",
user_email="singer@example.com",
action_type="lyrics",
request_metadata={"client_id": "kjbox"},
)
assert sent is True
review_url = service.template_service.render_action_needed_lyrics.call_args.kwargs["review_url"]
assert review_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
@pytest.mark.asyncio
async def test_send_instrumental_reminder_includes_url(self):
"""Test that instrumental reminder includes correct URL."""
+776
View File
@@ -0,0 +1,776 @@
"""Tests for the kjbox partner API (/api/kjbox/*).
Composed tests: the real kjbox router + real KjboxPartnerService + real
UserService, all over an in-memory Firestore fake. Only the true external
boundaries are mocked (email provider, disposable-email lookups, the welcome
credit AI evaluation).
"""
from __future__ import annotations
import hashlib
import itertools
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from google.api_core import exceptions as google_exceptions
from backend.api.routes import kjbox
from backend.services import kjbox_partner_service as kps
from backend.services.email_service import get_email_service
from backend.services.user_service import UserService, get_user_service
SECRET = "test-kjbox-secret"
EMAIL = "singer@example.com"
# ------------------------------------------------------------ Firestore fake
class FakeSnap:
def __init__(self, ref, data):
self.reference = ref
self._data = data
@property
def exists(self):
return self._data is not None
def to_dict(self):
return dict(self._data) if self._data is not None else None
class FakeRef:
def __init__(self, coll, doc_id):
self.coll = coll
self.id = doc_id
@property
def _docs(self):
return self.coll.docs
def get(self, transaction=None):
data = self._docs.get(self.id)
return FakeSnap(self, dict(data) if data is not None else None)
def set(self, data, merge=False):
if merge and self.id in self._docs:
self._docs[self.id].update(dict(data))
else:
self._docs[self.id] = dict(data)
def create(self, data):
if self.id in self._docs:
raise google_exceptions.AlreadyExists("exists")
self._docs[self.id] = dict(data)
def update(self, data):
if self.id not in self._docs:
raise google_exceptions.NotFound("missing")
doc = self._docs[self.id]
for key, value in data.items():
if type(value).__name__ == "Increment":
doc[key] = (doc.get(key) or 0) + value.value
else:
doc[key] = value
def delete(self):
self._docs.pop(self.id, None)
class FakeQuery:
def __init__(self, coll, filters, limit=None):
self.coll = coll
self.filters = filters
self._limit = limit
def where(self, *args, filter=None, **kwargs):
return FakeQuery(self.coll, self.filters + [filter], self._limit)
def limit(self, n):
return FakeQuery(self.coll, self.filters, n)
def stream(self):
out = []
for doc_id, data in list(self.coll.docs.items()):
if all(self._match(data, f) for f in self.filters):
out.append(FakeSnap(FakeRef(self.coll, doc_id), dict(data)))
return out[: self._limit] if self._limit else out
@staticmethod
def _match(data, f):
value = data.get(f.field_path)
if f.op_string == "==":
return value == f.value
if f.op_string == ">=":
return value is not None and value >= f.value
raise NotImplementedError(f.op_string)
class FakeCollection:
_ids = itertools.count()
def __init__(self):
self.docs = {}
def document(self, doc_id=None):
return FakeRef(self, doc_id or f"auto-{next(self._ids)}")
def where(self, *args, filter=None, **kwargs):
return FakeQuery(self, [filter])
class FakeTransaction:
"""Applies writes immediately (the service only writes after all reads)."""
def __init__(self, log):
self.log = log
def set(self, ref, data, merge=False):
self.log.append(("set", ref.coll, ref.id))
ref.set(data, merge=merge)
def update(self, ref, data):
self.log.append(("update", ref.coll, ref.id))
ref.update(data)
def create(self, ref, data):
self.log.append(("create", ref.coll, ref.id))
ref.create(data)
def delete(self, ref):
ref.delete()
class FakeDb:
def __init__(self):
self.collections = {}
self.txn_writes = []
self.txn_count = 0
def collection(self, name):
return self.collections.setdefault(name, FakeCollection())
# ------------------------------------------------------------------ fixtures
@pytest.fixture
def db():
return FakeDb()
@pytest.fixture
def user_service(db):
svc = UserService.__new__(UserService)
svc.db = db
svc.settings = MagicMock()
grant_calls = []
def fake_grant(email, precomputed_eval=None):
grant_calls.append({"email": email, "precomputed_eval": precomputed_eval})
user = svc.get_user(email)
if user.welcome_credits_granted:
return False, "already_granted"
svc.add_credits(email, svc.NEW_USER_FREE_CREDITS, "welcome_credit")
svc.update_user(email, welcome_credits_granted=True)
return True, "granted"
svc.grant_welcome_credits_if_eligible = fake_grant
svc.grant_calls = grant_calls
return svc
@pytest.fixture
def email_service():
svc = MagicMock()
svc.is_configured.return_value = True
svc.send_kjbox_login_code.return_value = True
svc.send_welcome_email.return_value = True
return svc
@pytest.fixture
def validation():
v = MagicMock()
v.is_disposable_domain.return_value = False
v.is_email_blocked.return_value = False
v.is_ip_blocked.return_value = False
return v
@pytest.fixture
def settings():
return SimpleNamespace(
kjbox_partner_secret=SECRET,
kjbox_signup_cap_per_24h=100,
kjbox_codes_per_email_per_hour=5,
kjbox_show_credits_per_user_per_24h=5,
)
@pytest.fixture
def precompute(monkeypatch):
"""Run the welcome-credit precompute synchronously and record calls."""
calls = []
monkeypatch.setattr(kjbox, "_precompute_credit_eval", lambda *a: calls.append(a))
class SyncThread:
def __init__(self, target, args=(), daemon=None):
self.target, self.args = target, args
def start(self):
self.target(*self.args)
# Only the kjbox module's view of threading — patching threading.Thread
# globally would also break asyncio.to_thread's executor.
monkeypatch.setattr(kjbox, "threading", SimpleNamespace(Thread=SyncThread))
return calls
@pytest.fixture
def client(monkeypatch, db, user_service, email_service, validation, settings, precompute):
def fake_run_transaction(self, fn):
db.txn_count += 1
return fn(FakeTransaction(db.txn_writes))
monkeypatch.setattr(kps.KjboxPartnerService, "_run_transaction", fake_run_transaction)
app = FastAPI()
app.include_router(kjbox.router, prefix="/api")
app.dependency_overrides[get_user_service] = lambda: user_service
app.dependency_overrides[get_email_service] = lambda: email_service
monkeypatch.setattr(kjbox, "get_settings", lambda: settings)
monkeypatch.setattr(kjbox, "get_email_validation_service", lambda: validation)
return TestClient(app)
H = {"X-Kjbox-Secret": SECRET}
def _send(client, email=EMAIL, **extra):
return client.post("/api/kjbox/auth/send-code", json={"email": email, **extra}, headers=H)
def _sent_code(email_service):
return email_service.send_kjbox_login_code.call_args.args[1]
def _verify(client, code, email=EMAIL):
return client.post("/api/kjbox/auth/verify-code", json={"email": email, "code": code}, headers=H)
def _code_doc(db, email=EMAIL):
return db.collection(kps.LOGIN_CODES_COLLECTION).docs[kps.code_doc_id(email)]
# ---------------------------------------------------------------- secret gate
class TestSecretGate:
@pytest.mark.parametrize("path,body", [
("/api/kjbox/auth/send-code", {"email": EMAIL}),
("/api/kjbox/auth/verify-code", {"email": EMAIL, "code": "123456"}),
("/api/kjbox/credits/show-credit", {"idempotency_key": "k"}),
])
def test_unconfigured_returns_503(self, client, settings, path, body):
settings.kjbox_partner_secret = ""
resp = client.post(path, json=body, headers=H)
assert resp.status_code == 503
assert resp.json() == {"detail": "not configured"}
@pytest.mark.parametrize("path,body", [
("/api/kjbox/auth/send-code", {"email": EMAIL}),
("/api/kjbox/auth/verify-code", {"email": EMAIL, "code": "123456"}),
("/api/kjbox/credits/show-credit", {"idempotency_key": "k"}),
])
def test_wrong_or_missing_secret_returns_403(self, client, path, body):
assert client.post(path, json=body, headers={"X-Kjbox-Secret": "nope"}).status_code == 403
assert client.post(path, json=body).status_code == 403
def test_router_registered_in_main_app(self):
from backend.main import app
paths = {getattr(r, "path", "") for r in app.routes}
assert {"/api/kjbox/auth/send-code", "/api/kjbox/auth/verify-code",
"/api/kjbox/credits/show-credit"} <= paths
# ------------------------------------------------------------------ send-code
class TestSendCode:
def test_new_email_gets_code_but_no_account_until_verified(self, client, user_service, db, email_service, precompute):
resp = _send(client, locale="es-MX", venue="The Dive Bar")
assert resp.status_code == 200
assert resp.json() == {"status": "sent"}
# No account and no signup-cap consumption for an unverified address
assert user_service.get_user(EMAIL) is None
assert db.collection(kps.SIGNUPS_COLLECTION).docs == {}
# Attribution rides on the code record until verify
doc = _code_doc(db)
assert doc["venue"] == "The Dive Bar" and doc["locale"] == "es" and doc["ui_locale"] == "es"
# Code email localised + welcome-credit eval precomputed onto the code doc
args, kwargs = email_service.send_kjbox_login_code.call_args
assert args[0] == EMAIL and len(args[1]) == 6 and args[1].isdigit()
assert kwargs == {"expiry_minutes": 10, "locale": "es"}
assert precompute == [(kps.code_doc_id(EMAIL), EMAIL, kps.LOGIN_CODES_COLLECTION)]
def test_throttle_and_code_write_happen_in_one_transaction(self, client, db):
_send(client)
assert db.txn_count == 1
assert db.txn_writes == [("set", db.collection(kps.LOGIN_CODES_COLLECTION), kps.code_doc_id(EMAIL))]
def test_code_stored_only_as_hash(self, client, db, email_service):
_send(client)
code = _sent_code(email_service)
doc = _code_doc(db)
assert code not in str(doc.values())
assert doc["code_hash"] and len(doc["code_hash"]) == 64
assert doc["attempts"] == 0
expires = doc["expires_at"] - doc["created_at"]
assert expires == timedelta(minutes=10)
def test_existing_user_not_recreated_or_counted(self, client, user_service, db, precompute):
user_service.get_or_create_user(EMAIL)
user_service.update_user(EMAIL, welcome_credits_granted=True)
assert _send(client).status_code == 200
assert db.collection(kps.SIGNUPS_COLLECTION).docs == {}
assert user_service.get_user(EMAIL).signup_source is None
assert precompute == [] # already had a welcome credit → nothing to evaluate
def test_email_normalised(self, client, db, email_service):
assert _send(client, email=" Singer@Example.COM ").status_code == 200
assert _code_doc(db)["email"] == EMAIL
assert _verify(client, _sent_code(email_service), email="SINGER@example.com ").status_code == 200
def test_invalid_email_422(self, client):
assert _send(client, email="not-an-email").status_code == 422
def test_disposable_domain_422_same_detail_as_magic_link(self, client, validation, user_service):
from backend.i18n import t
validation.is_disposable_domain.return_value = True
resp = _send(client)
assert resp.status_code == 422
assert resp.json()["detail"] == t("en", "users.disposableEmailBlocked")
assert user_service.get_user(EMAIL) is None
@pytest.mark.parametrize("blocked", ["email", "ip"])
def test_blocked_email_or_ip_pretends_success(self, client, validation, email_service, user_service, blocked):
getattr(validation, f"is_{blocked}_blocked").return_value = True
resp = _send(client)
assert resp.status_code == 200 and resp.json() == {"status": "sent"}
email_service.send_kjbox_login_code.assert_not_called()
assert user_service.get_user(EMAIL) is None
def test_per_email_throttle(self, client, email_service):
codes = [_send(client).status_code for _ in range(6)]
assert codes == [200] * 5 + [429]
assert _send(client).json() == {"detail": "too_many_codes"}
assert email_service.send_kjbox_login_code.call_count == 5
def test_throttle_window_is_rolling_hour(self, client, db):
_send(client)
doc = _code_doc(db)
doc["send_times"] = [datetime.now(timezone.utc) - timedelta(minutes=61)] * 10
assert _send(client).status_code == 200
def test_no_per_ip_signup_cap(self, client, user_service, email_service):
# gen's magic-link path allows 2 signups/IP/24h; a venue shares one IP.
user_service.is_signup_rate_limited = MagicMock(return_value=True)
for i in range(5):
email = f"s{i}@example.com"
assert _send(client, email=email).status_code == 200
assert _verify(client, _sent_code(email_service), email=email).status_code == 200
def test_signup_cap_not_consumed_by_unverified_sends(self, client, settings, db, email_service):
settings.kjbox_signup_cap_per_24h = 1
for i in range(5):
assert _send(client, email=f"fake{i}@example.com").status_code == 200
assert db.collection(kps.SIGNUPS_COLLECTION).docs == {}
_send(client)
assert _verify(client, _sent_code(email_service)).status_code == 200
# ---------------------------------------------------------------- verify-code
class TestVerifyCode:
def test_success_returns_session_and_grants_welcome_credit(self, client, db, user_service, email_service):
_send(client, locale="de", venue="The Dive Bar")
# Simulate the background eval having finished
_code_doc(db).update({"credit_eval_decision": "grant", "credit_eval_reasoning": "clean"})
resp = _verify(client, _sent_code(email_service))
assert resp.status_code == 200
body = resp.json()
assert set(body) == {"session_token", "user", "credits_granted", "credit_status"}
assert body["credits_granted"] == 1 and body["credit_status"] == "granted"
assert body["user"]["email"] == EMAIL and body["user"]["credits"] == 1
# Precomputed eval handed to the grant (instant verify)
assert user_service.grant_calls[-1]["precomputed_eval"] == {
"credit_eval_decision": "grant", "credit_eval_reasoning": "clean"}
# Account created on verify with kjbox attribution + counted as a signup
created = user_service.get_user(EMAIL)
assert created.signup_source == "kjbox" and created.signup_venue == "The Dive Bar"
assert created.signup_ip is None
assert [d["email"] for d in db.collection(kps.SIGNUPS_COLLECTION).docs.values()] == [EMAIL]
# Session is a real, valid gen session for the user
valid, user, _ = user_service.validate_session(body["session_token"])
assert valid and user.email == EMAIL
assert user.email_verified and user.last_login_at is not None
assert user.locale == "de" and user.ui_locale == "de"
email_service.send_welcome_email.assert_called_once_with(EMAIL, 1, locale="de")
def test_verified_signup_cap(self, client, settings, db, user_service, email_service):
settings.kjbox_signup_cap_per_24h = 2
for email in ("a@example.com", "b@example.com"):
_send(client, email=email)
assert _verify(client, _sent_code(email_service), email=email).status_code == 200
_send(client, email="c@example.com")
code_c = _sent_code(email_service)
resp = _verify(client, code_c, email="c@example.com")
assert resp.status_code == 429 and resp.json() == {"detail": "signup_cap"}
assert user_service.get_user("c@example.com") is None
# Cap checked before consuming the code: once it lifts, the same code works
settings.kjbox_signup_cap_per_24h = 3
assert _verify(client, code_c, email="c@example.com").status_code == 200
# Existing accounts are never blocked by the new-account cap
settings.kjbox_signup_cap_per_24h = 0
_send(client, email="a@example.com")
assert _verify(client, _sent_code(email_service), email="a@example.com").status_code == 200
def test_signup_cap_counts_only_last_24h(self, client, settings, db, email_service):
settings.kjbox_signup_cap_per_24h = 1
db.collection(kps.SIGNUPS_COLLECTION).document("old").set(
{"email": "old@example.com", "created_at": datetime.now(timezone.utc) - timedelta(hours=25)}
)
_send(client)
assert _verify(client, _sent_code(email_service)).status_code == 200
def test_returning_user_gets_no_second_welcome(self, client, user_service, email_service):
_send(client)
assert _verify(client, _sent_code(email_service)).status_code == 200
_send(client)
body = _verify(client, _sent_code(email_service)).json()
assert body["credits_granted"] == 0 and body["credit_status"] == "already_granted"
assert email_service.send_welcome_email.call_count == 1
def test_wrong_code_401_and_counts_attempt(self, client, db, email_service):
_send(client)
code = _sent_code(email_service)
wrong = f"{(int(code) + 1) % 1_000_000:06d}"
resp = _verify(client, wrong)
assert resp.status_code == 401 and resp.json() == {"detail": "invalid_code"}
assert _code_doc(db)["attempts"] == 1
assert _verify(client, code).status_code == 200 # still usable
def test_too_many_attempts_burns_code(self, client, email_service):
_send(client)
code = _sent_code(email_service)
wrong = f"{(int(code) + 1) % 1_000_000:06d}"
statuses = [_verify(client, wrong).status_code for _ in range(5)]
assert statuses == [401] * 5
resp = _verify(client, code) # correct code, but attempts exhausted
assert resp.status_code == 429 and resp.json() == {"detail": "too_many_attempts"}
assert _verify(client, code).status_code == 401 # burned
def test_expired_code(self, client, db, email_service):
_send(client)
_code_doc(db)["expires_at"] = datetime.now(timezone.utc) - timedelta(seconds=1)
resp = _verify(client, _sent_code(email_service))
assert resp.status_code == 401 and resp.json() == {"detail": "expired"}
def test_missing_code(self, client):
resp = _verify(client, "123456")
assert resp.status_code == 401 and resp.json() == {"detail": "expired"}
def test_code_single_use(self, client, email_service):
_send(client)
code = _sent_code(email_service)
assert _verify(client, code).status_code == 200
resp = _verify(client, code)
assert resp.status_code == 401 and resp.json() == {"detail": "expired"}
def test_new_code_invalidates_previous(self, client, email_service):
_send(client)
first = _sent_code(email_service)
_send(client)
second = _sent_code(email_service)
if first != second:
assert _verify(client, first).status_code == 401
assert _verify(client, second).status_code == 200
def test_concurrent_use_marker_blocks_replay(self, client, db, email_service):
_send(client)
code_id = _code_doc(db)["code_id"]
db.collection(kps.LOGIN_CODE_USES_COLLECTION).document(code_id).create({"email": EMAIL})
resp = _verify(client, _sent_code(email_service))
assert resp.status_code == 401 and resp.json() == {"detail": "expired"}
# --------------------------------------------------------------- show-credit
def _session(client, email_service, email=EMAIL):
_send(client, email=email)
return _verify(client, _sent_code(email_service), email=email).json()["session_token"]
def _show(client, token, key, **extra):
return client.post(
"/api/kjbox/credits/show-credit",
json={"idempotency_key": key, **extra},
headers={**H, "Authorization": f"Bearer {token}"},
)
class TestShowCredit:
def test_grants_one_credit_quietly(self, client, email_service, user_service):
token = _session(client, email_service) # welcome credit → 1
resp = _show(client, token, "job-abc", venue="The Dive Bar")
assert resp.status_code == 200 and resp.json() == {"granted": True, "credits": 2}
user = user_service.get_user(EMAIL)
assert user.credits == 2
assert user.credit_transactions[-1].reason == "kjbox show credit"
email_service.send_credits_added.assert_not_called()
def test_idempotent_repeat(self, client, email_service, user_service):
token = _session(client, email_service)
assert _show(client, token, "job-abc").json() == {"granted": True, "credits": 2}
assert _show(client, token, "job-abc").json() == {"granted": False, "credits": 2}
assert user_service.get_user(EMAIL).credits == 2
def test_key_stored_hashed_with_user(self, client, email_service, db):
token = _session(client, email_service)
_show(client, token, "a/b:c")
doc_id = hashlib.sha256(b"a/b:c").hexdigest()
assert db.collection(kps.SHOW_CREDITS_COLLECTION).docs[doc_id]["email"] == EMAIL
def test_daily_cap(self, client, email_service, settings):
settings.kjbox_show_credits_per_user_per_24h = 2
token = _session(client, email_service)
assert _show(client, token, "k1").status_code == 200
assert _show(client, token, "k2").status_code == 200
resp = _show(client, token, "k3")
assert resp.status_code == 429 and resp.json() == {"detail": "show_credit_cap"}
# An already-processed key still answers idempotently at the cap
assert _show(client, token, "k1").json()["granted"] is False
def test_cap_is_rolling_24h(self, client, email_service, settings, db):
settings.kjbox_show_credits_per_user_per_24h = 1
token = _session(client, email_service)
counter = db.collection(kps.SHOW_CREDIT_USERS_COLLECTION).document(hashlib.sha256(EMAIL.encode()).hexdigest())
counter.set({"email": EMAIL, "grant_times": [datetime.now(timezone.utc) - timedelta(hours=25)]})
assert _show(client, token, "k1").json()["granted"] is True
assert _show(client, token, "k2").status_code == 429 # the fresh grant counts
@pytest.mark.parametrize("auth", [None, "Bearer ", "Bearer nope", "Basic abc"])
def test_bad_session_401(self, client, auth):
headers = dict(H)
if auth is not None:
headers["Authorization"] = auth
resp = client.post("/api/kjbox/credits/show-credit", json={"idempotency_key": "k"}, headers=headers)
assert resp.status_code == 401 and resp.json() == {"detail": "invalid_session"}
def test_idempotency_key_length_validated(self, client, email_service):
token = _session(client, email_service)
assert _show(client, token, "x" * 129).status_code == 422
assert _show(client, token, "").status_code == 422
def test_only_if_empty_skips_when_user_has_credit(self, client, email_service, db, user_service):
token = _session(client, email_service) # welcome credit → 1
resp = _show(client, token, "k1", only_if_empty=True)
assert resp.json() == {"granted": False, "credits": 1}
# Key NOT claimed on a non-grant: the later job-time call can still use it
assert db.collection(kps.SHOW_CREDITS_COLLECTION).docs == {}
user_service.update_user(EMAIL, credits=0) # e.g. welcome credit spent elsewhere
assert _show(client, token, "k1").json() == {"granted": True, "credits": 1}
def test_only_if_empty_then_same_key_grants_once(self, client, email_service, user_service):
token = _session(client, email_service)
user_service.update_user(EMAIL, credits=0) # e.g. welcome credit denied
assert _show(client, token, "k1", only_if_empty=True).json() == {"granted": True, "credits": 1}
# Job-time call with the same key must not stack a second credit
assert _show(client, token, "k1").json() == {"granted": False, "credits": 1}
assert user_service.get_user(EMAIL).credits == 1
def test_non_grant_does_not_count_toward_cap(self, client, email_service, settings):
settings.kjbox_show_credits_per_user_per_24h = 1
token = _session(client, email_service)
for i in range(3):
assert _show(client, token, f"k{i}", only_if_empty=True).json()["granted"] is False
assert _show(client, token, "k9").json()["granted"] is True
def test_grant_is_one_transaction(self, client, email_service, db):
token = _session(client, email_service)
before_count, before_writes = db.txn_count, len(db.txn_writes)
_show(client, token, "k1")
assert db.txn_count == before_count + 1
kinds = sorted(w[0] for w in db.txn_writes[before_writes:])
assert kinds == ["create", "set", "update"] # key claim, cap counter, credits
class TestTransactionContention:
def _contend(self, monkeypatch, db):
calls = {"n": 0}
real = kps.KjboxPartnerService._run_transaction
def flaky(self, fn):
calls["n"] += 1
if calls["n"] == calls.get("fail_on", -1):
raise kps.TransactionContention()
return real(self, fn)
monkeypatch.setattr(kps.KjboxPartnerService, "_run_transaction", flaky)
return calls
def test_send_code_contention_is_throttled(self, client, monkeypatch, db, email_service):
calls = self._contend(monkeypatch, db)
calls["fail_on"] = 1
resp = _send(client)
assert resp.status_code == 429 and resp.json() == {"detail": "too_many_codes"}
email_service.send_kjbox_login_code.assert_not_called()
def test_show_credit_contention_is_retryable(self, client, monkeypatch, db, email_service, user_service):
token = _session(client, email_service)
calls = self._contend(monkeypatch, db)
calls["fail_on"] = 1
resp = _show(client, token, "k1")
assert resp.status_code == 409 and resp.json() == {"detail": "busy_retry"}
assert user_service.get_user(EMAIL).credits == 1 # nothing granted
assert _show(client, token, "k1").json() == {"granted": True, "credits": 2}
def test_real_runner_maps_firestore_giveup(self, monkeypatch):
svc = kps.KjboxPartnerService(MagicMock(), pepper="p")
def give_up(fn):
def wrapped(transaction):
raise ValueError("Failed to commit transaction in 10 attempts.")
return wrapped
monkeypatch.setattr(kps.firestore, "transactional", give_up)
with pytest.raises(kps.TransactionContention):
svc._run_transaction(lambda t: None)
# ------------------------------------------------------------- review link
class TestReviewLink:
@pytest.fixture
def jobs(self, monkeypatch):
from backend.services import job_manager as jm
from backend.services import job_notification_service as jns
store = {}
class FakeJobManager:
def get_job(self, job_id):
return store.get(job_id)
monkeypatch.setattr(jm, "JobManager", FakeJobManager)
minted = []
def fake_url(job_id, email, locale="en", frontend_url=None):
minted.append((job_id, email, locale))
return f"https://gen.example/{locale}/auth/verify?token=t-{job_id}"
monkeypatch.setattr(jns, "build_review_login_url", fake_url)
store["minted"] = minted
return store
def _job(self, status, email=EMAIL, state_data=None):
return SimpleNamespace(job_id="job1", user_email=email, status=status,
state_data=state_data or {})
def _link(self, client, token, job_id="job1", **body):
return client.post(f"/api/kjbox/jobs/{job_id}/review-link", json=body,
headers={**H, "Authorization": f"Bearer {token}"})
def test_owner_gets_sign_in_link_while_awaiting_review(self, client, email_service, jobs):
token = _session(client, email_service)
jobs["job1"] = self._job("awaiting_review")
resp = self._link(client, token, locale="es")
assert resp.status_code == 200
assert resp.json() == {"url": "https://gen.example/es/auth/verify?token=t-job1",
"status": "awaiting_review", "review_started_by": None}
assert jobs["minted"] == [("job1", EMAIL, "es")]
def test_in_review_reports_who_started(self, client, email_service, jobs):
token = _session(client, email_service)
jobs["job1"] = self._job("in_review", state_data={"review_started_by": "admin"})
body = self._link(client, token).json()
assert body["status"] == "in_review" and body["review_started_by"] == "admin"
def test_unknown_locale_falls_back_to_en(self, client, email_service, jobs):
token = _session(client, email_service)
jobs["job1"] = self._job("awaiting_review")
self._link(client, token, locale="xx")
assert jobs["minted"][-1][2] == "en"
def test_other_users_job_is_404(self, client, email_service, jobs):
token = _session(client, email_service)
jobs["job1"] = self._job("awaiting_review", email="someone@else.com")
assert self._link(client, token).status_code == 404
assert self._link(client, token, job_id="nope").status_code == 404
assert jobs["minted"] == []
def test_not_in_review_is_409(self, client, email_service, jobs):
token = _session(client, email_service)
jobs["job1"] = self._job("rendering_video")
resp = self._link(client, token)
assert resp.status_code == 409 and resp.json()["detail"] == "not_in_review"
def test_requires_session_and_secret(self, client, jobs):
jobs["job1"] = self._job("awaiting_review")
assert client.post("/api/kjbox/jobs/job1/review-link", json={}, headers=H).status_code == 401
assert client.post("/api/kjbox/jobs/job1/review-link", json={},
headers={"Authorization": "Bearer x"}).status_code == 403
# ---------------------------------------------------------- search resolve
class TestCatalogResolve:
@pytest.fixture(autouse=True)
def fresh(self, monkeypatch):
monkeypatch.setattr(kjbox, "_resolve_cache", {})
monkeypatch.setattr(kjbox, "_resolve_calls", [])
calls = []
async def fake_resolve(query):
calls.append(query)
if query == "flaky":
return {"kind": "none", "reason": "unavailable"}
return {"kind": "content", "confident": True, "canonical_artist": "The Strokes",
"canonical_title": "Machu Picchu", "typed_artist": "the strokes",
"typed_title": "max picu", "alternatives": [], "engine": "ai", "reason": ""}
from backend.services.match_judge import free_text
monkeypatch.setattr(free_text, "resolve_free_text", fake_resolve)
return calls
def _post(self, client, q):
return client.post("/api/kjbox/catalog/resolve", json={"query": q}, headers=H)
def test_resolves_and_caches(self, client, fresh):
r = self._post(client, "the strokes max picu")
assert r.status_code == 200 and r.json()["canonical_title"] == "Machu Picchu"
self._post(client, "THE STROKES max picu") # same query, folded
assert fresh == ["the strokes max picu"]
def test_transient_failures_are_not_cached(self, client, fresh):
self._post(client, "flaky")
self._post(client, "flaky")
assert fresh == ["flaky", "flaky"]
def test_rate_limited(self, client, fresh, monkeypatch):
monkeypatch.setattr(kjbox, "_RESOLVE_PER_MINUTE", 2)
assert self._post(client, "a1").status_code == 200
assert self._post(client, "a2").status_code == 200
assert self._post(client, "a3").status_code == 429
assert self._post(client, "a1").status_code == 200 # cache hit is free
def test_requires_partner_secret_and_valid_query(self, client):
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
@@ -0,0 +1,48 @@
"""Free-text song resolution (kjbox singer search auto-correct)."""
import asyncio
import pytest
from backend.services.match_judge.free_text import resolve_free_text, verdict_from_response
def _run(data=None, exc=None):
async def gen(model, system_prompt, user_prompt):
assert "the strokes max picu" in user_prompt
if exc:
raise exc
return data
return asyncio.run(resolve_free_text("the strokes max picu", generate=gen, model="m"))
def test_typo_is_corrected_and_split():
v = _run({"kind": "content", "confident": True, "typed_artist": "the strokes",
"typed_title": "max picu", "canonical_artist": "The Strokes",
"canonical_title": "Machu Picchu", "reason": "typo"})
assert v["kind"] == "content" and v["confident"] is True
assert (v["canonical_artist"], v["canonical_title"]) == ("The Strokes", "Machu Picchu")
assert (v["typed_artist"], v["typed_title"]) == ("the strokes", "max picu")
assert v["engine"] == "ai"
def test_model_failure_is_none_not_an_error():
v = _run(exc=TimeoutError("slow"))
assert v["kind"] == "none" and v["reason"] == "unavailable"
@pytest.mark.parametrize("data", [
None, "nope", {"kind": "bogus", "confident": True},
{"kind": "content", "confident": True, "canonical_artist": "The Strokes"}, # no title
{"kind": "ambiguous", "confident": False}, # no alternatives
{"kind": "content", "confident": True, "canonical_artist": ["x"], "canonical_title": "T"},
{"kind": "ambiguous", "confident": False, "alternatives": "Radiohead - Creep"},
{"kind": "ambiguous", "confident": False, "alternatives": [{"artist": {"a": 1}, "title": "T"}]},
])
def test_bad_model_output_degrades_to_none(data):
assert verdict_from_response(data, "q")["kind"] == "none"
def test_ambiguous_keeps_up_to_four_alternatives():
alts = [{"artist": f"A{i}", "title": f"T{i}"} for i in range(6)] + [{"artist": "x"}]
v = verdict_from_response({"kind": "ambiguous", "confident": False, "alternatives": alts}, "q")
assert v["kind"] == "ambiguous" and len(v["alternatives"]) == 4
+16
View File
@@ -120,6 +120,22 @@ class TestPipelineDecoupling:
assert result is True
mock_ws.trigger_screens_worker.assert_awaited_once_with("test-001")
@pytest.mark.asyncio
async def test_advance_triggers_screens_for_audio_edited_job(self, job_manager, mock_firestore_service):
"""Audio-edited jobs prep at AUDIO_EDIT_COMPLETE (the edit-submit endpoint
triggers the workers without passing back through DOWNLOADING). The
handoff must still fire — job 2c1b922e stalled here."""
job = _make_job(state_data={"lyrics_complete": True}, status=JobStatus.AUDIO_EDIT_COMPLETE)
mock_firestore_service.get_job.return_value = job
mock_ws = MagicMock()
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
result = await job_manager.advance_to_screens_if_ready("test-001")
assert result is True
mock_ws.trigger_screens_worker.assert_awaited_once_with("test-001")
@pytest.mark.asyncio
async def test_advance_noop_when_lyrics_not_done(self, job_manager, mock_firestore_service):
"""No screens trigger until lyrics complete, even if audio is done."""
+1 -1
View File
@@ -8,7 +8,7 @@ def test_settings_parse_titles_defaults():
from backend.config import Settings
s = Settings()
assert s.parse_titles_enabled is True
assert s.parse_titles_model == "gemini-3.5-flash"
assert s.parse_titles_model == "gemini-3.8-flash"
assert s.parse_titles_timeout_ms == 20000
assert s.parse_titles_max_items == 200
@@ -196,6 +196,37 @@ def test_stuck_downloading_with_lyrics_done_retriggers_screens(client):
mock_jm.advance_to_screens_if_ready.assert_awaited_once_with("s1")
def test_stuck_audio_edit_complete_with_lyrics_done_retriggers_screens(client):
"""Audio-edited jobs prep at AUDIO_EDIT_COMPLETE, not DOWNLOADING. A lost
screens trigger there must be recovered too (job 2c1b922e sat stuck)."""
job = _job("ae1", JobStatus.AUDIO_EDIT_COMPLETE, minutes_stale=15)
job.state_data["lyrics_complete"] = True
mock_jm = _mock_jm(downloading_prep=[_doc("ae1", JobStatus.AUDIO_EDIT_COMPLETE)], jobs={"ae1": job})
mock_jm.advance_to_screens_if_ready = AsyncMock(return_value=True)
resp, _ = _run(client, mock_jm)
assert resp.json()["screens_retriggered_jobs"] == ["ae1"]
mock_jm.advance_to_screens_if_ready.assert_awaited_once_with("ae1")
def test_lost_screens_sweep_queries_all_prep_statuses(client):
"""The lost-screens sweep must query both prep statuses, not just DOWNLOADING."""
mock_jm = _mock_jm()
# Record FieldFilter args directly — other test modules may stub the
# firestore package, so the real FieldFilter's attributes aren't reliable.
with patch("google.cloud.firestore_v1.FieldFilter",
side_effect=lambda field, op, value: (field, op, value)):
_run(client, mock_jm)
filters = [
c.kwargs["filter"]
for c in mock_jm.firestore.db.collection.return_value.where.call_args_list
]
in_filters = [f for f in filters if f[1] == "in"]
assert len(in_filters) == 1
assert set(in_filters[0][2]) == {
JobStatus.DOWNLOADING.value, JobStatus.AUDIO_EDIT_COMPLETE.value,
}
def test_fresh_downloading_not_retriggered(client):
"""A DOWNLOADING job updated 2 min ago (audio still separating) is NOT re-triggered."""
job = _job("s2", JobStatus.DOWNLOADING, minutes_stale=2)
@@ -0,0 +1,54 @@
"""request_metadata.custom_headers must never store credential headers raw —
GET /api/jobs/{id} returns request_metadata to the job owner."""
import pytest
from starlette.requests import Request
from backend.api.routes import audio_search, file_upload
from backend.utils.request_helpers import REDACTED, collect_custom_headers
SECRET_HEADERS = {
"X-Kjbox-Secret": "kj-secret-value",
"X-Admin-Token": "admin-token-value",
"X-KH-Forwarder-Secret": "kh-secret-value",
"X-E2E-Bypass-Key": "bypass-value",
"X-Api-Key": "api-key-value",
"X-Authorization": "Bearer abc",
"X-User-Password": "hunter2",
}
PLAIN_HEADERS = {"X-Client-Id": "kjbox", "X-Environment": "production", "X-Referral-Code": "abc"}
def _request(headers):
raw = [(k.lower().encode(), v.encode()) for k, v in headers.items()]
return Request({"type": "http", "method": "POST", "path": "/", "headers": raw,
"client": ("1.2.3.4", 1234)})
def test_collect_custom_headers_redacts_secrets_keeps_others():
out = collect_custom_headers({**{k.lower(): v for k, v in {**SECRET_HEADERS, **PLAIN_HEADERS}.items()},
"x-forwarded-for": "9.9.9.9", "user-agent": "ua"})
for name in SECRET_HEADERS:
assert out[name.lower()] == REDACTED
for name, value in PLAIN_HEADERS.items():
assert out[name.lower()] == value
assert "x-forwarded-for" not in out and "user-agent" not in out
@pytest.mark.parametrize("extract", [audio_search.extract_request_metadata,
file_upload.extract_request_metadata])
def test_extract_request_metadata_never_stores_secret_values(extract):
meta = extract(_request({**SECRET_HEADERS, **PLAIN_HEADERS}))
blob = repr(meta)
for value in SECRET_HEADERS.values():
assert value not in blob
assert meta["client_id"] == "kjbox"
assert meta["custom_headers"]["x-kjbox-secret"] == REDACTED
assert meta["custom_headers"]["x-client-id"] == "kjbox"
def test_session_and_jwt_headers_are_redacted():
from backend.utils.request_helpers import REDACTED, collect_custom_headers
out = collect_custom_headers({"X-JWT": "eyJ...", "X-Session-Id": "sess-abc", "X-Client-Id": "kjbox"})
assert out["X-JWT"] == REDACTED
assert out["X-Session-Id"] == REDACTED
assert out["X-Client-Id"] == "kjbox"
+33
View File
@@ -0,0 +1,33 @@
"""JobManager.record_review_started — who opened the lyrics review first."""
from unittest.mock import MagicMock
import pytest
from backend.services.job_manager import JobManager
@pytest.fixture
def jm():
m = JobManager.__new__(JobManager)
m.update_job = MagicMock()
return m
@pytest.mark.parametrize("reviewer,is_admin,expected", [
("singer@example.com", False, "owner"),
("SINGER@example.com", False, "owner"),
(None, False, "owner"), # review-token link (sent to the owner)
("andrew@nomadkaraoke.com", True, "admin"), # the KJ / support
("singer@example.com", True, "owner"), # an admin reviewing their own job
(None, True, "admin"), # admin token without an email
])
def test_started_by(jm, reviewer, is_admin, expected):
assert jm.record_review_started("j1", "singer@example.com", reviewer, is_admin) == expected
fields = jm.update_job.call_args.args[1]
assert fields["state_data.review_started_by"] == expected
assert "state_data.review_started_at" in fields
def test_write_failure_is_not_fatal(jm):
jm.update_job.side_effect = RuntimeError("firestore down")
assert jm.record_review_started("j1", "a@b.com", None, False) == "owner"
@@ -166,6 +166,38 @@ class TestProcessStaleReviews:
assert call_args[0][1]['state_data.expiry_reminder_sent'] is True
assert 'state_data.expiry_reminder_sent_at' in call_args[0][1]
async def test_kjbox_job_reminder_uses_one_click_login_link(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""kjbox singers never signed in on gen → the 24h reminder links via a sign-in token."""
job = _make_job(hours_ago=30)
job.request_metadata = {"client_id": "kjbox"}
mock_firestore.list_jobs.side_effect = [[job], [], []]
login_svc = Mock()
login_svc.create_admin_login_token.return_value = Mock(token="tok-123")
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service), \
patch('backend.services.job_notification_service.get_user_service', return_value=login_svc):
from backend.workers.stale_review_processor import process_stale_reviews
await process_stale_reviews()
call_kwargs = mock_email_service.send_review_reminder.call_args.kwargs
assert call_kwargs["review_url"].endswith("/auth/verify?token=tok-123")
login_svc.create_admin_login_token.assert_called_once()
assert login_svc.create_admin_login_token.call_args.kwargs["purpose"] == "job_review:job-123"
async def test_non_kjbox_job_reminder_keeps_bare_review_url(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
job = _make_job(hours_ago=30)
job.request_metadata = {"client_id": "test-runner"}
mock_firestore.list_jobs.side_effect = [[job], [], []]
login_svc = Mock()
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service), \
patch('backend.services.job_notification_service.get_user_service', return_value=login_svc):
from backend.workers.stale_review_processor import process_stale_reviews
await process_stale_reviews()
assert mock_email_service.send_review_reminder.call_args.kwargs["review_url"] is None
login_svc.create_admin_login_token.assert_not_called()
async def test_skips_if_expiry_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip reminder if expiry_reminder_sent is already True."""
job = _make_job(hours_ago=30, expiry_reminder_sent=True)
+22
View File
@@ -13,6 +13,7 @@ from unittest.mock import MagicMock, AsyncMock, patch
from fastapi.testclient import TestClient
from backend.models.job import Job, JobStatus
from backend.api.routes.audio_search import extract_request_metadata as _REAL_EXTRACT_REQUEST_METADATA
# ---------------------------------------------------------------------------
@@ -495,6 +496,27 @@ class TestCreateJobFromSearch:
assert "job_id" in data
assert data["job_id"] == "test-job-123"
def test_records_x_client_id_in_request_metadata(self, create_from_search_client, auth_headers):
"""X-Client-Id (e.g. kjbox) lands in request_metadata.client_id — kjbox jobs'
review emails key off it to send a one-click sign-in link."""
# The fixture stubs extract_request_metadata; use the real one here.
with patch("backend.api.routes.audio_search.extract_request_metadata",
_REAL_EXTRACT_REQUEST_METADATA):
response = create_from_search_client.post(
"/api/jobs/create-from-search",
json={
"search_session_id": "sess-abc-123",
"selection_index": 0,
"artist": "ABBA",
"title": "Waterloo",
},
headers={**auth_headers, "X-Client-Id": "kjbox"},
)
assert response.status_code == 200
job_create = create_from_search_client._mock_jm.create_job.call_args[0][0]
assert job_create.request_metadata["client_id"] == "kjbox"
assert job_create.request_metadata["created_from"] == "guided_flow"
def test_job_is_created_via_job_manager(self, create_from_search_client, auth_headers):
"""Job must be created through job_manager.create_job."""
create_from_search_client.post(
+7
View File
@@ -211,6 +211,13 @@
"fallbackLink": "If the button doesn't work, copy and paste this link into your browser:",
"ignoreNote": "If you didn't request this email, you can safely ignore it."
},
"kjboxLoginCode": {
"subject": "Your Nomad Karaoke code: {code}",
"greeting": "Hi there,",
"intro": "Here's your code to sign in on the karaoke night singer page. Type it into the page you're using:",
"expiry": "This code expires in {minutes} minutes and can only be used once.",
"ignoreNote": "If you didn't request this code, you can safely ignore this email."
},
"welcome": {
"subject": "Welcome to Nomad Karaoke!",
"welcomeGreeting": "Welcome to Nomad Karaoke!",
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "يرجى إلغاء تثبيت تطبيق KaraokeHunt.",
"uninstallIntro": "لقد قمت للتو بطلب أغنية عبر تطبيق KaraokeHunt - لكن هذا التطبيق متوقف ولم يعد مدعومًا، ولم تتم معالجة هذا الطلب.",
"uninstallNote": "شيء واحد مهم: كان هذا تحويلاً لمرة واحدة. لن تتم معالجة الطلبات المستقبلية التي يتم إجراؤها عبر تطبيق KaraokeHunt القديم، لذا يرجى إلغاء تثبيته وإنشاء مقاطع الكاريوكي الخاصة بك مباشرة على gen.nomadkaraoke.com من الآن فصاعدًا - حسابك جاهز هناك."
},
"kjboxLoginCode": {
"expiry": "تنتهي صلاحية هذا الرمز خلال {minutes} دقيقة ويمكن استخدامه مرة واحدة فقط.",
"greeting": "مرحباً،",
"ignoreNote": "إذا لم تطلب هذا الرمز، يمكنك تجاهل هذا البريد الإلكتروني بأمان.",
"intro": "إليك رمز تسجيل الدخول الخاص بك في صفحة مغني ليلة الكاريوكي. اكتبه في الصفحة التي تستخدمها:",
"subject": "رمز Nomad Karaoke الخاص بك: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Si us plau, desinstal·la l'aplicació KaraokeHunt.",
"uninstallIntro": "Acabes de fer una sol·licitud de cançó a través de l'aplicació KaraokeHunt, però aquesta aplicació s'ha retirat i ja no té suport, i aquesta sol·licitud no s'ha processat.",
"uninstallNote": "Una cosa important: aquesta ha estat una conversió puntual. Les futures sol·licituds fetes a través de l'antiga aplicació KaraokeHunt no es processaran, així que si us plau, desinstal·la-la i crea les teves pistes de karaoke directament a gen.nomadkaraoke.com a partir d'ara; el teu compte ja hi està preparat."
},
"kjboxLoginCode": {
"expiry": "Aquest codi caduca en {minutes} minuts i només es pot utilitzar una vegada.",
"greeting": "Hola,",
"ignoreNote": "Si no has sol·licitat aquest codi, pots ignorar aquest correu electrònic.",
"intro": "Aquí tens el teu codi per iniciar sessió a la pàgina de cantants de la nit de karaoke. Introdueix-lo a la pàgina que estàs utilitzant:",
"subject": "El teu codi de Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Prosím, odinstaluj si aplikaci KaraokeHunt.",
"uninstallIntro": "Právě jsi požádal o píseň přes aplikaci KaraokeHunt - ale tato aplikace byla ukončena a už není podporována, takže tento požadavek nebyl zpracován.",
"uninstallNote": "Jedna důležitá věc: toto byl jednorázový převod. Budoucí požadavky podané přes starou aplikaci KaraokeHunt nebudou zpracovány, takže si ji prosím odinstaluj a odteď vytvářej své karaoke skladby přímo na gen.nomadkaraoke.com - tvůj účet je tam připraven."
},
"kjboxLoginCode": {
"expiry": "Tento kód vyprší za {minutes} minut a lze jej použít pouze jednou.",
"greeting": "Ahoj,",
"ignoreNote": "Pokud jsi o tento kód nežádal(a), můžeš tento e-mail bez obav ignorovat.",
"intro": "Tady je tvůj kód pro přihlášení na stránku zpěváka karaoke večera. Zadej ho na stránce, kterou používáš:",
"subject": "Tvůj kód pro Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Afinstaller venligst KaraokeHunt-appen.",
"uninstallIntro": "Du har netop lavet en sanganmodning via KaraokeHunt-appen - men den app er udgået og understøttes ikke længere, og denne anmodning blev ikke behandlet.",
"uninstallNote": "En vigtig ting: Dette var en engangskonvertering. Fremtidige anmodninger via den gamle KaraokeHunt-app vil ikke blive behandlet, så afinstaller den venligst, og lav dine karaokenumre direkte på gen.nomadkaraoke.com fra nu af - din konto er klar der."
},
"kjboxLoginCode": {
"expiry": "Denne kode udløber om {minutes} minutter og kan kun bruges én gang.",
"greeting": "Hej,",
"ignoreNote": "Hvis du ikke har anmodet om denne kode, kan du trygt ignorere denne e-mail.",
"intro": "Her er din kode til at logge ind på sangersiden til karaokenatten. Indtast den på den side, du bruger:",
"subject": "Din Nomad Karaoke-kode: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Bitte deinstalliere die KaraokeHunt-App.",
"uninstallIntro": "Du hast gerade eine Songanfrage über die KaraokeHunt-App gestellt - aber diese App wurde eingestellt und wird nicht mehr unterstützt, und diese Anfrage wurde nicht bearbeitet.",
"uninstallNote": "Eine wichtige Sache: Dies war eine einmalige Konvertierung. Zukünftige Anfragen über die alte KaraokeHunt-App werden nicht bearbeitet, also deinstalliere sie bitte und erstelle deine Karaoke-Tracks von nun an direkt unter gen.nomadkaraoke.com - dein Konto ist dort bereit."
},
"kjboxLoginCode": {
"expiry": "Dieser Code läuft in {minutes} Minuten ab und kann nur einmal verwendet werden.",
"greeting": "Hallo,",
"ignoreNote": "Wenn du diesen Code nicht angefordert hast, kannst du diese E-Mail einfach ignorieren.",
"intro": "Hier ist dein Code zur Anmeldung auf der Sängerseite für den Karaoke-Abend. Gib ihn auf der Seite ein, die du gerade verwendest:",
"subject": "Dein Nomad Karaoke Code: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Σε παρακαλούμε απεγκατάστησε την εφαρμογή KaraokeHunt.",
"uninstallIntro": "Μόλις έκανες ένα αίτημα τραγουδιού μέσω της εφαρμογής KaraokeHunt - αλλά αυτή η εφαρμογή έχει αποσυρθεί και δεν υποστηρίζεται πλέον, και αυτό το αίτημα δεν επεξεργάστηκε.",
"uninstallNote": "Ένα σημαντικό πράγμα: αυτή ήταν μια εφάπαξ μετατροπή. Μελλοντικά αιτήματα που θα γίνουν μέσω της παλιάς εφαρμογής KaraokeHunt δεν θα επεξεργαστούν, οπότε σε παρακαλούμε απεγκατάστησέ την και φτιάξε τα κομμάτια καραόκε σου απευθείας στο gen.nomadkaraoke.com από εδώ και στο εξής - ο λογαριασμός σου είναι έτοιμος εκεί."
},
"kjboxLoginCode": {
"expiry": "Αυτός ο κωδικός λήγει σε {minutes} λεπτά και μπορεί να χρησιμοποιηθεί μόνο μία φορά.",
"greeting": "Γεια σου,",
"ignoreNote": "Αν δεν ζήτησες αυτόν τον κωδικό, μπορείς να αγνοήσεις αυτό το email.",
"intro": "Ορίστε ο κωδικός σου για να συνδεθείς στη σελίδα τραγουδιστή της βραδιάς καραόκε. Πληκτρολόγησέ τον στη σελίδα που χρησιμοποιείς:",
"subject": "Ο κωδικός σου για το Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -211,6 +211,13 @@
"fallbackLink": "If the button doesn't work, copy and paste this link into your browser:",
"ignoreNote": "If you didn't request this email, you can safely ignore it."
},
"kjboxLoginCode": {
"subject": "Your Nomad Karaoke code: {code}",
"greeting": "Hi there,",
"intro": "Here's your code to sign in on the karaoke night singer page. Type it into the page you're using:",
"expiry": "This code expires in {minutes} minutes and can only be used once.",
"ignoreNote": "If you didn't request this code, you can safely ignore this email."
},
"welcome": {
"subject": "Welcome to Nomad Karaoke!",
"welcomeGreeting": "Welcome to Nomad Karaoke!",
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Por favor, desinstala la aplicación KaraokeHunt.",
"uninstallIntro": "Acabas de hacer una solicitud de canción a través de la aplicación KaraokeHunt - pero esa aplicación está retirada y ya no tiene soporte, y esta solicitud no fue procesada.",
"uninstallNote": "Una cosa importante: esta fue una conversión por única vez. Las futuras solicitudes realizadas a través de la antigua aplicación KaraokeHunt no serán procesadas, así que por favor desinstálala y haz tus pistas de karaoke directamente en gen.nomadkaraoke.com de ahora en adelante - tu cuenta está lista allí."
},
"kjboxLoginCode": {
"expiry": "Este código caduca en {minutes} minutos y solo se puede usar una vez.",
"greeting": "Hola,",
"ignoreNote": "Si no solicitaste este código, puedes ignorar este correo electrónico de forma segura.",
"intro": "Aquí tienes tu código para iniciar sesión en la página de cantantes de la noche de karaoke. Escríbelo en la página que estás usando:",
"subject": "Tu código de Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Poista KaraokeHunt-sovellus.",
"uninstallIntro": "Teit juuri kappalepyynnön KaraokeHunt-sovelluksen kautta – mutta kyseinen sovellus on poistettu käytöstä eikä sitä enää tueta, joten tätä pyyntöä ei käsitelty.",
"uninstallNote": "Yksi tärkeä asia: tämä oli kertaluonteinen muunnos. Vanhan KaraokeHunt-sovelluksen kautta tehtyjä tulevia pyyntöjä ei käsitellä, joten poista se ja tee karaokekappaleesi tästä lähtien suoraan osoitteessa gen.nomadkaraoke.com – tilisi on siellä valmiina."
},
"kjboxLoginCode": {
"expiry": "Tämä koodi vanhenee {minutes} minuutin kuluttua ja sen voi käyttää vain kerran.",
"greeting": "Hei,",
"ignoreNote": "Jos et pyytänyt tätä koodia, voit turvallisesti jättää tämän sähköpostin huomiotta.",
"intro": "Tässä on koodisi karaokeillan laulajasivulle kirjautumista varten. Kirjoita se käyttämällesi sivulle:",
"subject": "Nomad Karaoke -koodisi: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Merci de désinstaller l'application KaraokeHunt.",
"uninstallIntro": "Tu viens de faire une demande de chanson via l'application KaraokeHunt - mais cette application est retirée et n'est plus prise en charge, et cette demande n'a pas été traitée.",
"uninstallNote": "Une chose importante : il s'agissait d'une conversion unique. Les futures demandes effectuées via l'ancienne application KaraokeHunt ne seront pas traitées, alors merci de la désinstaller et de créer tes pistes karaoké directement sur gen.nomadkaraoke.com à partir de maintenant - ton compte y est prêt."
},
"kjboxLoginCode": {
"expiry": "Ce code expire dans {minutes} minutes et ne peut être utilisé qu'une seule fois.",
"greeting": "Salut,",
"ignoreNote": "Si tu n'as pas demandé ce code, tu peux ignorer cet e-mail en toute sécurité.",
"intro": "Voici ton code pour te connecter sur la page des chanteurs de la soirée karaoké. Tape-le sur la page que tu utilises :",
"subject": "Ton code Nomad Karaoke : {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "אנא הסר את אפליקציית KaraokeHunt.",
"uninstallIntro": "הרגע הגשת בקשת שיר דרך אפליקציית KaraokeHunt - אבל האפליקציה הזו יצאה משימוש ואינה נתמכת יותר, והבקשה הזו לא עובדה.",
"uninstallNote": "דבר אחד חשוב: זו הייתה המרה חד-פעמית. בקשות עתידיות שייעשו דרך אפליקציית KaraokeHunt הישנה לא יעובדו, אז אנא הסר אותה וצור את רצועות הקריוקי שלך ישירות ב-gen.nomadkaraoke.com מעכשיו - החשבון שלך מוכן שם."
},
"kjboxLoginCode": {
"expiry": "קוד זה יפוג בעוד {minutes} דקות וניתן להשתמש בו פעם אחת בלבד.",
"greeting": "היי,",
"ignoreNote": "אם לא ביקשת את הקוד הזה, אפשר להתעלם מהאימייל הזה בבטחה.",
"intro": "הנה הקוד שלך להתחברות לעמוד הזמרים של ערב הקריוקי. יש להזין אותו בעמוד שבו אתם משתמשים:",
"subject": "קוד ה-Nomad Karaoke שלך: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "कृपया KaraokeHunt ऐप को अनइंस्टॉल कर दो।",
"uninstallIntro": "तुमने अभी KaraokeHunt ऐप के ज़रिए एक गाने की रिक्वेस्ट की है - लेकिन वह ऐप अब बंद हो चुका है और सपोर्ट नहीं किया जाता, और इस रिक्वेस्ट को प्रोसेस नहीं किया गया।",
"uninstallNote": "एक ज़रूरी बात: यह एक बार का कन्वर्ज़न था। पुराने KaraokeHunt ऐप के ज़रिए की गई भविष्य की रिक्वेस्ट प्रोसेस नहीं की जाएँगी, इसलिए कृपया इसे अनइंस्टॉल कर दो और अब से अपने कराओके ट्रैक सीधे gen.nomadkaraoke.com पर बनाओ - तुम्हारा अकाउंट वहाँ तैयार है।"
},
"kjboxLoginCode": {
"expiry": "यह कोड {minutes} मिनट में समाप्त हो जाएगा और इसका उपयोग केवल एक बार किया जा सकता है।",
"greeting": "नमस्ते,",
"ignoreNote": "अगर तुमने इस कोड का अनुरोध नहीं किया है, तो तुम इस ईमेल को अनदेखा कर सकते हो।",
"intro": "कराओके नाइट सिंगर पेज पर साइन इन करने के लिए यह तुम्हारा कोड है। तुम जिस पेज का उपयोग कर रहे हो, उसमें इसे टाइप करो:",
"subject": "तुम्हारा Nomad Karaoke कोड: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Molimo te, deinstaliraj aplikaciju KaraokeHunt.",
"uninstallIntro": "Upravo si poslao/la zahtjev za pjesmu putem aplikacije KaraokeHunt - ali ta aplikacija je umirovljena i više nije podržana, te ovaj zahtjev nije obrađen.",
"uninstallNote": "Jedna važna stvar: ovo je bila jednokratna konverzija. Budući zahtjevi poslani putem stare aplikacije KaraokeHunt neće biti obrađeni, stoga te molimo da je deinstaliraš i od sada izrađuješ svoje karaoke pjesme izravno na gen.nomadkaraoke.com - tvoj račun je tamo spreman."
},
"kjboxLoginCode": {
"expiry": "Ovaj kod istječe za {minutes} minuta i može se iskoristiti samo jednom.",
"greeting": "Pozdrav,",
"ignoreNote": "Ako nisi zatražio ovaj kod, možeš slobodno zanemariti ovaj e-mail.",
"intro": "Evo tvog koda za prijavu na stranicu pjevača za karaoke večer. Upiši ga na stranicu koju koristiš:",
"subject": "Tvoj Nomad Karaoke kod: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Kérjük, távolítsd el a KaraokeHunt alkalmazást.",
"uninstallIntro": "Épp most küldtél be egy dalkérést a KaraokeHunt alkalmazáson keresztül - de ez az alkalmazás már megszűnt és nem támogatott, így ezt a kérést nem dolgoztuk fel.",
"uninstallNote": "Egy fontos dolog: ez egy egyszeri konverzió volt. A régi KaraokeHunt alkalmazáson keresztül leadott jövőbeli kéréseket nem dolgozzuk fel, ezért kérjük, távolítsd el, és mostantól készítsd a karaoke számaidat közvetlenül a gen.nomadkaraoke.com oldalon - a fiókod már készen áll ott."
},
"kjboxLoginCode": {
"expiry": "Ez a kód {minutes} perc múlva lejár, és csak egyszer használható fel.",
"greeting": "Szia,",
"ignoreNote": "Ha nem te kérted ezt a kódot, nyugodtan hagyd figyelmen kívül ezt az e-mailt.",
"intro": "Itt a kódod, amivel bejelentkezhetsz a karaoke est énekesi oldalán. Írd be arra az oldalra, amit éppen használsz:",
"subject": "A Nomad Karaoke kódod: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Harap copot pemasangan aplikasi KaraokeHunt.",
"uninstallIntro": "Anda baru saja membuat permintaan lagu melalui aplikasi KaraokeHunt - tetapi aplikasi tersebut sudah dihentikan dan tidak lagi didukung, dan permintaan ini tidak diproses.",
"uninstallNote": "Satu hal penting: ini adalah konversi satu kali. Permintaan di masa mendatang yang dibuat melalui aplikasi KaraokeHunt lama tidak akan diproses, jadi harap copot pemasangannya dan buat trek karaoke Anda langsung di gen.nomadkaraoke.com mulai sekarang - akun Anda sudah siap di sana."
},
"kjboxLoginCode": {
"expiry": "Kode ini akan kedaluwarsa dalam {minutes} menit dan hanya dapat digunakan satu kali.",
"greeting": "Halo,",
"ignoreNote": "Jika Anda tidak meminta kode ini, Anda bisa mengabaikan email ini.",
"intro": "Berikut adalah kode Anda untuk masuk di halaman penyanyi malam karaoke. Masukkan kode ini ke halaman yang sedang Anda gunakan:",
"subject": "Kode Nomad Karaoke Anda: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Per favore, disinstalla l'app KaraokeHunt.",
"uninstallIntro": "Hai appena fatto una richiesta di canzone tramite l'app KaraokeHunt, ma quell'app è stata ritirata e non è più supportata, e questa richiesta non è stata elaborata.",
"uninstallNote": "Una cosa importante: questa era una conversione una tantum. Le future richieste effettuate tramite la vecchia app KaraokeHunt non verranno elaborate, quindi per favore disinstallala e crea le tue basi karaoke direttamente su gen.nomadkaraoke.com d'ora in poi: il tuo account è già pronto lì."
},
"kjboxLoginCode": {
"expiry": "Questo codice scade in {minutes} minuti e può essere utilizzato una sola volta.",
"greeting": "Ciao,",
"ignoreNote": "Se non hai richiesto questo codice, puoi tranquillamente ignorare questa email.",
"intro": "Ecco il tuo codice per accedere alla pagina dei cantanti della serata karaoke. Inseriscilo nella pagina che stai utilizzando:",
"subject": "Il tuo codice Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "KaraokeHuntアプリをアンインストールしてください。",
"uninstallIntro": "KaraokeHuntアプリを通じて曲のリクエストを行いましたが、そのアプリは提供とサポートを終了しているため、このリクエストは処理されませんでした。",
"uninstallNote": "重要な注意事項:これは1回限りの変換でした。今後、古いKaraokeHuntアプリからのリクエストは処理されません。アプリをアンインストールし、これからは gen.nomadkaraoke.com で直接カラオケトラックを作成してください。アカウントはすでに準備されています。"
},
"kjboxLoginCode": {
"expiry": "このコードの有効期限は{minutes}分で、1回のみ使用可能です。",
"greeting": "こんにちは、",
"ignoreNote": "このコードをリクエストした覚えがない場合は、このメールを無視していただいて構いません。",
"intro": "カラオケナイトのシンガーページにサインインするためのコードです。ご利用のページに入力してください:",
"subject": "Nomad Karaokeのコード: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "KaraokeHunt 앱을 삭제해 주세요.",
"uninstallIntro": "방금 KaraokeHunt 앱을 통해 노래를 요청하셨습니다. 하지만 해당 앱은 서비스가 종료되어 더 이상 지원되지 않으므로 이번 요청은 처리되지 않았습니다.",
"uninstallNote": "한 가지 중요한 점을 안내해 드립니다. 이번 변환은 1회성으로 제공된 것입니다. 앞으로 이전 KaraokeHunt 앱을 통해 접수된 요청은 처리되지 않으므로 앱을 삭제해 주시기 바랍니다. 이제부터는 gen.nomadkaraoke.com에서 직접 가라오케 트랙을 만들어 보세요. 고객님의 계정이 이미 준비되어 있습니다."
},
"kjboxLoginCode": {
"expiry": "이 코드는 {minutes}분 후에 만료되며 한 번만 사용할 수 있습니다.",
"greeting": "안녕하세요,",
"ignoreNote": "이 코드를 요청하지 않으셨다면 이 이메일을 무시하셔도 됩니다.",
"intro": "가라오케 나이트 가수 페이지에 로그인하기 위한 코드입니다. 사용 중인 페이지에 다음 코드를 입력해 주세요:",
"subject": "Nomad Karaoke 코드: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Sila nyahpasang aplikasi KaraokeHunt.",
"uninstallIntro": "Anda baru sahaja membuat permintaan lagu melalui aplikasi KaraokeHunt - tetapi aplikasi tersebut telah ditamatkan dan tidak lagi disokong, dan permintaan ini tidak diproses.",
"uninstallNote": "Satu perkara penting: ini adalah penukaran sekali sahaja. Permintaan masa hadapan yang dibuat melalui aplikasi KaraokeHunt lama tidak akan diproses, jadi sila nyahpasangnya dan buat trek karaoke anda terus di gen.nomadkaraoke.com mulai sekarang - akaun anda sudah sedia di sana."
},
"kjboxLoginCode": {
"expiry": "Kod ini akan tamat tempoh dalam masa {minutes} minit dan hanya boleh digunakan sekali.",
"greeting": "Hai,",
"ignoreNote": "Jika anda tidak meminta kod ini, anda boleh mengabaikan e-mel ini.",
"intro": "Berikut ialah kod anda untuk log masuk ke halaman penyanyi malam karaoke. Taipkan kod ini ke dalam halaman yang anda sedang gunakan:",
"subject": "Kod Nomad Karaoke anda: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Vennligst avinstaller KaraokeHunt-appen.",
"uninstallIntro": "Du sendte nettopp en sangforespørsel gjennom KaraokeHunt-appen - men den appen er avviklet og støttes ikke lenger, og denne forespørselen ble ikke behandlet.",
"uninstallNote": "En viktig ting: dette var en engangskonvertering. Fremtidige forespørsler gjort gjennom den gamle KaraokeHunt-appen vil ikke bli behandlet, så vennligst avinstaller den og lag karaokesporene dine direkte på gen.nomadkaraoke.com fra nå av - kontoen din er klar der."
},
"kjboxLoginCode": {
"expiry": "Denne koden utløper om {minutes} minutter og kan bare brukes én gang.",
"greeting": "Hei,",
"ignoreNote": "Hvis du ikke ba om denne koden, kan du trygt ignorere denne e-posten.",
"intro": "Her er koden din for å logge inn på sanger-siden for karaokekvelden. Skriv den inn på siden du bruker:",
"subject": "Din Nomad Karaoke-kode: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Verwijder alsjeblieft de KaraokeHunt app.",
"uninstallIntro": "Je hebt zojuist een nummer aangevraagd via de KaraokeHunt app - maar die app is met pensioen en wordt niet meer ondersteund, en deze aanvraag is niet verwerkt.",
"uninstallNote": "Eén belangrijk ding: dit was een eenmalige conversie. Toekomstige aanvragen via de oude KaraokeHunt app worden niet verwerkt, dus verwijder deze alsjeblieft en maak je karaoke-tracks vanaf nu direct op gen.nomadkaraoke.com - je account staat daar klaar."
},
"kjboxLoginCode": {
"expiry": "Deze code verloopt over {minutes} minuten en kan slechts één keer worden gebruikt.",
"greeting": "Hallo,",
"ignoreNote": "Als je deze code niet hebt aangevraagd, kun je deze e-mail veilig negeren.",
"intro": "Hier is je code om in te loggen op de zangerspagina van de karaoke-avond. Typ deze in op de pagina die je gebruikt:",
"subject": "Je Nomad Karaoke code: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Odinstaluj aplikację KaraokeHunt.",
"uninstallIntro": "Właśnie złożyłeś prośbę o piosenkę przez aplikację KaraokeHunt - ale ta aplikacja została wycofana i nie jest już wspierana, a ta prośba nie została przetworzona.",
"uninstallNote": "Jedna ważna rzecz: to była jednorazowa konwersja. Przyszłe prośby składane przez starą aplikację KaraokeHunt nie będą przetwarzane, więc odinstaluj ją i od teraz twórz swoje utwory karaoke bezpośrednio na gen.nomadkaraoke.com - twoje konto jest tam gotowe."
},
"kjboxLoginCode": {
"expiry": "Ten kod wygasa za {minutes} minut i może zostać użyty tylko raz.",
"greeting": "Cześć,",
"ignoreNote": "Jeśli nie prosiłeś/aś o ten kod, możesz bezpiecznie zignorować tę wiadomość.",
"intro": "Oto Twój kod do zalogowania się na stronie wokalisty wieczoru karaoke. Wpisz go na stronie, z której korzystasz:",
"subject": "Twój kod Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Por favor, desinstale o aplicativo KaraokeHunt.",
"uninstallIntro": "Você acabou de fazer uma solicitação de música pelo aplicativo KaraokeHunt - mas esse aplicativo foi descontinuado e não tem mais suporte, e esta solicitação não foi processada.",
"uninstallNote": "Uma coisa importante: esta foi uma conversão única. Solicitações futuras feitas pelo antigo aplicativo KaraokeHunt não serão processadas, então, por favor, desinstale-o e crie suas faixas de karaokê diretamente em gen.nomadkaraoke.com a partir de agora - sua conta está pronta lá."
},
"kjboxLoginCode": {
"expiry": "Este código expira em {minutes} minutos e só pode ser usado uma vez.",
"greeting": "Olá,",
"ignoreNote": "Se você não solicitou este código, pode ignorar este e-mail com segurança.",
"intro": "Aqui está o seu código para entrar na página do cantor da noite de karaokê. Digite-o na página que você está usando:",
"subject": "Seu código do Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Te rugăm să dezinstalezi aplicația KaraokeHunt.",
"uninstallIntro": "Tocmai ai făcut o solicitare de piesă prin aplicația KaraokeHunt - dar acea aplicație a fost retrasă și nu mai este suportată, iar această solicitare nu a fost procesată.",
"uninstallNote": "Un lucru important: aceasta a fost o conversie unică. Solicitările viitoare făcute prin vechea aplicație KaraokeHunt nu vor fi procesate, așa că te rugăm să o dezinstalezi și să îți creezi piesele de karaoke direct pe gen.nomadkaraoke.com de acum înainte - contul tău este pregătit acolo."
},
"kjboxLoginCode": {
"expiry": "Acest cod expiră în {minutes} minute și poate fi folosit o singură dată.",
"greeting": "Salut,",
"ignoreNote": "Dacă nu ai solicitat acest cod, poți ignora în siguranță acest e-mail.",
"intro": "Iată codul tău pentru a te conecta pe pagina cântărețului din seara de karaoke. Introdu-l în pagina pe care o folosești:",
"subject": "Codul tău Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Пожалуйста, удали приложение KaraokeHunt.",
"uninstallIntro": "Ты только что сделал запрос песни через приложение KaraokeHunt — но это приложение закрыто и больше не поддерживается, и этот запрос не был обработан.",
"uninstallNote": "Одна важная деталь: это была разовая конвертация. Будущие запросы, сделанные через старое приложение KaraokeHunt, не будут обрабатываться, поэтому, пожалуйста, удали его и отныне создавай свои караоке-треки прямо на gen.nomadkaraoke.com — твой аккаунт там уже готов."
},
"kjboxLoginCode": {
"expiry": "Срок действия этого кода истекает через {minutes} минут, и его можно использовать только один раз.",
"greeting": "Привет,",
"ignoreNote": "Если ты не запрашивал этот код, можешь смело проигнорировать это письмо.",
"intro": "Вот твой код для входа на страницу певца караоке-вечеринки. Введи его на странице, которую ты используешь:",
"subject": "Твой код Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Prosím, odinštaluj si aplikáciu KaraokeHunt.",
"uninstallIntro": "Práve si požiadal o pieseň cez aplikáciu KaraokeHunt - táto aplikácia je však ukončená a už nie je podporovaná, a táto požiadavka nebola spracovaná.",
"uninstallNote": "Jedna dôležitá vec: toto bola jednorazová konverzia. Budúce požiadavky zadané cez starú aplikáciu KaraokeHunt nebudú spracované, preto si ju prosím odinštaluj a odteraz si vytváraj karaoke skladby priamo na gen.nomadkaraoke.com - tvoj účet je tam pripravený."
},
"kjboxLoginCode": {
"expiry": "Tento kód vyprší o {minutes} minút a dá sa použiť len raz.",
"greeting": "Ahoj,",
"ignoreNote": "Ak si o tento kód nežiadal, môžeš tento e-mail pokojne ignorovať.",
"intro": "Tu je tvoj kód na prihlásenie na stránke speváka pre karaoke večer. Zadaj ho na stránke, ktorú používaš:",
"subject": "Tvoj kód pre Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Vänligen avinstallera KaraokeHunt-appen.",
"uninstallIntro": "Du gjorde precis en låtförfrågan via KaraokeHunt-appen - men den appen är nedlagd och stöds inte längre, och den här förfrågan behandlades inte.",
"uninstallNote": "En viktig sak: detta var en engångskonvertering. Framtida förfrågningar som görs via den gamla KaraokeHunt-appen kommer inte att behandlas, så vänligen avinstallera den och gör dina karaokespår direkt på gen.nomadkaraoke.com från och med nu - ditt konto är redo där."
},
"kjboxLoginCode": {
"expiry": "Den här koden går ut om {minutes} minuter och kan bara användas en gång.",
"greeting": "Hej,",
"ignoreNote": "Om du inte begärde den här koden kan du bortse från det här e-postmeddelandet.",
"intro": "Här är din kod för att logga in på karaokekvällens sångarsida. Skriv in den på sidan du använder:",
"subject": "Din Nomad Karaoke-kod: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "โปรดถอนการติดตั้งแอป KaraokeHunt",
"uninstallIntro": "คุณเพิ่งขอเพลงผ่านแอป KaraokeHunt - แต่แอปดังกล่าวถูกยกเลิกและไม่ได้รับการสนับสนุนอีกต่อไป และคำขอนี้ไม่ได้รับการดำเนินการ",
"uninstallNote": "สิ่งสำคัญประการหนึ่ง: นี่เป็นการแปลงเพลงฟรีเพียงครั้งเดียว คำขอในอนาคตที่ทำผ่านแอป KaraokeHunt ตัวเก่าจะไม่ได้รับการดำเนินการ ดังนั้นโปรดถอนการติดตั้งและสร้างแทร็กคาราโอเกะของคุณโดยตรงที่ gen.nomadkaraoke.com นับจากนี้ไป - บัญชีของคุณพร้อมใช้งานที่นั่นแล้ว"
},
"kjboxLoginCode": {
"expiry": "รหัสนี้จะหมดอายุใน {minutes} นาที และสามารถใช้ได้เพียงครั้งเดียวเท่านั้น",
"greeting": "สวัสดี,",
"ignoreNote": "หากคุณไม่ได้ขอรหัสนี้ คุณสามารถเพิกเฉยต่ออีเมลฉบับนี้ได้เลย",
"intro": "นี่คือรหัสของคุณสำหรับเข้าสู่ระบบในหน้าสำหรับนักร้องในคืนคาราโอเกะ กรอกรหัสนี้ลงในหน้าที่คุณกำลังใช้งานอยู่:",
"subject": "รหัส Nomad Karaoke ของคุณ: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Mangyaring i-uninstall ang KaraokeHunt app.",
"uninstallIntro": "Kaka-request mo lang ng kanta gamit ang KaraokeHunt app - ngunit ang app na iyon ay retired na at hindi na suportado, at hindi naproseso ang request na ito.",
"uninstallNote": "Isang mahalagang bagay: ito ay isang one-time conversion. Ang mga susunod na request gamit ang lumang KaraokeHunt app ay hindi na ipoproseso, kaya mangyaring i-uninstall ito at gumawa ng iyong mga karaoke track nang direkta sa gen.nomadkaraoke.com mula ngayon - handa na ang iyong account doon."
},
"kjboxLoginCode": {
"expiry": "Mage-expire ang code na ito sa loob ng {minutes} minuto at isang beses lang pwedeng gamitin.",
"greeting": "Kumusta,",
"ignoreNote": "Kung hindi mo ni-request ang code na ito, maaari mong balewalain ang email na ito.",
"intro": "Narito ang iyong code para mag-sign in sa karaoke night singer page. I-type ito sa page na ginagamit mo:",
"subject": "Ang iyong Nomad Karaoke code: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Lütfen KaraokeHunt uygulamasını kaldır.",
"uninstallIntro": "Az önce KaraokeHunt uygulaması üzerinden bir şarkı isteğinde bulundun - ancak bu uygulama emekliye ayrıldı ve artık desteklenmiyor, ve bu istek işleme alınmadı.",
"uninstallNote": "Önemli bir şey: bu tek seferlik bir dönüştürmeydi. Eski KaraokeHunt uygulaması üzerinden yapılan gelecekteki istekler işleme alınmayacak, bu yüzden lütfen onu kaldır ve bundan sonra karaoke parçalarını doğrudan gen.nomadkaraoke.com adresinde yap - hesabın orada hazır."
},
"kjboxLoginCode": {
"expiry": "Bu kod {minutes} dakika içinde sona erer ve sadece bir kez kullanılabilir.",
"greeting": "Merhaba,",
"ignoreNote": "Eğer bu kodu sen istemediysen, bu e-postayı güvenle görmezden gelebilirsin.",
"intro": "İşte karaoke gecesi şarkıcı sayfasına giriş yapmak için kodun. Bunu kullandığın sayfaya yaz:",
"subject": "Nomad Karaoke kodun: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Будь ласка, видали додаток KaraokeHunt.",
"uninstallIntro": "Ти щойно зробив запит на пісню через додаток KaraokeHunt - але цей додаток закрито і він більше не підтримується, тому цей запит не було оброблено.",
"uninstallNote": "Одна важлива річ: це була одноразова конвертація. Майбутні запити через старий додаток KaraokeHunt не оброблятимуться, тому, будь ласка, видали його і відтепер створюй свої караоке-треки безпосередньо на gen.nomadkaraoke.com - твій акаунт там уже готовий."
},
"kjboxLoginCode": {
"expiry": "Цей код діє протягом {minutes} хвилин і може бути використаний лише один раз.",
"greeting": "Привіт,",
"ignoreNote": "Якщо ти не робив запит на цей код, можеш просто проігнорувати цей лист.",
"intro": "Ось твій код для входу на сторінку співака караоке-вечірки. Введи його на сторінці, яку ти використовуєш:",
"subject": "Твій код Nomad Karaoke: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "Vui lòng gỡ cài đặt ứng dụng KaraokeHunt.",
"uninstallIntro": "Bạn vừa tạo một yêu cầu bài hát thông qua ứng dụng KaraokeHunt - nhưng ứng dụng đó đã ngừng hoạt động và không còn được hỗ trợ nữa, và yêu cầu này đã không được xử lý.",
"uninstallNote": "Một điều quan trọng: đây là lần chuyển đổi duy nhất. Các yêu cầu trong tương lai được thực hiện thông qua ứng dụng KaraokeHunt cũ sẽ không được xử lý, vì vậy vui lòng gỡ cài đặt nó và từ nay hãy tạo các bản karaoke của bạn trực tiếp tại gen.nomadkaraoke.com - tài khoản của bạn đã sẵn sàng ở đó."
},
"kjboxLoginCode": {
"expiry": "Mã này sẽ hết hạn trong {minutes} phút và chỉ có thể sử dụng một lần.",
"greeting": "Chào bạn,",
"ignoreNote": "Nếu bạn không yêu cầu mã này, bạn có thể an tâm bỏ qua email này.",
"intro": "Đây là mã của bạn để đăng nhập vào trang ca sĩ đêm karaoke. Hãy nhập mã này vào trang bạn đang sử dụng:",
"subject": "Mã Nomad Karaoke của bạn: {code}"
}
}
}
+7
View File
@@ -389,6 +389,13 @@
"uninstallHeadline": "请卸载 KaraokeHunt 应用程序。",
"uninstallIntro": "您刚刚通过 KaraokeHunt 应用程序发出了歌曲请求 - 但该应用程序已退役并不再受支持,因此未处理此请求。",
"uninstallNote": "重要提示:这是一次性转换。未来通过旧版 KaraokeHunt 应用程序发出的请求将不会被处理,因此请卸载它,从现在起直接在 gen.nomadkaraoke.com 制作您的卡拉OK伴奏 - 您的帐户已在那里准备就绪。"
},
"kjboxLoginCode": {
"expiry": "此验证码将在 {minutes} 分钟后过期,且只能使用一次。",
"greeting": "你好,",
"ignoreNote": "如果您没有请求此验证码,请放心忽略此邮件。",
"intro": "这是您登录卡拉OK之夜歌手页面的验证码。请在您正在使用的页面中输入它:",
"subject": "您的 Nomad Karaoke 验证码:{code}"
}
}
}
+28
View File
@@ -21,3 +21,31 @@ def get_client_ip(request: Request) -> Optional[str]:
if request.client:
return request.client.host
return None
# Headers never worth recording, even redacted (already captured elsewhere / noise).
_SKIPPED_CUSTOM_HEADERS = frozenset({"x-forwarded-for", "x-forwarded-proto", "x-forwarded-host"})
# Any x-* header whose name contains one of these carries a credential
# (x-kjbox-secret, x-admin-token, x-kh-forwarder-secret, x-e2e-bypass-key,
# x-api-key, x-authorization, ...). request_metadata.custom_headers is returned
# to the job owner by GET /api/jobs/{id}, so these must never be stored raw.
_SECRET_HEADER_MARKERS = ("secret", "token", "key", "auth", "password", "passwd", "cookie", "signature", "credential", "bypass", "jwt", "session")
REDACTED = "[redacted]"
def is_secret_header(name: str) -> bool:
lowered = name.lower()
return any(marker in lowered for marker in _SECRET_HEADER_MARKERS)
def collect_custom_headers(headers) -> dict:
"""All X-* request headers for job request_metadata, with secret-bearing
header values replaced by ``"[redacted]"`` (the name is kept for debugging)."""
custom = {}
for key, value in dict(headers).items():
lowered = key.lower()
if not lowered.startswith("x-") or lowered in _SKIPPED_CUSTOM_HEADERS:
continue
custom[key] = REDACTED if is_secret_header(lowered) else value
return custom
+66 -29
View File
@@ -181,6 +181,22 @@ async def process_audio_download(job_id: str) -> bool:
# Cloud Run Job auto-retries of a successful task — re-downloading
# would double-trigger downstream workers and break state transitions.
if job.status in DOWNLOAD_ALREADY_DONE_STATUSES:
# Exception: an audio-edit job still at DOWNLOADING means the previous
# run died between the download and entering AWAITING_AUDIO_EDIT
# (e.g. OOM-killed while pre-generating editor assets — job 2c1b922e).
# Nothing downstream is triggered on that path, so finishing it here
# is safe — skipping would orphan the job at `downloading` forever.
if (
job.status == JobStatus.DOWNLOADING
and job.state_data.get('requires_audio_edit')
and job.input_media_gcs_path
):
logger.info(
f"[job:{job_id}] Download complete but audio-edit prep unfinished; "
f"resuming"
)
_enter_audio_edit(job_manager, job_id, job.input_media_gcs_path)
return True
logger.info(
f"[job:{job_id}] Download already complete (status={job.status}), "
f"skipping re-run"
@@ -296,35 +312,7 @@ async def process_audio_download(job_id: str) -> bool:
# Check if audio editing was requested — enter blocking state instead of processing
job = job_manager.get_job(job_id)
if job and job.state_data.get('requires_audio_edit'):
# Preserve the original input path before any edits
job_manager.update_state_data(job_id, 'original_input_media_gcs_path', audio_gcs_path)
# Pre-generate audio editor assets (OGG transcode + waveform data)
# so the editor UI loads instantly. Non-fatal if this fails.
waveform_cache_path = f"jobs/{job_id}/audio_edit/waveform_original.json"
try:
from backend.services.audio_transcoding_service import AudioTranscodingService
from backend.services.audio_analysis_service import AudioAnalysisService
transcoding = AudioTranscodingService()
transcoding.transcode_if_needed(audio_gcs_path)
logger.info(f"[job:{job_id}] Pre-transcoded input audio to OGG for editor")
analysis = AudioAnalysisService()
analysis.cache_waveform_data(audio_gcs_path, job_id, waveform_cache_path)
logger.info(f"[job:{job_id}] Pre-generated waveform data for editor")
job_manager.update_state_data(job_id, 'audio_edit_waveform_cache_path', waveform_cache_path)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to pre-generate editor assets (non-fatal): {e}")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_EDIT,
progress=15,
message="Audio downloaded. Please review and edit the audio before processing."
)
logger.info(f"[job:{job_id}] Audio download complete, awaiting audio edit")
_enter_audio_edit(job_manager, job_id, audio_gcs_path)
return True
# Reconcile credit charge against actual audio duration before processing.
@@ -356,6 +344,55 @@ async def process_audio_download(job_id: str) -> bool:
return False
def _enter_audio_edit(job_manager: JobManager, job_id: str, audio_gcs_path: str) -> None:
"""Prepare editor assets and park the job at AWAITING_AUDIO_EDIT."""
# Preserve the original input path before any edits
job_manager.update_state_data(job_id, 'original_input_media_gcs_path', audio_gcs_path)
# Pre-generate audio editor assets (OGG transcode + waveform data)
# so the editor UI loads instantly. Non-fatal if this fails.
waveform_cache_path = f"jobs/{job_id}/audio_edit/waveform_original.json"
try:
from backend.services.audio_transcoding_service import AudioTranscodingService
from backend.services.audio_analysis_service import AudioAnalysisService
transcoding = AudioTranscodingService()
transcoding.transcode_if_needed(audio_gcs_path)
logger.info(f"[job:{job_id}] Pre-transcoded input audio to OGG for editor")
analysis = AudioAnalysisService()
analysis.cache_waveform_data(audio_gcs_path, job_id, waveform_cache_path)
logger.info(f"[job:{job_id}] Pre-generated waveform data for editor")
job_manager.update_state_data(job_id, 'audio_edit_waveform_cache_path', waveform_cache_path)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to pre-generate editor assets (non-fatal): {e}")
# raise_on_invalid=False: a concurrent run (e.g. manual retry racing a Cloud
# Run auto-retry) may already have moved the job on — that's success, and
# raising would reach the caller's fail_job and clobber the advanced job.
transitioned = job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_EDIT,
progress=15,
message="Audio downloaded. Please review and edit the audio before processing.",
raise_on_invalid=False,
)
if not transitioned:
latest = job_manager.get_job(job_id)
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES and latest.status != JobStatus.DOWNLOADING:
logger.info(
f"[job:{job_id}] Concurrent run already advanced the job "
f"(status={latest.status}); treating as idempotent success"
)
return
raise DownloadError(
f"Could not transition to AWAITING_AUDIO_EDIT "
f"(status={latest.status if latest else 'missing'})"
)
logger.info(f"[job:{job_id}] Audio download complete, awaiting audio edit")
async def _download_audio(
job_id: str,
source_name: str,
@@ -271,12 +271,17 @@ async def process_stale_reviews() -> Dict[str, Any]:
locale=user_locale,
)
else:
from backend.services.job_notification_service import (
review_login_url_for_job,
)
email_service.send_review_reminder(
to_email=job.user_email,
artist=job.artist,
title=job.title,
job_id=job.job_id,
locale=user_locale,
# kjbox singers never signed in on gen → one-click sign-in link
review_url=review_login_url_for_job(job, locale=user_locale),
)
except Exception as email_err:
logger.error(
+2 -2
View File
@@ -77,7 +77,7 @@ The verify page (`/auth/verify`) shows these states in sequence:
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `CREDIT_EVAL_ENABLED` | `true` | Set to `false` to disable AI evaluation and auto-grant all credits |
| `CREDIT_EVAL_MODEL` | `gemini-3.1-pro-preview` | Gemini model to use for evaluation |
| `CREDIT_EVAL_MODEL` | `gemini-3.8-flash` | Gemini model to use for evaluation |
### Emergency Rollback
@@ -96,7 +96,7 @@ Every evaluation is logged to the `credit_evaluations` Firestore collection:
"reasoning": "No suspicious correlations found — clean user",
"confidence": 1.0,
"error": null,
"model": "gemini-3.1-pro-preview",
"model": "gemini-3.8-flash",
"signals_snapshot": {
"fingerprint_match_count": 0,
"ip_match_count": 0,
+139 -3
View File
@@ -689,13 +689,13 @@ Returns:
"reason": "All references read 'chlorine' here",
"category": "mishearing",
"confidence": 0.95,
"models": ["claude-opus-4-8", "gemini-3.1-pro-preview"],
"models": ["claude-opus-5-5", "gemini-3.8-flash"],
"consensus": 2,
"total_models": 2,
"conflict_group": null
}
],
"model": "claude-opus-4-8, gemini-3.1-pro-preview",
"model": "claude-opus-5-5, gemini-3.8-flash",
"elapsed_seconds": 27.4,
"settings_applied": { "suggest_adlib_removal": true, "allow_insertions": true, "min_confidence": 0.0 },
"warnings": [],
@@ -932,7 +932,7 @@ Content-Type: application/json
Decides the official formatting for a typed artist/title and whether it matches a
real song. A deterministic normalizer + the catalog run first; a light Vertex
Gemini model (`MATCH_JUDGE_MODEL`, default `gemini-3.5-flash`) is consulted
Gemini model (`MATCH_JUDGE_MODEL`, default `gemini-3.8-flash`) is consulted
**only** when those aren't confident. `audio_confidence_tier` (1=strong..3=weak,
optional) lets the judge tell whether weak audio results hint at a typo. The call
never blocks job creation — on timeout/error it returns a `none` verdict. Disable
@@ -2740,6 +2740,142 @@ Admin-token retry for an intake doc whose `outcome` is `error` (or forcing a
terminal one). Idempotent: durable markers on the doc (`credit_granted`,
`job_id`) prevent double credits/jobs.
## kjbox Partner API
Server-to-server API for **kjbox** (the KJ device app at live karaoke nights).
A singer verifies their email inside the kjbox singer page (never visiting the
gen website) with a 6-digit emailed code; kjbox then searches audio / creates
gen jobs **as that real gen user** with the returned session token (sending
`X-Client-Id: kjbox` on `/api/audio-search/search-standalone` and
`/api/jobs/create-from-search`), so the singer gets normal gen emails.
Every endpoint requires header `X-Kjbox-Secret` (setting `kjbox_partner_secret`,
env `KJBOX_PARTNER_SECRET`, Secret Manager `kjbox-partner-secret`):
`503 {"detail": "not configured"}` while unset (deploys dark), `403` if wrong.
Code: `backend/api/routes/kjbox.py` + `backend/services/kjbox_partner_service.py`.
### Send code
```http
POST /api/kjbox/auth/send-code
{"email": "singer@example.com", "locale": "es", "venue": "The Dive Bar"}
```
→ `200 {"status": "sent"}`. Emails a 6-digit code (10-minute expiry; a new code
invalidates the previous one). Only an HMAC of the code (peppered with the
partner secret) is stored, in Firestore `kjbox_login_codes` (doc id =
sha256(email)). **No gen account is created here** — the venue/locale ride on
the code record and the account is created at verify-code, so unverified
addresses can't burn the signup cap or get accounts made for them. The
welcome-credit AI evaluation is precomputed onto the code record so verify is
instant.
- Disposable domain → `422` (same detail as magic links); blocked email/IP →
silently `200 {"status": "sent"}`; malformed email → `422 {"detail": "invalid_email"}`.
- Max `KJBOX_CODES_PER_EMAIL_PER_HOUR` (default 5) codes per email per rolling
hour → `429 {"detail": "too_many_codes"}`. The check, the send-time append and
the code write are one Firestore transaction (parallel requests can't exceed
it; a transaction giving up under contention also returns this 429).
### Verify code
```http
POST /api/kjbox/auth/verify-code
{"email": "singer@example.com", "code": "042917"}
```
→ `200 {"session_token", "user": <UserPublic, same shape as magic-link verify>,
"credits_granted": int, "credit_status": str}`. If the email has no gen account
yet, this is where it is created, with `signup_source="kjbox"` + `signup_venue`
(no `signup_ip` — the caller's IP is the whole venue's). gen's per-IP signup cap
does **not** apply; instead max `KJBOX_SIGNUP_CAP_PER_24H` (default 100) new
**verified** accounts per rolling 24h partner-wide (counted in `kjbox_signups`)
→ `429 {"detail": "signup_cap"}`, checked before the code is consumed (existing
users are never capped). Then runs the same post-verification
steps as `GET /api/users/auth/verify` (shared helper `complete_verified_login`):
email verified + last login, welcome credit (with the precomputed eval), locale
persistence (from the send-code `locale`), a normal gen session, and the welcome
email on first login.
Errors: wrong code → `401 {"detail": "invalid_code"}` (counts an attempt);
missing/expired/already-used → `401 {"detail": "expired"}`; more than 5 attempts
→ `429 {"detail": "too_many_attempts"}` and the code is burned. Attempts are an
atomic increment before a constant-time compare; single use is enforced by a
create()-only marker in `kjbox_login_code_uses`.
### Show credit ("free at the show")
```http
POST /api/kjbox/credits/show-credit
Authorization: Bearer <singer session_token>
{"idempotency_key": "<sha256 hex>", "venue": "The Dive Bar", "only_if_empty": false}
```
→ `200 {"granted": bool, "credits": int}`. Quietly adds 1 credit (reason
`kjbox show credit`, **no** credits-added email) so the make-it job is paid for
by Nomad.
- `only_if_empty` (default `false`): grant only if the user's balance is < 1.
- `idempotency_key` (≤128 chars) is claimed **only when a credit is actually
granted** (stored in `kjbox_show_credits`), so kjbox can call with
`only_if_empty=true` at search time and again with the SAME key and
`only_if_empty=false` at job creation: the second call grants only if the
first didn't. A repeat of an already-granting key returns `granted: false`
with the current balance.
- Max `KJBOX_SHOW_CREDITS_PER_USER_PER_24H` (default 5) grants per user per
rolling 24h → `429 {"detail": "show_credit_cap"}` (non-grants don't count).
- Idempotency check, only-if-empty check, cap check, key claim and the credit
increment are one Firestore transaction; if it gives up under contention →
`409 {"detail": "busy_retry"}` (nothing written — retry with the same key).
- Missing/invalid session → `401 {"detail": "invalid_session"}`.
### Singer search auto-correct
```http
POST /api/kjbox/catalog/resolve
X-Kjbox-Secret: <partner secret>
{"query": "the strokes max picu"}
→ {"kind": "content", "confident": true, "typed_artist": "the strokes", "typed_title": "max picu",
"canonical_artist": "The Strokes", "canonical_title": "Machu Picchu", "alternatives": [],
"engine": "ai", "reason": "…"}
```
Splits a singer's one-line search into artist/title and corrects typos in one
small Gemini call (`backend/services/match_judge/free_text.py`, the match
judge's model + kinds). kjbox calls it only when its own catalogue search is
empty. Model trouble → `kind: "none"` (never 5xx). Results are cached per
case-folded query (in-process, 2000 entries); AI calls are capped partner-wide
at 120/min per instance (`429 rate_limited`; cache hits are free).
### Review emails for kjbox jobs
Jobs whose `request_metadata.client_id` starts with `kjbox` get a **one-click
sign-in link** (magic-link token, purpose `job_review:<job_id>`, 72h, single use)
in the review-needed email and the 24h review reminder instead of the bare
review URL — these singers have never signed in on the gen website. Other jobs
are unchanged.
```http
POST /api/kjbox/jobs/{job_id}/review-link
X-Kjbox-Secret: <partner secret>
Authorization: Bearer <singer session_token>
{"locale": "es"} → {"url": "...", "status": "in_review", "review_started_by": "admin"}
```
The same one-click review sign-in link, minted on demand for the kjbox singer
page's "Tap here to review it yourself". Only the job's owner gets one (`404
not_found` otherwise, also for unknown ids) and only while the job is
`awaiting_review` / `in_review` (`409 not_in_review`).
`review_started_by` (also `job.state_data.review_started_by`, with
`review_started_at`) records who opened the review first — set on the
`awaiting_review → in_review` transition: `"admin"` if an admin other than the
owner (the KJ) opened it, else `"owner"` (incl. review-token links).
Note: `request_metadata.custom_headers` (all `X-*` request headers, returned to
the job owner by `GET /api/jobs/{id}`) stores credential-looking headers
(names containing secret/token/key/auth/password/…) as `"[redacted]"`.
### Vocals Peaks (Waveforms review mode)
```http
+8 -1
View File
@@ -72,6 +72,13 @@ Discord-alerting pipeline. `ChunkLoadError` after deploy triggers an automatic
hard reload; the `CrashReport` card also checks `/version.json` and shows an
"Update now" CTA when the running bundle is stale.
Noise is dropped before alerting: benign messages (media `AbortError`, ResizeObserver
loop) and opaque cross-origin `Script error.` events (no error object — thrown by
third-party/extension scripts) are skipped client-side, and `/api/client-errors`
accepts-but-ignores reports from bot user agents and `Script error.` window errors
with a blank filename/lineno
(covers older cached bundles).
## Edge Security (Cloudflare)
`api.nomadkaraoke.com` is proxied through Cloudflare (orange-cloud) — the same
@@ -244,7 +251,7 @@ LyricsTranscriber LyricsTranscriber
|---------|---------|----------|
| Cloud Run GPU Job (L4, us-east4) | Audio stem separation — `Separator` runs directly in the audio worker Job (no HTTP hop) | Yes |
| AudioShake | Lyrics transcription | Yes |
| Vertex AI | Agentic AI correction (Gemini 3 Flash) | Default off (SKIP_CORRECTION=false to enable) |
| Vertex AI | Agentic AI correction (Gemini 3.8 Flash) | Default off (SKIP_CORRECTION=false to enable) |
| Genius | Reference lyrics | Yes |
| Flacfetch | Audio downloads (YouTube, torrents) | Recommended* |
| YouTube API | Video upload | Optional |
+7 -1
View File
@@ -242,7 +242,13 @@ GitHub schedules onto any runner whose labels are a superset of the job's.
Each image is tagged `gha-runner-<variant>-<YYYYMMDD-HHMMSS>` and joined to the
matching image family. The dispatcher always selects from the family, so the
newest non-deprecated image wins automatically. The build workflow keeps the
newest 3 images per family and deprecates the rest.
newest 2 images per family and **deletes** the rest (deprecated images still bill
for storage; images that an existing disk was created from are never deleted).
Until 2026-09-26 this step used an invalid gcloud filter and silently pruned
nothing — 31 runner images (~360 GB archived, ~$18/mo) had accumulated; they were pruned by hand to
2 per family when the step was fixed. Note a gcloud `family=gha-runner-gpu`
filter also matches `gha-runner-gpu-windows` (word-boundary regex), so the step
matches the family exactly client-side.
Build cadence: monthly cron (`0 2 1 * *` UTC) + `workflow_dispatch`. Manual:
+2 -1
View File
@@ -85,7 +85,8 @@ The `concurrency=1` setting may have been added deliberately for performance rea
(c4d/c4/n4d/c2d/n2d/n2) for stockout resilience.
- **Idle auto-shutdown is live** (JIT start on the lyrics-review page; a Cloud
Function stops idle VMs after 15 min). When idle, cost is just boot disks
(~$10/VM/mo); compute is billed only while encoding — so the historical
(50 GB since 2026-09-26, ~$4-5/VM/mo; was 100 GB / ~$10 — see
docs/archive/2026-09-26-encoding-worker-disk-cost.md); compute is billed only while encoding — so the historical
"~$700/mo running 24/7" no longer applies.
**Opportunities (status):**
+17
View File
@@ -2033,3 +2033,20 @@ Also: colour-code the bars with the **exact** `HIGHLIGHT_CLASSES` tints the Adva
pills use (not hand-picked solids) so the two views read identically, and persist the
view mode under a new `lyricsReviewViewMode` enum that migrates the old
`lyricsReviewAdvancedMode` boolean.
### Encoding-worker disks: shrink via in-place boot-disk swap, not Pulumi replace (2026-09-26)
- Workers used ~8-15 GB of their 100 GB boot disks. Shrunk to 50 GB (Packer image
`disk_size` 100→30 — a disk can't be smaller than its source image).
- Changing `boot_disk.initialize_params.size` in Pulumi means replace (or an
impossible in-place shrink); replacing a c4d/n4d/c2d VM needs capacity that may be
stocked out for hours. Instead: while TERMINATED, detach + delete the old boot disk,
create a new one from the new image, attach `--boot --device-name=persistent-disk-0`,
then `pulumi refresh --target` the instance → no diff. No compute allocation needed.
- New hyperdisks default to paid IOPS/throughput above the free 3000/140 baseline —
always pass `--provisioned-iops=3000 --provisioned-throughput=140` (Pulumi doesn't
set them because boot-disk init params force replacement).
- A gcloud `family=X` filter is a word-boundary regex (`gha-runner-gpu` also matches
`gha-runner-gpu-windows`), and an invalid filter errors to stderr with empty stdout
— pipelines that treat empty output as "nothing to do" silently no-op. The runner
image prune step did this for months (31 images, ~$18/mo).
+13
View File
@@ -152,6 +152,19 @@ curl -X POST "https://api.nomadkaraoke.com/api/jobs/YOUR_JOB_ID/retry" \
---
## Job stuck at `downloading` or `audio_edit_complete` (no error)
Two known signatures (both fixed in v0.238.5, job 2c1b922e):
- **Audio-edit job stuck at `downloading`, `requires_audio_edit=true`, never reached `awaiting_audio_edit`.** The download worker was OOM-killed while pre-generating the editor waveform (a 24-bit/96kHz FLAC decoded at native resolution peaked at ~1 GB in the 1 GiB `audio-download-job`), and the Cloud Run auto-retry saw `downloading` and skipped. Since v0.238.5 the waveform decodes at 16 kHz mono and a retry resumes the unfinished editor prep. Manual fix: `POST /api/admin/jobs/{id}/reset` with `{"target_state": "awaiting_audio_edit"}`.
- **Audio-edited job stuck at `audio_edit_complete` with `lyrics_complete=true`.** Logs show `screens not (re)triggered — status=audio_edit_complete (expected downloading)`. The lyrics→screens handoff only accepted `downloading`; since v0.238.5 it (and the `recover-stuck-jobs` lost-screens sweep) also accepts `audio_edit_complete`. Manual fix — dispatch the screens worker directly (don't use `regenerate-screens`: it restores the original status afterwards, so the job never reaches review):
```bash
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/screens" \
-H "Authorization: Bearer $KARAOKE_ADMIN_TOKEN" -H "Content-Type: application/json" \
-d '{"job_id": "<job_id>"}'
```
## Job stuck at `encoding` status
**Cause:** A Cloud Run deployment killed the poller mid-encoding. The GCE worker finished but nobody received the result. The health service will flag this as `encoding_stuck` after 50 minutes.
@@ -1,5 +1,20 @@
# KaraokeHunt decommission + user outreach — session handoff (2026-09-13)
> **SESSION 5 — PHASE C STARTED (2026-09-17)**
> - Review triage (`outreach_out/review_triage.json`): 15 EASY (Andrew DONE) · 26 MEDIUM
> (10 opened in tabs for him) · 34 SKIP (non-English/no-reference → users review).
> - **One-click authed review links SHIPPED + verified in prod** (PR #1015 + #1016):
> `POST /api/admin/users/{email}/login-link {expiry_hours≤168, purpose:"job_review:<id>"}`
> → URL logs the user in (scanner-safe interstitial) and lands directly on that job's
> review page. Mint at email-drafting time (7-day expiry).
> - **Reassignment DONE**: 62 jobs (28 complete + 34 skip) reassigned to their requesters;
> 49 accounts (48 created silently with 3 credits; <user>@ pre-existed, NO
> credits granted — /admin/credits would email them). `outreach_out/phasec_state.json`.
> - **Email batch 1 DRAFTED in Andrew's Gmail (10 drafts, NOT sent)** — completed-video
> variant for fully-resolved English requesters. 9 more fully-resolved await batching
> (incl. he/it/es speakers — bilingual after wording approved). Skip-pile emails next:
> mint per-user job_review links at draft time.
> **SESSION 4 — BATCH GENERATION EXECUTED (2026-09-15, autonomous overnight)**
> All 90 unique songs SUBMITTED as public jobs owned by holding account
> **karaokehunt@nomadkaraoke.com** (created, 120 credits; @nomadkaraoke.com catchall →
@@ -0,0 +1,190 @@
# KaraokeHunt outreach — Phase C handoff (2026-09-19)
**Purpose:** hand a FRESH session everything needed to finish the KaraokeHunt outreach
and fully draw a line under the KaraokeHunt era. This doc is self-contained for the
remaining work; deep history lives in
[`2026-09-13-karaokehunt-outreach-handoff.md`](2026-09-13-karaokehunt-outreach-handoff.md)
(sessions 1–5 prepended chronologically) and memory `project_karaokehunt_batch_generation`.
Worktree: `/Users/andrew/Projects/nomadkaraoke/karaoke-gen-karaokehunt-outreach`
Branch: `feat/sess-20260913-0106-karaokehunt-outreach` (long-running; several PRs already
squash-merged from it — #1004 #1005 #1015 #1016; unmerged tip = docs only).
---
## 1. Mission state (UPDATED 2026-09-23 — reviews DONE, all 90 reassigned)
90 unique requested songs were generated as public jobs under holding account
**karaokehunt@nomadkaraoke.com** (all job emails → @nomadkaraoke.com catchall → Andrew's
gmail). **Final fleet state (2026-09-23):**
- **complete: 55** (live on YouTube, NOMAD-#### numbered)
- **in_review: 25** · **awaiting_review: 10** — these 35 are the skip pile (+ resubmitted
Bhimsen 7a16be60): the REQUESTERS review them via one-click links.
- Ownership: **ALL 90 jobs reassigned to requesters; karaokehunt@ holding account is
CLEAR.** 63 requester accounts exist (see `phasec_state.json`; <user> =
`exists_via_interceptor_no_silent_credits` — mention credits in their email; same for
<user>).
**ANDREW IS DONE REVIEWING (his directive, 2026-09-23):** all 15 EASY + all 26 MEDIUM
reviewed and complete. He will review NO more of these jobs. Anything still pending is
handled by the requesting users via one-click links, and **cleaned up if the requester
takes no action within 2 WEEKS of us sending their outreach email** (track send dates
per batch; cleanup = cancel/delete the parked job, account+credits stay).
Final segmentation (recompute with the snippet that produced it — session 2026-09-23):
- **Batch 1** (drafted 09-17, in Gmail drafts, UNSENT): 10 fully-resolved en requesters.
- **Batch 2 candidates**: 24 more requesters whose songs are ALL complete (incl.
bilingual: <user> he, <user> it, <user> es, <user> es, <user> sv).
- **Skip-pile/mixed**: 29 requesters with ≥1 pending user-review job (some also have
completed songs — ONE email each covering both, links minted at draft time).
- **No-generated-jobs**: 24 requesters (community-only / no-match variants).
Related: the **app-request interceptor is LIVE** (v0.236.0, session record
`docs/sessions/2026-Q3/2026-09-22-karaokehunt-app-interceptor.md`) — any NEW requests
from old app installs auto-convert (one freebie ever, community short-circuit,
uninstall emails). This outreach covers only the historical 90.
## 2. Where everything lives
Local PII dir (NEVER commit): `old-or-other/karaokehunt-users-export-2026-09-09/outreach_out/`
- `batch_state.json` — song → job_id → requester email(s). THE core mapping.
- `phasec_state.json` — accounts created (49; 3 credits each) + 62 job reassignments.
- `review_triage.json` — easy/medium/skip with job_ids + per-song signals.
- `actions_v3.json` — per-requester buckets (community/torrent/cmake/no_match/dropped).
- `language_inference.json` — per-requester locale+confidence (28 non-en of 89).
- earlier artifacts: canonical_v2.json, audio_search_cache.json, review packets.
Scripts (committed): `scripts/karaokehunt_outreach/` (phase1b/1c, phase2_execute,
phase_batch_generate, torrent_review).
Google Sheet (Andrew's Drive): "KaraokeHunt Outreach — Torrent Review v2 (2026-09-13)".
## 3. Verified mechanics & HARD-WON GOTCHAS
- **Admin browser login (for opening review tabs)**: in the playwright browser, on
gen.nomadkaraoke.com run `localStorage.setItem('karaoke_access_token', '<admin token>')`
(token: `gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1`).
Review URL: `https://gen.nomadkaraoke.com/app/jobs#/<job_id>/review`.
**Andrew reviews in playwright-chrome-3** (profile already logged in as admin).
- **One-click authed review links (SHIPPED + prod-verified)**:
`POST /api/admin/users/{email}/login-link {"expiry_hours": 168, "purpose": "job_review:<job_id>"}`
(admin token) → `{url}`. The URL shows a scanner-safe "Complete Sign-In" click, logs the
user in, lands DIRECTLY on that job's review page. **Mint at email-draft time** (7-day
expiry). PRs #1015 (backend) + #1016 (frontend hash-redirect fix).
- **Reassignment**: `PATCH /api/admin/jobs/{id} {"user_email": ...}` — silent,
auto-creates account if missing (but create properly with credits FIRST).
- **Account creation**: `POST /api/users/admin/users {email, initial_credits: 3,
credit_reason: "KaraokeHunt outreach — apology credits"}` — SILENT. 409 = exists;
**`/api/users/admin/credits` EMAILS the user — never use it silently**
(<user> pre-existed → got NO credits yet; mention in their email).
- **made_for_you is DUAL-ROLE**: exempts from stale-review 48h auto-expiry AND blocks
auto-approval enforcement. All still-parked jobs have MFY=true (no expiry). To full-auto
eval: flip MFY false → `POST /api/internal/jobs/{id}/auto-approval-eval` → re-flag.
- **Failed jobs**: `POST /api/jobs/{id}/retry` (admin) resumes from last checkpoint —
worked for RED download failures and an encoding-worker disconnect. Tangled jobs:
cancel + resubmit fresh.
- **NEVER scrape karaokenerds.com** — workspace `docs/KARAOKENERDS-DATA-ACCESS.md`.
- **RED IP-bans torrent-fetch bursts** (~60/hr got flacup banned ~90 min). Irrelevant now
(downloads done) unless resubmitting.
- **EMAIL POLICY (standing)**: Andrew reviews ALL outreach emails; DRAFTS in his Gmail
(via Gmail MCP `create_draft`); he sends in batches of ~10, waits a day, reviews
reactions. NEVER send programmatically.
## 4. NEXT STEPS, in order
1. ~~Open the 16 remaining medium tabs~~ ✅ DONE 2026-09-20; Andrew reviewed all by 09-23.
2. ~~Reassign newly-completed jobs~~ ✅ DONE 2026-09-23 — all 90 reassigned, holding
account clear, phasec_state.json current.
3. **Email batches** (Gmail drafts; to-addresses = requester; Andrew sends ~10/day):
- **Batch 1 ✅ SENT by Andrew 2026-09-24 ~04:13 UTC** (all 10 confirmed in Sent,
From andrew@nomadkaraoke.com): <user>, <user>, <user>,
<user>, <user>, <user>, <user>, <user>,
<user>, <user>. Batch-1 wording is APPROVED FINAL = the template.
➜ NEXT: monitor replies/bounces in Andrew's Gmail over the coming days.
- **DECISION (Andrew, 2026-09-24): NO bilingual bodies** — every batch uses the
English template; the multilingual PS strip + hosted /karaokehunt page covers
non-English speakers. (Supersedes the earlier bilingual-body plan for batch 2.)
- **DRAFTING CONVENTIONS (Andrew, 2026-09-23 — apply to ALL later batches):**
(a) NO em-dashes — hyphens only, subject + body; (b) include the original
request date: "a while back (April 1st 2025) you requested…" (dates per song in
`actions_v3.json`; requests <~2 months old get softened wording — no "far too
long"); (c) From = andrew@nomadkaraoke.com with his real Gmail signature.
⚠️ The Gmail API/MCP CANNOT set From and mangles the signature+links
(google.com/url wrappers) — draft via the Gmail UI in playwright-chrome-3:
Compose → From dropdown → nomadkaraoke (signature auto-inserts) → To/Subject
via fill → body via `document.execCommand('insertText')` at collapsed-to-start
selection (fill() wipes the signature; insertHTML is Trusted-Types-blocked).
Sign-off "Cheers,\nAndrew" (signature block follows).
- **ALL REMAINING SEGMENT-A EMAILS ✅ DRAFTED 2026-09-24 (77 Gmail drafts,
verified count)**: batch 2 (24 complete), skip-pile (29, one-click links minted
168h on 09-24 — LINKS EXPIRE ~Oct 1; if sending slips past ~Sep 28, re-mint and
update drafts), community-only (19) + no-match (5). Content archive:
`outreach_out/drafted_emails_2026-09-24.json`; links:
`outreach_out/minted_links_2026-09-24.txt`.
✅ **ALL 77 SENT 2026-09-24 ~05:00-05:53 UTC** (Andrew approved exemplars per
type; sent via Gmail UI in 8 batches of ~10 with ~6.5 min gaps; 0 failures;
0 KaraokeHunt drafts remain). **SEGMENT A IS COMPLETE: all 87 requester
outreach emails sent.** 2-week inaction cleanup clock for the 35 parked
review jobs runs to **~2026-10-08**; review links expire ~Oct 1 (re-mint
on request if someone replies late).
⚠️ DRAFTING GOTCHA: rapid scripted composes get their saves silently DROPPED by
Gmail — always wait for the compose header's "Draft saved" ack before Save &
close, and verify the drafts count grew after each batch.
- **Skip-pile batches (29 requesters, 35 pending jobs)**: "we made a first draft —
review the lyrics yourself with one click" variant. MINT the per-job one-click link
at draft time (`job_review:<their job_id>`, 168h). Users get their 3 credits
mentioned. Requesters with BOTH complete + pending songs (<user>,
<user>, <user>, <user>, <user>) get ONE combined email.
- **⏲ 2-WEEK CLEANUP RULE (Andrew, 2026-09-23)**: any job still unactioned by its
requester 2 weeks after their email was SENT → clean up (cancel/delete the parked
job; accounts + credits stay). Track send date per batch.
- **No-match-only + community-only requesters** (from actions_v3: no_match rows and
requesters whose only songs were community links) — "couldn't find a clear match /
here's the existing version" variants + credits.
- After each batch: check replies/bounces in Andrew's Gmail before the next.
- **ENGAGEMENT TRACKING — Andrew's Gmail send-as relays via POSTMARK SMTP, so
opens AND link clicks ARE tracked** (server token = Secret Manager
`postmark-server-token`; feeds: `/messages/outbound/opens` + `/clicks`,
filter Recipient against the 87). Also server-side: (a) logins:
`gen_users/{email}.last_login_at`; (b) parked-job status flips in `jobs`;
(c) `total_jobs_created`; (d) /karaokehunt views: CF zone analytics;
(e) replies/bounces in Gmail. First hours (by ~11:15 UTC 09-24): 28/87
opened, 6 link clicks, first full conversion <user> (clicked 06:43 UTC,
BABYMONSTER FOREVER reviewed → YouTube by 06:59, ~1h after send).
4. ~~Hosted localized letter page~~ ✅ SHIPPED 2026-09-23 (PR #1044, v0.238.1):
**https://gen.nomadkaraoke.com/karaokehunt** — bare URL locale-redirects, page has
language switcher, all 33 locales. **Andrew: include the link in ALL emails** (even
guessed-English recipients) as a PS line before the signature:
a two-line PS before the signature (batch 1 already has it):
"PS: You can read this note in your own language at
https://gen.nomadkaraoke.com/karaokehunt" + a native-language strip
"Español · Português · Français · Italiano · Svenska · Filipino · Bahasa
Indonesia · Tiếng Việt · 한국어 · 中文 · हिन्दी · العربية · עברית · +19 more"
(the inferred requester languages, so recipients recognise theirs).
5. **Segments B & C** (after Segment A settles): B = 266 app-users-never-requested,
C = 37 kit-only. Drafts exist from phase 1 (`outreach_out/review_packet_bc.md` — needs
refresh with final wording + credits). ⚠️ **C overlaps Frog #1 launch-email** —
reconcile to ONE offer with Andrew before sending C.
6. **Draw the line under KaraokeHunt** (final cleanup):
- All 90 jobs at final state + reassigned; karaokehunt@ holding account left as
archive (or zero its credits).
- GCP **Phase E is ungated**: `gcloud projects delete projectbread-karaokay` + close
billing acct `0123B3-AAC0D8-4344D3` (needs Andrew's auth'd gcloud; ask him).
- Play/App Store: apps already unpublished (do NOT "Delete app" on Play — keeps
analytics).
- BACKLOG: `/backlog-finish` Frog #2 "KaraokeHunt order-email recovery + app
redirect" when emails are flowing; move to CHANGELOG.
- Memory: update `project_karaokehunt_batch_generation` + MEMORY.md when done.
## 5. Loose ends / known issues
- 3 pre-existing gen users among requesters (see `outreach_out/existing_gen_users.txt`,
local): no silent credit path — handle in their emails (offer to add credits on reply,
or Andrew grants via admin UI accepting the notification email).
- Post-deploy canary (happy-path E2E) was flaky/failing on some main runs during batch
load; PyPI publish failed on the 0.225.7 run — another session was on CI/errors.
- 2 cancelled jobs are expected (Emily King CF-524 duplicate; tangled Bhimsen original).
- Multi-song requesters not yet fully resolved (e.g. <user> ~15 songs, <user>,
<user>, <user>, hello@thepropervolume) — email each ONCE when their
whole set resolves; their skip-pile songs get one-click links in the same email.
@@ -0,0 +1,147 @@
# KaraokeHunt outreach — FINAL PHASE handoff (2026-09-24)
**Purpose:** Segment A is COMPLETE. This doc hands a fresh session everything needed
for the remaining KaraokeHunt-era work: reply/engagement monitoring, the Oct-8 cleanup
sweep, Segments B & C, and the final line-drawing (GCP Phase E, /backlog-finish).
Deep history: [`2026-09-19-karaokehunt-outreach-phase-c-handoff.md`](2026-09-19-karaokehunt-outreach-phase-c-handoff.md)
(now fully ✅ through step 3) and memory `project_karaokehunt_batch_generation`.
Worktree: `/Users/andrew/Projects/nomadkaraoke/karaoke-gen-karaokehunt-outreach`
Branch: `feat/sess-20260913-0106-karaokehunt-outreach` (docs-only tip; PRs #1004 #1005
#1015 #1016 + letter-page #1044 all merged/deployed).
## 0. UPDATE 2026-09-24 (later session) — Segments B + C SENT
- **Segment B SENT 238/238** (11:05 local, 0 errors): KaraokeHunt APP registrants who never
requested (NOT Kit form signups). 266 → 238 after dropping 17 test/disposable/typo, 10 who
DELETED their KH account (`karaokehunt_account_deletions.csv` — check this for any future
send!), 1 existing Gen user (<user>@). All 238 got accounts + 3 credits SILENTLY first
(`POST /api/users/admin/users`, 0 conflicts). Andrew approved a test at andrew@beveridge.uk.
- **Segment C SENT 35/35** = Frog #1 launch email (Andrew: fold C into Frog #1). Kit list is
mostly app users bulk-imported 2026-04-23 (301/348 rows) — so Frog #1's audience is ONLY these
35 genuine form signups; the rest already got A/B. CTA = vanity referral link
`nomadkaraoke.com/r/thankyou50` (50% off 90d, attaches on next sign-in; created via
`POST /api/referrals/admin/vanity`). Andrew's edit: "(original song, not a cover band)".
- **Letter pages** (all 33 locales, shared `components/karaokehunt/KaraokeHuntLetter`):
`/karaokehunt` (A), `/karaokehuntlist` (B, PR #1045), `/karaokehuntnews` (C, PR #1046 + #1047).
- **SENDING METHOD (use this, not Gmail UI)**: Postmark API, **`outbound` stream**, HTML = Gmail
structure + Andrew's real signature captured from a Segment A message
(`outreach_out/segment_b_signature.{html,txt}`). This is the SAME path Segment A took (Gmail
send-as relays via Postmark SMTP → outbound). **Do NOT use the `broadcast` stream**: it forces a
Postmark unsubscribe footer + List-Unsubscribe header (Andrew disliked it — lands in his
unsubscribe filter); Custom unsubscribe handling needs Postmark support. Opt-out = "just reply".
Scripts: `outreach_out/segment_{b,c}_email.py`, `segment_b_run.py` (idempotent, paced 20/3min);
state in `segment_{b,c}_state.json`. urllib needs a curl User-Agent (Cloudflare WAF 1010).
- Engagement snapshot 09-24 ~12:00Z (Segment A): 30/87 opened, 7 clicked, 0 replies/bounces;
<user> + <user> clicked review links but never pressed "Complete Sign-In".
- Segment A recipient <user>@ had previously DELETED their KH account (missed check).
- Remaining: engagement/replies for A+B+C → ~Oct 1 link re-mints → Oct 8 cleanup → Phase E
(Andrew: wait until after Oct 8) → `/backlog-finish` Frog #2 AND Frog #1.
---
## 1. State (2026-09-24, after sends)
- **ALL 87 Segment-A outreach emails SENT 2026-09-24** (04:12–05:53 UTC): batch 1
(10) clicked Send by Andrew; remaining 77 sent by agent via Gmail UI (Andrew
approved one exemplar per message type, then authorized sending in 8 paced
batches of ~10 with ~6.5 min gaps). 0 failures; 0 KaraokeHunt drafts remain.
- All 90 generated jobs belong to their requesters; **karaokehunt@ holding account
CLEAR**. 55 complete/on YouTube; 35 parked awaiting requester review (34 skip-pile
+ resubmitted Bhimsen 7a16be60). 1 already converted post-send (<user> →
BABYMONSTER FOREVER → NOMAD-1705 live ~06:59 UTC, 16 min after her click).
- **Hosted localized letter LIVE**: https://gen.nomadkaraoke.com/karaokehunt
(PR #1044, v0.238.1; bare URL locale-redirects; 33 locales; ThemeToggle localized;
no-JS fallback). Linked from every email's PS + native-language strip.
- **App-request interceptor LIVE** (v0.236.0) — new requests from old installs
auto-convert; nothing ongoing to do there.
- Early engagement (~11:15 UTC): **28/87 opened, 6 link clicks, 1 full conversion**.
## 2. Deadlines / clocks
- **~Oct 1**: the 35 one-click review links EXPIRE (minted 2026-09-24 ~04:00 UTC,
168h = API max). If a recipient engages late, RE-MINT + reply/resend:
`POST /api/admin/users/{email}/login-link {"expiry_hours":168,"purpose":"job_review:<job_id>"}`
(admin token from `admin-tokens` secret). Per-job links: `outreach_out/minted_links_2026-09-24.txt`.
- **~Oct 8 (2 weeks after send)**: CLEANUP SWEEP — Andrew's rule: parked jobs whose
requester took no action get cancelled/deleted (accounts + credits STAY). Check
`jobs` status + `gen_users.last_login_at` per recipient before deleting; record
outcomes in `phasec_state.json`.
## 3. Engagement / reply monitoring (the "check engagement" recipe)
Andrew's Gmail send-as relays via **Postmark SMTP → opens AND link clicks ARE
tracked** (do NOT assume plain Gmail = untracked; that was corrected 09-24).
- Postmark server token: Secret Manager `postmark-server-token`.
- Opens: `GET https://api.postmarkapp.com/messages/outbound/opens?count=500&offset=N`
· Clicks: `.../clicks` — filter `Recipient` against the 87 (recipient list =
`outreach_out/drafted_emails_2026-09-24.json` + the 10 batch-1 addresses in the
phase-c handoff). Timestamps are EDT (-04:00).
- Server-side: `gen_users/{email}.last_login_at` (docs keyed by EMAIL);
parked-job status flips in `jobs` (fleet ids in `batch_state.json`);
`total_jobs_created` for credit usage; /karaokehunt views via CF zone analytics.
- Replies/bounces: Andrew's Gmail (`in:inbox subject:KaraokeHunt` etc.). Triage:
- **<user> / <user> reply for credits** → their
emails promised 3 credits on reply; grant via admin (the `/api/users/admin/credits`
endpoint EMAILS the user — fine once they've replied) or Andrew via admin UI.
- **Vague-request replies** (<user>=Justin Bieber song?, <user>=Arijit
song?, <user>="My songs") → they name a song → generate it for them (these are
legit requested songs, not "popular songs").
- Bounced addresses → note in phasec_state, nothing else owed.
## 4. NEXT STEPS, in order
1. **Daily-ish engagement check + reply triage** (§3) until ~Oct 8.
2. **Oct 8 cleanup sweep** (§2). After it: zero/archive the karaokehunt@ account.
3. **Segment B (266 app-users-never-requested) & C (37 kit-buyers-only)**:
- Base drafts exist in `outreach_out/review_packet_bc.md` — REFRESH to the final
approved template (hyphens, Cheers/Andrew+signature, PS + language strip,
/karaokehunt link, credits offer). These are generic (no per-user songs).
- ⚠️ **C overlaps Frog #1 launch-email — reconcile to ONE offer with Andrew
BEFORE drafting C.**
- ⚠️ **Volume decision needed from Andrew for B**: 266 emails at ~10/day via
Gmail UI = ~4 weeks. Options: bigger daily batches, or send B via Postmark
broadcast stream (they're generic letters, not personal apologies) — ask him.
4. **GCP Phase E** (destructive — get Andrew's explicit go, his gcloud is authed):
`gcloud projects delete projectbread-karaokay` + close billing acct
`0123B3-AAC0D8-4344D3`. Play/App Store: apps unpublished; do NOT "Delete app".
5. **Close out**: `/backlog-finish` Frog #2 ("KaraokeHunt order-email recovery + app
redirect") → CHANGELOG; update memory `project_karaokehunt_batch_generation` +
MEMORY.md; `/cleanup` the outreach + letter worktrees when truly done.
## 5. HARD-WON GOTCHAS (email automation via Gmail UI)
- **Drafting/sending MUST go through the Gmail UI in playwright-chrome-3** (his
logged-in profile). The Gmail API/MCP cannot set the From alias and mangles
signature + links (google.com/url wrappers).
- Compose flow: Compose → From dropdown → andrew@nomadkaraoke.com (Gmail inserts his
real signature) → fill To/Subject → insert body with
`document.execCommand('insertText')` at a collapsed-to-start selection.
`fill()` WIPES the signature; `insertHTML` is blocked by Trusted Types.
- **Gmail SILENTLY DROPS saves under rapid scripted composing** (~56 of 77 lost on
the first pass). Always wait for the compose header's "Draft saved" ack before
Save & close, pace ≥1s, and VERIFY the drafts count grew after each chunk.
- Send = focus body + ⌘Enter; sending 10-batches with ~6.5 min gaps tripped no bot
protection.
- `getByRole('link', {name:/KaraokeHunt/})` matches the SIDEBAR LABEL "KaraokeHunt"
— scope row locators to `tr.zA` or match on full subjects.
- Gmail search does NOT reliably index fresh drafts (to:, body, or subject) —
operate on the #drafts folder rows, not search.
- Bulk automation: `browser_run_code_unsafe` with a script file under
`.playwright-mcp/kh-scripts/` (allowed root). Reusable scripts there:
`kh_send10.js` (send 10 oldest KH drafts), redo/draft chunk templates.
- Postmark 168h is the login-link expiry_hours MAX (422 above).
- Email content conventions (LOCKED): hyphens never em-dashes; original request
date in opening ("a while back (April 1st 2025)…", softened if <2 months);
NO bilingual bodies (PS strip + localized page instead); "Cheers,\nAndrew".
## 6. Where everything lives
Local PII dir (NEVER commit): `old-or-other/karaokehunt-users-export-2026-09-09/outreach_out/`
- `drafted_emails_2026-09-24.json` — full text of all 77 sent emails (with types).
- `minted_links_2026-09-24.txt` — email → job_id → one-click URL for the 35 parked.
- `batch_state.json` / `phasec_state.json` / `actions_v3.json` /
`language_inference.json` / `review_packet_bc.md` — as before (phase-c handoff §2).
Docs: phase-c handoff (history), this doc (continuation), workspace session records
`docs/sessions/2026-Q3/2026-09-24-karaokehunt-segment-a-complete.md` (+ 09-19/09-22 ones).
@@ -0,0 +1,116 @@
# Encoding-worker disk cost reduction (2026-09-26)
## Problem
The 10 encoding-worker VMs (c4d primary pair + 8 stockout fallbacks) are stopped
between jobs, so their cost is mostly their boot disks. Last-30-day billing:
Hyperdisk Balanced capacity ~$48 (601 GiB-mo) + provisioned throughput ~$12 +
provisioned IOPS ~$6; Balanced PD capacity ~$45 (includes 2 runner disks). Plus
~$18/mo "Storage Image" for 39 custom images.
## Findings
- **Disks were ~85% empty.** `encoding-worker-b`, 8 months in service: 15 GB used
of 99 GB (7 GB venv, 3 GB pip cache, 0.7 GB logs). Fresh disks from the current
image use 8 GB.
- **Scratch need is small.** Each `/encode` downloads its whole `jobs/<id>/` folder
into `/tmp` on the boot disk. Across 1,904 job folders: median 0.43 GB, p99 1.3 GB,
max 4.0 GB. Downloads happen before the (serialized) heavy lane, so queued jobs
hold their inputs at the same time. The deepest queue seen in 30 days was 8.
Realistic peak: ~8 GB base + ~10-15 GB scratch.
- **Only two disks had paid IOPS/throughput.** `-c4a` and `-n4db`, created 2026-08-15
after the June IOPS tune, got the Hyperdisk defaults of 3600 IOPS / 290 MB/s. The
other hyperdisks were already on the free baseline of 3000 / 140.
- **Image size set the disk floor.** Packer built the image with `disk_size = 100`.
GCE cannot create a disk smaller than its source image, so every worker had to be
at least 100 GB.
- **Runner image pruning had never run.** The monthly `build-runner-images.yml`
step used an invalid filter (`-deprecated.state:*`). gcloud wrote the error to
stderr and the step printed "Nothing to deprecate". Deprecating wouldn't have
saved money anyway, because deprecated images are still billed.
## Changes
| Lever | Change | Est. saving |
|---|---|---|
| Boot disk size | 100 GB to **50 GB** on all 10 workers (`DiskSizes.ENCODING_WORKER`); Packer image `disk_size` 100 to **30** | ~$44/mo |
| Hyperdisk IOPS/throughput | `-c4a`/`-n4db` 3600/290 to 3000/140 (free baseline). New hyperdisks are created at 3000/140 explicitly | ~$18/mo |
| Custom images | Deleted 23 old runner images (kept newest 2 per family). Fixed the prune step so it deletes beyond the newest 2, matches the family exactly, and skips images that are a disk's source | ~$13/mo |
**Total: ~$75/mo.**
Levers considered and **not** taken:
- **Removing fallback VMs.** Not done. They are the stockout insurance, and machine-family diversity is deliberate.
- **Ephemeral boot disks (create from image at start).** Not done. This adds disk-creation and hydration latency to every cold start, plus another failure mode during stockouts. The saving (~$4/VM/mo after the shrink) isn't worth that.
- **pd-standard for the fallbacks.** Not done. A 50 GB pd-standard disk gets ~75 read IOPS, which would slow boot and pip installs badly. c4/c4d/n4d VMs require Hyperdisk anyway.
- **Smaller than 50 GB.** Not done. It saves only ~$1/disk/mo per 10 GB, and a disk-full error during a bulk-queue encode costs far more than that.
## Performance
pd-balanced performance scales with size: 100 GB gives 3600 IOPS / 168 MB/s, and
50 GB gives 3300 / 154. Hyperdisk Balanced at 3000 / 140 is the same at any size.
Encoding is CPU-bound: a full 4K finalization writes ~200 MB of outputs in ~2 min.
Real full `/encode` of the same job (`bench/disk-swap-input`, the Aug-2026 benchmark
song; formats 4k lossless + 4k lossy + 720p), wall time in seconds:
| VM | CPU platform | Before (100 GB, old image) | After (50 GB, new image) | start to healthy |
|---|---|---|---|---|
| fallback-c2df (pd-balanced) | AMD Milan | 142.6, 138.9 | 142.2, 136.9 | 34.9 s to 33.5 s |
| fallback-c4a (hyperdisk) | Intel Emerald Rapids | 132.1, 121.4 | 147.4, 144.5, then a re-run of 143.9, 138.7, 138.6 | 39.1 s to 50-53 s |
| fallback-n2da (pd-balanced) | AMD Milan | failed: transient metadata-server SSL error (pre-existing, see v0.217.0) | 155.7 | to 41.7 s |
| fallback-n2f (pd-balanced) | Intel Cascade Lake | 247.2 (Aug benchmark) | 246.8 | to 39.7 s |
| fallback-a (hyperdisk) | AMD Turin (c4d) | n/a | 99.0 | to 42.3 s |
| fallback-b (hyperdisk) | AMD Turin (c4d) | n/a | 105.4 | to 52.5 s |
| encoding-worker-b (hyperdisk) | AMD Turin (c4d) | n/a | 100.8 | to 35.9 s |
| encoding-worker-a (hyperdisk, primary) | AMD Turin (c4d) | n/a | 98.9 | to 36.9 s |
On c4a the after-median of 139 s is exactly the 138.6 s August median, which was
measured on the old 100 GB disk. The two "before" samples today were at the fast
end of the ~35% run-to-run noise the August benchmark documented. Hyperdisk
performance at 3000/140 doesn't depend on disk size, so the disk change can't
explain the difference.
## Rollout procedure: in-place boot-disk swap
Changing `boot_disk.initialize_params.size` makes Pulumi either replace the VM or
try an in-place resize. An in-place resize can't shrink a disk, and a replacement
has to re-allocate the VM, which for c4d/n4d/c2d can be blocked for hours by a
stockout. Each VM was left in place and only its boot disk was swapped, while the
VM was `TERMINATED`. No compute capacity is needed for this.
```bash
# Per VM, only if status == TERMINATED and config/encoding-worker.deploy_in_progress is false
gcloud compute instances detach-disk $VM --zone=$Z --disk=$VM
gcloud compute disks delete $VM --zone=$Z --quiet
# hyperdisk-balanced (c4d/c4/n4d):
gcloud compute disks create $VM --zone=$Z --image=$NEW_IMAGE --image-project=nomadkaraoke \
--size=50GB --type=hyperdisk-balanced --provisioned-iops=3000 --provisioned-throughput=140
# pd-balanced (n2/n2d/c2d):
gcloud compute disks create $VM --zone=$Z --image=$NEW_IMAGE --image-project=nomadkaraoke \
--size=50GB --type=pd-balanced
gcloud compute instances attach-disk $VM --zone=$Z --disk=$VM --boot --device-name=persistent-disk-0
gcloud compute instances set-disk-auto-delete $VM --zone=$Z --disk=$VM --auto-delete
# then: pulumi refresh --target <instance urn> → state picks up size 50 / new image;
# pulumi preview shows no diff for that VM (the family-image URL diff-suppresses).
```
The old disk is deleted without a snapshot on purpose. Worker boot disks hold no
state that can't be rebuilt: the image, the wheel downloaded at boot, and caches.
Jobs live in GCS and Firestore.
Rollback: repeat the swap using the previous image. `encoding-worker-1786843294`
is kept for this.
Verification per VM: start it, check `/health` (wheel version), run a real `/encode`,
check `df`, then stop it. VMs that hit a stockout at start were swapped but could
only be verified later.
## Status
All 10 workers were swapped to 50 GB on `encoding-worker-1790444464` and their
Pulumi state was refreshed, and `pulumi preview` shows no encoding-VM diff. The old
encoding-worker images were deleted, keeping `encoding-worker-1786843294` for
rollback. Custom images went from 39 to 10. `-n4db` (n4d, us-central1-b) and `-n2c`
(n2, us-central1-c) couldn't be boot-verified because both zones were stocked out
during the rollout. They got the same swap as the 8 verified VMs.
@@ -0,0 +1,56 @@
# KaraokeHunt outreach — batch generation through Phase C — 2026-09-19
**Project:** karaoke-gen (worktree `karaoke-gen-karaokehunt-outreach`)
**Branch:** `feat/sess-20260913-0106-karaokehunt-outreach` (PRs #1004 #1005 #1015 #1016 merged from it)
**Status:** in-progress — handoff to fresh session
## Summary
One long multi-day session (2026-09-13 → 09-19) that took the KaraokeHunt requester
outreach from analysis to near-completion: canonicalized all 139 requested songs
(InputURL-oEmbed + search evidence + web search), batch-generated 90 public karaoke
jobs under holding account karaokehunt@nomadkaraoke.com, ran the full-auto-review
experiment (13/89 ≈ 15% full-auto), triaged the rest for Andrew's review (15 easy +
26 medium done or in progress; 34 skip → users), shipped one-click authed review
links, reassigned 62 jobs to requester accounts (48 created silently with 3 credits),
and drafted the first Gmail outreach batch (10, NOT sent).
## What changed
- **Prod jobs**: 90 jobs created (review_mode=auto, public, MFY=true); 39 complete/live
on YouTube as of wrap; 62 reassigned to requesters; 49 accounts exist.
- **karaoke-gen PRs shipped**: #1004 made_for_you admin-editable (stale-review
exemption); #1005 `POST /api/internal/jobs/{id}/auto-approval-eval`; #1015 admin
login-link mint endpoint with `job_review:<id>` redirect purpose; #1016 verify-page
hard-navigation fix for hash redirect paths. All deployed + prod-verified.
- **Gmail**: 10 outreach drafts created in Andrew's account (batch 1, English,
completed-video variant). Nothing sent to anyone.
- **Ops incidents handled**: RED IP-ban of flacup (27 download failures, 100%
recovered via retry loop); encoding-worker disconnect (Buck Owens, retried);
Cloudflare-524 duplicate job (cancelled); tangled reset job (cancelled+resubmitted).
## Decisions & rationale
- Holding-account pattern (karaokehunt@ + catchall) to contain ALL job emails until
coordinated outreach — worked perfectly.
- Relaxed torrent rule (Andrew): any FLAC ≥2 seeders with roughly-matching filename.
- Brand-only karaoke versions on KN → generate anyway (Andrew).
- Non-English / no-reference songs → skip Andrew's review; requesters self-review via
one-click links.
- Emails: Gmail drafts only, Andrew sends in ~10 batches (standing policy).
## Learnings / gotchas
See §3 of `docs/archive/2026-09-19-karaokehunt-outreach-phase-c-handoff.md` — the
authoritative list (MFY dual-role, /admin/credits emails users, RED burst bans,
CF-524 double-creates, retry vs reset semantics, KN never-scrape).
## Open threads & next steps
**Pick up from `docs/archive/2026-09-19-karaokehunt-outreach-phase-c-handoff.md`** —
it is the self-contained continuation doc: open the 16 remaining medium review tabs,
reassign newly-completed jobs, run the email batches (batch 1 awaiting Andrew's
review/send), bilingual + skip-pile batches with minted links, hosted localized
letter, Segments B/C (reconcile C with Frog #1), then final KaraokeHunt-era cleanup
(GCP Phase E delete, /backlog-finish Frog #2).
## Related docs
- `docs/archive/2026-09-19-karaokehunt-outreach-phase-c-handoff.md` (CONTINUATION)
- `docs/archive/2026-09-13-karaokehunt-outreach-handoff.md` (full history, sessions 1–5)
- Memory: `project_karaokehunt_batch_generation`, `feedback_outreach_email_sending_policy`
- Local PII data: `old-or-other/karaokehunt-users-export-2026-09-09/outreach_out/`
+6 -62
View File
@@ -1,68 +1,12 @@
'use client';
import KaraokeHuntLetter from '@/components/karaokehunt/KaraokeHuntLetter';
import { useTranslations } from 'next-intl';
import { Music } from 'lucide-react';
import LanguageSwitcher from '@/components/LanguageSwitcher';
import { ThemeToggle } from '@/components/ThemeToggle';
// Letter to former KaraokeHunt app users, linked from the outreach emails.
// Letter to former KaraokeHunt app users who requested songs, linked from the outreach emails.
// The bare /karaokehunt URL locale-redirects here, so one link serves all 33 languages.
export default function KaraokeHuntLetterPage() {
const t = useTranslations('karaokehuntLetter');
return (
<div className="min-h-screen" style={{ background: 'var(--bg)' }}>
<header className="flex items-center justify-between px-4 py-3 max-w-2xl mx-auto">
<div className="flex items-center gap-2" style={{ color: 'var(--text)' }}>
<Music className="h-5 w-5" style={{ color: 'var(--accent)' }} />
<span className="font-semibold">Nomad Karaoke</span>
</div>
<div className="flex items-center gap-2">
<LanguageSwitcher />
<ThemeToggle />
</div>
</header>
<main className="max-w-2xl mx-auto px-4 pb-16">
<div
className="rounded-2xl p-6 sm:p-10 mt-4"
style={{ background: 'var(--card)', color: 'var(--text)', border: '1px solid var(--border)' }}
>
<h1 className="text-2xl sm:text-3xl font-bold mb-6">{t('title')}</h1>
<div className="space-y-4 leading-relaxed">
<p>{t('greeting')}</p>
<p>{t('apology')}</p>
<p>{t('goodNews')}</p>
<p>
{t('creditsBefore')}{' '}
<a
href="https://gen.nomadkaraoke.com"
className="underline font-medium"
style={{ color: 'var(--accent)' }}
>
gen.nomadkaraoke.com
</a>{' '}
{t('creditsAfter')}
</p>
<p>{t('appRetired')}</p>
<p>{t('thanks')}</p>
<p>
{t('signoff')}
<br />
Andrew
<br />
<span className="text-sm" style={{ color: 'var(--text-muted)' }}>
{t('founderRole')}
</span>
</p>
</div>
</div>
<p className="text-center text-sm mt-6" style={{ color: 'var(--text-muted)' }}>
{t('languageHint')}
</p>
</main>
</div>
<KaraokeHuntLetter
namespace="karaokehuntLetter"
paragraphs={['apology', 'goodNews', 'credits', 'appRetired', 'thanks']}
/>
);
}
@@ -0,0 +1,13 @@
import KaraokeHuntLetter from '@/components/karaokehunt/KaraokeHuntLetter';
// Letter to KaraokeHunt app users who signed up but never requested a song,
// linked from the Segment B outreach email. The bare /karaokehuntlist URL
// locale-redirects here, so one link serves all 33 languages.
export default function KaraokeHuntListLetterPage() {
return (
<KaraokeHuntLetter
namespace="karaokehuntListLetter"
paragraphs={['apology', 'goodNews', 'credits', 'thanks']}
/>
);
}
@@ -0,0 +1,15 @@
import KaraokeHuntLetter from '@/components/karaokehunt/KaraokeHuntLetter';
// Letter to KaraokeHunt mailing-list subscribers (signed up on karaokehunt.com to hear
// what was being built, never used the app), linked from the launch email.
// The bare /karaokehuntnews URL locale-redirects here, so one link serves all 33 languages.
export default function KaraokeHuntNewsLetterPage() {
return (
<KaraokeHuntLetter
namespace="karaokehuntNewsLetter"
paragraphs={['apology', 'stillHere', 'whatItIs', 'credits', 'thatsIt']}
link={{ href: 'https://nomadkaraoke.com/r/thankyou50', label: 'nomadkaraoke.com/r/thankyou50' }}
hasCreditsAfter={false}
/>
);
}
+2 -1
View File
@@ -1,5 +1,6 @@
import Link from "next/link"
import { LocaleRedirect } from "@/components/LocaleRedirect"
import enMessages from "@/messages/en.json"
// This URL is linked from outreach emails, so it must degrade gracefully
// without JavaScript: <noscript> meta-refresh plus a visible fallback link.
@@ -12,7 +13,7 @@ export default function KaraokeHuntPage() {
<LocaleRedirect />
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Link href="/en/karaokehunt" style={{ textDecoration: 'underline' }}>
A note for KaraokeHunt users →
{enMessages.karaokehuntLetter.title} →
</Link>
</div>
</>
+21
View File
@@ -0,0 +1,21 @@
import Link from "next/link"
import { LocaleRedirect } from "@/components/LocaleRedirect"
import enMessages from "@/messages/en.json"
// This URL is linked from outreach emails, so it must degrade gracefully
// without JavaScript: <noscript> meta-refresh plus a visible fallback link.
export default function KaraokeHuntListPage() {
return (
<>
<noscript>
<meta httpEquiv="refresh" content="0;url=/en/karaokehuntlist" />
</noscript>
<LocaleRedirect />
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Link href="/en/karaokehuntlist" style={{ textDecoration: 'underline' }}>
{enMessages.karaokehuntListLetter.title} →
</Link>
</div>
</>
)
}
+21
View File
@@ -0,0 +1,21 @@
import Link from "next/link"
import { LocaleRedirect } from "@/components/LocaleRedirect"
import enMessages from "@/messages/en.json"
// This URL is linked from outreach emails, so it must degrade gracefully
// without JavaScript: <noscript> meta-refresh plus a visible fallback link.
export default function KaraokeHuntNewsPage() {
return (
<>
<noscript>
<meta httpEquiv="refresh" content="0;url=/en/karaokehuntnews" />
</noscript>
<LocaleRedirect />
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Link href="/en/karaokehuntnews" style={{ textDecoration: 'underline' }}>
{enMessages.karaokehuntNewsLetter.title} →
</Link>
</div>
</>
)
}
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more