Compare commits

...
13 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 5ae9d407b2 chore: remove duplicate start-review 409 guard (v0.290.3) (#1248)
#1243 and #1246 merged within minutes of each other and both added a 409
to `start-review`. This removes the one from #1246. The guard from #1243
stays, since it also handles losing the race to auto-approval. No
behaviour change for a finished job, and the #1246 test for it stays.

The two guards differ for statuses like `lyrics_complete`, which could
technically move to `in_review`: under the #1243 guard those already get
a 409.

Docs-free, small diff; no local CodeRabbit run, so the bot can review
it.

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

https://claude.ai/code/session_012RYLVTajJiZnzPUt9qsVEJ

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

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

## Summary by CodeRabbit

* **Bug Fixes**
* Starting a review is now limited to jobs awaiting review or already in
review; other job statuses receive a conflict response.
* Repeated requests to open an eligible review remain safe, and
concurrent state changes are handled using the job’s current status.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:30:59 -05:00
Andrew Beveridge ☄️andClaude Opus 5.5 a10e548606 fix(url-jobs): retry a YouTube bot block, then point to Audio Search (v0.290.1) (#1244)
Implements fix C from section 4 of the 2026-11-03 alerts triage handoff.
Job 526bf46c, from a paying customer, failed within 3s of a YouTube bot
wall and showed the raw yt-dlp error. The credit was refunded, and the
customer then uploaded an MP3.

## Changes

- **Download:** `create-from-url` retries a bot-blocked download once
after 30s. Other download errors behave as before.
- **Still blocked:** the job fails with a translated message pointing to
Audio Search. The raw error goes in `error_details`. The response stays
a 500, because the frontend treats 503 as a transient backend blip.
- **Pre-check:** a bot-blocked availability check now waits 30s and
checks again before rejecting. No job or credit exists yet at that
point. A repeat block returns the same translated message instead of the
old hardcoded English. CodeRabbit raised this: without it, the retry
never ran when the pre-check caught the block.
- **Logging:** the bot-block paths log WARNING rather than ERROR,
because `fail_job` already raises the alert for the failure.

`audio_search.py` has its own bot-block handling, which this PR doesn't
change. The monitor and start-review changes are in a separate PR.

## Depends on flacfetch

The retries only help much with
https://github.com/nomadkaraoke/flacfetch/pull/61 deployed, since that's
what requests fresh cookies straight away. Without it, new cookies only
arrive from the keeper's 30-minute probe, so a 30s wait rarely helps.
This PR is safe to deploy first, but it adds up to 30s before the same
failure.

## Testing

- New `test_create_from_url_bot_block.py`, written test-first: retries,
final failure, pre-check, non-bot errors and all 33 locales.
- Backend tests selected with `-k "url or youtube or audio_search or
i18n or translation"`: 785 passed, 5 skipped. Emulator and integration
tests excluded. I did not run the full `make test`, so CI is the full
check.
- Backend translation key parity passes.
- Local CodeRabbit review: 1 finding, fixed. The fresh re-review had no
new findings.

**Not verified:**
- Nothing has run in production, and I created no test jobs.
- **The 32 new translations were written by hand, not by
`translate.py`.** gcloud auth had expired, so the Gemini key wasn't
available. To replace them, run `translate.py` for that key with a valid
login.
- ruff reports F823 for `asyncio` at about line 647 of `file_upload.py`.
It's also on main, in a different function, and I left it alone.

Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567241547739570298
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567252495535841386
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567252497620537415

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVTvqXyL4QyA2EjzQMG

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 23:18:13 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 08b146fce0 fix: no review push before AI suggestions are scored; start-review 409 after review ends (v0.290.1) (#1246)
Andrew's job `7f89f884` (2026-11-03) got a "review your lyrics" push,
then auto-approved about 3.7 minutes later. Tapping the push afterwards
left the app on its loader.

**False review push.** The screens worker's first score ran at 00:15:40,
before the proactive auto-correct finished at 00:15:46. Without
suggestions the lyrics scored `needs-review`, so `hold_for_audio` was
false and review opened with its push. The audio worker's re-score then
saw the suggestions (`auto/ai-resolved`) and auto-approved. In the last
14 days 5 jobs auto-approved, and 4 of them opened review first
(typically about 3.7 minutes before).

`route_after_scoring` now waits for the suggestions and scores again
when the first pass ran without them, then holds or auto-completes. If
suggestions can't be had, or the re-score reaches no verdict, the first
verdict stands and review opens as before.

**start-review on a finished job.** `complete -> in_review` raised an
invalid transition: a 500, an ERROR log (4 in prod for this job, which
the error monitor can turn into an #alerts message), and the app
retrying as if it were transient. It now returns 409 without attempting
the transition. The app's handling is in nomad-mobile #44.

**Tests:** `test_review_gate.py` and `test_jobs_api.py` pass with new
cases. `test_internal_api.py` has 7 auth test failures locally that also
fail on the main clone, so they aren't from this change.

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVTajJiZnzPUt9qsVEJ

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:13:25 -05:00
Andrew Beveridge ☄️andClaude Opus 5.5 70bdd0e693 fix(alerts): start-review 409, per-cause crash patterns, one alert per job failure (v0.290.1) (#1243)
Section 1 of the 2026-11-03 #alerts triage handoff: a stale push on a
finished song got a 500, and the error monitor could stay silent on a
new crash.

Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566980744448843886
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566980746394996879
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566980747905073224
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1565697725280948294
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1565803187334815775
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1565818418072916110
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566225593354420226
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566256141074169987
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567207141994135654
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567252495535841386
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567252497620537415

## What changed

**1a. start-review:** a job not in review gets 409
(`jobs.jobNotInReviewState`) with no transition attempted. Losing the
auto-approver race is a 409 too. `correction-data` has the same race,
and its `except Exception` turned it into a 500; it now returns 409
(`except HTTPException: raise` added). Its status gate still returns
400, as before.

**1b. Crash patterns:** `Exception in ASGI application` and
`request_audit_error` become `Unhandled exception: <Type: message>`,
read from the entry's `exception` field. The handoff's suspicion is
confirmed in `upsert_pattern`: an existing `new` pattern returns
`is_new=False`, so a second, different crash stayed silent. Both log
lines of one crash now share one pattern. The path and method go in the
sample only.

I read the line after the last frame rather than the traceback's last
line. pydantic's last line is a docs link shared by every failure, and
group tracebacks end in a separator.

**1c. One alert per failure:**
- YouTube ids are normalized out of signatures, which also fixes the
false "first time" line in `ops_alerts`.
- `Job <id> failed` (both call sites in `job_manager`) logs WARNING,
since the status write sends the job-failed alert.
- `URL download failed:` is ignored in the monitor, not demoted, because
`file_upload.py` belongs to the section 4 PR.
- `[job:<id>] Download failed` logs WARNING for the expected
`DownloadError`/`FlacfetchServiceError` types. This wasn't named in the
handoff, but it is the same duplicate on the audio-search path.
Unexpected exceptions there stay ERROR with a traceback.

**1d. Suppressions and demotions:**
- Zalo's `zaloJSV2 is not defined`: dropped at `/api/client-errors`,
only with a Zalo UA.
- `python -c` experiments on `audio-separation-job`: ignored, using the
handoff's regex.
- Spotify 403 on `/lyrics`: WARNING with `response.text[:200]`. 401 on
`/lyrics` and 401/403 on `/search` stay ERROR.
- Dropbox token probe: WARNING. A rejected refresh used to log nothing,
so it now logs ERROR, as does having no refresh credentials.
- decide-search health aborts: this was a small change. `should_ignore`
takes an optional `request_url` and matches the exact path
`/api/search/health`.

**1e. Cold start:** `anyio._backends._asyncio` is added to
`_LAZY_ROUTE_IMPORTS`. The prod stack from 10-30 confirms the stall was
in that import. Lifespan also sends one `/api/health` request through
the app in a worker thread, bounded by the existing 30s timeout and
best-effort.

## Testing

- TDD: new tests failed first, then passed.
- Affected suites: 826 passed.
- `backend/tests` (excluding `backend/tests/emulator`): 7088 passed, 8
failed, 29 skipped. All 8 are in `test_emulator_integration.py`, and
that file also shows 8 failures at the base commit a8f9618a. I did not
compare the 8 test names one by one.
- `tests/unit` outside the listed files was not run.
`test_audio_fetcher.py` and `test_remote_cli.py` fail to collect in my
environment; I didn't change either file.
- Read-only replay of real prod entries through the new code: the 11-03
crash gave one specific pattern with `POST
/api/jobs/7f89f884/start-review` in the sample, the decide-search health
aborts and the experiment traceback were ignored.
- Local CodeRabbit review completed with 0 findings.

## Not verified

- Nothing is live, so the alert volume and the cold-start stall haven't
been measured. The warm request has only run in tests, not on a real
Cloud Run cold start.
- A request's first-use imports beyond the anyio backend aren't
individually checked.
- My test environment has no `flacfetch`, so its lazy imports only log a
warning here.
- Zalo: the trigger is one report (11-03).

## Known leftovers

- `validate_state_transition` still logs ERROR before raising, so the
auto-approver race (and the existing in_review race) still emits one
`Invalid state transition` ERROR even though the client now gets a clean
response. The stale-push case no longer reaches it. I left this because
other callers rely on that log.
- A crash that also logs its own ERROR first still gives two patterns,
the ERROR and `Unhandled exception`.
- The first bot block after deploy shows "first time" once, because the
normalized signature is new.
- Old `Exception in ASGI application` and `request_audit_error` patterns
stop recurring and will auto-resolve.
- If the section 4 PR rewords `URL download failed:`, the ignore entry
in `known_issues.py` needs the same wording.

## For Andrew (infra and cost, not changed here)

- Cloud Run startup probe and min-instances for `karaoke-backend`, if
cold-start stalls continue after this ships.
- decide-search's min-0 is why its health pings abort. The suppression
hides those, but real search paths will still alert on the same abort.

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVTvqXyL4QyA2EjzQMG

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 23:04:04 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 ea69386e50 fix(ci): Java 25 for the Firestore emulator (#1245)
`google-cloud-cli-firestore-emulator` 592.0.0 is compiled for Java 25
(class file 69), and the package is installed unpinned from apt, so CI's
Java 21 fails with `UnsupportedClassVersionError`. This blocks every PR:
Backend Emulator Integration and Local Stack E2E both failed on #1243
and #1244 (runs 41705112128, 41706068761). Main last passed 11-02.
CI-only change; this PR's own run is the test.

@coderabbitai ignore not added: no local review was run on this one-line
CI change, so the bot may review it.

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

https://claude.ai/code/session_012RYLVTvqXyL4QyA2EjzQMG

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:53:53 -05:00
Andrew Beveridge ☄️andClaude Opus 5.5 a8f9618a07 feat(review): admin "perfectly synced" mark for the word-timing reference set (v0.290.0) (#1242)
## Summary
Andrew's review depth varies: Thursday live-event jobs often get only a
quick review. Treating every admin review as perfect sync truth
therefore poisons aligner training and evaluation (full-auto v2). This
adds an explicit, admin-only **"perfectly synced"** mark in the lyrics
review. Ticked jobs join the word-timing reference set; unticked means
unverified. Andrew's definition: a confident spot-check (anchors +
waveforms), not necessarily a full listen.

## Changes
- **Backend:** new `POST /api/review/{job_id}/sync-reference`
(`require_admin`).
  - Stores `state_data.sync_reference = {verified, by, at, notes}`.
- `verified: true` needs saved review output: the `file_urls` pointer,
or the direct GCS path for older jobs. Otherwise it returns 409.
Revoking is always allowed.
- **`correction-data`** returns `sync_reference`, so a re-review shows
the existing mark and can revoke it.
- **Frontend:**
- The review modal shows the checkbox plus an optional notes field, to
admins only.
- The modal passes the mark to `onSubmit`. `LyricsAnalyzer` saves it
**after** `submitCorrections` succeeds, so a mark can't sit on unsaved
timing. A failure shows a toast and never blocks the review.
- Once the box is touched, its current state is always sent, so it can
be revoked.
- **i18n:** 4 new strings × 33 locales.
- **Docs:** API.md. Version 0.290.0.

## Testing
- Backend: `test_review_sync_reference.py` (admin store, notes trim,
404, 422, 403 non-admin, 409 without review, direct-path fallback).
Related review suites pass (29).
- Frontend: `ReviewChangesModal.syncReference.test.tsx` (hidden for
non-admin, tick passes the mark, untick sends nothing, saved mark
pre-ticks and revokes, touched-then-unticked sends `false`). The modal
suites pass (29). tsc shows no new errors (21 pre-existing test-file
errors, the same on main).
- **CodeRabbit:** ran locally for 3 cycles and fixed 6 findings. One was
left by design: a pre-ticked mark on an edited re-review is visible in
the modal Andrew confirms, so submitting re-affirms it. The only user is
Andrew.

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVVVPsvPbXFhRYY5VSJ

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:17:41 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 452a8a3e28 fix(encoding): stems-ready resumes reach the AWS video worker (v0.289.1) (#1241)
## Summary
Found by the prod E2E on 2026-10-31.
- With `aws_video_worker` on, the render worker dispatched the video
worker to AWS, and it parked waiting for stems.
- The **stems-ready resume** came from `audio-separation-job`, which has
no `ENCODING_WORKER_FALLBACK_VMS` env. It never saw the AWS worker, so
it silently started the Cloud Run job.
- The job completed fine, because the Cloud Run job is the fallback, but
its distribution ran from GCP.

## Changes
- `EncodingWorkerManager.fallback_entries()`: in production, when the
env var is missing, read the `encoding-worker-fallback-vms` secret
(cached per process by `get_secret`). This affects the audio, lyrics and
download jobs, which also trigger and warm the encoder. Outside
production it never fetches.
- `_trigger_video_worker_on_aws`: logs when the AWS dispatch is skipped
because AWS isn't the top-ranked worker, so it can't fail silently
again.

## Testing
- 3 new tests: secret fallback in prod, no fetch outside prod, env
preferred over the secret. All 171 related tests pass.
- Local CodeRabbit: no findings.
- After deploy: another prod E2E to confirm the resume reaches AWS.

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVSR5qgwsxTQtvGimKF

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:07:15 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 78264fa23a feat(encoding): run the video worker (distribution) on the AWS box (v0.289.0) (#1240)
## Summary
Phase 2 of moving encoding to AWS; Phase 1 was #1236 and #1239. Design
and rationale are in
`docs/archive/2026-10-29-aws-encoding-worker-plan.md` § Phase 2.

When Firestore `config/encoding-worker.aws_video_worker` is true **and**
the AWS worker ranks first, `trigger_video_worker` runs the video worker
**on the AWS box** instead of starting the Cloud Run job
`video-encoding-job`.
- **Uploads move to AWS:** the Dropbox/YouTube/Drive uploads (~187
GB/mo, ~$18/mo of Cloud Run internet egress) leave from AWS, on credits.
- **No Cloud Run CPU** for the job (~$11/mo).
- **Off by default.** Any failure falls back to the Cloud Run job, so
this path can't drop a job.

## Changes
- **`POST /run-worker` (worker):**
- Spawns `python -m backend.workers.video_worker --job-id …` with the
box's video-worker env.
  - Status is reported via `/status/{id}`.
- A run counts in `/health` `active_jobs` from the moment it's accepted,
so the idle watchdog won't stop the box mid-run.
  - Returns 503 unless the env file exists.
  - `job_id` is pattern-validated.
  - Any startup failure marks the run failed.
- **`backend/services/local_encoded_outputs.py`:** a same-box handoff.
- When the co-located video worker asks (`stash_local_outputs`, set only
where `LOCAL_ENCODED_OUTPUTS_DIR` exists), the encoder keeps local
copies of the finals, keyed by blob path.
- The video worker takes those instead of downloading them back out of
GCS. Without this, the move would *add* ~400 MB/job of GCS egress.
  - Copies are made off the event loop and purged after 6 h.
  - No change on GCE or Cloud Run.
- **`video-worker-env.py` (box, every boot):**
- Mirrors the **live** `video-encoding-job` env, with secrets resolved,
so nothing is hand-copied and nothing drifts.
- Runs as the job's identity, `karaoke-backend@`, via a second WIF
binding (Pulumi `aws-encoding-worker-wif-backend-user`).
- On failure it writes no env file, so `/run-worker` answers 503 and the
Cloud Run job is used.
- **`WorkerService._trigger_video_worker_on_aws`:** checks the flag and
that the AWS worker ranks first, ensures it's running, waits for health,
then POSTs `/run-worker`. Returns False on any doubt.
- **Also:** `startup-aws.sh` creates the backend credential config and
runs the env helper; CI uploads `video-worker-env.py`;
`worker_code_paths.txt` now gates `local_encoded_outputs.py`.

## Rollout (needs `/gcp-admin`)
1. **Before merge:** targeted `pulumi up` of the backend WIF binding.
It's additive.
2. **After stage B of Phase 1** (AWS worker preferred, timings
verified): stop/start the box once so the new `startup-aws.sh` writes
the env, then set `aws_video_worker: true`. Set it to `false` to roll
back.

## Testing
- **27 new tests:**
- handoff stash/take/purge, path-escape guard, and the per-request stash
flag;
- `/run-worker`: disabled, bad module, dedupe, active immediately, spawn
args/env, failure log tail, wheel-not-ready, safe start, unsafe ids;
  - env builder;
- the trigger's AWS branch: off, not first, happy path, didn't start,
refusals, errors.
- **Full backend + unit suites:** no new failures (the 13 local failures
are identical on main).
- **Local CodeRabbit:** 5 findings, all fixed. The code-paths gate test
also caught a missing worker path, now fixed.

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVSR5qgwsxTQtvGimKF

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:02:42 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 20b957958c infra(aws): encoding worker on-demand c7a.4xlarge; stage A status (#1239)
Follow-up to #1236.

- **Instance type:** the AWS encoding worker is now **on-demand
c7a.4xlarge** instead of Spot c7a.8xlarge.
- The Spot create failed with `InsufficientInstanceCapacity`, and Spot
placement scores were 1-3/10 for c7a/c7i/c6a/c8a 4-8xlarge across
us-east-1/2.
- A worker that stops and starts on demand has to win capacity on every
start.
- Cost is ~$82/mo of credits. The 4xlarge matched or beat GCE in the
replay benchmark.
- **Already applied** (instance `i-0c21505d7017356bb`, EIP
3.128.70.236).
- **Docs and plan:** stage A status, plus the live end-to-end test
through the worker HTTP API (render 117s; all 9 outputs; portrait SSIM
0.993, the only difference being anti-aliasing of the header text).

The only code-file change is a comment in
`encoding_worker_preference.py`, so there is no version bump.

No local CodeRabbit run (IaC and docs only), so the bot review stays on.

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

https://claude.ai/code/session_012RYLVSR5qgwsxTQtvGimKF

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

## Summary by CodeRabbit

* **Operational Updates**
* The AWS encoding worker now runs on an on-demand `c7a.4xlarge`
instance rather than a Spot `c7a.8xlarge`.
* The worker stops when the operating system shuts down, while its root
volume is preserved.
* If AWS cannot start the worker because capacity is insufficient, it is
temporarily deprioritized for 15 minutes, allowing processing to fall
back to GCE.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:16:19 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 4c648bd16c infra: grant Google Play Pub/Sub Publisher on the RTDN topic (#1238)
## Summary
Google Play real-time developer notifications (RTDN) for the mobile app
(`com.nomadkaraoke.mobile`) publish to the Pub/Sub topic
`Play-Store-Notifications`. RevenueCat pulls them through its own
subscription (`RevenueCat-Subscriber-appc2bb515ecd`) and calls gen's
`/webhooks/revenuecat`.

The topic was set in Play Console > Monetization setup on 2026-10-31,
but **Send test notification** failed. The topic has no
`roles/pubsub.publisher` grant for
`google-play-developer-notifications@system.gserviceaccount.com`.

## Changes
- New `infrastructure/modules/play_rtdn.py`: one non-authoritative
`gcp.pubsub.TopicIAMMember` (Publisher for Play's service account). The
topic and the RevenueCat subscription were created by RevenueCat's
"Connect to Google" flow and stay unmanaged.
- Wired into `infrastructure/__main__.py`.

## Testing
- `pulumi preview --stack prod --diff --target …play-rtdn-publisher`
(read-only ADC): `+ 1 to create, 292 unchanged`, with exactly the
member, role and topic above.
- CodeRabbit CLI: no findings.
- Infra-only change, so no version bump.

## Apply
CI never runs Pulumi. Apply **before merging**, through `/gcp-admin`:
`scripts/gcp-admin pulumi up --stack prod --target
'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:pubsub/topicIAMMember:TopicIAMMember::play-rtdn-publisher'`
Then resend Play's test notification.

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVUH7B2p5YotvzcFsAR

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:38:58 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 ce57b4b598 fix(review): Tap To Sync partial pass keeps word order; local stack never reaches prod (v0.288.1) (#1237)
## Summary

### 1. Tap To Sync: a pass that stops before the last word
(customer-facing)
If a pass stopped before the last word (auto-stop about a second after
the line end, or the user pressing Stop), the untapped words after the
last tapped one kept their **old** timings, and those could now start
*before* the last tapped word. On gen's fake fixture line ("Nothing here
was ever transcribed", words 15.5 to 19.5, next line at 20.0), taps at
16.0, 17.2, 18.4 and 19.6 followed by auto-stop left "ever" at 19.6 and
"transcribed" at a stale 18.74 to 19.5. The two words were out of order,
and the video rendered them out of order.

- `frontend/hooks/useManualSync.ts`: new pure
`commitPartialSyncPass(words, synced)` runs in `cleanupManualSync`,
which is both the auto-stop path and the Stop toggle. It clears (sets
start/end to null) every untapped word after the last tapped one that
starts before it, then caps the last tapped word's end before the next
still-timed word in the line. The existing untimed-lyrics guard then
blocks finishing and points the user at those words. This is the same
rule as nomad-mobile's review-core `commitTapSync`
(`packages/review-core/src/tapSync.ts`, branch
`feat/sess-20261030-1930-e2e-health`). It uses the hook's existing
`syncedIndicesRef`.
- Backend backstop, `backend/services/timing_sanitizer.py`
`sanitize_corrections`: within a line, a word that starts before the
previous word's **start** is now treated like any other invalid start.
Small overlaps (a start a few ms before the previous word's end, common
in AI transcriptions) are left exactly as on main, so they get no move,
no WARNING and no edit-modal toast. It is **moved** to the previous
word's end, not cleared. I chose moving because that is how the module
already repairs bad or missing starts, because a cleared word would just
be refilled at prev_end on the next sanitize, and because nulls would
crash the render (`find_missing_timings` only guards the preview). The
module logs one aggregated `WARNING` per submission (never ERROR, since
this is an expected and repaired condition).
- `frontend/lib/lyrics-review/sanitizeWordTimings.ts` (the frontend
mirror, run when the edit modal opens) applies the same ordering rule,
with the same exemption for small overlaps.

### 2. The local stack must not reach production
nomad-mobile's E2E runs gen web inside an Android emulator's Chrome.
- `components/google-analytics.tsx`: GA (`G-D0E63LB9FY`) is no longer
loaded when the page host is localhost, 127.0.0.1 or 10.0.2.2. The check
runs at runtime after mount, so it also covers CI, and the server render
and first client render match.
- `lib/api/autoCorrect.ts` and `lib/api/customLyrics.ts` now use
`API_BASE_URL` from `lib/api.ts` instead of `NEXT_PUBLIC_API_BASE ??
'https://api.nomadkaraoke.com'`. That env var is set nowhere. A local
page now calls its own backend through relative URLs, so it never sends
its bearer token to production.
- New `lib/local-host.ts` is the single list of local hostnames, shared
by `lib/api.ts` and GA. `lib/api.ts` now also treats 10.0.2.2 as local.
- `scripts/local-stack.sh` backend_env: blank `FLACFETCH_API_URL=` and
`FLACFETCH_API_KEY=`, so direnv can't point the local stack at the real
flacfetch.

Version is bumped to 0.288.1.

## Testing
Each change had a failing test written first.
- Frontend jest (hook, sanitizer, edit modals, GA, API clients,
api/local-mode, auto-correct, custom lyrics): 13 suites, **150 passed**.
- New tests: 3 partial-pass hook tests (auto-stop, Stop, and the
keep-and-cap case), 2 sanitizer tests (the stale-word move, and a 20 ms
overlap left untouched), 4 GA tests, and 8 API-base tests (local hosts
use relative URLs, the production host uses the production API).
- Backend pytest: `test_timing_sanitizer.py` +
`test_jobs_corrections.py` **20 passed** (3 new, including a 20 ms
overlap that is left untouched), and `test_routes_review.py` **114
passed**.
- `customLyrics.test.ts`'s AbortSignal test now asserts that the
caller's abort reaches fetch, not that the signal object is identical. A
relative URL makes `apiFetch` manage the request and wrap the signal.

## Notes
- The web hook has no view of the next line, so the cap only uses words
in the same line. The backend sanitizer and segment bounds handle the
rest.
- The render-time `SegmentResizer._sanitize_segment_timings` is
unchanged (it clamps to the window only).

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

https://claude.ai/code/session_012RYLVSLS3eVDqPctfYBMTt



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

## Summary by CodeRabbit

* **Bug Fixes**
* Improved lyric timing cleanup when recording or editing stops before
the final word. Out-of-order timings are corrected while small overlaps
are preserved, helping keep lyrics synchronized without changing valid
timings.
* Corrected out-of-order word timings during lyric cleanup and editing.
* **Improvements**
* Local app use now works more consistently across supported addresses,
including Android emulators, with API requests routed appropriately.
  * Analytics scripts are now omitted on local pages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 20:28:19 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 de5dfcd50d feat(encoding): AWS EC2 encoding worker as a pool candidate (v0.288.0) (#1236)
## Summary
Phase 1 of moving encoding to AWS. EC2 is paid for by the AWS Activate
credits (acct 790139457751, expiring 2028-10-31).
- **Plan:** `docs/archive/2026-10-29-aws-encoding-worker-plan.md`.
- **Benchmark** (3 real prod jobs replayed): an EC2 c7a.4xlarge matched
or beat GCE c4d-highcpu-16.

The EC2 box runs the **unchanged** `gce_encoding` worker service and
joins the existing candidate pool as `provider: aws`. The existing
failover, active override, lost-job detection and stockout cooldowns all
apply to it as they are.

## Changes
- **`backend/services/aws_encoding_compute.py` (new):**
`AwsComputeAdapter` looks to the manager like the
`compute_v1.InstancesClient` methods it uses.
  - EC2 states map to GCE statuses.
  - EC2 capacity errors are added to `CAPACITY_ERROR_CODES`.
  - A missing instance raises `NotFound`.
- Controller credentials come from Secret Manager
`aws-encoding-controller-credentials`.
- **`EncodingWorkerManager`:**
- `_compute_for(vm)` sends AWS VMs to the adapter; the GCE paths are
untouched.
- A shared `parse_fallback_vms` passes `provider`/`instance_id`/`region`
through.
- `ranked_candidates()` is used by both the encode path and the warmups.
- `ensure_preferred_running()` behaves **exactly like
`ensure_primary_running` whenever the GCE primary ranks first**, which
is today's case.
  - An AWS control-plane fault fails over to the GCE candidates.
- **Ranking:** `SPEED_RANK["c7a"] = 90`, so AWS is the last resort by
default. Firestore `config/encoding-worker.speed_rank_overrides =
{"c7a": 5}` makes it preferred, with no deploy.
- **Isolation from GCE-only tooling:**
  - The override now records `active_override_provider`.
- The CI blue-green deploy, `deploy_promote` and the idle Cloud Function
all ignore the AWS worker; it hot-updates its wheel per job.
  - A GCE promotion clears any stale provider tag.
- **Worker:**
- Uses `gcloud storage` on AWS, because gsutil can't use WIF credential
files. GCE keeps gsutil.
  - `infrastructure/encoding-worker/aws/` adds:
    - `provision.sh`, as EC2 user-data;
    - `startup-aws.sh`, uploaded by CI;
- `idle-watchdog.py`, an idle self-stop that runs as its own systemd
timer.
- **Infra (GCP), already applied with `/gcp-admin`:**
- The WIF pool `aws-encoding`, plus an AWS provider that only admits the
`nomad-encoding-worker` role, federated to `encoding-worker@`.
  - The secret `aws-encoding-controller-credentials`.
  - Preview and apply: 4 creates, 288 unchanged.
- **Infra (AWS):** a new Pulumi project `infrastructure/aws` (stack
`nomadkaraoke/prod`):
- the c7a.8xlarge **persistent Spot** worker, which stops on
interruption or shutdown;
  - an Elastic IP;
  - a security group on 8080 (API key, same as the GCE firewall);
  - the worker role with SSM;
  - a tag-scoped `nomad-encoding-controller` user.
- Preview: 10 creates. **I apply it after merge**, because the box
provisions from the deployed wheel and boot scripts.
- `boto3` is now an explicit dependency.
- CI also runs the `encoding_worker_idle` function tests, in the job
renamed "Infra - Cloud Function tests".

## Rollout (after merge)
1. **Stage A:** `pulumi up` the AWS stack. Store the controller key in
the secret, then add the worker's entry to
`encoding-worker-fallback-vms`. It's inert unless both c4d and c2d stock
out.
2. **Stage B:** a supervised `speed_rank_overrides {"c7a": 5}` window.
Run real jobs, then compare timings and outputs, including a visual
check of the portrait video.
3. **Stage C:** keep it preferred. After a clean week, delete the c4d
pair.

Phase 2, running distribution (Dropbox/YouTube/Drive uploads) from AWS,
follows in a separate PR.

## Testing
- **New tests:**
- adapter: botocore `Stubber`, covering the state map, capacity and
NotFound handling;
  - manager routing and ranking with overrides;
  - `ensure_preferred_running` branches;
  - failover on an AWS control-plane fault;
  - provider tagging;
  - deploy_promote exclusions;
  - the idle function skipping AWS;
  - watchdog decisions;
  - the gcs CLI choice.
- **Updated** the candidate and warmup-route tests to the new seams.
- **Full backend + unit suites** have no new failures. The local
emulator and cross-suite failures are identical on main.
- **Local CodeRabbit:** 2 findings, both fixed (failover on AWS faults;
stale provider tag).

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVSR5qgwsxTQtvGimKF

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:42:35 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 65940c6f57 fix(local-stack): decide partner calls go to local decide, never production (#1235)
The local stack's backend env had no `KARAOKE_DECIDE_API_URL`, so gen's
decide partner client (account deletion) used the production default and
sent `DELETE /api/partner/gen/users` to decide.nomadkaraoke.com.
Production answered 401, because the local secret differs, so nothing
was touched. It surfaced in nomad-mobile's E2E account-1 flow. The fix
defaults it to decide's local stack on :8030, and callers can still
override it. Script only, no runtime code.

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

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

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

## Summary by CodeRabbit

* **Configuration**
* The local environment can now use a custom karaoke decision service
address, with a default address provided when none is configured.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:34:54 -04:00
159 changed files with 4808 additions and 236 deletions

No files matched your search

+28 -5
View File
@@ -87,7 +87,7 @@ jobs:
# ============================================
runner-manager-tests:
name: "Infra - runner_manager function tests"
name: "Infra - Cloud Function tests"
runs-on: ubuntu-latest
needs: changes
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.infra == 'true' || needs.changes.outputs.deps == 'true')
@@ -100,6 +100,9 @@ jobs:
# google.cloud namespace package is genuinely installed.
- run: pip install pytest -r infrastructure/functions/runner_manager/requirements.txt
- run: pytest infrastructure/functions/runner_manager -q -p no:cacheprovider -o addopts=""
- run: pip install -r infrastructure/functions/encoding_worker_idle/requirements.txt
# Separate invocation: both functions have a top-level `main` module.
- run: pytest infrastructure/functions/encoding_worker_idle -q -p no:cacheprovider -o addopts=""
frontend-lint:
name: "Frontend - Lint (Rules of Hooks)"
@@ -720,11 +723,13 @@ jobs:
restore-keys: |
venv-backend-hosted-${{ runner.os }}-py3.13-
- name: Set up Java 21 (required by Firestore emulator)
# The emulator package is unpinned (latest from apt), and 592.0.0 is compiled for
# Java 25 (class file 69): older runtimes fail with UnsupportedClassVersionError.
- name: Set up Java 25 (required by Firestore emulator)
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "21"
java-version: "25"
- name: Install Firestore emulator
run: |
@@ -831,11 +836,13 @@ jobs:
restore-keys: |
venv-backend-hosted-${{ runner.os }}-py3.13-
- name: Set up Java 21 (required by Firestore emulator)
# The emulator package is unpinned (latest from apt), and 592.0.0 is compiled for
# Java 25 (class file 69): older runtimes fail with UnsupportedClassVersionError.
- name: Set up Java 25 (required by Firestore emulator)
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "21"
java-version: "25"
- name: Install Firestore emulator + ffmpeg
run: |
@@ -1399,6 +1406,13 @@ jobs:
echo "Uploading startup.sh..."
gsutil cp infrastructure/encoding-worker/startup.sh \
"${BUCKET}/encoding-worker/startup.sh"
# AWS encoding worker (EC2): its startup + idle self-stop, fetched on boot
gsutil cp infrastructure/encoding-worker/aws/startup-aws.sh \
"${BUCKET}/encoding-worker/startup-aws.sh"
gsutil cp infrastructure/encoding-worker/aws/idle-watchdog.py \
"${BUCKET}/encoding-worker/idle-watchdog.py"
gsutil cp infrastructure/encoding-worker/aws/video-worker-env.py \
"${BUCKET}/encoding-worker/video-worker-env.py"
# 4. Write version manifest for verification
echo "Writing version manifest..."
@@ -1425,6 +1439,15 @@ jobs:
print("::error::Encoding worker config not found in Firestore")
raise SystemExit(1)
data = doc.to_dict()
if (data.get("active_override_provider") or "").lower() == "aws":
# The AWS encoding worker (EC2) is serving by preference. This
# GCE blue-green flow can't gcloud-start/stop it and must not
# clear its override; it picks up the new wheel on its next job.
# Treat it as "no GCE override" so every step below ignores it.
print(f"AWS worker {data.get('active_override_vm')} is the serving override; "
"leaving it untouched by the GCE blue-green deploy")
for key in ("active_override_vm", "active_override_ip", "active_override_zone"):
data[key] = None
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
for key in ["primary_vm", "primary_ip", "primary_version",
"secondary_vm", "secondary_ip",
+6
View File
@@ -171,6 +171,12 @@ gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke
For job stuck at `encoding` status, see [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md).
**AWS encoding worker** (`aws-encoding-worker-1`, EC2 c7a.4xlarge on-demand, us-east-2) is a pool
candidate too (`provider: aws` in `encoding-worker-fallback-vms`): last resort by default,
preferred when Firestore `config/encoding-worker.speed_rank_overrides = {"c7a": 5}`. Not
blue-green deployed, idle-stops itself, shell via SSM, logs are on the box (journald). See
`infrastructure/aws/README.md`.
### What Doesn't Work
- `gcloud auth print-identity-token` - Wrong token type for internal endpoints
- Cloud Tasks without proper service account - Gets 401 from Cloud Run
+10
View File
@@ -19,6 +19,7 @@ from backend.services.error_monitor.frontend_ingestion import (
RateLimiter,
build_pattern_data,
is_bot_user_agent,
is_host_app_injection_error,
is_opaque_script_error,
sanitize_url,
)
@@ -90,6 +91,15 @@ def report_client_error(payload: ClientErrorPayload, request: Request) -> Client
)
return ClientErrorResponse(pattern_id="opaque-script-error-ignored", is_new=False)
# A script the in-app browser's host app injected (Zalo), not our code.
if is_host_app_injection_error(payload.message, payload.user_agent):
logger.info(
"frontend_crash_ignored_host_app_injection url=%s source=%s",
sanitize_url(payload.url),
payload.source,
)
return ClientErrorResponse(pattern_id="host-app-injection-ignored", is_new=False)
report = FrontendErrorReport(
message=payload.message,
stack=payload.stack,
+2 -2
View File
@@ -51,7 +51,7 @@ async def warmup_encoding_worker(
_auth: Tuple[str, str] = Depends(require_review_auth),
manager=Depends(get_worker_manager),
):
"""Start the primary encoding worker VM if it's stopped.
"""Start the preferred encoding worker if it's stopped (normally the GCE primary).
Called on lyrics-review page load so the VM is warm by the time the
reviewer previews a render. ``job_id`` scopes auth to the job under review.
@@ -63,7 +63,7 @@ async def warmup_encoding_worker(
# WHOLE instance for ~11s on every review-page open with a cold VM,
# stalling that same page's audio/lyrics requests behind it
# (2026-09-19, follow-up to the concurrent-load investigation).
result = await asyncio.to_thread(manager.ensure_primary_running)
result = await asyncio.to_thread(manager.ensure_preferred_running)
if result["started"]:
logger.info(f"Started encoding worker VM: {result['vm_name']}")
return result
+46 -7
View File
@@ -45,6 +45,7 @@ from backend.services.tracing import add_span_attribute
from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
is_bot_block_error,
)
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
@@ -56,6 +57,9 @@ def _is_youtube_url(url: str) -> bool:
return any(domain in url.lower() for domain in [
'youtube.com', 'youtu.be', 'youtube-nocookie.com'
])
# Wait before retrying a bot-blocked URL download, so a cookie re-export can finish.
BOT_BLOCK_RETRY_DELAY_SECONDS = 30
router = APIRouter(tags=["jobs"])
@@ -1975,6 +1979,25 @@ def validate_job_url(
return ValidateUrlResponse(supported=True)
async def _download_url_with_bot_block_retry(download_service, **download_kwargs) -> str:
"""Download a URL, retrying once if YouTube bot-blocks flacfetch's session.
flacfetch already asks its credential keeper for fresh cookies and retries before
reporting a bot block. The delay here covers the case where that re-export was
still in progress or on cooldown.
"""
try:
return await download_service.download(**download_kwargs)
except YouTubeDownloadError as e:
if not is_bot_block_error(e):
raise
logger.warning(
f"URL download bot-blocked, retrying in {BOT_BLOCK_RETRY_DELAY_SECONDS}s: {e}"
)
await asyncio.sleep(BOT_BLOCK_RETRY_DELAY_SECONDS)
return await download_service.download(**download_kwargs)
@router.post("/jobs/create-from-url", response_model=CreateJobFromUrlResponse)
async def create_job_from_url(
request: Request,
@@ -2032,6 +2055,15 @@ async def create_job_from_url(
youtube_service = get_youtube_download_service()
availability = await youtube_service.check_availability(body.url)
# flacfetch starts a cookie re-export when this check gets bot-blocked,
# so give it time and check again before turning the user away.
if availability and availability.get("is_bot_blocked"):
logger.warning(
f"Availability check bot-blocked, rechecking in {BOT_BLOCK_RETRY_DELAY_SECONDS}s: {body.url}"
)
await asyncio.sleep(BOT_BLOCK_RETRY_DELAY_SECONDS)
availability = await youtube_service.check_availability(body.url)
if availability and not availability.get("available"):
error_msg = availability.get("error", "This video is not available")
@@ -2046,12 +2078,7 @@ async def create_job_from_url(
elif availability.get("is_removed"):
detail = "This YouTube video has been removed and cannot be downloaded."
elif availability.get("is_bot_blocked"):
detail = (
"We're temporarily unable to access YouTube to download this video — "
"YouTube is asking our server to verify it's not a bot. "
"Please try again in a few minutes, or use Audio Search to find this song "
"from another source."
)
detail = t(locale, "audioSearch.youtubeBotBlocked")
elif availability.get("is_age_restricted"):
detail = "This YouTube video is age-restricted and cannot be downloaded."
else:
@@ -2209,7 +2236,8 @@ async def create_job_from_url(
logger.info(f"Downloading audio from URL via flacfetch: {body.url}")
try:
download_service = get_youtube_download_service()
audio_gcs_path = await download_service.download(
audio_gcs_path = await _download_url_with_bot_block_retry(
download_service,
url=body.url,
job_id=job_id,
artist=artist,
@@ -2236,6 +2264,17 @@ async def create_job_from_url(
)
except YouTubeDownloadError as e:
if is_bot_block_error(e):
# Our problem, not the user's or the video's: don't show them yt-dlp's
# advice about cookies. fail_job raises the alert, so WARNING here.
logger.warning(f"URL download still bot-blocked after retry: {e}")
detail = t(locale, "audioSearch.youtubeBotBlocked")
job_manager.fail_job(
job_id,
detail,
error_details={"code": "youtube_bot_block", "raw_error": str(e)},
)
raise HTTPException(status_code=500, detail=detail)
logger.error(f"URL download failed: {e}")
job_manager.fail_job(job_id, f"Download failed: {e}")
raise HTTPException(
+22 -3
View File
@@ -1085,6 +1085,14 @@ def get_review_data(
}
def _job_not_in_review_conflict(locale: str, status: Any) -> HTTPException:
"""409 for a review request on a job that isn't in review."""
return HTTPException(
status_code=409,
detail=t(locale, "jobs.jobNotInReviewState", status=getattr(status, "value", status)),
)
@router.post("/{job_id}/start-review")
def start_review(
job_id: str,
@@ -1109,10 +1117,21 @@ def start_review(
# Idempotent: concurrent/duplicate opens (React double-mount, double-tap, two
# tabs) must not fail with "in_review -> in_review". Already in review == success,
# and the one-time side effects (record_review_started) are not repeated.
# A job past review (e.g. a stale "review lyrics" push tapped on a finished song)
# is the client's to handle: 409, no transition attempted, nothing logged at ERROR.
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise _job_not_in_review_conflict(locale, job.status)
was_awaiting = job.status == JobStatus.AWAITING_REVIEW
result = ensure_in_review(
job_manager, job_id, job.status, "User started reviewing lyrics"
)
try:
result = ensure_in_review(
job_manager, job_id, job.status, "User started reviewing lyrics"
)
except InvalidStateTransitionError:
# Lost the race: the auto-approver (or another worker) moved the job on
# between our read and the transition.
current = job_manager.get_job(job_id)
raise _job_not_in_review_conflict(locale, current.status if current else job.status)
if result == "refused":
raise HTTPException(status_code=400, detail=t(locale, "jobs.reviewCannotStart"))
if result == "started" and was_awaiting:
+63 -8
View File
@@ -32,6 +32,7 @@ from google.cloud.firestore_v1.field_path import FieldPath
from backend.models.job import JobStatus
from backend.models.review_session import ReviewSession, ReviewSessionSummary
from backend.services.job_manager import JobManager
from backend.exceptions import InvalidStateTransitionError
from backend.services.review_state import ensure_in_review
from backend.services.firestore_service import FirestoreService
from backend.services.storage_service import StorageService
@@ -45,7 +46,7 @@ from backend.services.job_logging import job_log_context, JobLogger
from backend.services.tracing import create_span, add_span_attribute, add_span_event
from backend.services.auto_approval.instrumental import with_unified_recommendation
from backend.services.encoding_service import get_encoding_service
from backend.api.dependencies import require_auth, require_review_auth
from backend.api.dependencies import require_admin, require_auth, require_review_auth
from backend.utils.stems import vocals_stem_path as _vocals_stem_path
from backend.services.auth_service import UserType
from backend.config import get_settings
@@ -909,6 +910,10 @@ async def get_correction_data(
# "evidenced" gaps and offers the reference lines for insertion.
corrections_data['vocal_gaps'] = job.state_data.get('vocal_gaps') or None
# Admin "perfectly synced" mark (word-timing reference set), so a re-review
# shows the existing mark and can revoke it.
corrections_data['sync_reference'] = job.state_data.get('sync_reference') or None
# Per-screen skip (C1): tell the frontend whether each review half is
# confidently auto-resolved, so it can skip the instrumental screen (or the
# lyrics screen). Derived from the stored auto-approval verdict + the job's
@@ -928,13 +933,23 @@ async def get_correction_data(
if not replay and job.status == JobStatus.AWAITING_REVIEW:
# Idempotent: iOS/in-app browsers fire two concurrent loads; the loser
# must not 500 on "in_review -> in_review" nor repeat one-time side effects.
started = "started" == await asyncio.to_thread(
ensure_in_review,
job_manager,
job_id,
job.status,
"User opened combined review interface",
)
try:
started = "started" == await asyncio.to_thread(
ensure_in_review,
job_manager,
job_id,
job.status,
"User opened combined review interface",
)
except InvalidStateTransitionError:
# Lost the race: the auto-approver moved the job on after the status
# gate above. Not a load failure, so 409 rather than the 500 below.
current = await asyncio.to_thread(job_manager.get_job, job_id)
status = current.status if current else job.status
raise HTTPException(
status_code=409,
detail=t("en", "review.reviewNotReady", status=getattr(status, "value", status)),
)
if started:
# Set by require_review_auth (absent for review-token links).
auth_state = getattr(request, "state", None)
@@ -974,6 +989,8 @@ async def get_correction_data(
logger.info(f"Job {job_id}: Serving correction data (replay={replay}) for combined review")
return corrections_data
except HTTPException:
raise
except Exception as e:
logger.error(f"Job {job_id}: Error loading corrections: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
@@ -1327,6 +1344,44 @@ async def complete_review(
}
class SyncReferenceRequest(_PydBaseModel):
verified: bool
notes: Optional[str] = None
@router.post("/{job_id}/sync-reference")
async def set_sync_reference(job_id: str, body: SyncReferenceRequest, auth_result=Depends(require_admin)):
"""Admin-only: mark this job's reviewed word timing as "perfectly synced".
Verified jobs form the reference set for word-timing training and evaluation
(full-auto v2). A tick means the admin is confident the sync is right, from a
listen or a confident spot-check; jobs never marked are treated as unverified.
"""
from datetime import datetime, timezone
job_manager = JobManager()
job = await asyncio.to_thread(job_manager.get_job, job_id)
if not job:
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# A "verified" mark vouches for reviewed timing, so it needs saved review output.
lyrics_urls = ((job.file_urls or {}).get("lyrics") or {}) if isinstance(job.file_urls, dict) else {}
if body.verified and not lyrics_urls.get("corrections_updated"):
# Older jobs may have the file without the file_urls pointer (same fallback
# get_correction_data uses).
direct = f"jobs/{job_id}/lyrics/corrections_updated.json"
if not await asyncio.to_thread(StorageService().file_exists, direct):
raise HTTPException(status_code=409, detail="No reviewed lyrics saved yet; save the review first")
record = {
"verified": body.verified,
"by": auth_result.user_email or str(auth_result.user_type),
"at": datetime.now(timezone.utc).isoformat(),
"notes": (body.notes or "").strip()[:2000] or None,
}
await asyncio.to_thread(job_manager.update_state_data, job_id, "sync_reference", record)
logger.info(f"Job {job_id}: sync_reference verified={body.verified} by {record['by']}")
return {"status": "success", "sync_reference": record}
def _fake_complete_failure_hook(job_id: str) -> None:
"""Raise a 503 once when the job's user set ``review_complete_fail_once`` (fake workers only)."""
from backend.services.fake_workers.config import consume_review_complete_failure
+37
View File
@@ -9,6 +9,7 @@ import logging
import threading
import time
from contextlib import asynccontextmanager
from typing import Any
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
@@ -95,6 +96,9 @@ _LAZY_ROUTE_IMPORTS = (
"flacfetch.core.manager",
"flacfetch.downloaders.youtube",
"yt_dlp",
# starlette/middleware/base.py picks the anyio backend on the first request:
# 17.3s on the loop with 18 requests in flight (2026-10-30).
"anyio._backends._asyncio",
)
@@ -137,6 +141,29 @@ def _warm_route_contexts(application: FastAPI) -> int:
return count
def _warm_middleware_stack(application: Any) -> None:
"""Send one request through the app, so the first user's request isn't what builds
the middleware stack and runs its first-use imports on the loop.
Blocking: runs its own event loop, so call it from a worker thread. /api/health is
exempt from the edge lock, skips the audit log and touches no storage. Best-effort.
"""
import httpx
async def _request() -> None:
transport = httpx.ASGITransport(app=application)
async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
await client.get("/api/health")
start = time.time()
try:
asyncio.run(_request())
except Exception as e: # noqa: BLE001 - warmup must never block startup
logger.warning(f"Middleware warm request failed (stack builds on first request): {e}")
return
logger.info(f"Warmed middleware stack in {time.time() - start:.2f}s")
def _warm_route_contexts_safely(application: FastAPI) -> None:
start = time.time()
try:
@@ -243,6 +270,16 @@ async def lifespan(app: FastAPI):
f"Route-context warmup exceeded {LAZY_ROUTE_IMPORT_TIMEOUT_S}s; continuing startup"
)
# Same reason, for what only the first request through the middleware touches.
try:
await asyncio.wait_for(
asyncio.to_thread(_warm_middleware_stack, app), timeout=LAZY_ROUTE_IMPORT_TIMEOUT_S
)
except asyncio.TimeoutError:
logger.warning(
f"Middleware warmup exceeded {LAZY_ROUTE_IMPORT_TIMEOUT_S}s; continuing startup"
)
# NLP model / credential warmup runs in the background so it doesn't gate
# readiness — Cloud Run holds all routed requests until lifespan startup
# returns, and these preloads were ~7.5s of the ~16s cold start.
+2 -1
View File
@@ -261,7 +261,8 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
payload["hold_for_audio"] = hold_for_audio
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
return {"outcome": "review", "overall_auto": verdict.overall_auto,
"blockers": blockers, "hold_for_audio": hold_for_audio}
"blockers": blockers, "hold_for_audio": hold_for_audio,
"ai_suggestions_available": ai_suggestions is not None}
# ---- ENFORCE: complete the review exactly like a human would ----
# The status gate above used a snapshot read. Re-read now so a human who
@@ -70,6 +70,9 @@ async def route_after_scoring(
from backend.services.job_manager import JobManager
job_manager = job_manager or JobManager()
auto_result = await _rescore_if_suggestions_were_missing(job_id, auto_result, job_log)
if auto_result.get("outcome") in ("auto_completed", "wrong_status"):
return str(auto_result["outcome"])
if not auto_result.get("hold_for_audio"):
await enter_human_review(job_id, job_log, job_manager)
return "review"
@@ -91,6 +94,43 @@ async def route_after_scoring(
return "released_elsewhere"
async def _rescore_if_suggestions_were_missing(
job_id: str, auto_result: Dict[str, Any], job_log: Optional[logging.Logger] = None
) -> Dict[str, Any]:
"""Score again if the first pass ran before the AI suggestions landed.
Lyrics finish moments before the proactive auto-correct, and without its
suggestions the lyrics score "needs review". Opening review on that verdict
sent the customer a "review your lyrics" push, and the audio worker's re-score
then auto-approved the job minutes later (4 of 5 auto-approved jobs,
2026-10-20..11-03). Returns the verdict to route on; the original one when
suggestions can't be had or the re-score didn't reach a verdict.
"""
if auto_result.get("outcome") != "review" or auto_result.get("ai_suggestions_available") is not False:
return auto_result
from backend.config import get_settings
from backend.services.auto_approval.executor import maybe_auto_complete_review
if not getattr(get_settings(), "auto_correct_proactive_enabled", False):
return auto_result
try:
from backend.workers.auto_correct_worker import process_proactive_auto_correct
await process_proactive_auto_correct(job_id) # bounded (180s), joins a run in flight
except Exception as e: # noqa: BLE001 best-effort, like ensure_and_pre_apply
logger.warning(f"[job:{job_id}] Waiting for AI suggestions before review failed: {e}")
return auto_result
rescored = await maybe_auto_complete_review(job_id, trigger="screens_worker")
outcome = rescored.get("outcome")
logger.info(f"[job:{job_id}] Re-scored once AI suggestions were ready: {outcome} "
f"(hold_for_audio={rescored.get('hold_for_audio', False)})")
if outcome == "auto_completed" and job_log:
job_log.info("Auto-approved once AI suggestions were ready: review skipped")
return rescored if outcome in ("review", "auto_completed", "wrong_status") else auto_result
async def release_audio_hold(job_id: str, reason: str) -> Optional[str]:
"""Release a held job (audio worker / stuck-job sweep).
+167
View File
@@ -0,0 +1,167 @@
"""EC2 adapter for the AWS encoding worker.
The AWS worker (an EC2 Spot instance running the same ``gce_encoding`` HTTP
service) is just another candidate in the encoding-worker pool. Rather than
teach every caller about EC2, this module mimics the slice of
``google.cloud.compute_v1.InstancesClient`` that ``EncodingWorkerManager`` uses
(``get`` / ``start`` / ``stop``), so the manager routes AWS VMs here and the
GCE code paths stay untouched:
- EC2 states map to GCE statuses (``running`` → ``RUNNING``, ``stopped`` →
``TERMINATED``, …) so the existing RUNNING/STAGING/stopped checks just work.
- ``start`` returns an operation object shaped like a compute ExtendedOperation
(``result()``, ``error_code``, ``error_message``); EC2 capacity errors surface
as codes in ``CAPACITY_ERROR_CODES`` so stockout cooldowns apply unchanged.
- A missing instance raises ``google.api_core.exceptions.NotFound``, which the
manager already treats as "skip this candidate".
Credentials: an IAM user limited to Start/Stop/Describe on instances tagged
``Project=nomad-encoding``, stored as JSON ``{"access_key_id", "secret_access_key"}``
in Secret Manager ``aws-encoding-controller-credentials`` (env
``AWS_ENCODING_CONTROLLER_CREDENTIALS`` overrides, for tests/local runs).
"""
from __future__ import annotations
import json
import logging
import os
import threading
from dataclasses import dataclass
from typing import Any, Dict, Optional
from google.api_core import exceptions as gcp_exceptions
logger = logging.getLogger(__name__)
CREDENTIALS_SECRET = "aws-encoding-controller-credentials"
CREDENTIALS_ENV = "AWS_ENCODING_CONTROLLER_CREDENTIALS"
# EC2 instance state → GCE instance status.
_EC2_TO_GCE_STATUS = {
"pending": "STAGING",
"running": "RUNNING",
"stopping": "STOPPING",
"stopped": "TERMINATED",
"shutting-down": "STOPPING",
"terminated": "TERMINATED",
}
@dataclass(frozen=True)
class AwsVm:
"""Where an AWS worker lives. Built from a fallback-pool entry."""
instance_id: str
region: str
@dataclass
class _Instance:
status: str
class AwsStartOperation:
"""Duck-types a compute ExtendedOperation for ``_wait_for_compute_operation``."""
def __init__(self, run):
self._run = run
self.error_code = ""
self.error_message = ""
def result(self, timeout: Optional[float] = None) -> None:
from botocore.exceptions import ClientError
try:
self._run()
except ClientError as e:
err = e.response.get("Error", {})
self.error_code = err.get("Code", "") or "ClientError"
self.error_message = err.get("Message", "") or str(e)
def _load_credentials(project_id: str) -> Dict[str, str]:
raw = os.environ.get(CREDENTIALS_ENV)
if not raw:
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
name = f"projects/{project_id}/secrets/{CREDENTIALS_SECRET}/versions/latest"
raw = client.access_secret_version(name=name).payload.data.decode("utf-8")
creds = json.loads(raw)
return {"access_key_id": creds["access_key_id"], "secret_access_key": creds["secret_access_key"]}
class AwsComputeAdapter:
"""``get``/``start``/``stop`` for registered AWS worker VMs, by VM name."""
def __init__(self, vms: Dict[str, AwsVm], project_id: str = "nomadkaraoke", client_factory=None):
self._vms = dict(vms)
self._project_id = project_id
self._client_factory = client_factory
self._clients: Dict[str, Any] = {}
self._lock = threading.Lock()
def handles(self, vm_name: str) -> bool:
return vm_name in self._vms
def _client(self, region: str):
with self._lock:
if region not in self._clients:
if self._client_factory is not None:
self._clients[region] = self._client_factory(region)
else:
import boto3
creds = _load_credentials(self._project_id)
self._clients[region] = boto3.client(
"ec2",
region_name=region,
aws_access_key_id=creds["access_key_id"],
aws_secret_access_key=creds["secret_access_key"],
)
return self._clients[region]
def _vm(self, instance: str) -> AwsVm:
vm = self._vms.get(instance)
if vm is None:
raise gcp_exceptions.NotFound(f"AWS worker {instance} is not registered")
return vm
def get(self, project: str = "", zone: str = "", instance: str = "") -> _Instance:
from botocore.exceptions import ClientError
vm = self._vm(instance)
try:
resp = self._client(vm.region).describe_instances(InstanceIds=[vm.instance_id])
except ClientError as e:
if e.response.get("Error", {}).get("Code", "").startswith("InvalidInstanceID"):
raise gcp_exceptions.NotFound(f"AWS worker {instance} ({vm.instance_id}) not found") from e
raise
reservations = resp.get("Reservations") or []
if not reservations or not reservations[0].get("Instances"):
raise gcp_exceptions.NotFound(f"AWS worker {instance} ({vm.instance_id}) not found")
state = reservations[0]["Instances"][0]["State"]["Name"]
return _Instance(status=_EC2_TO_GCE_STATUS.get(state, state.upper()))
def start(self, project: str = "", zone: str = "", instance: str = "") -> AwsStartOperation:
vm = self._vm(instance)
logger.info("Starting AWS worker %s (%s in %s)", instance, vm.instance_id, vm.region)
return AwsStartOperation(lambda: self._client(vm.region).start_instances(InstanceIds=[vm.instance_id]))
def stop(self, project: str = "", zone: str = "", instance: str = "") -> None:
vm = self._vm(instance)
logger.info("Stopping AWS worker %s (%s in %s)", instance, vm.instance_id, vm.region)
self._client(vm.region).stop_instances(InstanceIds=[vm.instance_id])
def aws_vms_from_pool(entries) -> Dict[str, AwsVm]:
"""``{vm_name: AwsVm}`` for the ``provider == "aws"`` entries of a fallback pool."""
vms: Dict[str, AwsVm] = {}
for e in entries or []:
if (e.get("provider") or "").lower() != "aws":
continue
name = e.get("vm") or e.get("vm_name")
if name and e.get("instance_id") and e.get("region"):
vms[name] = AwsVm(instance_id=e["instance_id"], region=e["region"])
return vms
+8 -3
View File
@@ -222,7 +222,9 @@ class CredentialManager:
message="Dropbox credentials refreshed successfully",
last_checked=datetime.utcnow()
)
else:
logger.error("Dropbox access token rejected and no refresh credentials are stored")
return CredentialCheckResult(
service="dropbox",
status=CredentialStatus.INVALID,
@@ -410,7 +412,9 @@ class CredentialManager:
return True
except Exception as e:
logger.error(f"Dropbox API test failed: {e}")
# Short-lived tokens expire constantly and the caller refreshes them, so
# the probe failing isn't page-worthy; the refresh failing is.
logger.warning(f"Dropbox API test failed: {e}")
return False
def _refresh_dropbox_token(self, creds: dict) -> bool:
@@ -436,7 +440,8 @@ class CredentialManager:
# Update in Secret Manager
self._update_dropbox_credentials(creds)
return True
logger.error(f"Dropbox token refresh rejected ({response.status_code}): {response.text[:200]}")
return False
except Exception as e:
+6
View File
@@ -12,6 +12,12 @@ CAPACITY_ERROR_CODES: FrozenSet[str] = frozenset({
"ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS",
"STOCKOUT",
"QUOTA_EXCEEDED",
# AWS EC2 (the AWS encoding worker; see aws_encoding_compute.py)
"InsufficientInstanceCapacity",
"InsufficientHostCapacity",
"InsufficientCapacity",
"VcpuLimitExceeded",
"MaxSpotInstanceCountExceeded",
})
+6
View File
@@ -467,6 +467,12 @@ class GCEEncodingBackend(EncodingBackend):
# Screens the theme leaves out: the encoder must skip them rather than
# rebuild them from whatever matching PNG it finds in the job folder.
# On the AWS box the video worker sits next to the encoder: ask it
# to keep local copies so we take them instead of downloading back
# from GCS (local_encoded_outputs). Unset everywhere else.
if os.environ.get("LOCAL_ENCODED_OUTPUTS_DIR"):
encoding_config["stash_local_outputs"] = True
for flag in ("include_title_screen", "include_end_screen"):
if input_config.options.get(flag) is False:
encoding_config[flag] = False
+13 -79
View File
@@ -294,43 +294,14 @@ class EncodingService:
yield
def _fallback_entries(self) -> list:
"""Parse ENCODING_WORKER_FALLBACK_VMS into candidate dicts.
"""Parse ENCODING_WORKER_FALLBACK_VMS into candidate dicts (never raises).
Schema: '[{"vm":"encoding-worker-fallback-c2df","zone":"us-central1-f",
"ip":"34.x.x.x","machine_type":"c2d-highcpu-16"}, ...]'. machine_type is
optional (inferred from the VM name for legacy entries). Malformed input
degrades to fewer/no fallbacks — this runs during connection recovery and
must never raise.
See ``encoding_worker_manager.parse_fallback_vms`` for the schema (GCE
entries, plus AWS ones carrying provider/instance_id/region).
"""
import json as _json
raw = self.settings.encoding_worker_fallback_vms
if not raw:
return []
try:
parsed = _json.loads(raw)
except (ValueError, TypeError) as e:
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
return []
# A non-list root (null, dict, scalar) parses fine but would blow up
# `for item in parsed` and escape during connection recovery — degrade
# to no fallbacks instead.
if not isinstance(parsed, list):
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
return []
entries = []
for item in parsed:
try:
entries.append({
"vm": item["vm"],
"zone": item["zone"],
"ip": item["ip"],
"machine_type": item.get("machine_type"),
"kind": "fallback",
})
except (KeyError, TypeError) as e:
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
continue
return entries
from backend.services.encoding_worker_manager import parse_fallback_vms
return parse_fallback_vms(self.settings.encoding_worker_fallback_vms)
def _vm_for_worker_url(self, worker_url: Optional[str]) -> Optional[tuple]:
"""Map a worker base URL (http://<ip>:8080) back to its (vm_name, zone).
@@ -394,13 +365,12 @@ class EncodingService:
def _build_worker_candidates(self) -> list:
"""Build the ranked candidate list for ensure_any_running.
Reads optional fallback VMs from settings (env var
ENCODING_WORKER_FALLBACK_VMS, JSON list of {vm, zone, ip, machine_type?}).
The primary + all fallbacks are ranked by the shared preference logic
(fastest-first, demoting recently-stocked-out types) so runtime selection
stays in lock-step with the deploy green selection. Returns an empty list
when no worker manager / no configured fallbacks — caller falls back to
the single-VM ensure_primary_running path.
Delegates to ``EncodingWorkerManager.ranked_candidates`` (primary +
ENCODING_WORKER_FALLBACK_VMS, fastest-first, demoting recently
stocked-out types, honouring ``speed_rank_overrides``) so runtime
selection, the warmups and the deploy green selection rank identically.
Returns an empty list when there is no worker manager or its config
can't be read — caller falls back to ensure_primary_running.
"""
if not self._worker_manager:
return []
@@ -409,43 +379,7 @@ class EncodingService:
except Exception as e: # noqa: BLE001
logger.warning(f"Could not read worker config for candidates: {_format_exception(e)}")
return []
from backend.services.encoding_worker_manager import EncodingWorkerCandidate
from backend.services.encoding_worker_preference import (
PRIMARY_MACHINE_TYPE,
ordered_candidates,
)
# Build a dict pool (primary + fallbacks), each tagged with machine_type so
# the shared preference logic can rank them. The primary/secondary pair is
# always c4d; the config may override via primary_machine_type.
primary_mt = getattr(config, "primary_machine_type", None) or PRIMARY_MACHINE_TYPE
pool = [{
"vm": config.primary_vm,
"zone": self._worker_manager._zone,
"ip": config.primary_ip,
"machine_type": primary_mt,
"kind": "primary",
"is_primary": True,
}]
# Optional capacity-fallback VMs in alternate zones/families (see
# _fallback_entries). Empty when unconfigured.
pool.extend(self._fallback_entries())
# Rank fastest-first, demoting types that recently stocked out. Keeps the
# primary (c4d) at the top whenever it has capacity.
ranked = ordered_candidates(pool, capacity_state=config.capacity_state)
return [
EncodingWorkerCandidate(
vm_name=c["vm"],
zone=c["zone"],
ip=c["ip"],
machine_type=c.get("machine_type"),
is_primary=c.get("is_primary", False),
)
for c in ranked
]
return self._worker_manager.ranked_candidates(config)
def _load_credentials(self):
"""Load encoding worker URL and API key from config/secrets."""
+177 -4
View File
@@ -112,6 +112,12 @@ class EncodingWorkerConfig:
# shared preference logic to demote recently-exhausted types. See
# backend/services/encoding_worker_preference.py.
capacity_state: dict = field(default_factory=dict)
# {machine_family: rank} replacing SPEED_RANK at runtime, e.g. {"c7a": 5}
# makes the AWS worker preferred. Absent/empty ⇒ the built-in ranking.
speed_rank_overrides: dict = field(default_factory=dict)
# True ⇒ when the AWS worker ranks first, the video worker (distribution)
# also runs on it instead of the Cloud Run job (worker_service). Default off.
aws_video_worker: bool = False
@property
def primary_url(self) -> str:
@@ -155,6 +161,8 @@ class EncodingWorkerCandidate:
# the preference logic may rank a fallback ahead of a stocked-out primary, so
# "first candidate" is no longer synonymous with "primary".
is_primary: bool = False
# "aws" for the EC2 worker (routed to AwsComputeAdapter); None ⇒ GCE.
provider: Optional[str] = None
@property
def url(self) -> str:
@@ -165,14 +173,156 @@ class EncodingWorkerCandidate:
return {"vm": self.vm_name, "zone": self.zone, "machine_type": self.machine_type}
def parse_fallback_vms(raw: Optional[str]) -> list:
"""Parse ENCODING_WORKER_FALLBACK_VMS into candidate dicts. Never raises.
Schema: '[{"vm","zone","ip","machine_type"?}, ...]'. AWS workers add
``"provider": "aws", "instance_id", "region"`` (passed through so the
manager can route them to the EC2 adapter). machine_type is optional
(inferred from the VM name for legacy entries). Malformed input degrades to
fewer/no fallbacks — this runs during connection recovery.
"""
import json as _json
if not raw:
return []
try:
parsed = _json.loads(raw)
except (ValueError, TypeError) as e:
logger.warning("Invalid ENCODING_WORKER_FALLBACK_VMS JSON: %s", e)
return []
if not isinstance(parsed, list):
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
return []
entries = []
for item in parsed:
try:
entry = {
"vm": item["vm"],
"zone": item["zone"],
"ip": item["ip"],
"machine_type": item.get("machine_type"),
"kind": "fallback",
}
for key in ("provider", "instance_id", "region"):
if item.get(key):
entry[key] = item[key]
entries.append(entry)
except (KeyError, TypeError) as e:
logger.warning("Skipping malformed fallback candidate %s: %s", item, e)
continue
return entries
class EncodingWorkerManager:
"""Manages blue-green encoding worker VMs via Firestore config and Compute API."""
def __init__(self, db, compute_client=None, project_id="nomadkaraoke", zone="us-central1-c"):
def __init__(
self,
db,
compute_client=None,
project_id="nomadkaraoke",
zone="us-central1-c",
fallback_vms_raw: Optional[str] = None,
aws_compute=None,
):
self._db = db
self._compute = compute_client
self._project_id = project_id
self._zone = zone
# Raw ENCODING_WORKER_FALLBACK_VMS JSON; None → read from settings lazily.
self._fallback_vms_raw = fallback_vms_raw
self._aws_compute = aws_compute # injectable for tests; built lazily otherwise
def fallback_entries(self) -> list:
"""The configured capacity-fallback candidates (GCE and AWS), never raising."""
raw = self._fallback_vms_raw
if raw is None:
try:
from backend.config import get_settings, is_production
settings = get_settings()
raw = settings.encoding_worker_fallback_vms
if not raw and is_production():
# Only the API service and video-encoding-job get the env var;
# the audio/lyrics/download jobs also trigger the video worker
# and warm the encoder, so read the secret directly (cached
# per process by get_secret). Without this they never see the
# AWS worker and silently keep the old path.
raw = settings.get_secret("encoding-worker-fallback-vms")
except Exception as e: # noqa: BLE001
logger.warning("Could not read ENCODING_WORKER_FALLBACK_VMS: %s", e)
raw = None
return parse_fallback_vms(raw)
def _compute_for(self, vm_name: str):
"""The compute client for a VM: the EC2 adapter for AWS workers, else GCE."""
if self._aws_compute is None:
from backend.services.aws_encoding_compute import AwsComputeAdapter, aws_vms_from_pool
self._aws_compute = AwsComputeAdapter(
aws_vms_from_pool(self.fallback_entries()), project_id=self._project_id
)
if self._aws_compute.handles(vm_name):
return self._aws_compute
return self._compute
def ranked_candidates(self, config: Optional["EncodingWorkerConfig"] = None) -> list:
"""Primary + fallbacks ranked by the shared preference logic.
Fastest-first (SPEED_RANK, overridable per family via
``config/encoding-worker.speed_rank_overrides``), demoting types that
recently stocked out. Shared by the encode path and the warmups so they
always start the worker that requests will actually be routed to.
"""
from backend.services.encoding_worker_preference import (
PRIMARY_MACHINE_TYPE,
ordered_candidates,
)
config = config or self.get_config()
primary_mt = getattr(config, "primary_machine_type", None) or PRIMARY_MACHINE_TYPE
pool = [{
"vm": config.primary_vm,
"zone": self._zone,
"ip": config.primary_ip,
"machine_type": primary_mt,
"kind": "primary",
"is_primary": True,
}]
pool.extend(self.fallback_entries())
ranked = ordered_candidates(
pool,
capacity_state=config.capacity_state,
rank_overrides=getattr(config, "speed_rank_overrides", None),
)
return [
EncodingWorkerCandidate(
vm_name=c["vm"],
zone=c["zone"],
ip=c["ip"],
machine_type=c.get("machine_type"),
is_primary=c.get("is_primary", False),
provider=c.get("provider"),
)
for c in ranked
]
def ensure_preferred_running(self) -> dict:
"""Warm the worker requests will be routed to (ranked, with failover).
When the GCE primary ranks first (the normal case) this is exactly
``ensure_primary_running`` — unchanged behaviour. When something else
ranks first (a ``speed_rank_overrides`` preferring the AWS worker, or the
primary's type in stockout cooldown) it runs the same ranked
``ensure_any_running`` the encode path uses, so the worker that requests
will be routed to is the one warmed, and the active override points at it.
"""
config = self.get_config()
candidates = self.ranked_candidates(config)
if not candidates or candidates[0].is_primary:
return self.ensure_primary_running()
return self.ensure_any_running(candidates)
def _doc_ref(self):
"""Return a reference to the config/encoding-worker document."""
@@ -209,6 +359,8 @@ class EncodingWorkerManager:
active_override_zone=data.get("active_override_zone"),
active_override_set_at=data.get("active_override_set_at"),
capacity_state=data.get("capacity_state") or {},
speed_rank_overrides=data.get("speed_rank_overrides") or {},
aws_video_worker=bool(data.get("aws_video_worker", False)),
)
def update_activity(self) -> None:
@@ -271,7 +423,7 @@ class EncodingWorkerManager:
Pass `zone` for fallback VMs that live in alternate zones.
"""
instance = self._compute.get(
instance = self._compute_for(vm_name).get(
project=self._project_id,
zone=zone or self._zone,
instance=vm_name,
@@ -303,7 +455,7 @@ class EncodingWorkerManager:
logger.info("VM %s is already %s, skipping start", vm_name, status)
return
logger.info("Starting VM %s in zone %s (current status: %s)", vm_name, target_zone, status)
operation = self._compute.start(
operation = self._compute_for(vm_name).start(
project=self._project_id,
zone=target_zone,
instance=vm_name,
@@ -318,7 +470,7 @@ class EncodingWorkerManager:
logger.info("VM %s is already %s, skipping stop", vm_name, status)
return
logger.info("Stopping VM %s in zone %s (current status: %s)", vm_name, target_zone, status)
self._compute.stop(
self._compute_for(vm_name).stop(
project=self._project_id,
zone=target_zone,
instance=vm_name,
@@ -459,6 +611,22 @@ class EncodingWorkerManager:
zone=candidate.zone,
code="NOT_FOUND",
) from nf
except EncodingWorkerStartError:
raise
except Exception as err: # noqa: BLE001
if getattr(candidate, "provider", None) != "aws":
raise # GCE: unchanged behaviour
# An AWS control-plane fault (bad/missing controller creds,
# throttling, botocore error) must fail over to the GCE
# candidates, not abort selection — when the AWS worker is
# preferred it ranks first, so escaping here would block all
# encoding.
raise EncodingWorkerStartError(
f"VM {candidate.vm_name} status check failed in {candidate.zone}: {err}",
vm_name=candidate.vm_name,
zone=candidate.zone,
code="STATUS_CHECK_FAILED",
) from err
started = False
if status not in ("RUNNING", "STAGING"):
logger.info(
@@ -575,6 +743,10 @@ class EncodingWorkerManager:
"active_override_ip": candidate.ip,
"active_override_zone": candidate.zone,
"active_override_set_at": now,
# "aws" for the EC2 worker; the CI blue-green deploy leaves an AWS
# override serving (it can't gcloud-stop it, and it hot-updates its
# wheel per job). None for GCE.
"active_override_provider": getattr(candidate, "provider", None),
})
logger.info(
"Set active_override to %s in %s (capacity fallback)",
@@ -597,6 +769,7 @@ class EncodingWorkerManager:
"active_override_ip": None,
"active_override_zone": None,
"active_override_set_at": None,
"active_override_provider": None,
})
logger.info("Cleared active_override (primary is healthy again)")
+18 -3
View File
@@ -51,6 +51,11 @@ SPEED_RANK: Dict[str, int] = {
"c2d": 50,
"n2d": 60,
"n2": 70,
# AWS EC2 c7a (AMD Genoa, us-east-2) — the AWS encoding worker
# (provider "aws"; machine_type "c7a-4xlarge", "." → "-" for Firestore-safe
# cooldown keys). Last resort by default; make it preferred at runtime with
# config/encoding-worker.speed_rank_overrides = {"c7a": 5}.
"c7a": 90,
}
# Rank for a candidate whose machine type is unknown and cannot be inferred:
@@ -106,8 +111,14 @@ def infer_machine_type(candidate: Dict[str, Any]) -> Optional[str]:
return None
def _speed_rank(candidate: Dict[str, Any]) -> int:
return SPEED_RANK.get(machine_family(infer_machine_type(candidate)), UNKNOWN_RANK)
def _speed_rank(candidate: Dict[str, Any], rank_overrides: Optional[Dict[str, Any]] = None) -> int:
family = machine_family(infer_machine_type(candidate))
if rank_overrides and family in rank_overrides:
try:
return int(rank_overrides[family])
except (TypeError, ValueError):
pass # a malformed override must never break worker selection
return SPEED_RANK.get(family, UNKNOWN_RANK)
def cooldown_key(candidate: Dict[str, Any]) -> Optional[str]:
@@ -164,6 +175,7 @@ def ordered_candidates(
capacity_state: Optional[Dict[str, Any]] = None,
now: Optional[datetime] = None,
cooldown_seconds: float = COOLDOWN_SECONDS,
rank_overrides: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
"""Rank ``pool`` fastest-first, demoting recently-stocked-out types to the back.
@@ -175,6 +187,9 @@ def ordered_candidates(
Absent/empty ⇒ pure fastest-first order (today's behaviour).
now: current UTC time (injectable for tests); defaults to ``datetime.now(UTC)``.
cooldown_seconds: demotion window; defaults to ``COOLDOWN_SECONDS``.
rank_overrides: ``{family: rank}`` from Firestore
``config/encoding-worker.speed_rank_overrides``; replaces SPEED_RANK
for those families (e.g. ``{"c7a": 5}`` prefers the AWS worker).
The speed sort is STABLE, so equal-rank candidates keep their input order —
callers express a secondary preference (e.g. zone spread) purely via input
@@ -182,7 +197,7 @@ def ordered_candidates(
"""
if now is None:
now = datetime.now(timezone.utc)
ranked = sorted(pool, key=_speed_rank) # stable: fastest first
ranked = sorted(pool, key=lambda c: _speed_rank(c, rank_overrides)) # stable: fastest first
hot = [c for c in ranked if not _recently_stocked_out(c, capacity_state, now, cooldown_seconds)]
cold = [c for c in ranked if _recently_stocked_out(c, capacity_state, now, cooldown_seconds)]
return hot + cold
@@ -74,6 +74,20 @@ def is_opaque_script_error(message: str | None, source: str | None = None, extra
return not extra.get("filename") and not extra.get("lineno")
# Zalo's in-app browser injects scripts into every page it opens; one references a
# global it hasn't defined yet. Not our code, and nothing the user sees. Needs both
# the host app's UA and its global, so a real error inside Zalo still reports.
_HOST_APP_INJECTION_RE = re.compile(r"\bzaloJSV\d*\b is not defined")
_ZALO_UA_RE = re.compile(r"\bZalo\b", re.IGNORECASE)
def is_host_app_injection_error(message: str | None, user_agent: str | None) -> bool:
"""True for an error from a script the in-app browser's host app injected."""
if not message or not user_agent:
return False
return bool(_HOST_APP_INJECTION_RE.search(message) and _ZALO_UA_RE.search(user_agent))
# A chunk-load failure is a tab running an old build after a deploy: the client
# auto-reloads (frontend/lib/version-check.ts), so one report is not actionable.
# Mirrors isChunkLoadError() there. Reports collapse into one pattern per build
+46 -2
View File
@@ -15,6 +15,7 @@ Usage:
import re
from dataclasses import dataclass
from urllib.parse import urlsplit
@dataclass
@@ -129,18 +130,55 @@ _SERVICE_IGNORE_PATTERNS: list[tuple[str, frozenset[str], re.Pattern, str]] = [
"while instances start, GitHub redelivers and the runners still dispatch "
"(seen 2026-09-20, 09-23, 09-27, 10-08)",
),
(
"audio_separation_experiment_traceback",
frozenset({"audio-separation-job"}),
# Two consecutive <string> frames: `python -c` running exec'd code, i.e. an
# experiment on a prod job image. A multiprocessing-spawn traceback also
# starts with a <string> frame, but its second frame is a real file.
re.compile(r'File "<string>", line 1, in <module>\s+File "<string>", line \d+'),
"Ad-hoc experiment run on a prod audio-separation-job image, not a job failure "
"(seen 2026-10-31, 11-01)",
),
(
"url_download_failed_duplicate",
frozenset({"karaoke-backend"}),
# file_upload.py logs this, then fail_job: ops_alerts' job-failed alert is the
# one alert for the failure.
re.compile(r"^URL download failed: "),
"Same failure as the job-failed alert that fail_job sends right after this line",
),
]
def should_ignore(service: str, message: str) -> IgnoreReason | None:
# Noise only for one service AND request URL path (Cloud Run request logs carry the
# URL outside the message). (pattern_name, services, message regex, exact URL path, reason)
_SERVICE_URL_IGNORE_PATTERNS: list[tuple[str, frozenset[str], re.Pattern, str, str]] = [
(
"decide_search_health_abort",
frozenset({"karaoke-decide-search"}),
re.compile(
r"request was aborted after waiting too long for an available instance",
re.IGNORECASE,
),
"/api/search/health",
"The keep-warm ping waiting on a min-0 cold start (seen 2026-10-30). The same "
"abort on a real search path drops a user's request and still alerts.",
),
]
def should_ignore(service: str, message: str, request_url: str | None = None) -> IgnoreReason | None:
"""Check whether a log entry matches a known infrastructure noise pattern.
``_IGNORE_PATTERNS`` match on the message alone; ``_SERVICE_IGNORE_PATTERNS``
also require ``service`` to be one of the listed services.
also require ``service`` to be one of the listed services, and
``_SERVICE_URL_IGNORE_PATTERNS`` also require ``request_url``'s path.
Args:
service: The originating service name (e.g. ``"karaoke-backend"``).
message: The raw log message string to evaluate.
request_url: The entry's request URL, if it is a request log.
Returns:
An :class:`IgnoreReason` if the message matches a known noise pattern,
@@ -157,4 +195,10 @@ def should_ignore(service: str, message: str) -> IgnoreReason | None:
if service in services and pattern.search(message):
return IgnoreReason(pattern_name=pattern_name, reason=reason)
if request_url:
url_path = urlsplit(request_url).path
for pattern_name, services, pattern, path, reason in _SERVICE_URL_IGNORE_PATTERNS:
if service in services and url_path == path and pattern.search(message):
return IgnoreReason(pattern_name=pattern_name, reason=reason)
return None
+67 -3
View File
@@ -15,6 +15,7 @@ from __future__ import annotations
import logging
import os
import re
from datetime import datetime, timedelta, timezone
from typing import Any
@@ -115,6 +116,39 @@ def _build_log_filter(
)
#: Fixed messages uvicorn and the audit middleware log for every unhandled exception.
#: The cause is only in the entry's ``exception`` field.
_UNHANDLED_EXCEPTION_MESSAGES = frozenset({"Exception in ASGI application", "request_audit_error"})
#: The margin of an ExceptionGroup traceback (" | ", " | | ", " + ").
_TRACEBACK_MARGIN_RE = re.compile(r"^\s*(?:[|+] )+")
#: Its separators (" +-+---- 1 ----", " +-------").
_TRACEBACK_SEPARATOR_RE = re.compile(r"^\s*(?:\| )*\+[-+]")
_TRACEBACK_FRAME_RE = re.compile(r'^\s*File ".*", line \d+')
def _exception_summary(exception_text: str) -> str | None:
"""The ``Type: message`` line a traceback ends on, without its group margin.
Looks after the last frame, not at the last line: a multi-line exception message
(pydantic's ends in a docs link shared by every failure) would otherwise replace
the cause. Frame source and caret lines are indented; the exception line isn't.
"""
lines = [
_TRACEBACK_MARGIN_RE.sub("", line)
for line in exception_text.splitlines()
if line.strip() and not _TRACEBACK_SEPARATOR_RE.match(line)
]
if not lines:
return None
last_frame = max((i for i, line in enumerate(lines) if _TRACEBACK_FRAME_RE.match(line)), default=None)
if last_frame is not None:
for line in lines[last_frame + 1 :]:
if not line[0].isspace():
return line
return lines[-1].strip()
def _extract_message(entry: Any) -> str | None:
"""Extract the log message text from a Cloud Logging entry.
@@ -125,6 +159,9 @@ def _extract_message(entry: Any) -> str | None:
``"msg"`` keys in that order.
* ``None`` payload — returns ``None``.
An unhandled-exception message becomes ``Unhandled exception: <cause>``, so
each cause is its own pattern and both log lines of one crash share it.
Args:
entry: A Cloud Logging ``LogEntry`` object.
@@ -140,13 +177,40 @@ def _extract_message(entry: Any) -> str | None:
for key in ("message", "textPayload", "error", "msg"):
value = payload.get(key)
if value:
return str(value)
text = str(value)
if text.strip() in _UNHANDLED_EXCEPTION_MESSAGES:
summary = _exception_summary(str(payload.get("exception") or ""))
if summary:
return f"Unhandled exception: {summary}"
return text
return None
# Fallback: convert to string representation
text = str(payload)
return text if text else None
def _extract_sample(entry: Any, message: str) -> str:
"""The alert's sample: the message, led by the request path when the entry has one.
The path stays out of the pattern (one cause on many jobs or endpoints is one
alert) but the alert needs it to say where to look.
"""
payload = entry.payload
path = payload.get("path") if isinstance(payload, dict) else None
if not path:
return message
method = payload.get("method")
return f"{method} {path}\n{message}" if method else f"{path}\n{message}"
def _extract_request_url(entry: Any) -> str | None:
"""The request URL on a Cloud Run request-log entry, if any."""
http_request = getattr(entry, "http_request", None)
if not isinstance(http_request, dict):
return None
return http_request.get("requestUrl") or None
def _extract_service_name(entry: Any, resource_type: str) -> str:
"""Extract the service/job/function/instance name from a log entry.
@@ -370,7 +434,7 @@ class ErrorMonitor:
if not message:
continue
service = _extract_service_name(entry, resource_type)
ignore_reason = should_ignore(service, message)
ignore_reason = should_ignore(service, message, _extract_request_url(entry))
if ignore_reason:
logger.debug(
"Ignoring entry from %s (%s): %s",
@@ -387,7 +451,7 @@ class ErrorMonitor:
"service": service,
"resource_type": _classify_resource_type(resource_type),
"normalized": normalized,
"message": message,
"message": _extract_sample(entry, message),
}
)
except Exception as exc: # noqa: BLE001
@@ -74,6 +74,17 @@ _NORMALIZERS: list[tuple[re.Pattern, str]] = [
re.compile(r"https?://([A-Za-z0-9.\-]+(:\d+)?)/[^\s]*"),
r"https://\1",
),
# 8b. YouTube video IDs: yt-dlp's "[youtube] <id>: <error>" and bare watch links.
# Otherwise the same error on each video is a new pattern and a "first time"
# job-failure signature (ops_alerts._signature uses this normalizer).
(
re.compile(r"(\[youtube(?::[\w-]+)?\]) [A-Za-z0-9_-]{11}(?=:)"),
r"\1 <VIDEO_ID>",
),
(
re.compile(r"(youtube\.com/watch\?v=|youtu\.be/)[A-Za-z0-9_-]{11}(?![A-Za-z0-9_-])"),
r"\1<VIDEO_ID>",
),
# 9. Job IDs in paths (/jobs/<alphanumeric>)
(
re.compile(r"/jobs/[A-Za-z0-9]+"),
+148 -3
View File
@@ -27,7 +27,7 @@ os.environ.setdefault("GCE_METADATA_MTLS_MODE", "none")
from fastapi import FastAPI, BackgroundTasks, HTTPException, Header, Depends
from google.cloud import storage
from packaging.version import Version
from pydantic import BaseModel
from pydantic import BaseModel, Field
from . import self_heal
from .persistence import JobStatePersister
@@ -120,6 +120,12 @@ async def lifespan(app: FastAPI):
logger.critical("Encoding worker booted unhealthy, exiting for systemd restart: %s", problem)
raise RuntimeError(f"Encoding worker booted unhealthy: {problem}")
# AWS box only (no-op elsewhere): drop local finals no video worker took.
from backend.services import local_encoded_outputs
removed = await asyncio.to_thread(local_encoded_outputs.purge_stale)
if removed:
logger.info("Purged %d stale locally-stashed encoded outputs", removed)
# Startup: read back any in-progress jobs from Firestore. They were
# interrupted by the restart that brought us here — their work_dir is
# gone, so mark them failed with the restart code so polls return a
@@ -707,6 +713,18 @@ def verify_wheel_imports():
return True
def _gcs_cli() -> list:
"""The GCS CLI for wheel listing/copying on this worker.
GCE workers use ``gsutil`` (unchanged). The AWS worker authenticates to GCP
via Workload Identity Federation, which ``gsutil`` doesn't support, so it
uses ``gcloud storage`` (same ``ls``/``cp`` syntax).
"""
if os.environ.get("ENCODING_WORKER_PROVIDER", "").lower() == "aws":
return ["gcloud", "storage"]
return ["gsutil"]
def ensure_latest_wheel():
'''Ensure the latest karaoke-gen wheel is installed & verified (thread-safe).
@@ -748,7 +766,7 @@ def _ensure_latest_wheel_locked():
# job and blow the timeout on fresh workers — the historical cause of
# "no wheel found" / partial installs. Listing + single copy is ~2s.
ls_result = subprocess.run(
["gsutil", "ls", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl"],
[*_gcs_cli(), "ls", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl"],
capture_output=True, text=True, timeout=60
)
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
@@ -787,7 +805,7 @@ def _ensure_latest_wheel_locked():
)
cp_result = subprocess.run(
["gsutil", "cp", latest_uri, wheel_path],
[*_gcs_cli(), "cp", latest_uri, wheel_path],
capture_output=True, text=True, timeout=120
)
if cp_result.returncode != 0:
@@ -1329,6 +1347,21 @@ async def process_job(job_id: str, request: EncodeRequest):
jobs[job_id]["output_files"] = blob_paths
logger.info(f"Output files (blob paths): {blob_paths}")
# On the AWS box the video worker runs here too: keep local copies
# (keyed by blob path) so it needn't download them back out of GCS.
# Only when that co-located video worker asked (stash_local_outputs),
# and only where LOCAL_ENCODED_OUTPUTS_DIR is set. Off the event loop:
# it copies ~400 MB.
if (request.encoding_config or {}).get("stash_local_outputs"):
from backend.services import local_encoded_outputs
def _stash_all():
local_encoded_outputs.purge_stale()
for local_path, blob_path in zip(local_output_files, blob_paths):
local_encoded_outputs.stash(Path(local_path), blob_path)
await asyncio.to_thread(_stash_all)
jobs[job_id]["status"] = "complete"
jobs[job_id]["progress"] = 100
_persist(job_id)
@@ -1482,6 +1515,118 @@ async def submit_render_video_job(request: RenderVideoRequest, background_tasks:
return {"status": "accepted", "job_id": job_id}
# ---------------------------------------------------------------------------
# /run-worker — run a backend worker (the video worker) on this box
# ---------------------------------------------------------------------------
# AWS box only: there the video worker (packaging + encode + Dropbox/YouTube/Drive
# distribution) runs next to the encoder, so the big uploads leave from AWS
# (credits) instead of GCP, and finals are handed over locally
# (local_encoded_outputs). Enabled only where the environment file written by
# startup-aws.sh exists; the backend falls back to the Cloud Run job otherwise.
RUN_WORKER_ENV_FILE = os.environ.get("RUN_WORKER_ENV_FILE", "/opt/encoding-worker/video-worker-env.json")
RUN_WORKER_LOG_DIR = Path(os.environ.get("RUN_WORKER_LOG_DIR", "/var/log/encoding-worker-runs"))
_RUN_WORKER_MODULES = frozenset({"video_worker"})
class RunWorkerRequest(BaseModel):
# Used in a log file name and as a CLI argument: gen job ids only.
job_id: str = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
module: str = "video_worker"
def run_worker_id(module: str, job_id: str) -> str:
return f"run-{module}-{job_id}"
def _run_worker_env() -> Optional[dict]:
"""Env for the worker subprocess: ours + the video-worker env file, or None if absent."""
try:
with open(RUN_WORKER_ENV_FILE) as f:
extra = json.load(f)
except (OSError, ValueError):
return None
if not isinstance(extra, dict):
return None
env = dict(os.environ)
env.pop("ENCODING_API_KEY", None) # the worker's own key isn't the subprocess's business
env.update({str(k): str(v) for k, v in extra.items()})
return env
def _watch_worker_run(run_id: str, proc: subprocess.Popen, log_path: Path) -> None:
rc = proc.wait()
state = jobs.get(run_id)
if state is None:
return
if rc == 0:
state["status"] = "complete"
state["progress"] = 100
else:
tail = ""
try:
tail = log_path.read_text(errors="replace")[-1500:]
except OSError:
pass
state["status"] = "failed"
state["error"] = f"{state.get('module')} exited {rc}: {tail}"
state["returncode"] = rc
_persist(run_id)
logger.info("Worker run %s finished rc=%s (log %s)", run_id, rc, log_path)
def _start_worker_run(run_id: str, request: RunWorkerRequest, env: dict) -> None:
# The subprocess imports the installed wheel: make sure it's the latest.
if not ensure_latest_wheel():
jobs[run_id].update(status="failed", error="karaoke-gen wheel not ready on this worker")
_persist(run_id)
return
RUN_WORKER_LOG_DIR.mkdir(parents=True, exist_ok=True)
log_path = RUN_WORKER_LOG_DIR / f"{request.job_id}-{uuid.uuid4().hex[:8]}.log"
with open(log_path, "ab") as log:
proc = subprocess.Popen(
[sys.executable, "-m", f"backend.workers.{request.module}", "--job-id", request.job_id],
env=env, stdout=log, stderr=subprocess.STDOUT, cwd="/tmp",
)
jobs[run_id].update(status="running", pid=proc.pid, log=str(log_path))
_persist(run_id)
logger.info("Started %s for job %s (pid %s, log %s)", request.module, request.job_id, proc.pid, log_path)
threading.Thread(target=_watch_worker_run, args=(run_id, proc, log_path), daemon=True).start()
def _start_worker_run_safe(run_id: str, request: RunWorkerRequest, env: dict) -> None:
"""Never leave a run stuck "running": that would hold the box up (idle
watchdog) and lose the job (the backend got "accepted", so no fallback)."""
try:
_start_worker_run(run_id, request, env)
except Exception as exc: # noqa: BLE001
logger.exception("Failed to start worker run %s", run_id)
jobs[run_id].update(status="failed", error=f"failed to start worker: {exc}")
_persist(run_id)
@app.post("/run-worker")
async def submit_worker_run(request: RunWorkerRequest, _auth: bool = Depends(verify_api_key)):
if request.module not in _RUN_WORKER_MODULES:
raise HTTPException(status_code=400, detail=f"module {request.module!r} not allowed")
env = _run_worker_env()
if env is None:
raise HTTPException(status_code=503, detail="worker runs are not enabled on this worker")
run_id = run_worker_id(request.module, request.job_id)
existing = jobs.get(run_id)
if existing and existing.get("status") == "running":
return {"status": "in_progress", "job_id": run_id}
# "running" from the start: /health counts only running jobs, and the
# idle watchdog must not stop the box while the wheel check precedes spawn.
jobs[run_id] = {
"job_id": run_id, "status": "running", "progress": 0, "error": None,
"output_files": None, "kind": "worker_run", "module": request.module,
}
_persist(run_id)
loop = asyncio.get_event_loop()
loop.run_in_executor(light_executor, _start_worker_run_safe, run_id, request, env)
return {"status": "accepted", "job_id": run_id}
@app.post("/encode")
async def submit_encode_job(request: EncodeRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit an encoding job
+4 -2
View File
@@ -1346,7 +1346,8 @@ class JobManager:
message=error_message
)
logger.error(f"Job {job_id} failed: {error_message}")
# WARNING: the status write above sends the one job-failed alert (ops_alerts).
logger.warning(f"Job {job_id} failed: {error_message}")
# Auto-refund credit on failure
job = self.get_job(job_id)
@@ -1693,7 +1694,8 @@ class JobManager:
message=f"Failed: {error_message}",
**updates
)
logger.error(f"Job {job_id} failed: {error_message}")
# WARNING: the status write above sends the one job-failed alert (ops_alerts).
logger.warning(f"Job {job_id} failed: {error_message}")
if not already_notified:
self._trigger_state_notifications(job_id, JobStatus.FAILED)
+91
View File
@@ -0,0 +1,91 @@
"""Same-box handoff of encoded finals from the encoding worker to the video worker.
On the AWS encoding worker, the video worker (distribution) runs on the same box
as the encoding service. Without this, the video worker would download every
final the encoder just uploaded back out of GCS — ~400 MB of out-of-pocket GCS
egress per job, more than moving distribution to AWS saves. So the encoder
"stashes" a local copy of each output keyed by its GCS blob path, and the video
worker "takes" it instead of downloading.
Active only when ``LOCAL_ENCODED_OUTPUTS_DIR`` is set (the AWS box). Everywhere
else ``stash`` is a no-op and ``take`` returns False, i.e. today's behaviour.
Best effort: any failure falls back to GCS.
"""
from __future__ import annotations
import logging
import os
import shutil
import time
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
ENV_VAR = "LOCAL_ENCODED_OUTPUTS_DIR"
MAX_AGE_SECONDS = 6 * 3600 # a take happens minutes after the stash
def _root() -> Optional[Path]:
raw = os.environ.get(ENV_VAR, "").strip()
return Path(raw) if raw else None
def _path_for(root: Path, blob_path: str) -> Path:
rel = blob_path.lstrip("/")
target = (root / rel).resolve()
if root.resolve() not in target.parents:
raise ValueError(f"blob path escapes the stash dir: {blob_path!r}")
return target
def stash(local_file: Path, blob_path: str) -> bool:
"""Keep a copy of ``local_file`` for a co-located video worker. Never raises."""
root = _root()
if root is None:
return False
try:
dest = _path_for(root, blob_path)
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_name(dest.name + ".partial")
shutil.copyfile(local_file, tmp)
os.replace(tmp, dest)
return True
except Exception as e: # noqa: BLE001
logger.warning("Could not stash %s for local handoff: %s", blob_path, e)
return False
def take(blob_path: str, dest: str) -> bool:
"""Move the stashed copy of ``blob_path`` to ``dest``. False ⇒ download from GCS."""
root = _root()
if root is None:
return False
try:
src = _path_for(root, blob_path)
if not src.is_file():
return False
Path(dest).parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(src), dest)
return True
except Exception as e: # noqa: BLE001
logger.warning("Local handoff of %s failed, falling back to GCS: %s", blob_path, e)
return False
def purge_stale(max_age_seconds: float = MAX_AGE_SECONDS) -> int:
"""Delete stashed files older than ``max_age_seconds`` (never taken). Returns count."""
root = _root()
if root is None or not root.is_dir():
return 0
cutoff = time.time() - max_age_seconds
removed = 0
for p in root.rglob("*"):
try:
if p.is_file() and p.stat().st_mtime < cutoff:
p.unlink()
removed += 1
except OSError:
continue
return removed
+26 -3
View File
@@ -3,16 +3,21 @@
Mirrors the frontend sanitizeWordTimings.ts and the render-time
SegmentResizer._sanitize_segment_timings. Operates on the raw corrections dict the
frontend POSTs (Dict[str, Any]); clamps any word whose start/end falls outside its
segment window or is inverted. A segment whose own bounds are missing/non-finite
segment window or is inverted, or that starts before the previous word in its line
started (out of order: a Tap To Sync pass that stopped mid-line can leave a stale
untapped word behind the last tapped one). A segment whose own bounds are missing/non-finite
(JSON.stringify drops `undefined`, so an in-browser edit can arrive without them)
gets them from its words' timings, else from its neighbours; one with no usable
timing anywhere is left untouched (see find_missing_timings). Mutates and returns
the same dict for caller convenience, plus the number of fields changed."""
from __future__ import annotations
import logging
import math
from typing import Any, Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
def _finite(v: Any) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
@@ -59,6 +64,7 @@ def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], i
return corrections, 0
changes = _fill_segment_bounds(segments)
out_of_order: List[str] = []
for seg in segments:
if not isinstance(seg, dict):
continue
@@ -69,6 +75,7 @@ def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], i
continue
seg_end = max(seg_end, seg_start)
prev_start = seg_start
prev_end = seg_start
for w in seg.get("words", []):
if not isinstance(w, dict):
@@ -76,10 +83,18 @@ def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], i
start = w.get("start_time")
end = w.get("end_time")
# Invalid start = missing/non-finite OR outside the segment window.
if _finite(start) and seg_start <= start <= seg_end:
# Invalid start = missing/non-finite, outside the segment window, OR before the
# previous word's START (out of order). A start between the previous word's start and
# end is a small overlap, common in AI transcriptions, and is left alone. Invalid
# starts are all repaired the same way: placed at the previous word's end. Moving rather than clearing, because a cleared word
# would be refilled at prev_end on the next sanitize anyway, and nulls crash the
# render (find_missing_timings only guards the preview).
in_window = _finite(start) and seg_start <= start <= seg_end
if in_window and start >= prev_start:
new_start = start
else:
if in_window:
out_of_order.append(str(w.get("text", "")))
new_start = min(max(prev_end, seg_start), seg_end)
# Invalid end = missing/non-finite, before start, or past segment end.
@@ -96,8 +111,16 @@ def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], i
if new_end != end:
w["end_time"] = new_end
changes += 1
prev_start = new_start
prev_end = new_end
if out_of_order:
# Expected after a partial Tap To Sync pass, and repaired here: WARNING, not ERROR.
# One aggregated line per submission (alert rules: one root cause, one message).
logger.warning(
"timing_sanitizer: moved %d out-of-order word(s) to the previous word's end: %s",
len(out_of_order), ", ".join(repr(t) for t in out_of_order[:10]),
)
return corrections, changes
+66 -1
View File
@@ -624,7 +624,7 @@ class WorkerService:
compute_client=compute_client,
project_id=self.settings.google_cloud_project,
)
result = manager.ensure_primary_running()
result = manager.ensure_preferred_running()
if result["started"]:
logger.info(f"[job:{job_id}] Encoding worker warmup: started VM {result['vm_name']}")
else:
@@ -645,8 +645,73 @@ class WorkerService:
await asyncio.to_thread(self._bump_worker_generation, job_id) # Firestore write
self._start_encoding_worker_warmup(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
if await self._trigger_video_worker_on_aws(job_id):
return True
return await self._trigger_cloud_run_job(job_id)
return await self.trigger_worker("video", job_id)
async def _trigger_video_worker_on_aws(self, job_id: str) -> bool:
"""Run the video worker on the AWS encoding box instead of Cloud Run, if enabled.
Only when Firestore ``config/encoding-worker.aws_video_worker`` is true AND
the AWS worker ranks first (it's the preferred encoder, via
``speed_rank_overrides``). There the distribution uploads (Dropbox/YouTube/
Drive) leave from AWS, and finals are handed over locally instead of
downloaded back out of GCS. Returns False on any doubt or failure so the
caller falls back to the Cloud Run job — this path must never lose a job.
"""
try:
from backend.services.encoding_service import get_encoding_service
manager = self._build_encoding_worker_manager()
config = await asyncio.to_thread(manager.get_config)
if not getattr(config, "aws_video_worker", False):
return False
candidates = await asyncio.to_thread(manager.ranked_candidates, config)
if not candidates or candidates[0].provider != "aws":
logger.info(
f"[job:{job_id}] AWS video worker enabled but not the preferred encoder "
f"(top: {candidates[0].vm_name if candidates else 'none'}); using Cloud Run"
)
return False
aws = candidates[0]
result = await asyncio.to_thread(manager.ensure_any_running, candidates)
if result.get("vm_name") != aws.vm_name:
logger.warning(
f"[job:{job_id}] AWS video worker: {aws.vm_name} unavailable "
f"(started {result.get('vm_name')}); using Cloud Run"
)
return False
await manager.wait_for_worker_ready(aws.vm_name, f"{aws.url}/health", zone=aws.zone)
service = get_encoding_service()
service._load_credentials()
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.post(
f"{aws.url}/run-worker",
json={"job_id": job_id, "module": "video_worker"},
headers={"X-API-Key": service._api_key},
)
if resp.status_code == 200 and resp.json().get("status") in ("accepted", "in_progress"):
logger.info(f"[job:{job_id}] Video worker started on AWS ({aws.vm_name})")
return True
logger.warning(
f"[job:{job_id}] AWS video worker refused ({resp.status_code}: {resp.text[:300]}); using Cloud Run"
)
return False
except Exception as e: # noqa: BLE001 — fall back to Cloud Run, never drop the job
logger.warning(f"[job:{job_id}] AWS video worker dispatch failed ({e}); using Cloud Run")
return False
def _build_encoding_worker_manager(self):
from backend.services.encoding_worker_manager import EncodingWorkerManager
from google.cloud import compute_v1, firestore
return EncodingWorkerManager(
db=firestore.Client(project=self.settings.google_cloud_project),
compute_client=compute_v1.InstancesClient(),
project_id=self.settings.google_cloud_project,
)
async def _trigger_cloud_run_job(self, job_id: str) -> bool:
"""
@@ -29,6 +29,16 @@ class YouTubeDownloadError(Exception):
pass
def is_bot_block_error(error: Exception) -> bool:
"""Whether YouTube rejected flacfetch's session, as opposed to the video failing.
Matches flacfetch's own check. Loose so rewording doesn't disarm it, and "not a
bot" sidesteps yt-dlp's curly apostrophe in "you're".
"""
message = str(error).lower()
return "not a bot" in message or "cookies are no longer valid" in message
class YouTubeDownloadService:
"""
Single point of entry for all YouTube downloads in the cloud backend.
+29
View File
@@ -142,3 +142,32 @@ def test_strips_sensitive_query_string(client):
(pd,), _ = client.fake_adapter.upsert_pattern.call_args
assert "SECRET" not in pd.sample_message
assert "token=" not in pd.sample_message
ZALO_UA = (
"Mozilla/5.0 (Linux; Android 16; X Build/Y;) AppleWebKit/537.36 (KHTML, like Gecko) "
"Version/4.0 Chrome/156.0.8078.47 Mobile Safari/537.36 Zalo android/261002903 ZaloTheme/light"
)
ZALO_MESSAGE = "ReferenceError: zaloJSV2 is not defined"
def test_zalo_host_app_injection_is_accepted_but_not_persisted(client):
resp = client.post(
"/api/client-errors",
json=_payload(message=ZALO_MESSAGE, stack=f"{ZALO_MESSAGE}\n at <anonymous>:1:2", user_agent=ZALO_UA),
)
assert resp.status_code == 202
assert resp.json()["is_new"] is False
client.fake_adapter.upsert_pattern.assert_not_called()
def test_real_errors_inside_zalo_are_persisted(client):
resp = client.post("/api/client-errors", json=_payload(user_agent=ZALO_UA))
assert resp.status_code == 202
client.fake_adapter.upsert_pattern.assert_called_once()
def test_zalo_message_from_another_browser_is_persisted(client):
resp = client.post("/api/client-errors", json=_payload(message=ZALO_MESSAGE))
assert resp.status_code == 202
client.fake_adapter.upsert_pattern.assert_called_once()
@@ -156,3 +156,80 @@ async def test_review_fallback_crash_restores_hold_for_sweep() -> None:
auto_result={"outcome": "review"})
assert out == "error"
jm.park_review_for_auto_check.assert_called_once_with("j1")
def _suggestion_patches(wait=None):
return (
patch("backend.workers.auto_correct_worker.process_proactive_auto_correct",
wait or AsyncMock()),
patch("backend.config.get_settings",
return_value=SimpleNamespace(auto_correct_proactive_enabled=True)),
)
async def _route_without_suggestions(jm, rescored, wait=None):
first = {"outcome": "review", "ai_suggestions_available": False}
p_wait, p_settings = _suggestion_patches(wait)
with p_wait, p_settings:
return await _call(review_gate.route_after_scoring, jm, "j1", first, auto_result=rescored)
@pytest.mark.asyncio
async def test_missing_suggestions_rescore_holds_instead_of_notifying() -> None:
"""Job 7f89f884: the "review your lyrics" push went out minutes before auto-approval."""
jm = _jm(_job(audio_complete=False))
out, auto, pre = await _route_without_suggestions(
jm, {"outcome": "review", "hold_for_audio": True, "ai_suggestions_available": True})
assert out == "held"
auto.assert_awaited_once_with("j1", trigger="screens_worker")
jm.park_review_for_auto_check.assert_called_once_with("j1")
jm.transition_to_state.assert_not_called()
pre.assert_not_awaited()
@pytest.mark.asyncio
async def test_missing_suggestions_rescore_can_auto_complete() -> None:
jm = _jm()
out, _, pre = await _route_without_suggestions(jm, {"outcome": "auto_completed"})
assert out == "auto_completed"
jm.transition_to_state.assert_not_called()
pre.assert_not_awaited()
@pytest.mark.asyncio
async def test_missing_suggestions_rescore_still_review_opens_review() -> None:
jm = _jm()
out, auto, pre = await _route_without_suggestions(
jm, {"outcome": "review", "hold_for_audio": False, "ai_suggestions_available": True})
assert out == "review"
auto.assert_awaited_once()
pre.assert_awaited_once_with("j1")
assert jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.AWAITING_REVIEW
@pytest.mark.asyncio
async def test_suggestions_wait_failure_still_opens_review() -> None:
jm = _jm()
out, auto, _ = await _route_without_suggestions(
jm, {"outcome": "auto_completed"}, wait=AsyncMock(side_effect=RuntimeError("llm down")))
assert out == "review"
auto.assert_not_awaited()
assert jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.AWAITING_REVIEW
@pytest.mark.asyncio
async def test_rescore_with_no_verdict_keeps_first_verdict() -> None:
jm = _jm()
out, _, _ = await _route_without_suggestions(jm, {"outcome": "error"})
assert out == "review"
assert jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.AWAITING_REVIEW
@pytest.mark.asyncio
async def test_suggestions_present_scores_only_once() -> None:
jm = _jm()
out, auto, _ = await _call(
review_gate.route_after_scoring, jm, "j1",
{"outcome": "review", "ai_suggestions_available": True})
assert out == "review"
auto.assert_not_awaited()
@@ -138,3 +138,63 @@ def test_non_finite_word_timing_is_clamped(bad_value):
w = cleaned["corrected_segments"][0]["words"][0]
assert 10.0 <= w["start_time"] <= 12.0
assert w["end_time"] >= w["start_time"]
def _partial_pass_line():
"""gen's fake-fixture line after a Tap To Sync pass that stopped before the last word:
"ever" was re-tapped at 19.6 but "transcribed" kept its stale 18.74-19.5."""
return {"corrected_segments": [{
"id": "s", "text": "Nothing here was ever transcribed", "start_time": 16.0, "end_time": 20.1,
"words": [
{"id": "w0", "text": "Nothing", "start_time": 16.0, "end_time": 16.9},
{"id": "w1", "text": "here", "start_time": 17.2, "end_time": 18.1},
{"id": "w2", "text": "was", "start_time": 18.4, "end_time": 19.3},
{"id": "w3", "text": "ever", "start_time": 19.6, "end_time": 20.1},
{"id": "w4", "text": "transcribed", "start_time": 18.74, "end_time": 19.5},
],
}]}
def test_word_starting_before_previous_word_end_is_moved_after_it(caplog):
with caplog.at_level("WARNING", logger="backend.services.timing_sanitizer"):
cleaned, count = sanitize_corrections(_partial_pass_line())
words = cleaned["corrected_segments"][0]["words"]
assert count >= 1
# Untouched in-order words keep their timings.
assert [w["start_time"] for w in words[:4]] == [16.0, 17.2, 18.4, 19.6]
# "transcribed" now follows "ever" (placed at its end, like any other bad start) inside the line.
transcribed = words[4]
assert transcribed["start_time"] == 20.1
assert transcribed["start_time"] <= transcribed["end_time"] <= 20.1
for prev, cur in zip(words, words[1:]):
assert cur["start_time"] >= prev["end_time"]
warnings = [r for r in caplog.records if r.levelname == "WARNING"]
assert len(warnings) == 1 # one aggregated warning per call, not one per word
assert "transcribed" in warnings[0].getMessage()
assert not [r for r in caplog.records if r.levelno >= 40] # expected condition: never ERROR
def test_in_order_words_log_nothing(caplog):
payload = {"corrected_segments": [{
"id": "s", "text": "a b", "start_time": 1.0, "end_time": 3.0,
"words": [{"id": "a", "text": "a", "start_time": 1.0, "end_time": 2.0},
{"id": "b", "text": "b", "start_time": 2.0, "end_time": 3.0}],
}]}
with caplog.at_level("WARNING", logger="backend.services.timing_sanitizer"):
_, count = sanitize_corrections(payload)
assert count == 0
assert not caplog.records
def test_small_overlap_with_previous_word_is_left_untouched(caplog):
"""AI transcriptions often start a word a few ms before the previous one ends: not out of order."""
payload = {"corrected_segments": [{
"id": "s", "text": "a b", "start_time": 1.0, "end_time": 3.0,
"words": [{"id": "a", "text": "a", "start_time": 1.0, "end_time": 2.0},
{"id": "b", "text": "b", "start_time": 1.98, "end_time": 3.0}],
}]}
with caplog.at_level("WARNING", logger="backend.services.timing_sanitizer"):
cleaned, count = sanitize_corrections(payload)
assert count == 0
assert cleaned["corrected_segments"][0]["words"][1]["start_time"] == 1.98
assert not caplog.records
@@ -1085,6 +1085,17 @@ class TestTorrentStallAwaitsUser:
assert details["stall_minutes"] == 60
assert details["keep_trying"] is True
@pytest.mark.asyncio
async def test_known_download_failure_logs_warning_not_error(self, caplog):
"""fail_job's job-failed alert is the one alert for this failure."""
import logging
flacfetch = _mock_flacfetch(FlacfetchServiceError("Download failed: tracker 500"))
with caplog.at_level(logging.INFO, logger="backend.workers.audio_download_worker"):
await self._run(_red_job(), flacfetch, attempt="0")
records = [r for r in caplog.records if "Download failed: Download failed" in r.getMessage()]
assert [r.levelno for r in records] == [logging.WARNING]
@pytest.mark.asyncio
async def test_non_stall_failure_still_marks_retry_pending(self):
flacfetch = _mock_flacfetch(FlacfetchServiceError("Download failed: tracker 500"))
+115
View File
@@ -0,0 +1,115 @@
"""Unit tests for the EC2 adapter behind the AWS encoding worker.
The adapter must look exactly like the compute_v1.InstancesClient slice the
manager uses, so the manager's GCE-shaped status checks, capacity cooldowns
and NotFound skips apply to the AWS worker unchanged.
"""
import json
import boto3
import pytest
from botocore.stub import Stubber
from google.api_core import exceptions as gcp_exceptions
from backend.services.aws_encoding_compute import (
AwsComputeAdapter,
AwsVm,
_load_credentials,
aws_vms_from_pool,
)
from backend.services.encoding_errors import CAPACITY_ERROR_CODES
VM = "aws-encoding-worker-1"
IID = "i-0123456789abcdef0"
@pytest.fixture
def ec2():
client = boto3.client("ec2", region_name="us-east-2", aws_access_key_id="x", aws_secret_access_key="y")
with Stubber(client) as stub:
yield client, stub
def _adapter(client):
return AwsComputeAdapter({VM: AwsVm(IID, "us-east-2")}, client_factory=lambda region: client)
def _describe(state):
return {"Reservations": [{"Instances": [{"InstanceId": IID, "State": {"Name": state, "Code": 0}}]}]}
@pytest.mark.parametrize("ec2_state,gce_status", [
("running", "RUNNING"),
("pending", "STAGING"),
("stopping", "STOPPING"),
("stopped", "TERMINATED"),
("shutting-down", "STOPPING"),
])
def test_get_maps_ec2_state_to_gce_status(ec2, ec2_state, gce_status):
client, stub = ec2
stub.add_response("describe_instances", _describe(ec2_state), {"InstanceIds": [IID]})
assert _adapter(client).get(project="p", zone="us-east-2b", instance=VM).status == gce_status
def test_get_missing_instance_raises_not_found(ec2):
client, stub = ec2
stub.add_client_error("describe_instances", service_error_code="InvalidInstanceID.NotFound")
with pytest.raises(gcp_exceptions.NotFound):
_adapter(client).get(instance=VM)
def test_unregistered_vm_raises_not_found(ec2):
client, _ = ec2
with pytest.raises(gcp_exceptions.NotFound):
_adapter(client).get(instance="encoding-worker-a")
def test_start_success_leaves_no_error_code(ec2):
client, stub = ec2
stub.add_response("start_instances", {"StartingInstances": []}, {"InstanceIds": [IID]})
op = _adapter(client).start(instance=VM)
op.result(timeout=30)
assert op.error_code == ""
def test_start_capacity_error_is_a_capacity_code(ec2):
client, stub = ec2
stub.add_client_error(
"start_instances", service_error_code="InsufficientInstanceCapacity",
service_message="no c7a.8xlarge capacity in us-east-2b",
)
op = _adapter(client).start(instance=VM)
op.result()
assert op.error_code == "InsufficientInstanceCapacity"
assert op.error_code in CAPACITY_ERROR_CODES
assert "capacity" in op.error_message
def test_stop_calls_stop_instances(ec2):
client, stub = ec2
stub.add_response("stop_instances", {"StoppingInstances": []}, {"InstanceIds": [IID]})
_adapter(client).stop(instance=VM)
stub.assert_no_pending_responses()
def test_handles_only_registered_vms():
adapter = AwsComputeAdapter({VM: AwsVm(IID, "us-east-2")}, client_factory=lambda r: None)
assert adapter.handles(VM)
assert not adapter.handles("encoding-worker-a")
def test_aws_vms_from_pool_keeps_only_complete_aws_entries():
pool = [
{"vm": "encoding-worker-fallback-c2df", "zone": "us-central1-f", "ip": "1.2.3.4"},
{"vm": VM, "zone": "us-east-2b", "ip": "5.6.7.8", "provider": "aws", "instance_id": IID, "region": "us-east-2"},
{"vm": "aws-incomplete", "zone": "us-east-2b", "ip": "9.9.9.9", "provider": "aws"},
]
assert aws_vms_from_pool(pool) == {VM: AwsVm(IID, "us-east-2")}
def test_credentials_env_override(monkeypatch):
monkeypatch.setenv(
"AWS_ENCODING_CONTROLLER_CREDENTIALS",
json.dumps({"access_key_id": "AKIA", "secret_access_key": "s3cr3t", "extra": 1}),
)
assert _load_credentials("nomadkaraoke") == {"access_key_id": "AKIA", "secret_access_key": "s3cr3t"}
+54
View File
@@ -0,0 +1,54 @@
"""Tests for the AWS encoding worker's idle self-stop decision."""
import importlib.util
from datetime import datetime, timedelta, timezone
from pathlib import Path
_spec = importlib.util.spec_from_file_location("idle_watchdog", Path(__file__).resolve().parents[2] / "infrastructure" / "encoding-worker" / "aws" / "idle-watchdog.py")
wd = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(wd)
NOW = datetime(2026, 10, 29, 12, 0, tzinfo=timezone.utc)
VM = "aws-encoding-worker-1"
def _decide(active_jobs=0, config=None, unknown_since=None):
return wd.decide(now=NOW, active_jobs=active_jobs, config=config, vm_name=VM, unknown_since=unknown_since)[0]
def _routed(minutes_ago):
return {"active_override_vm": VM, "last_activity_at": (NOW - timedelta(minutes=minutes_ago)).isoformat()}
def test_busy_worker_keeps_running_even_if_not_routed():
assert _decide(active_jobs=2, config={"active_override_vm": "encoding-worker-a"}) == "keep"
def test_idle_and_not_routed_stops():
assert _decide(config={"active_override_vm": None}) == "stop"
def test_routed_with_recent_activity_keeps_running():
assert _decide(config=_routed(2)) == "keep"
def test_routed_but_idle_past_timeout_stops():
assert _decide(config=_routed(6)) == "stop"
def test_routed_without_activity_timestamp_stops():
assert _decide(config={"active_override_vm": VM}) == "stop"
def test_naive_timestamp_treated_as_utc():
assert _decide(config={"active_override_vm": VM, "last_activity_at": "2026-10-29T11:58:00"}) == "keep"
def test_unreadable_health_starts_grace_then_stops():
assert _decide(active_jobs=None, config=_routed(1)) == "unknown"
assert _decide(active_jobs=None, config=_routed(1), unknown_since=NOW - timedelta(minutes=5)) == "unknown"
assert _decide(active_jobs=None, config=_routed(1), unknown_since=NOW - timedelta(minutes=16)) == "stop"
def test_unreadable_firestore_starts_grace_then_stops():
assert _decide(config=None) == "unknown"
assert _decide(config=None, unknown_since=NOW - timedelta(minutes=20)) == "stop"
+304
View File
@@ -0,0 +1,304 @@
"""Phase 2: the video worker (distribution) on the AWS encoding box.
Covers the same-box finals handoff, the worker's /run-worker endpoint, the
box's env builder (mirrors the live Cloud Run job), and the backend trigger's
AWS branch — which must fall back to the Cloud Run job on any doubt.
"""
import asyncio
import importlib.util
import json
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import HTTPException
from backend.services import local_encoded_outputs as leo
# --- local_encoded_outputs ------------------------------------------------------
BLOB = "jobs/abc123/finals/Artist - Title (Final Karaoke Lossless 4k).mp4"
def test_handoff_is_noop_without_env(tmp_path, monkeypatch):
monkeypatch.delenv(leo.ENV_VAR, raising=False)
f = tmp_path / "x.mp4"
f.write_bytes(b"v")
assert leo.stash(f, BLOB) is False
assert leo.take(BLOB, str(tmp_path / "out.mp4")) is False
def test_stash_then_take_moves_file(tmp_path, monkeypatch):
monkeypatch.setenv(leo.ENV_VAR, str(tmp_path / "stash"))
src = tmp_path / "encoded.mp4"
src.write_bytes(b"video-bytes")
assert leo.stash(src, BLOB) is True
dest = tmp_path / "work" / "final.mp4"
assert leo.take(BLOB, str(dest)) is True
assert dest.read_bytes() == b"video-bytes"
assert leo.take(BLOB, str(dest)) is False # moved, so a second take falls back to GCS
def test_take_missing_falls_back(tmp_path, monkeypatch):
monkeypatch.setenv(leo.ENV_VAR, str(tmp_path))
assert leo.take(BLOB, str(tmp_path / "o.mp4")) is False
def test_blob_path_cannot_escape_stash_dir(tmp_path, monkeypatch):
monkeypatch.setenv(leo.ENV_VAR, str(tmp_path / "stash"))
f = tmp_path / "x"
f.write_bytes(b"1")
assert leo.stash(f, "../../etc/evil") is False
def test_purge_stale_removes_only_old_files(tmp_path, monkeypatch):
import os
import time
monkeypatch.setenv(leo.ENV_VAR, str(tmp_path))
old, new = tmp_path / "jobs/a/old.mp4", tmp_path / "jobs/b/new.mp4"
for p in (old, new):
p.parent.mkdir(parents=True)
p.write_bytes(b"1")
os.utime(old, (time.time() - 2 * 86400,) * 2)
assert leo.purge_stale() == 1
assert not old.exists() and new.exists()
# --- worker /run-worker -----------------------------------------------------------
@pytest.fixture
def worker(monkeypatch, tmp_path):
from backend.services.gce_encoding import main
env_file = tmp_path / "video-worker-env.json"
monkeypatch.setattr(main, "RUN_WORKER_ENV_FILE", str(env_file))
monkeypatch.setattr(main, "RUN_WORKER_LOG_DIR", tmp_path / "runs")
monkeypatch.setattr(main, "_persist", lambda job_id: None)
main.jobs.clear()
yield main, env_file
main.jobs.clear()
def _req(main, job_id="abc123", module="video_worker"):
return main.RunWorkerRequest(job_id=job_id, module=module)
def test_run_worker_disabled_without_env_file(worker):
main, _ = worker
with pytest.raises(HTTPException) as exc:
asyncio.run(main.submit_worker_run(_req(main)))
assert exc.value.status_code == 503
def test_run_worker_rejects_unknown_module(worker):
main, env_file = worker
env_file.write_text("{}")
with pytest.raises(HTTPException) as exc:
asyncio.run(main.submit_worker_run(_req(main, module="audio_worker")))
assert exc.value.status_code == 400
def test_run_worker_dedupes_running_job(worker):
main, env_file = worker
env_file.write_text("{}")
main.jobs[main.run_worker_id("video_worker", "abc123")] = {"status": "running"}
out = asyncio.run(main.submit_worker_run(_req(main)))
assert out["status"] == "in_progress"
def test_run_worker_counts_as_active_immediately(worker):
main, env_file = worker
env_file.write_text(json.dumps({"ENVIRONMENT": "production"}))
with patch.object(main, "_start_worker_run"):
out = asyncio.run(main.submit_worker_run(_req(main)))
assert out["status"] == "accepted"
assert main.jobs[out["job_id"]]["status"] == "running" # /health active_jobs counts it
def test_start_worker_run_spawns_module_with_box_env(worker):
main, env_file = worker
env_file.write_text(json.dumps({"ENVIRONMENT": "production", "LOCAL_ENCODED_OUTPUTS_DIR": "/x"}))
run_id = main.run_worker_id("video_worker", "abc123")
main.jobs[run_id] = {"status": "running", "module": "video_worker"}
proc = MagicMock(pid=4242)
proc.wait.return_value = 0
with patch.object(main, "ensure_latest_wheel", return_value=True), \
patch.object(main.subprocess, "Popen", return_value=proc) as popen:
main._start_worker_run(run_id, _req(main), main._run_worker_env())
args, kwargs = popen.call_args
assert args[0][1:] == ["-m", "backend.workers.video_worker", "--job-id", "abc123"]
assert kwargs["env"]["LOCAL_ENCODED_OUTPUTS_DIR"] == "/x"
assert "ENCODING_API_KEY" not in kwargs["env"]
main._watch_worker_run(run_id, proc, Path(main.jobs[run_id]["log"]))
assert main.jobs[run_id]["status"] == "complete"
def test_failed_run_reports_log_tail(worker, tmp_path):
main, _ = worker
run_id = main.run_worker_id("video_worker", "abc123")
main.jobs[run_id] = {"status": "running", "module": "video_worker"}
log = tmp_path / "run.log"
log.write_text("Traceback ... Dropbox upload failed")
proc = MagicMock()
proc.wait.return_value = 1
main._watch_worker_run(run_id, proc, log)
assert main.jobs[run_id]["status"] == "failed"
assert "Dropbox upload failed" in main.jobs[run_id]["error"]
def test_wheel_not_ready_fails_run_without_spawning(worker):
main, env_file = worker
env_file.write_text("{}")
run_id = main.run_worker_id("video_worker", "abc123")
main.jobs[run_id] = {"status": "running"}
with patch.object(main, "ensure_latest_wheel", return_value=False), \
patch.object(main.subprocess, "Popen") as popen:
main._start_worker_run(run_id, _req(main), {})
popen.assert_not_called()
assert main.jobs[run_id]["status"] == "failed"
# --- video-worker-env.py ------------------------------------------------------------
_ENV_PATH = Path(__file__).resolve().parents[2] / "infrastructure" / "encoding-worker" / "aws" / "video-worker-env.py"
_spec = importlib.util.spec_from_file_location("video_worker_env", _ENV_PATH)
vwe = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(vwe)
def test_build_env_mirrors_job_and_resolves_secrets():
job = {"template": {"template": {"containers": [{"env": [
{"name": "ENVIRONMENT", "value": "production"},
{"name": "POSTMARK_SERVER_TOKEN", "valueSource": {"secretKeyRef": {
"secret": "projects/nomadkaraoke/secrets/postmark-server-token", "version": "latest"}}},
]}]}}}
env = vwe.build_env(job, lambda secret, version: f"<{secret}@{version}>")
assert env["ENVIRONMENT"] == "production"
assert env["POSTMARK_SERVER_TOKEN"] == "<postmark-server-token@latest>"
assert env["GOOGLE_APPLICATION_CREDENTIALS"].endswith("gcp-wif-backend.json")
assert env["LOCAL_ENCODED_OUTPUTS_DIR"] and env["CLOUD_RUN_JOB"] == "video-encoding-job"
# --- backend trigger ------------------------------------------------------------------
def _candidate(provider, vm="aws-encoding-worker-1"):
return SimpleNamespace(provider=provider, vm_name=vm, url="http://3.3.3.3:8080", zone="us-east-2b")
@pytest.fixture
def service():
from backend.services.worker_service import WorkerService
svc = WorkerService.__new__(WorkerService)
svc.settings = MagicMock(google_cloud_project="nomadkaraoke")
return svc
def _manager(aws_video_worker=True, top="aws", started="aws-encoding-worker-1"):
m = MagicMock()
m.get_config.return_value = SimpleNamespace(aws_video_worker=aws_video_worker)
m.ranked_candidates.return_value = [_candidate(top, "aws-encoding-worker-1" if top == "aws" else "encoding-worker-a")]
m.ensure_any_running.return_value = {"vm_name": started}
m.wait_for_worker_ready = AsyncMock()
return m
def _run(service, manager, response=None, post_exc=None):
client = MagicMock()
client.__aenter__ = AsyncMock(return_value=client)
client.__aexit__ = AsyncMock(return_value=False)
client.post = AsyncMock(side_effect=post_exc, return_value=response)
enc = MagicMock(_api_key="k")
with patch.object(service, "_build_encoding_worker_manager", return_value=manager), \
patch("backend.services.encoding_service.get_encoding_service", return_value=enc), \
patch("backend.services.worker_service.httpx.AsyncClient", return_value=client):
return asyncio.run(service._trigger_video_worker_on_aws("abc123")), client
def test_aws_dispatch_off_by_default(service):
ok, client = _run(service, _manager(aws_video_worker=False))
assert ok is False
client.post.assert_not_called()
def test_aws_dispatch_requires_aws_to_rank_first(service):
ok, client = _run(service, _manager(top=None))
assert ok is False
client.post.assert_not_called()
def test_aws_dispatch_posts_run_worker(service):
resp = MagicMock(status_code=200)
resp.json.return_value = {"status": "accepted"}
ok, client = _run(service, _manager(), response=resp)
assert ok is True
url = client.post.call_args.args[0]
assert url == "http://3.3.3.3:8080/run-worker"
assert client.post.call_args.kwargs["json"] == {"job_id": "abc123", "module": "video_worker"}
def test_aws_dispatch_falls_back_when_aws_did_not_start(service):
ok, client = _run(service, _manager(started="encoding-worker-a"))
assert ok is False
client.post.assert_not_called()
@pytest.mark.parametrize("status,body", [(503, {"detail": "not enabled"}), (200, {"status": "weird"})])
def test_aws_dispatch_falls_back_on_refusal(service, status, body):
resp = MagicMock(status_code=status, text=json.dumps(body))
resp.json.return_value = body
ok, _ = _run(service, _manager(), response=resp)
assert ok is False
def test_aws_dispatch_falls_back_on_error(service):
ok, _ = _run(service, _manager(), post_exc=ConnectionError("boom"))
assert ok is False
def test_start_failure_never_leaves_run_stuck(worker):
main, env_file = worker
run_id = main.run_worker_id("video_worker", "abc123")
main.jobs[run_id] = {"status": "running"}
with patch.object(main, "_start_worker_run", side_effect=OSError("disk full")):
main._start_worker_run_safe(run_id, _req(main), {})
assert main.jobs[run_id]["status"] == "failed"
assert "disk full" in main.jobs[run_id]["error"]
@pytest.mark.parametrize("bad", ["../../tmp/x", "-h", "", "a b", "x" * 80])
def test_run_worker_rejects_unsafe_job_ids(bad):
from pydantic import ValidationError
from backend.services.gce_encoding import main
with pytest.raises(ValidationError):
main.RunWorkerRequest(job_id=bad)
def test_gce_backend_requests_stash_only_on_the_box(monkeypatch):
"""The encode payload asks for local copies only where the video worker
shares the box with the encoder (LOCAL_ENCODED_OUTPUTS_DIR set)."""
from backend.services.encoding_interface import EncodingInput, GCEEncodingBackend
async def capture(env_value):
if env_value:
monkeypatch.setenv("LOCAL_ENCODED_OUTPUTS_DIR", env_value)
else:
monkeypatch.delenv("LOCAL_ENCODED_OUTPUTS_DIR", raising=False)
svc = MagicMock()
svc.encode_videos = AsyncMock(return_value={"status": "complete", "output_files": []})
backend = GCEEncodingBackend()
backend._service = svc
with patch.object(GCEEncodingBackend, "_get_service", return_value=svc):
await backend.encode(EncodingInput(
title_video_path="t", karaoke_video_path="k", instrumental_audio_path="i",
artist="A", title="T", output_dir="/tmp",
options={"job_id": "abc123_g1", "input_gcs_path": "gs://b/jobs/abc123/",
"output_gcs_path": "gs://b/jobs/abc123/finals/"},
))
return svc.encode_videos.call_args
on = asyncio.run(capture("/var/lib/encoding-worker/outputs"))
off = asyncio.run(capture(None))
on_cfg = on.kwargs.get("encoding_config") or on.args[-1]
off_cfg = off.kwargs.get("encoding_config") or off.args[-1]
assert on_cfg.get("stash_local_outputs") is True
assert "stash_local_outputs" not in off_cfg
@@ -0,0 +1,174 @@
"""create-from-url when YouTube bot-blocks the download.
Job 526bf46c (2026-11-03) failed within 3s of the first bot wall and showed the
customer the raw yt-dlp error, while the credential keeper replaces dead cookies
within minutes.
"""
import json
from pathlib import Path
from unittest.mock import AsyncMock, Mock, patch
import pytest
from fastapi import HTTPException
from backend.api.routes import file_upload
from backend.api.routes.file_upload import CreateJobFromUrlRequest, create_job_from_url
from backend.services.auth_service import AuthResult, UserType
from backend.services.youtube_download_service import (
YouTubeDownloadError,
is_bot_block_error,
)
BOT_WALL = (
"Remote download failed: Download failed: ERROR: [youtube] abcdefghijk: Sign in to "
"confirm you’re not a bot. This helps protect our community. Use "
"--cookies-from-browser or --cookies for the authentication."
)
TRANSLATIONS = Path(file_upload.__file__).parents[2] / "translations"
async def _create(download, availability=None):
request = Mock()
request.headers = {}
request.client = Mock(host="127.0.0.1")
request.url = Mock(path="/api/jobs/create-from-url")
request.state.tenant_config = None
service = Mock()
service.check_availability = availability or AsyncMock(return_value=None)
service.download = download
auth = AuthResult(
is_valid=True, user_type=UserType.ADMIN, remaining_uses=-1,
message="ok", user_email="user@example.com", is_admin=True,
)
body = CreateJobFromUrlRequest(url="https://www.youtube.com/watch?v=abcdefghijk", artist="A", title="T")
with patch.object(file_upload, "job_manager") as job_manager, \
patch.object(file_upload, "worker_service"), \
patch.object(file_upload, "get_credential_manager"), \
patch.object(file_upload, "get_youtube_download_service", return_value=service), \
patch.object(file_upload.asyncio, "sleep", new=AsyncMock()) as sleep:
job_manager.create_job.return_value = Mock(job_id="job-1")
try:
result = await create_job_from_url(
request=request, background_tasks=Mock(), body=body, auth_result=auth,
)
except HTTPException as e:
result = e
return result, job_manager, sleep
@pytest.mark.asyncio
async def test_bot_block_retries_after_delay_and_succeeds():
download = AsyncMock(side_effect=[YouTubeDownloadError(BOT_WALL), "uploads/job-1/audio/a.flac"])
result, job_manager, sleep = await _create(download)
assert result.job_id == "job-1"
assert download.await_count == 2
sleep.assert_awaited_once_with(file_upload.BOT_BLOCK_RETRY_DELAY_SECONDS)
job_manager.fail_job.assert_not_called()
@pytest.mark.asyncio
async def test_bot_block_twice_fails_job_with_friendly_message():
download = AsyncMock(side_effect=YouTubeDownloadError(BOT_WALL))
result, job_manager, _ = await _create(download)
assert download.await_count == 2
assert isinstance(result, HTTPException)
assert result.status_code == 500 # 503 would read as a backend blip in the frontend
assert "Audio Search" in result.detail
assert "cookies" not in result.detail
assert "ERROR" not in result.detail
job_manager.fail_job.assert_called_once()
args = job_manager.fail_job.call_args
assert args.args[1] == result.detail
# Operators keep the real error.
assert "not a bot" in args.kwargs["error_details"]["raw_error"]
assert args.kwargs["error_details"]["code"] == "youtube_bot_block"
@pytest.mark.asyncio
async def test_retry_failing_differently_reports_the_new_error():
download = AsyncMock(side_effect=[YouTubeDownloadError(BOT_WALL), YouTubeDownloadError("Video unavailable")])
result, job_manager, _ = await _create(download)
assert download.await_count == 2
assert "Video unavailable" in result.detail
assert "Video unavailable" in job_manager.fail_job.call_args.args[1]
@pytest.mark.asyncio
async def test_other_download_errors_fail_without_retry():
download = AsyncMock(side_effect=YouTubeDownloadError("Video unavailable"))
result, job_manager, sleep = await _create(download)
assert download.await_count == 1
sleep.assert_not_awaited()
assert result.status_code == 500
assert "Video unavailable" in result.detail
assert job_manager.fail_job.call_args.args[1] == "Download failed: Video unavailable"
BLOCKED_CHECK = {"available": False, "is_bot_blocked": True, "error": "not a bot"}
@pytest.mark.asyncio
async def test_bot_blocked_precheck_is_rechecked_and_job_proceeds():
"""Before any job exists, the same wait gives the cookie re-export time to finish."""
availability = AsyncMock(side_effect=[BLOCKED_CHECK, {"available": True}])
download = AsyncMock(return_value="uploads/job-1/audio/a.flac")
result, job_manager, sleep = await _create(download, availability)
assert result.job_id == "job-1"
assert availability.await_count == 2
sleep.assert_awaited_once_with(file_upload.BOT_BLOCK_RETRY_DELAY_SECONDS)
job_manager.create_job.assert_called_once()
@pytest.mark.asyncio
async def test_bot_blocked_precheck_twice_rejects_without_creating_a_job():
availability = AsyncMock(return_value=BLOCKED_CHECK)
download = AsyncMock()
result, job_manager, _ = await _create(download, availability)
assert availability.await_count == 2
assert result.status_code == 400
assert "Audio Search" in result.detail
job_manager.create_job.assert_not_called()
download.assert_not_awaited()
@pytest.mark.asyncio
async def test_other_unavailable_precheck_rejects_without_recheck():
availability = AsyncMock(return_value={"available": False, "is_private": True})
result, _, sleep = await _create(AsyncMock(), availability)
assert availability.await_count == 1
sleep.assert_not_awaited()
assert result.status_code == 400
assert "private" in result.detail
@pytest.mark.parametrize("message,expected", [
(BOT_WALL, True),
("Sign in to confirm you're NOT A BOT", True),
("The provided YouTube account cookies are no longer valid.", True),
("Sign in to confirm your age", False),
("Video unavailable", False),
])
def test_is_bot_block_error(message, expected):
assert is_bot_block_error(YouTubeDownloadError(message)) is expected
def test_friendly_message_is_translated_in_every_locale():
locale_files = sorted(TRANSLATIONS.glob("*.json"))
assert len(locale_files) == 33
english = json.loads((TRANSLATIONS / "en.json").read_text())["audioSearch"]["youtubeBotBlocked"]
for path in locale_files:
value = json.loads(path.read_text())["audioSearch"]["youtubeBotBlocked"]
assert value.strip(), path.name
if path.name != "en.json":
assert value != english, f"{path.name} is untranslated"
+60
View File
@@ -1,6 +1,7 @@
"""
Tests for credential manager and auth endpoints.
"""
import logging
import pytest
import json
from unittest.mock import MagicMock, patch
@@ -194,6 +195,65 @@ class TestCredentialManager:
assert result is False
def test_expired_dropbox_token_probe_logs_warning_not_error(self, caplog):
"""Short-lived tokens expire constantly and get refreshed; that isn't page-worthy."""
manager = CredentialManager()
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
assert manager._test_dropbox_api({"access_token": "test"}) is False
levels = [r.levelno for r in caplog.records if "Dropbox" in r.message]
assert levels == [logging.WARNING]
def _dropbox_manager(self, creds):
manager = CredentialManager()
manager.settings = MagicMock()
manager.settings.get_secret.return_value = json.dumps(creds)
return manager
FULL_DROPBOX_CREDS = {"access_token": "a", "refresh_token": "r", "app_key": "k", "app_secret": "s"}
def test_dropbox_refresh_success_logs_no_error(self, caplog):
manager = self._dropbox_manager(self.FULL_DROPBOX_CREDS)
ok = MagicMock(status_code=200)
ok.json.return_value = {"access_token": "new"}
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")), \
patch('requests.post', return_value=ok), \
patch.object(manager, "_update_dropbox_credentials", return_value=True):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
result = manager.check_dropbox_credentials()
assert result.status == CredentialStatus.VALID
assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
def test_dropbox_refresh_rejected_logs_error(self, caplog):
manager = self._dropbox_manager(self.FULL_DROPBOX_CREDS)
bad = MagicMock(status_code=400, text='{"error": "invalid_grant"}')
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")), \
patch('requests.post', return_value=bad):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
result = manager.check_dropbox_credentials()
assert result.status == CredentialStatus.INVALID
errors = [r.message for r in caplog.records if r.levelno >= logging.ERROR]
assert len(errors) == 1
assert "400" in errors[0]
assert "invalid_grant" in errors[0]
def test_dropbox_refresh_raising_logs_one_error(self, caplog):
manager = self._dropbox_manager(self.FULL_DROPBOX_CREDS)
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")), \
patch('requests.post', side_effect=RuntimeError("network down")):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
result = manager.check_dropbox_credentials()
assert result.status == CredentialStatus.INVALID
assert len([r for r in caplog.records if r.levelno >= logging.ERROR]) == 1
def test_dropbox_invalid_with_no_refresh_token_logs_error(self, caplog):
manager = self._dropbox_manager({"access_token": "a"})
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
result = manager.check_dropbox_credentials()
assert result.status == CredentialStatus.INVALID
assert len([r for r in caplog.records if r.levelno >= logging.ERROR]) == 1
def test_send_credential_alert_no_webhook(self):
"""Test alert without webhook URL."""
manager = CredentialManager()
+40
View File
@@ -219,3 +219,43 @@ class TestSelectGreenRankingSharedWithRuntime:
cands = select_green_candidates(_config(active_override_vm=None), self.POOL)
c4 = next(c for c in cands if c["vm"] == "encoding-worker-fallback-c4a")
assert c4["machine_type"] == "c4-highcpu-16"
# --- AWS encoding worker: never touched by the GCE blue-green deploy ----------
_AWS = {"vm": "aws-encoding-worker-1", "zone": "us-east-2b", "ip": "3.3.3.3",
"machine_type": "c7a-8xlarge", "provider": "aws", "instance_id": "i-0abc", "region": "us-east-2"}
def test_aws_worker_is_never_a_green_candidate():
config = {"secondary_vm": "encoding-worker-b", "secondary_ip": "1.1.1.2"}
fallbacks = [{"vm": "encoding-worker-fallback-c2df", "zone": "us-central1-f", "ip": "2.2.2.2"}, _AWS]
names = [c["vm"] for c in deploy_promote.select_green_candidates(config, fallbacks)]
assert "aws-encoding-worker-1" not in names
assert names == ["encoding-worker-b", "encoding-worker-fallback-c2df"]
def test_secondary_promotion_leaves_aws_override_serving():
config = {
"primary_vm": "encoding-worker-a", "primary_ip": "1.1.1.1", "primary_version": "1.0",
"active_override_vm": "aws-encoding-worker-1", "active_override_ip": "3.3.3.3",
"active_override_zone": "us-east-2b", "active_override_provider": "aws",
}
green = {"vm": "encoding-worker-b", "ip": "1.1.1.2", "zone": "us-central1-c", "kind": "secondary"}
plan = deploy_promote.promote_plan(green, config, now="2026-10-29T00:00:00Z", version="2.0")
assert "active_override_vm" not in plan["firestore_updates"]
assert [d["vm"] for d in plan["drain_and_stop"]] == ["encoding-worker-a"]
def test_fallback_promotion_does_not_drain_aws_override():
config = {"active_override_vm": "aws-encoding-worker-1", "active_override_zone": "us-east-2b",
"active_override_provider": "aws"}
green = {"vm": "encoding-worker-fallback-c2df", "ip": "2.2.2.2", "zone": "us-central1-f", "kind": "fallback"}
plan = deploy_promote.promote_plan(green, config, now="2026-10-29T00:00:00Z", version="2.0")
assert plan["drain_and_stop"] == []
def test_fallback_promotion_clears_provider_tag():
green = {"vm": "encoding-worker-fallback-c2df", "ip": "2.2.2.2", "zone": "us-central1-f", "kind": "fallback"}
plan = deploy_promote.promote_plan(green, {}, now="2026-10-29T00:00:00Z", version="2.0")
assert plan["firestore_updates"]["active_override_provider"] is None
+10 -3
View File
@@ -1351,12 +1351,19 @@ class TestBuildWorkerCandidates:
cfg.primary_ip = "10.0.0.1"
cfg.primary_machine_type = None # → defaults to c4d
cfg.capacity_state = capacity_state or {}
cfg.speed_rank_overrides = {}
return cfg
def _service_with_fallbacks(self, encoding_service, fallbacks_json, capacity_state=None):
mgr = MagicMock()
mgr._zone = "us-central1-c"
mgr.get_config.return_value = self._config(capacity_state)
# Ranking lives in EncodingWorkerManager.ranked_candidates (shared with the
# warmups), so use a real manager with a mocked config read.
from backend.services.encoding_worker_manager import EncodingWorkerManager
mgr = EncodingWorkerManager(
db=MagicMock(), compute_client=MagicMock(), zone="us-central1-c",
fallback_vms_raw=fallbacks_json,
)
mgr.get_config = MagicMock(return_value=self._config(capacity_state))
encoding_service._worker_manager = mgr
encoding_service.settings.encoding_worker_fallback_vms = fallbacks_json
return encoding_service
@@ -0,0 +1,188 @@
"""EncodingWorkerManager with the AWS encoding worker in the pool.
Covers routing AWS VMs to the EC2 adapter (GCE untouched), the shared fallback
parser passing provider fields through, ranking with Firestore
speed_rank_overrides, the ranked warmup, and the override's provider tag.
"""
import json
from unittest.mock import MagicMock
import pytest
from backend.services.aws_encoding_compute import AwsStartOperation
from backend.services.encoding_errors import EncodingWorkerCapacityError
from backend.services.encoding_worker_manager import EncodingWorkerManager, parse_fallback_vms
AWS_ENTRY = {
"vm": "aws-encoding-worker-1", "zone": "us-east-2b", "ip": "3.3.3.3",
"machine_type": "c7a-8xlarge", "provider": "aws", "instance_id": "i-0abc", "region": "us-east-2",
}
C2D_ENTRY = {"vm": "encoding-worker-fallback-c2df", "zone": "us-central1-f", "ip": "2.2.2.2",
"machine_type": "c2d-highcpu-16"}
def _db(**config):
data = {
"primary_vm": "encoding-worker-a", "primary_ip": "1.1.1.1", "primary_version": "1.0",
"secondary_vm": "encoding-worker-b", "secondary_ip": "1.1.1.2",
"last_activity_at": None, "capacity_state": {}, **config,
}
db = MagicMock()
snap = MagicMock(exists=True)
snap.to_dict.return_value = data
doc = MagicMock()
doc.get.return_value = snap
db.collection.return_value.document.return_value = doc
return db, doc
def _manager(db, aws=None, entries=(C2D_ENTRY, AWS_ENTRY)):
gce = MagicMock(name="gce")
aws = aws or MagicMock(name="aws")
aws.handles.side_effect = lambda vm: vm == AWS_ENTRY["vm"]
m = EncodingWorkerManager(db=db, compute_client=gce, fallback_vms_raw=json.dumps(list(entries)), aws_compute=aws)
return m, gce, aws
def test_parse_fallback_vms_passes_aws_fields_through():
parsed = parse_fallback_vms(json.dumps([C2D_ENTRY, AWS_ENTRY]))
assert parsed[0] == {**C2D_ENTRY, "kind": "fallback"}
assert parsed[1]["provider"] == "aws"
assert parsed[1]["instance_id"] == "i-0abc" and parsed[1]["region"] == "us-east-2"
@pytest.mark.parametrize("raw", [None, "", "not json", "{}", "null"])
def test_parse_fallback_vms_never_raises(raw):
assert parse_fallback_vms(raw) == []
def test_aws_vm_ops_go_to_adapter_and_gce_untouched():
db, _ = _db()
m, gce, aws = _manager(db)
aws.get.return_value = MagicMock(status="RUNNING")
gce.get.return_value = MagicMock(status="TERMINATED")
assert m.get_vm_status("aws-encoding-worker-1", zone="us-east-2b") == "RUNNING"
assert m.get_vm_status("encoding-worker-a") == "TERMINATED"
aws.get.assert_called_once()
gce.get.assert_called_once()
def test_aws_capacity_error_raises_typed_capacity_error():
db, _ = _db()
m, _, aws = _manager(db)
aws.get.return_value = MagicMock(status="TERMINATED")
def _no_capacity():
from botocore.exceptions import ClientError
raise ClientError({"Error": {"Code": "InsufficientInstanceCapacity", "Message": "none"}}, "StartInstances")
aws.start.return_value = AwsStartOperation(_no_capacity)
with pytest.raises(EncodingWorkerCapacityError):
m.start_vm("aws-encoding-worker-1", zone="us-east-2b")
def test_ranked_candidates_default_keeps_gce_primary_first_and_aws_last():
db, _ = _db()
m, _, _ = _manager(db)
ranked = m.ranked_candidates()
assert [c.vm_name for c in ranked] == ["encoding-worker-a", "encoding-worker-fallback-c2df", "aws-encoding-worker-1"]
assert ranked[0].is_primary and ranked[-1].provider == "aws"
def test_ranked_candidates_honour_speed_rank_overrides():
db, _ = _db(speed_rank_overrides={"c7a": 5})
m, _, _ = _manager(db)
assert m.ranked_candidates()[0].vm_name == "aws-encoding-worker-1"
def test_ensure_preferred_running_is_primary_path_when_primary_ranks_first():
db, _ = _db()
m, _, _ = _manager(db)
m.ensure_primary_running = MagicMock(return_value={"started": False})
m.ensure_any_running = MagicMock()
m.ensure_preferred_running()
m.ensure_primary_running.assert_called_once()
m.ensure_any_running.assert_not_called()
def test_ensure_preferred_running_starts_aws_when_preferred():
db, _ = _db(speed_rank_overrides={"c7a": 5})
m, _, _ = _manager(db)
m.ensure_primary_running = MagicMock()
m.ensure_any_running = MagicMock(return_value={"started": True, "vm_name": "aws-encoding-worker-1"})
m.ensure_preferred_running()
m.ensure_primary_running.assert_not_called()
(candidates,), _ = m.ensure_any_running.call_args
assert candidates[0].vm_name == "aws-encoding-worker-1"
def test_active_override_records_provider():
db, doc = _db()
m, _, _ = _manager(db)
aws_candidate = next(c for c in m.ranked_candidates() if c.provider == "aws")
m._set_active_override(aws_candidate)
update = doc.update.call_args[0][0]
assert update["active_override_vm"] == "aws-encoding-worker-1"
assert update["active_override_provider"] == "aws"
db2, doc2 = _db(active_override_vm="aws-encoding-worker-1", active_override_provider="aws")
m2, _, _ = _manager(db2)
m2._clear_active_override()
assert doc2.update.call_args[0][0]["active_override_provider"] is None
def test_aws_control_plane_fault_fails_over_to_gce():
db, _ = _db(speed_rank_overrides={"c7a": 5})
m, gce, aws = _manager(db, entries=(AWS_ENTRY,))
aws.get.side_effect = RuntimeError("could not load aws-encoding-controller-credentials")
gce.get.return_value = MagicMock(status="RUNNING")
m.update_activity = MagicMock()
m._clear_active_override = MagicMock()
m._clear_stockout = MagicMock()
result = m.ensure_any_running(m.ranked_candidates())
assert result["vm_name"] == "encoding-worker-a"
def _settings(env_value, secret_value):
s = MagicMock()
s.encoding_worker_fallback_vms = env_value
s.get_secret = MagicMock(return_value=secret_value)
return s
def test_fallback_entries_read_secret_in_prod_when_env_missing(monkeypatch):
"""Jobs without the env var (audio/lyrics/download) still see the AWS worker:
they trigger the video worker after stems, so they must rank identically."""
from unittest.mock import patch
db, _ = _db()
m = EncodingWorkerManager(db=db, compute_client=MagicMock(), aws_compute=MagicMock())
settings = _settings(None, json.dumps([AWS_ENTRY]))
with patch("backend.config.get_settings", return_value=settings), \
patch("backend.config.is_production", return_value=True):
assert [e["vm"] for e in m.fallback_entries()] == ["aws-encoding-worker-1"]
settings.get_secret.assert_called_once_with("encoding-worker-fallback-vms")
def test_fallback_entries_never_fetch_secret_outside_prod():
from unittest.mock import patch
db, _ = _db()
m = EncodingWorkerManager(db=db, compute_client=MagicMock(), aws_compute=MagicMock())
settings = _settings(None, json.dumps([AWS_ENTRY]))
with patch("backend.config.get_settings", return_value=settings), \
patch("backend.config.is_production", return_value=False):
assert m.fallback_entries() == []
settings.get_secret.assert_not_called()
def test_fallback_entries_prefer_env_over_secret():
from unittest.mock import patch
db, _ = _db()
m = EncodingWorkerManager(db=db, compute_client=MagicMock(), aws_compute=MagicMock())
settings = _settings(json.dumps([C2D_ENTRY]), json.dumps([AWS_ENTRY]))
with patch("backend.config.get_settings", return_value=settings), \
patch("backend.config.is_production", return_value=True):
assert [e["vm"] for e in m.fallback_entries()] == ["encoding-worker-fallback-c2df"]
settings.get_secret.assert_not_called()
@@ -170,3 +170,56 @@ def test_cooldown_key_shape():
assert cooldown_key(_c("x", "us-central1-c", "c4d-highcpu-16")) == "c4d-highcpu-16@us-central1-c"
assert cooldown_key(_c("x", None, "n2-highcpu-16")) == "n2-highcpu-16"
assert cooldown_key(_c("no-token", "z")) is None
# --- AWS encoding worker (c7a) + runtime rank overrides -----------------------
AWS = dict(provider="aws", instance_id="i-0abc", region="us-east-2")
def test_aws_worker_is_last_resort_by_default():
pool = [
_c("aws-encoding-worker-1", "us-east-2b", "c7a-8xlarge", **AWS),
_c("encoding-worker-fallback-c2df", "us-central1-f", "c2d-highcpu-16"),
_c("encoding-worker-a", "us-central1-c", "c4d-highcpu-16"),
]
ranked = ordered_candidates(pool, now=NOW)
assert [c["vm"] for c in ranked] == [
"encoding-worker-a", "encoding-worker-fallback-c2df", "aws-encoding-worker-1",
]
def test_rank_override_prefers_aws_worker():
pool = [
_c("encoding-worker-a", "us-central1-c", "c4d-highcpu-16"),
_c("encoding-worker-fallback-c2df", "us-central1-f", "c2d-highcpu-16"),
_c("aws-encoding-worker-1", "us-east-2b", "c7a-8xlarge", **AWS),
]
ranked = ordered_candidates(pool, now=NOW, rank_overrides={"c7a": 5})
assert ranked[0]["vm"] == "aws-encoding-worker-1"
# The rest keep the built-in order behind it.
assert [c["vm"] for c in ranked[1:]] == ["encoding-worker-a", "encoding-worker-fallback-c2df"]
def test_stocked_out_aws_worker_still_demoted_despite_override():
aws = _c("aws-encoding-worker-1", "us-east-2b", "c7a-8xlarge", **AWS)
pool = [aws, _c("encoding-worker-a", "us-central1-c", "c4d-highcpu-16")]
state = {cooldown_key(aws): (NOW - timedelta(seconds=60)).isoformat()}
ranked = ordered_candidates(pool, capacity_state=state, now=NOW, rank_overrides={"c7a": 5})
assert ranked[-1]["vm"] == "aws-encoding-worker-1"
def test_malformed_rank_override_falls_back_to_builtin_rank():
pool = [
_c("aws-encoding-worker-1", "us-east-2b", "c7a-8xlarge", **AWS),
_c("encoding-worker-a", "us-central1-c", "c4d-highcpu-16"),
]
ranked = ordered_candidates(pool, now=NOW, rank_overrides={"c7a": "first please"})
assert ranked[0]["vm"] == "encoding-worker-a"
def test_aws_cooldown_key_is_firestore_safe():
key = cooldown_key(_c("aws-encoding-worker-1", "us-east-2b", "c7a-8xlarge", **AWS))
assert key == "c7a-8xlarge@us-east-2b"
assert "." not in key
assert SPEED_RANK["c7a"] > SPEED_RANK["c2d"]
+3 -3
View File
@@ -23,12 +23,12 @@ class TestWarmupHandler:
def test_success_passthrough(self):
manager = MagicMock()
manager.ensure_primary_running.return_value = {"started": True, "vm_name": "encoding-worker-a"}
manager.ensure_preferred_running.return_value = {"started": True, "vm_name": "encoding-worker-a"}
assert self._run(manager)["started"] is True
def test_start_error_is_soft(self):
manager = MagicMock()
manager.ensure_primary_running.side_effect = EncodingWorkerStartError("zone exhausted")
manager.ensure_preferred_running.side_effect = EncodingWorkerStartError("zone exhausted")
result = self._run(manager)
assert result["started"] is False
assert "zone exhausted" in result["error"]
@@ -41,7 +41,7 @@ class TestWarmupHandler:
time.sleep(0.5)
return {"started": False}
manager.ensure_primary_running.side_effect = slow_warmup
manager.ensure_preferred_running.side_effect = slow_warmup
async def scenario():
ticks = 0
+14
View File
@@ -733,3 +733,17 @@ class TestVerifyWheelImports:
monkeypatch.setattr(main.subprocess, "run", _timeout)
assert main.verify_wheel_imports() is False
class TestGcsCli:
"""The AWS worker (WIF auth) can't use gsutil; GCE workers keep it."""
def test_gce_worker_uses_gsutil(self, monkeypatch):
from backend.services.gce_encoding import main as worker
monkeypatch.delenv("ENCODING_WORKER_PROVIDER", raising=False)
assert worker._gcs_cli() == ["gsutil"]
def test_aws_worker_uses_gcloud_storage(self, monkeypatch):
from backend.services.gce_encoding import main as worker
monkeypatch.setenv("ENCODING_WORKER_PROVIDER", "aws")
assert worker._gcs_cli() == ["gcloud", "storage"]
+18
View File
@@ -290,6 +290,24 @@ class TestJobStatusTransitions:
class TestJobFailure:
"""Test job failure handling."""
def test_fail_job_logs_warning_not_error(self, job_manager, mock_firestore_service, caplog):
"""ops_alerts' job-failed alert is the one alert; an ERROR here made a second one."""
import logging
mock_firestore_service.get_job.return_value = None
with caplog.at_level(logging.INFO, logger="backend.services.job_manager"):
job_manager.fail_job("job-1", "Download failed: boom")
records = [r for r in caplog.records if "job-1 failed" in r.getMessage()]
assert [r.levelno for r in records] == [logging.WARNING]
def test_mark_job_failed_logs_warning_not_error(self, job_manager, mock_firestore_service, caplog):
import logging
with caplog.at_level(logging.INFO, logger="backend.services.job_manager"):
job_manager.mark_job_failed("job-2", "boom")
records = [r for r in caplog.records if "job-2 failed" in r.getMessage()]
assert [r.levelno for r in records] == [logging.WARNING]
def test_mark_job_as_failed(self, job_manager, mock_firestore_service):
"""Test marking a job as failed."""
error_message = "Audio separation failed"
+29 -3
View File
@@ -426,6 +426,14 @@ class TestStartReview:
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.record_review_started.assert_not_called()
@pytest.mark.parametrize("status", [JobStatus.COMPLETE, JobStatus.REVIEW_COMPLETE, JobStatus.ENCODING])
def test_start_review_after_review_ended_is_409(self, client, mock_job_manager, mock_job, auth_headers, status):
"""A stale link or notification gets an expected 409, with no transition attempt (which logs ERROR)."""
mock_job.status = status
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 409
mock_job_manager.transition_to_state.assert_not_called()
def test_start_review_lost_race_is_success(self, client, mock_job_manager, mock_job, auth_headers):
"""Both requests saw awaiting_review; the loser's transition raises but job is in_review."""
from backend.exceptions import InvalidStateTransitionError
@@ -440,12 +448,30 @@ class TestStartReview:
assert response.json() == {"status": "success", "job_status": "in_review"}
mock_job_manager.record_review_started.assert_not_called()
def test_start_review_invalid_transition_otherwise_still_errors(self, client, mock_job_manager, mock_job, auth_headers):
def test_start_review_invalid_transition_race_returns_409(self, client, mock_job_manager, mock_job, auth_headers):
"""The auto-approver moved the job past review between our read and the transition."""
from backend.exceptions import InvalidStateTransitionError
mock_job.status = JobStatus.AWAITING_REVIEW
moved_on = mock_job.model_copy(update={"status": JobStatus.REVIEW_COMPLETE})
mock_job_manager.get_job.side_effect = [mock_job, moved_on, moved_on]
mock_job_manager.transition_to_state.side_effect = InvalidStateTransitionError(message="nope")
with pytest.raises(InvalidStateTransitionError):
client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 409
assert "review_complete" in response.json()["detail"]
mock_job_manager.record_review_started.assert_not_called()
@pytest.mark.parametrize("status", [JobStatus.COMPLETE, JobStatus.FAILED, JobStatus.PENDING])
def test_start_review_outside_review_returns_409_without_transition(
self, client, mock_job_manager, mock_job, auth_headers, status
):
"""A stale "review lyrics" push on a finished job: no 500, no transition, no ERROR log."""
mock_job.status = status
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 409
assert status.value in response.json()["detail"]
assert "JobStatus." not in response.json()["detail"]
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.record_review_started.assert_not_called()
def test_start_review_from_awaiting_records_once(self, client, mock_job_manager, mock_job, auth_headers):
mock_job.status = JobStatus.AWAITING_REVIEW
+64
View File
@@ -181,3 +181,67 @@ def test_lifespan_warms_route_contexts_off_loop_before_readiness():
assert seen[0][0] is main_module.app
assert seen[0][1].startswith("asyncio_"), seen
def test_anyio_backend_is_a_lazy_route_import():
"""starlette/middleware/base.py imports it on the first request: 17.3s on the loop
with 18 requests in flight, 2026-10-30."""
assert "anyio._backends._asyncio" in main_module._LAZY_ROUTE_IMPORTS
def test_warm_request_runs_through_the_whole_middleware_stack_off_loop():
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import PlainTextResponse
from starlette.routing import Route
seen = {}
class Spy(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
seen["thread"] = threading.current_thread().name
seen["path"] = request.url.path
return await call_next(request)
async def health(_request):
return PlainTextResponse("ok")
app = Starlette(routes=[Route("/api/health", health)], middleware=[Middleware(Spy)])
assert app.middleware_stack is None
worker = threading.Thread(target=main_module._warm_middleware_stack, args=(app,), name="warm-test")
worker.start()
worker.join(timeout=10)
assert seen == {"thread": "warm-test", "path": "/api/health"}
assert app.middleware_stack is not None
def test_warm_request_failure_never_blocks_startup():
async def broken_app(scope, receive, send):
raise RuntimeError("boom")
main_module._warm_middleware_stack(broken_app) # must not raise
def test_lifespan_warms_the_middleware_stack_before_readiness():
calls = []
def fake_warm(application):
calls.append(application)
with patch.object(main_module, "_run_background_warmup"), \
patch.object(main_module, "_warm_middleware_stack", fake_warm):
with TestClient(main_module.app):
assert calls == [main_module.app]
def test_warm_request_on_the_real_app_returns_healthy_and_skips_the_audit_log(caplog):
import logging
with caplog.at_level(logging.INFO):
main_module._warm_middleware_stack(main_module.app)
assert main_module.app.middleware_stack is not None
assert not [r for r in caplog.records if r.name == "audit"]
assert not [r for r in caplog.records if "warm request failed" in r.message.lower()]
+103
View File
@@ -0,0 +1,103 @@
"""POST /api/review/{job_id}/sync-reference: admin-only "perfectly synced" mark that
puts a job's reviewed word timing in the reference set (full-auto v2)."""
from unittest.mock import MagicMock, patch
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
from backend.api.dependencies import require_admin, require_auth
from backend.main import app
from backend.services.auth_service import AuthResult, UserType
def _admin():
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999, message="ok",
is_admin=True, user_email="andrew@nomadkaraoke.com")
@pytest.fixture
def jm():
m = MagicMock()
m.get_job.return_value = MagicMock(
job_id="j1", file_urls={"lyrics": {"corrections_updated": "jobs/j1/lyrics/corrections_updated.json"}})
return m
@pytest.fixture
def client(jm):
async def fake_admin():
return _admin()
saved = dict(app.dependency_overrides)
app.dependency_overrides[require_admin] = fake_admin
try:
with patch("backend.api.routes.review.JobManager", return_value=jm):
yield TestClient(app)
finally:
app.dependency_overrides.clear(); app.dependency_overrides.update(saved)
def test_admin_marks_job_verified(client, jm):
r = client.post("/api/review/j1/sync-reference", json={"verified": True, "notes": " spot-checked chorus "})
assert r.status_code == 200
jid, key, record = jm.update_state_data.call_args.args
assert (jid, key) == ("j1", "sync_reference")
assert record["verified"] is True
assert record["by"] == "andrew@nomadkaraoke.com"
assert record["notes"] == "spot-checked chorus"
assert record["at"]
def test_blank_notes_stored_as_none(client, jm):
client.post("/api/review/j1/sync-reference", json={"verified": False, "notes": " "})
assert jm.update_state_data.call_args.args[2]["notes"] is None
assert jm.update_state_data.call_args.args[2]["verified"] is False
def test_unknown_job_404(client, jm):
jm.get_job.return_value = None
r = client.post("/api/review/nope/sync-reference", json={"verified": True})
assert r.status_code == 404
jm.update_state_data.assert_not_called()
def test_missing_verified_is_422(client):
assert client.post("/api/review/j1/sync-reference", json={}).status_code == 422
def test_non_admin_forbidden(jm):
async def fake_user():
return AuthResult(is_valid=True, user_type=UserType.UNLIMITED, remaining_uses=999, message="ok",
is_admin=False, user_email="someone@example.com")
saved = dict(app.dependency_overrides)
app.dependency_overrides.pop(require_admin, None) # conftest stubs it to always-admin
app.dependency_overrides[require_auth] = fake_user
try:
with patch("backend.api.routes.review.JobManager", return_value=jm):
r = TestClient(app).post("/api/review/j1/sync-reference", json={"verified": True})
assert r.status_code == 403
jm.update_state_data.assert_not_called()
finally:
app.dependency_overrides.clear(); app.dependency_overrides.update(saved)
def test_verified_requires_saved_review(client, jm):
jm.get_job.return_value = MagicMock(job_id="j1", file_urls={"lyrics": {}})
with patch("backend.api.routes.review.StorageService") as st:
st.return_value.file_exists.return_value = False
r = client.post("/api/review/j1/sync-reference", json={"verified": True})
assert r.status_code == 409
jm.update_state_data.assert_not_called()
# revoking is always allowed
assert client.post("/api/review/j1/sync-reference", json={"verified": False}).status_code == 200
def test_verified_accepts_direct_path_file(client, jm):
jm.get_job.return_value = MagicMock(job_id="j1", file_urls={})
with patch("backend.api.routes.review.StorageService") as st:
st.return_value.file_exists.return_value = True
r = client.post("/api/review/j1/sync-reference", json={"verified": True})
assert r.status_code == 200
st.return_value.file_exists.assert_called_with("jobs/j1/lyrics/corrections_updated.json")
+29
View File
@@ -1738,6 +1738,35 @@ class TestReplayCorrectionData:
finally:
self._teardown()
def _awaiting_job(self):
from backend.models.job import JobStatus
job = self._completed_job()
job.status = JobStatus.AWAITING_REVIEW
job.state_data = {}
return job
def test_auto_approver_race_returns_409_not_500(self):
"""Job read as awaiting_review, then auto-approved before our transition."""
from backend.exceptions import InvalidStateTransitionError
from backend.models.job import JobStatus
client = self._client_with_auth("full")
try:
with patch("backend.api.routes.review.JobManager") as jm, \
patch("backend.api.routes.review.StorageService") as storage_cls:
moved_on = self._awaiting_job()
moved_on.status = JobStatus.REVIEW_COMPLETE
jm.return_value.get_job.side_effect = [self._awaiting_job(), moved_on, moved_on]
jm.return_value.transition_to_state.side_effect = InvalidStateTransitionError(message="nope")
storage_cls.return_value.file_exists.return_value = True
storage_cls.return_value.download_json.return_value = {"corrected_segments": []}
resp = client.get("/api/review/job1/correction-data")
assert resp.status_code == 409
assert "review_complete" in resp.json()["detail"]
jm.return_value.record_review_started.assert_not_called()
finally:
self._teardown()
def test_replay_requires_full_auth(self):
client = self._client_with_auth("review_token")
try:
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "فهرس تحديد غير صالح {selection_index}. النطاق الصالح: 0-{max}",
"selectionError": "خطأ أثناء تحديد الصوت للمهمة {job_id}: {error}",
"youtubeDownloadError": "فشل تنزيل YouTube: {error}",
"youtubeBotBlocked": "يحظر YouTube خادمنا مؤقتاً، لذا لم نتمكن من تنزيل هذا الفيديو. يرجى استخدام البحث الصوتي للعثور على هذه الأغنية من مصدر آخر، أو المحاولة مرة أخرى بعد بضع دقائق.",
"torrentDownloadError": "لا يمكن التنزيل من {source} بدون خدمة flacfetch عن بُعد. قم بإعداد FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "لا يتوفر source_id أو remote_search_id لتنزيل {source}",
"remoteDownloadCompleteNoPath": "اكتمل التنزيل عن بُعد ولكن لم يتم إرجاع مسار الملف",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Índex de selecció no vàlid {selection_index}. Rang vàlid: 0-{max}",
"selectionError": "Error durant la selecció d'àudio per a la tasca {job_id}: {error}",
"youtubeDownloadError": "La descàrrega de YouTube ha fallat: {error}",
"youtubeBotBlocked": "YouTube està bloquejant temporalment el nostre servidor, així que no hem pogut baixar aquest vídeo. Utilitza la Cerca d'àudio per trobar aquesta cançó en una altra font, o torna-ho a provar d'aquí a uns minuts.",
"torrentDownloadError": "No es pot descarregar des de {source} sense el servei remot flacfetch. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No hi ha cap source_id o remote_search_id disponible per a la descàrrega de {source}",
"remoteDownloadCompleteNoPath": "Descàrrega remota completada però no s'ha retornat cap camí de fitxer",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Neplatný index výběru {selection_index}. Platný rozsah: 0-{max}",
"selectionError": "Chyba při výběru zvuku pro úlohu {job_id}: {error}",
"youtubeDownloadError": "Stahování z YouTube selhalo: {error}",
"youtubeBotBlocked": "YouTube dočasně blokuje náš server, takže se nám toto video nepodařilo stáhnout. Použij prosím Audio Search k vyhledání této písně z jiného zdroje, nebo to zkus znovu za pár minut.",
"torrentDownloadError": "Nelze stahovat z {source} bez vzdálené služby flacfetch. Nakonfiguruj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Pro stahování z {source} není k dispozici žádné source_id nebo remote_search_id",
"remoteDownloadCompleteNoPath": "Vzdálené stahování bylo dokončeno, ale nebyla vrácena žádná cesta k souboru",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ugyldigt valgindeks {selection_index}. Gyldigt område: 0-{max}",
"selectionError": "Fejl under lydvalg for job {job_id}: {error}",
"youtubeDownloadError": "YouTube-download mislykkedes: {error}",
"youtubeBotBlocked": "YouTube blokerer midlertidigt vores server, så vi kunne ikke downloade denne video. Brug Audio Search til at finde denne sang fra en anden kilde, eller prøv igen om et par minutter.",
"torrentDownloadError": "Kan ikke downloade fra {source} uden ekstern flacfetch-tjeneste. Konfigurer FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Ingen source_id eller remote_search_id tilgængelig for {source}-download",
"remoteDownloadCompleteNoPath": "Ekstern download fuldført, men ingen filsti blev returneret",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ungültiger Auswahlindex {selection_index}. Gültiger Bereich: 0-{max}",
"selectionError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
"youtubeDownloadError": "YouTube-Download fehlgeschlagen: {error}",
"youtubeBotBlocked": "YouTube blockiert unseren Server vorübergehend, daher konnten wir dieses Video nicht herunterladen. Bitte verwende die Audiosuche, um diesen Song aus einer anderen Quelle zu finden, oder versuche es in ein paar Minuten noch einmal.",
"torrentDownloadError": "Download von {source} ohne Remote-flacfetch-Dienst nicht möglich. Konfiguriere FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Keine source_id oder remote_search_id für den {source}-Download verfügbar",
"remoteDownloadCompleteNoPath": "Remote-Download abgeschlossen, aber kein Dateipfad zurückgegeben",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Μη έγκυρο ευρετήριο επιλογής {selection_index}. Έγκυρο εύρος: 0-{max}",
"selectionError": "Σφάλμα κατά την επιλογή ήχου για την εργασία {job_id}: {error}",
"youtubeDownloadError": "Η λήψη από το YouTube απέτυχε: {error}",
"youtubeBotBlocked": "Το YouTube μπλοκάρει προσωρινά τον διακομιστή μας, οπότε δεν μπορέσαμε να κατεβάσουμε αυτό το βίντεο. Χρησιμοποίησε την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι από άλλη πηγή, ή δοκίμασε ξανά σε λίγα λεπτά.",
"torrentDownloadError": "Δεν είναι δυνατή η λήψη από το {source} χωρίς την απομακρυσμένη υπηρεσία flacfetch. Ρύθμισε το FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Δεν υπάρχει διαθέσιμο source_id ή remote_search_id για τη λήψη από το {source}",
"remoteDownloadCompleteNoPath": "Η απομακρυσμένη λήψη ολοκληρώθηκε αλλά δεν επιστράφηκε διαδρομή αρχείου",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}",
"selectionError": "Error during audio selection for job {job_id}: {error}",
"youtubeDownloadError": "YouTube download failed: {error}",
"youtubeBotBlocked": "YouTube is temporarily blocking our server, so we couldn't download this video. Please use Audio Search to find this song from another source, or try again in a few minutes.",
"drmUrlUnsupported": "{platform} links are copy-protected, so we can't download them directly. Try downloading the audio with a third-party tool first, then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"drmUrlUnsupportedWithLink": "{platform} links are copy-protected, so we can't download them directly. You can download the track using a tool like {downloader} and then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"drmUrlUnsupportedSearch": "{platform} links are copy-protected, so we can't download them directly. Search the web for a \"{platform} downloader\" to get the audio — for example {searchUrl} — then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Índice de selección inválido {selection_index}. Rango válido: 0-{max}",
"selectionError": "Error durante la selección de audio para el trabajo {job_id}: {error}",
"youtubeDownloadError": "La descarga de YouTube falló: {error}",
"youtubeBotBlocked": "YouTube está bloqueando temporalmente nuestro servidor, así que no pudimos descargar este video. Usa la Búsqueda de Audio para encontrar esta canción en otra fuente, o inténtalo de nuevo en unos minutos.",
"torrentDownloadError": "No se puede descargar de {source} sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No hay source_id o remote_search_id disponible para la descarga de {source}",
"remoteDownloadCompleteNoPath": "Descarga remota completada pero no se devolvió la ruta del archivo",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Virheellinen valintaindeksi {selection_index}. Sallittu väli: 0-{max}",
"selectionError": "Virhe äänen valinnassa työlle {job_id}: {error}",
"youtubeDownloadError": "YouTube-lataus epäonnistui: {error}",
"youtubeBotBlocked": "YouTube estää palvelimemme tilapäisesti, joten emme voineet ladata tätä videota. Etsi tämä kappale toisesta lähteestä Äänihaun avulla tai yritä uudelleen muutaman minuutin kuluttua.",
"torrentDownloadError": "Ei voida ladata lähteestä {source} ilman etä-flacfetch-palvelua. Määritä FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Lähdetunnusta (source_id) tai etähakutunnusta (remote_search_id) ei ole saatavilla {source}-lataukseen",
"remoteDownloadCompleteNoPath": "Etälataus valmistui, mutta tiedostopolkua ei palautettu",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Index de sélection invalide {selection_index}. Plage valide : 0-{max}",
"selectionError": "Erreur lors de la sélection audio pour la tâche {job_id} : {error}",
"youtubeDownloadError": "Le téléchargement YouTube a échoué : {error}",
"youtubeBotBlocked": "YouTube bloque temporairement notre serveur, nous n'avons donc pas pu télécharger cette vidéo. Utilise la Recherche Audio pour trouver cette chanson depuis une autre source, ou réessaie dans quelques minutes.",
"torrentDownloadError": "Impossible de télécharger depuis {source} sans le service flacfetch distant. Configure FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Aucun source_id ou remote_search_id disponible pour le téléchargement {source}",
"remoteDownloadCompleteNoPath": "Téléchargement distant terminé mais aucun chemin de fichier retourné",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "אינדקס בחירה לא חוקי {selection_index}. טווח חוקי: 0-{max}",
"selectionError": "שגיאה במהלך בחירת האודיו עבור המשימה {job_id}: {error}",
"youtubeDownloadError": "ההורדה מ-YouTube נכשלה: {error}",
"youtubeBotBlocked": "YouTube חוסם זמנית את השרת שלנו, ולכן לא הצלחנו להוריד את הסרטון הזה. אפשר להשתמש בחיפוש אודיו כדי למצוא את השיר הזה ממקור אחר, או לנסות שוב בעוד כמה דקות.",
"torrentDownloadError": "לא ניתן להוריד מ-{source} ללא שירות flacfetch מרוחק. הגדירו את FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "אין source_id או remote_search_id זמינים להורדה מ-{source}",
"remoteDownloadCompleteNoPath": "ההורדה המרוחקת הושלמה אך לא הוחזר נתיב קובץ",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "अमान्य सिलेक्शन इंडेक्स {selection_index}। मान्य रेंज: 0-{max}",
"selectionError": "जॉब {job_id} के लिए ऑडियो सिलेक्शन के दौरान त्रुटि: {error}",
"youtubeDownloadError": "YouTube डाउनलोड विफल: {error}",
"youtubeBotBlocked": "YouTube अस्थायी रूप से हमारे सर्वर को ब्लॉक कर रहा है, इसलिए हम यह वीडियो डाउनलोड नहीं कर सके। कृपया इस गाने को किसी अन्य स्रोत से खोजने के लिए Audio Search का उपयोग करो, या कुछ मिनट बाद फिर से कोशिश करो।",
"torrentDownloadError": "रिमोट flacfetch सर्विस के बिना {source} से डाउनलोड नहीं किया जा सकता। FLACFETCH_API_URL कॉन्फ़िगर करो।",
"remoteDownloadNoSearchId": "{source} डाउनलोड के लिए कोई source_id या remote_search_id उपलब्ध नहीं है",
"remoteDownloadCompleteNoPath": "रिमोट डाउनलोड पूरा हुआ लेकिन कोई फ़ाइल पाथ नहीं मिला",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Nevažeći indeks odabira {selection_index}. Važeći raspon: 0-{max}",
"selectionError": "Pogreška tijekom odabira zvuka za zadatak {job_id}: {error}",
"youtubeDownloadError": "Preuzimanje s YouTubea nije uspjelo: {error}",
"youtubeBotBlocked": "YouTube privremeno blokira naš poslužitelj pa nismo mogli preuzeti ovaj videozapis. Koristi pretraživanje zvuka da pronađeš ovu pjesmu iz drugog izvora ili pokušaj ponovno za nekoliko minuta.",
"torrentDownloadError": "Nije moguće preuzeti s {source} bez udaljene flacfetch usluge. Konfiguriraj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Nema dostupnog source_id ili remote_search_id za preuzimanje s {source}",
"remoteDownloadCompleteNoPath": "Udaljeno preuzimanje je završeno, ali putanja datoteke nije vraćena",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Érvénytelen kiválasztási index: {selection_index}. Érvényes tartomány: 0-{max}",
"selectionError": "Hiba a hang kiválasztása során a(z) {job_id} feladatnál: {error}",
"youtubeDownloadError": "A YouTube letöltés sikertelen: {error}",
"youtubeBotBlocked": "A YouTube ideiglenesen blokkolja a szerverünket, ezért nem tudtuk letölteni ezt a videót. Használd az Audio Search funkciót, hogy más forrásból találd meg a dalt, vagy próbáld újra néhány perc múlva.",
"torrentDownloadError": "Nem lehet letölteni a(z) {source} forrásból távoli flacfetch szolgáltatás nélkül. Konfiguráld a FLACFETCH_API_URL-t.",
"remoteDownloadNoSearchId": "Nincs elérhető source_id vagy remote_search_id a(z) {source} letöltéshez",
"remoteDownloadCompleteNoPath": "A távoli letöltés befejeződött, de nem tért vissza fájlútvonallal",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Indeks pilihan tidak valid {selection_index}. Rentang yang valid: 0-{max}",
"selectionError": "Kesalahan selama pemilihan audio untuk tugas {job_id}: {error}",
"youtubeDownloadError": "Unduhan YouTube gagal: {error}",
"youtubeBotBlocked": "YouTube sedang memblokir server kami untuk sementara, jadi kami tidak dapat mengunduh video ini. Gunakan Pencarian Audio untuk menemukan lagu ini dari sumber lain, atau coba lagi dalam beberapa menit.",
"torrentDownloadError": "Tidak dapat mengunduh dari {source} tanpa layanan flacfetch jarak jauh. Konfigurasikan FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Tidak ada source_id atau remote_search_id yang tersedia untuk unduhan {source}",
"remoteDownloadCompleteNoPath": "Unduhan jarak jauh selesai tetapi tidak ada jalur file yang dikembalikan",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Indice di selezione non valido {selection_index}. Intervallo valido: 0-{max}",
"selectionError": "Errore durante la selezione dell'audio per il lavoro {job_id}: {error}",
"youtubeDownloadError": "Download da YouTube non riuscito: {error}",
"youtubeBotBlocked": "YouTube sta bloccando temporaneamente il nostro server, quindi non siamo riusciti a scaricare questo video. Usa la Ricerca Audio per trovare questa canzone da un'altra fonte, oppure riprova tra qualche minuto.",
"torrentDownloadError": "Impossibile scaricare da {source} senza il servizio flacfetch remoto. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Nessun source_id o remote_search_id disponibile per il download da {source}",
"remoteDownloadCompleteNoPath": "Download remoto completato ma non è stato restituito alcun percorso file",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "無効な選択インデックス {selection_index} です。有効な範囲: 0-{max}",
"selectionError": "ジョブ {job_id} のオーディオ選択中にエラーが発生しました: {error}",
"youtubeDownloadError": "YouTubeのダウンロードに失敗しました: {error}",
"youtubeBotBlocked": "YouTubeが一時的に当社のサーバーをブロックしているため、この動画をダウンロードできませんでした。オーディオ検索を使って別のソースからこの曲を探すか、数分後にもう一度お試しください。",
"torrentDownloadError": "リモートのflacfetchサービスなしで {source} からダウンロードすることはできません。FLACFETCH_API_URLを設定してください。",
"remoteDownloadNoSearchId": "{source} のダウンロードに利用できる source_id または remote_search_id がありません",
"remoteDownloadCompleteNoPath": "リモートダウンロードは完了しましたが、ファイルパスが返されませんでした",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "잘못된 선택 인덱스 {selection_index}. 유효 범위: 0-{max}",
"selectionError": "작업 {job_id}의 오디오 선택 중 오류 발생: {error}",
"youtubeDownloadError": "YouTube 다운로드 실패: {error}",
"youtubeBotBlocked": "YouTube가 일시적으로 저희 서버를 차단하고 있어 이 동영상을 다운로드할 수 없습니다. 오디오 검색을 사용하여 다른 소스에서 이 노래를 찾거나 몇 분 후에 다시 시도해 주세요.",
"torrentDownloadError": "원격 flacfetch 서비스 없이 {source}에서 다운로드할 수 없습니다. FLACFETCH_API_URL을 구성하세요.",
"remoteDownloadNoSearchId": "{source} 다운로드에 사용할 수 있는 source_id 또는 remote_search_id가 없습니다",
"remoteDownloadCompleteNoPath": "원격 다운로드가 완료되었지만 파일 경로가 반환되지 않았습니다",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Indeks pilihan tidak sah {selection_index}. Julat sah: 0-{max}",
"selectionError": "Ralat semasa pemilihan audio untuk tugasan {job_id}: {error}",
"youtubeDownloadError": "Muat turun YouTube gagal: {error}",
"youtubeBotBlocked": "YouTube sedang menyekat pelayan kami buat sementara waktu, jadi kami tidak dapat memuat turun video ini. Sila gunakan Carian Audio untuk mencari lagu ini daripada sumber lain, atau cuba lagi dalam beberapa minit.",
"torrentDownloadError": "Tidak dapat memuat turun daripada {source} tanpa perkhidmatan flacfetch jauh. Konfigurasikan FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Tiada source_id atau remote_search_id tersedia untuk muat turun {source}",
"remoteDownloadCompleteNoPath": "Muat turun jauh selesai tetapi tiada laluan fail dikembalikan",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ugyldig valgindeks {selection_index}. Gyldig område: 0-{max}",
"selectionError": "Feil under lydvalg for jobb {job_id}: {error}",
"youtubeDownloadError": "YouTube-nedlasting mislyktes: {error}",
"youtubeBotBlocked": "YouTube blokkerer serveren vår midlertidig, så vi kunne ikke laste ned denne videoen. Bruk Lydsøk for å finne denne sangen fra en annen kilde, eller prøv igjen om noen minutter.",
"torrentDownloadError": "Kan ikke laste ned fra {source} uten ekstern flacfetch-tjeneste. Konfigurer FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Ingen source_id eller remote_search_id tilgjengelig for {source}-nedlasting",
"remoteDownloadCompleteNoPath": "Ekstern nedlasting fullført, men ingen filbane returnert",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ongeldige selectie-index {selection_index}. Geldig bereik: 0-{max}",
"selectionError": "Fout tijdens audioselectie voor taak {job_id}: {error}",
"youtubeDownloadError": "YouTube download mislukt: {error}",
"youtubeBotBlocked": "YouTube blokkeert onze server tijdelijk, dus we konden deze video niet downloaden. Gebruik Audio Search om dit nummer via een andere bron te vinden, of probeer het over een paar minuten opnieuw.",
"torrentDownloadError": "Kan niet downloaden van {source} zonder externe flacfetch-service. Configureer FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Geen source_id of remote_search_id beschikbaar voor {source} download",
"remoteDownloadCompleteNoPath": "Externe download voltooid maar geen bestandspad geretourneerd",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Nieprawidłowy indeks wyboru {selection_index}. Prawidłowy zakres: 0-{max}",
"selectionError": "Błąd podczas wyboru audio dla zadania {job_id}: {error}",
"youtubeDownloadError": "Pobieranie z YouTube nie powiodło się: {error}",
"youtubeBotBlocked": "YouTube tymczasowo blokuje nasz serwer, więc nie udało się pobrać tego filmu. Użyj wyszukiwania audio, aby znaleźć tę piosenkę z innego źródła, lub spróbuj ponownie za kilka minut.",
"torrentDownloadError": "Nie można pobrać z {source} bez zdalnej usługi flacfetch. Skonfiguruj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Brak dostępnego source_id lub remote_search_id dla pobierania z {source}",
"remoteDownloadCompleteNoPath": "Zdalne pobieranie zakończone, ale nie zwrócono ścieżki pliku",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Índice de seleção inválido {selection_index}. Intervalo válido: 0-{max}",
"selectionError": "Erro durante a seleção de áudio para o job {job_id}: {error}",
"youtubeDownloadError": "Falha no download do YouTube: {error}",
"youtubeBotBlocked": "O YouTube está bloqueando temporariamente nosso servidor, então não conseguimos baixar este vídeo. Use a Pesquisa de Áudio para encontrar esta música em outra fonte ou tente novamente em alguns minutos.",
"torrentDownloadError": "Não é possível baixar de {source} sem o serviço remoto flacfetch. Configure FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Nenhum source_id ou remote_search_id disponível para o download de {source}",
"remoteDownloadCompleteNoPath": "Download remoto concluído, mas nenhum caminho de arquivo retornado",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Index de selecție invalid {selection_index}. Interval valid: 0-{max}",
"selectionError": "Eroare în timpul selecției audio pentru jobul {job_id}: {error}",
"youtubeDownloadError": "Descărcarea de pe YouTube a eșuat: {error}",
"youtubeBotBlocked": "YouTube ne blochează temporar serverul, așa că nu am putut descărca acest videoclip. Folosește Căutare Audio pentru a găsi această melodie din altă sursă sau încearcă din nou peste câteva minute.",
"torrentDownloadError": "Nu se poate descărca de pe {source} fără serviciul remote flacfetch. Configurează FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Niciun source_id sau remote_search_id disponibil pentru descărcarea de pe {source}",
"remoteDownloadCompleteNoPath": "Descărcarea de la distanță s-a finalizat, dar nu a fost returnată nicio cale de fișier",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Недопустимый индекс выбора {selection_index}. Допустимый диапазон: 0-{max}",
"selectionError": "Ошибка при выборе аудио для задачи {job_id}: {error}",
"youtubeDownloadError": "Ошибка скачивания с YouTube: {error}",
"youtubeBotBlocked": "YouTube временно блокирует наш сервер, поэтому нам не удалось скачать это видео. Используй Поиск аудио, чтобы найти эту песню в другом источнике, или попробуй ещё раз через несколько минут.",
"torrentDownloadError": "Невозможно скачать с {source} без удаленного сервиса flacfetch. Настрой FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Нет доступных source_id или remote_search_id для скачивания с {source}",
"remoteDownloadCompleteNoPath": "Удаленное скачивание завершено, но путь к файлу не возвращен",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Neplatný index výberu {selection_index}. Platný rozsah: 0-{max}",
"selectionError": "Chyba počas výberu zvuku pre úlohu {job_id}: {error}",
"youtubeDownloadError": "Sťahovanie z YouTube zlyhalo: {error}",
"youtubeBotBlocked": "YouTube dočasne blokuje náš server, takže sa nám toto video nepodarilo stiahnuť. Použi vyhľadávanie zvuku na nájdenie tejto piesne z iného zdroja alebo to skús znova o pár minút.",
"torrentDownloadError": "Nemožno sťahovať z {source} bez vzdialenej služby flacfetch. Nakonfiguruj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Pre sťahovanie z {source} nie je k dispozícii žiadne source_id alebo remote_search_id",
"remoteDownloadCompleteNoPath": "Vzdialené sťahovanie bolo dokončené, ale nebola vrátená žiadna cesta k súboru",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ogiltigt urvalsindex {selection_index}. Giltigt intervall: 0-{max}",
"selectionError": "Fel vid ljudval för jobb {job_id}: {error}",
"youtubeDownloadError": "YouTube-nedladdning misslyckades: {error}",
"youtubeBotBlocked": "YouTube blockerar tillfälligt vår server, så vi kunde inte ladda ner den här videon. Använd Ljudsökning för att hitta den här låten från en annan källa, eller försök igen om några minuter.",
"torrentDownloadError": "Kan inte ladda ner från {source} utan fjärrtjänsten flacfetch. Konfigurera FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Inget source_id eller remote_search_id tillgängligt för nedladdning från {source}",
"remoteDownloadCompleteNoPath": "Fjärrnedladdning slutförd men ingen filsökväg returnerades",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "ดัชนีการเลือก {selection_index} ไม่ถูกต้อง ช่วงที่ถูกต้อง: 0-{max}",
"selectionError": "เกิดข้อผิดพลาดระหว่างการเลือกเสียงสำหรับงาน {job_id}: {error}",
"youtubeDownloadError": "การดาวน์โหลด YouTube ล้มเหลว: {error}",
"youtubeBotBlocked": "YouTube กำลังบล็อกเซิร์ฟเวอร์ของเราชั่วคราว เราจึงไม่สามารถดาวน์โหลดวิดีโอนี้ได้ โปรดใช้ Audio Search เพื่อค้นหาเพลงนี้จากแหล่งอื่น หรือลองอีกครั้งในอีกสักครู่",
"torrentDownloadError": "ไม่สามารถดาวน์โหลดจาก {source} โดยไม่มีบริการ flacfetch ระยะไกล โปรดกำหนดค่า FLACFETCH_API_URL",
"remoteDownloadNoSearchId": "ไม่มี source_id หรือ remote_search_id สำหรับการดาวน์โหลด {source}",
"remoteDownloadCompleteNoPath": "การดาวน์โหลดระยะไกลเสร็จสมบูรณ์แต่ไม่ส่งคืนเส้นทางไฟล์",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Mali ang selection index na {selection_index}. Valid na range: 0-{max}",
"selectionError": "Error habang pumipili ng audio para sa job {job_id}: {error}",
"youtubeDownloadError": "Nabigo ang pag-download sa YouTube: {error}",
"youtubeBotBlocked": "Pansamantalang bina-block ng YouTube ang aming server, kaya hindi namin na-download ang video na ito. Gamitin ang Audio Search para hanapin ang kantang ito mula sa ibang source, o subukang muli pagkalipas ng ilang minuto.",
"torrentDownloadError": "Hindi maka-download mula sa {source} nang walang remote flacfetch service. I-configure ang FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Walang available na source_id o remote_search_id para sa {source} download",
"remoteDownloadCompleteNoPath": "Nakumpleto ang remote download pero walang ibinalik na file path",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Geçersiz seçim indeksi {selection_index}. Geçerli aralık: 0-{max}",
"selectionError": "{job_id} işi için ses seçimi sırasında hata: {error}",
"youtubeDownloadError": "YouTube indirmesi başarısız oldu: {error}",
"youtubeBotBlocked": "YouTube sunucumuzu geçici olarak engelliyor, bu yüzden bu videoyu indiremedik. Bu şarkıyı başka bir kaynaktan bulmak için Ses Arama'yı kullan veya birkaç dakika sonra tekrar dene.",
"torrentDownloadError": "Uzak flacfetch hizmeti olmadan {source} kaynağından indirilemiyor. FLACFETCH_API_URL'yi yapılandır.",
"remoteDownloadNoSearchId": "{source} indirmesi için source_id veya remote_search_id mevcut değil",
"remoteDownloadCompleteNoPath": "Uzak indirme tamamlandı ancak dosya yolu döndürülmedi",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Недійсний індекс вибору {selection_index}. Допустимий діапазон: 0-{max}",
"selectionError": "Помилка під час вибору аудіо для завдання {job_id}: {error}",
"youtubeDownloadError": "Помилка завантаження з YouTube: {error}",
"youtubeBotBlocked": "YouTube тимчасово блокує наш сервер, тому нам не вдалося завантажити це відео. Скористайся пошуком аудіо, щоб знайти цю пісню в іншому джерелі, або спробуй ще раз за кілька хвилин.",
"torrentDownloadError": "Не вдається завантажити з {source} без віддаленого сервісу flacfetch. Налаштуй FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Немає доступного source_id або remote_search_id для завантаження з {source}",
"remoteDownloadCompleteNoPath": "Віддалене завантаження завершено, але шлях до файлу не повернуто",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Chỉ số lựa chọn không hợp lệ {selection_index}. Phạm vi hợp lệ: 0-{max}",
"selectionError": "Lỗi trong quá trình chọn âm thanh cho công việc {job_id}: {error}",
"youtubeDownloadError": "Tải xuống YouTube thất bại: {error}",
"youtubeBotBlocked": "YouTube đang tạm thời chặn máy chủ của chúng tôi nên chúng tôi không thể tải video này xuống. Vui lòng sử dụng Tìm kiếm Âm thanh để tìm bài hát này từ nguồn khác hoặc thử lại sau vài phút.",
"torrentDownloadError": "Không thể tải xuống từ {source} mà không có dịch vụ flacfetch từ xa. Hãy cấu hình FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Không có source_id hoặc remote_search_id nào cho tải xuống {source}",
"remoteDownloadCompleteNoPath": "Tải xuống từ xa hoàn tất nhưng không trả về đường dẫn tệp",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "无效的选择索引 {selection_index}。有效范围:0-{max}",
"selectionError": "在为任务 {job_id} 选择音频时出错:{error}",
"youtubeDownloadError": "YouTube 下载失败:{error}",
"youtubeBotBlocked": "YouTube 暂时屏蔽了我们的服务器,因此我们无法下载此视频。请使用音频搜索从其他来源查找这首歌,或者几分钟后再试。",
"torrentDownloadError": "如果没有远程 flacfetch 服务,则无法从 {source} 下载。请配置 FLACFETCH_API_URL。",
"remoteDownloadNoSearchId": "没有可用于 {source} 下载的 source_id 或 remote_search_id",
"remoteDownloadCompleteNoPath": "远程下载已完成,但未返回文件路径",
+2 -1
View File
@@ -399,7 +399,8 @@ async def process_audio_download(job_id: str) -> bool:
if not isinstance(e, (DownloadError, FlacfetchServiceError)):
logger.error(f"[job:{job_id}] Download failed: {e}", exc_info=True)
else:
logger.error(f"[job:{job_id}] Download failed: {e}")
# Expected failure type; fail_job below sends the one job-failed alert.
logger.warning(f"[job:{job_id}] Download failed: {e}")
_mark_retry_pending_if_attempts_remain(job_manager, job_id)
job_manager.fail_job(job_id, f"Audio download failed: {e}",
error_details={'stage': 'audio_download'})
+8 -2
View File
@@ -691,8 +691,14 @@ class VideoWorkerOrchestrator:
local_path = os.path.join(self.config.output_dir, filename)
try:
self.job_log.info(f"Downloading {filename} from GCS")
self.storage.download_file(gcs_path, local_path)
# On the AWS encoding box the encoder left a local copy: take it
# instead of downloading back out of GCS (see local_encoded_outputs).
from backend.services import local_encoded_outputs
if local_encoded_outputs.take(gcs_path, local_path):
self.job_log.info(f"Took {filename} from the co-located encoder (no GCS download)")
else:
self.job_log.info(f"Downloading {filename} from GCS")
self.storage.download_file(gcs_path, local_path)
# Update the result to point to local file
setattr(self.result, result_attr, local_path)
+10
View File
@@ -452,6 +452,16 @@ Content-Type: application/json
Saves corrections, stores instrumental selection, and triggers video rendering. The instrumental selection is now required as part of the combined review flow.
#### Mark sync as reference (admin only)
```
POST /api/review/{job_id}/sync-reference
{"verified": true, "notes": "optional"}
```
Admin users only (403 otherwise). Stores `state_data.sync_reference = {verified, by, at, notes}`.
Verified jobs form the word-timing reference set for aligner training/evaluation (full-auto v2).
The lyrics review modal shows the checkbox to admins; unticked jobs are treated as unverified.
#### Generate Preview
```http
+26 -1
View File
@@ -117,7 +117,14 @@ Keeping #alerts readable (one root cause → one message):
`ended` line is ERROR (≥10s blocked with a request affected), so one freeze is
one pattern. The `backend/event_loop_stalls` metric keys on that line too.
- **Known noise** (`known_issues.py`) can be service-scoped, e.g.
github-runner-manager's scale-up "no available instance" aborts.
github-runner-manager's scale-up "no available instance" aborts, and scoped to a
request path too (decide-search's `/api/search/health` aborts).
- **Unhandled exceptions**: `Exception in ASGI application` and `request_audit_error`
become one `Unhandled exception: <Type: message>` pattern per cause, read from the
entry's `exception` field; the path goes in the sample only.
- **One alert per job failure**: `ops_alerts` sends it from the status write, so
`Job <id> failed` and the download-failure lines before it are not ERROR patterns.
YouTube video ids are normalized out of signatures.
Frontend crashes are captured via `window.onerror`, `unhandledrejection`, Next.js
`error.tsx`, and a `CrashReportBoundary` around the review UIs. They POST to
@@ -476,6 +483,24 @@ and raised as `EncodingJobLostError`, which `run_with_lost_job_resubmit` resubmi
— the resubmit's connection failure then starts the Spot VM again, or the
on-demand fallback if Spot capacity is gone.
### AWS encoding worker (EC2, provider "aws")
**`aws-encoding-worker-1`** is a c7a.4xlarge on-demand instance in us-east-2. It runs the same `gce_encoding` service and is one more entry in the `encoding-worker-fallback-vms` pool (`"provider": "aws"`, plus `instance_id` and `region`). It is paid for by AWS Activate credits. IaC lives in `infrastructure/aws/` (its own Pulumi stack; see its README).
- **Control:**
- The manager routes AWS VMs to `backend/services/aws_encoding_compute.py`, an EC2 adapter that mimics the compute client. EC2 states map to GCE statuses, and EC2 capacity errors join `CAPACITY_ERROR_CODES`.
- So failover, overrides, lost-job detection and stockout cooldowns apply unchanged.
- The override records `active_override_provider: "aws"`. The CI blue-green deploy and the idle Cloud Function both ignore the AWS worker.
- **Ranking:**
- It is a last resort by default (`SPEED_RANK["c7a"] = 90`).
- Firestore `config/encoding-worker.speed_rank_overrides = {"c7a": 5}` makes it preferred with no deploy.
- Both warmups (`ensure_preferred_running`) follow the same ranking, so they warm the worker requests are routed to.
- **Distribution on AWS (Phase 2, off by default):** with `config/encoding-worker.aws_video_worker = true` and the AWS worker ranked first, `trigger_video_worker` runs the video worker on the box (`POST /run-worker`, env mirrored from the live `video-encoding-job`, identity `karaoke-backend@` via WIF). Uploads leave from AWS, and finals are handed over locally (`local_encoded_outputs`) instead of downloaded back from GCS. Any failure falls back to the Cloud Run job.
- **Auth and lifecycle:**
- GCP access is Workload Identity Federation as `encoding-worker@`: no keys.
- It stops itself when idle (`infrastructure/encoding-worker/aws/idle-watchdog.py`).
- It gets new code at boot and per job, with no blue-green deploy.
### Architecture
```text
@@ -0,0 +1,138 @@
# AWS encoding worker: implementation plan (2026-10-29)
**Goal:** run gen's encoding worker on EC2 Spot, paid for with the AWS Activate credits (acct 790139457751, expiring 2028-10-31). Then run distribution (Dropbox/YouTube/Drive uploads) from AWS too, so the large output egress moves off the GCP bill. **Constraint:** job→published must not get slower, and the move runs in parallel with GCP first.
Evidence: workspace `docs/archive/2026-10-29-aws-encoding-worker-migration-plan.md`. A c7a.4xlarge matched or beat the GCE c4d-highcpu-16 on 3 replayed prod jobs.
## Phase 1: AWS box as an encoding-worker candidate (this PR set)
> **Amended 2026-10-29 (after the first `pulumi up`): on-demand c7a.4xlarge, not Spot c7a.8xlarge.**
> - Creating the Spot c7a.8xlarge failed with `InsufficientInstanceCapacity`.
> - Spot placement scores were 1–3/10 for c7a/c7i/c6a/c8a 4–8xlarge across us-east-1 and us-east-2.
> - A worker that stops and starts on demand has to win capacity on every start, and a Spot interruption mid-job is costly, especially for Phase 2's video-worker runs.
> - On-demand c7a.4xlarge costs ~$0.82/h × ~100 h ≈ $82/mo of the ~$212/mo of credits. It matched or beat GCE in the benchmark.
> - The design below otherwise stands; read "Spot"/"8xlarge" in it as superseded.
The box runs the **unchanged worker HTTP service** (`backend.services.gce_encoding.main`). It joins the existing candidate pool, so failover, overrides, lost-job detection and cooldowns all apply unchanged.
### Design
**Instance**
- `aws-encoding-worker-1`: **c7a.8xlarge** (32 vCPU / 64 GB), us-east-2.
- A **persistent Spot** request with `stop` on interruption, matching GCE's STOP-on-preempt, plus an Elastic IP.
- Port 8080 open with API-key auth, the same as the GCE firewall today.
- The root EBS volume persists across stop/start, like the GCE boot disks. It is provisioned once by user-data (a port of packer `provision.sh`).
- **Why 8xlarge:** ~100 h/mo × ~$0.46/h ≈ $46/mo of *credits* (we accrue ~$205/mo of credits). It encodes faster than today's 16 vCPU and fits two heavy jobs in RAM.
**GCP auth**
- Workload Identity Federation: an `aws-encoding` pool plus an AWS provider for acct 790139457751.
- The `nomad-encoding-worker` role is bound to the existing **encoding-worker SA** (`roles/iam.workloadIdentityUser`). No SA keys.
- The box uses an `external_account` credential config (not secret) with IMDSv2, for both the client libraries and `gcloud`.
**Backend control of EC2**
- An IAM user `nomad-encoding-controller` limited to `ec2:Start/Stop/DescribeInstances` on instances tagged `Project=nomad-encoding`.
- Its keys go in Secret Manager `aws-encoding-controller-credentials`, the same pattern as backup-to-aws; the backend SA can read it.
**Registry**
- The box is an entry in the existing `encoding-worker-fallback-vms` secret:
`{"vm":"aws-encoding-worker-1","zone":"us-east-2b","ip":<EIP>,"machine_type":"c7a-4xlarge","provider":"aws","instance_id":"i-…","region":"us-east-2"}`
- The `.` in the AWS type becomes `-`, so Firestore cooldown keys stay valid.
**Manager**
- `AwsComputeAdapter` (`backend/services/aws_encoding_compute.py`) mimics the `compute_v1.InstancesClient` surface the manager uses (`get/start/stop`). It maps EC2 states to GCE ones (`running→RUNNING`, `pending→STAGING`, `stopping→STOPPING`, `stopped→TERMINATED`), EC2 capacity errors to `CAPACITY_ERROR_CODES`, and `InvalidInstanceID.NotFound` to `NotFound`.
- `EncodingWorkerManager._compute_for(vm)` routes AWS VMs to the adapter. GCE code paths are untouched.
**Ranking**
- `SPEED_RANK["c7a"] = 90`, so by default AWS is a **last-resort** fallback (stage A).
- A new Firestore field `config/encoding-worker.speed_rank_overrides` (e.g. `{"c7a": 5}`) makes it **preferred** (stage C) with no deploy. Rollback deletes the field.
**Warmups**
- `worker_service._warmup_encoding_worker` and `POST /internal/encoding-worker/warmup` currently start only the GCE primary.
- They will use the same ranked path as the encode itself (`manager.ensure_preferred_running()`). Otherwise, with AWS preferred, they would warm a VM that isn't routed to.
**Exclusions from GCE-only machinery**
- CI blue-green green selection: `deploy_promote.select_green_candidates` and the jq in ci.yml.
- The idle Cloud Function's `_parse_fallback_vms`.
- The box gets new code through the existing per-job `ensure_latest_wheel` hot update, so it needs no blue-green deploy.
**Idle stop**
- A systemd timer **on the box**, independent of the uvicorn process, runs every 2 min.
- It stops the instance (`shutdown -h now`, instance-initiated shutdown = stop) when either:
- `/health` reports `active_jobs == 0`, and `last_activity_at` is older than 5 min or the box isn't the routed worker; or
- `/health` has failed for 15 min.
- This mirrors the idle function's rules.
**Worker boot on AWS**
- `startup-aws.sh` has no GCE metadata server. It fetches the API key and wheel with `gcloud` over WIF and sets `ENCODING_WORKER_VM_NAME`.
- `ensure_latest_wheel` uses `gsutil`, which doesn't support WIF credential files. On AWS (`ENCODING_WORKER_PROVIDER=aws`) it uses `gcloud storage`; the GCE path is unchanged.
### Rollout
- **A:** deploy and register the box at rank 90. It's only exercised on c4d+c2d stockouts.
- **B:** set `speed_rank_overrides {"c7a": 5}` for a supervised window. Run the daily E2E plus admin test jobs, and compare render/encode times and outputs (including the portrait parity check) against GCE.
- **C:** leave the override on; AWS is preferred. After a week clean, delete the c4d pair (Pulumi), leaving c2df as the GCP fallback.
### Testing
- **Unit:**
- adapter (botocore `Stubber`): state map, capacity/NotFound mapping, start/stop idempotency
- manager routing (`_compute_for`), `ensure_preferred_running`
- preference `rank_overrides`, `c7a` family
- fallback parsing passthrough of `provider`/`instance_id`/`region`
- deploy_promote and idle-fn exclusion of aws entries
- the idle watchdog decision function
- `ensure_latest_wheel` command selection
- Extend the existing test files listed in the GCE-coupling map.
- **Integration (prod, supervised):** stage B runs real jobs through the AWS worker. The prod daily E2E (payment + happy path) is the end-to-end check.
## Phase 2: distribution from AWS (implemented 2026-10-31, off by default)
The video worker (packaging, encode, Dropbox/YouTube/Drive uploads, notifications) can run **on the AWS box** instead of in the Cloud Run job `video-encoding-job`. The large uploads then leave from AWS (credits) instead of GCP (the ~$18/mo of Cloud Run internet egress), and the job's Cloud Run CPU (~$11/mo) goes away.
**Encoding path unchanged (output parity)**
- The video worker on the box still encodes through the worker HTTP API, so the deliverables (portrait included) are identical.
- `LocalEncodingBackend` was rejected: it lacks the worker's portrait render.
**Same-box handoff** (`backend/services/local_encoded_outputs.py`)
- Without it, the video worker would download every final back out of GCS: ~400 MB/job of out-of-pocket egress, which costs more than the move saves.
- The encoder stashes each output under `LOCAL_ENCODED_OUTPUTS_DIR`, keyed by its GCS blob path, and the video worker takes it from there.
- The video worker asks for it per encode (`stash_local_outputs`, set only where the env var exists), so GCE and Cloud Run are unaffected. Copies not taken within 6 h are purged on every stash and at worker boot.
**`POST /run-worker`** (worker)
- Spawns `python -m backend.workers.video_worker --job-id …` with the box's video-worker env.
- Status is reported through the usual `/status/{id}`. A run counts in `/health` `active_jobs`, so the idle watchdog won't stop the box mid-run.
- It answers 503 unless `/opt/encoding-worker/video-worker-env.json` exists.
**Env and identity**
- At boot, `video-worker-env.py` reads the **live** `video-encoding-job` definition and resolves its secret refs, so nothing is hand-copied and nothing drifts.
- It adds `LOCAL_ENCODED_OUTPUTS_DIR` and `CLOUD_RUN_JOB`.
- The run uses the job's own identity, `karaoke-backend@`, via a second WIF binding (`aws-encoding-worker-wif-backend-user`).
**Trigger** (`WorkerService._trigger_video_worker_on_aws`)
- It applies only when Firestore `config/encoding-worker.aws_video_worker` is true **and** the AWS worker ranks first.
- It then ensures the box is running, waits for `/health`, and POSTs `/run-worker`.
- **Any** doubt or failure returns False, and the caller starts the Cloud Run job as today.
**Not covered**
- Deferred YouTube uploads (the hourly queue processor on the API) still leave from GCP; volume is low.
- Video-worker stdout stays on the box at `/var/log/encoding-worker-runs/`. The job's Firestore worker logs are unaffected, but the error monitor doesn't see the box's stderr.
- With the box on-demand (see the amendment above), Spot-interruption recovery is moot. A systemd restart of the worker during a run would still kill it; the existing `encoding_stuck` flag at 50 min surfaces that.
**Enable (after stage B, needs `/gcp-admin` for the IAM binding)**
1. Apply the GCP WIF backend binding.
2. Reboot the box once (`stop`/`start`) so `startup-aws.sh` writes the backend credentials and the env.
3. Set `aws_video_worker: true`.
4. Roll back by setting it to false.
## Stage A status (2026-10-29/31)
**Live:**
- `aws-encoding-worker-1`: `i-0c21505d7017356bb`, c7a.4xlarge on-demand, us-east-2b, EIP `3.128.70.236`.
- Provisioned from v0.288.0. WIF auth works for both reads and writes, and the API key, wheel and static ffmpeg all fetched fine.
- Controller key stored as `aws-encoding-controller-credentials` v1. Verified: `AwsComputeAdapter` with that key reads the box's state.
**Live test through the worker's real HTTP API** (job 4b611a81, outputs written to `gs://…/bench/aws-live/`, no prod paths):
- render-video completed in 117s.
- The encode wrote all 9 deliverables; 8 of 9 are byte-identical in size to prod's GCE finals.
- **Portrait parity:** same duration, SSIM 0.993, and identical lyrics. The only difference is sub-pixel anti-aliasing of the header/footer text (title, artist, brand), from the newer `fonts-noto` on Ubuntu 24.04. Visually indistinguishable, so it doesn't block stage C.
- A status poll timed out once while the worker downloaded inputs. `process_job` downloads synchronously on the event loop; that is pre-existing and the same on GCE, and the backend's poller tolerates it.
**Remaining for stage A (needs `/gcp-admin`):** append `pulumi stack output fallback_vms_entry` to the `encoding-worker-fallback-vms` secret, then **redeploy the backend**. Running Cloud Run instances keep the value they loaded at startup. Stage B begins after that deploy, by setting `speed_rank_overrides`.
@@ -0,0 +1,37 @@
import { render } from '@testing-library/react'
import { GoogleAnalytics } from '../google-analytics'
// next/script injects tags itself; render a marker so the test can see what would load.
jest.mock('next/script', () => ({
__esModule: true,
default: ({ id, src }: { id?: string; src?: string }) => (
<span data-testid="next-script" data-id={id} data-src={src} />
),
}))
function renderOn(hostname: string) {
const original = window.location
delete (window as unknown as { location?: Location }).location
Object.defineProperty(window, 'location', { value: { ...original, hostname } as Location, configurable: true, writable: true })
try {
return render(<GoogleAnalytics />)
} finally {
Object.defineProperty(window, 'location', { value: original, configurable: true, writable: true })
}
}
describe('GoogleAnalytics', () => {
it.each(['localhost', '127.0.0.1', '10.0.2.2'])(
'loads nothing on local host %s (local stack / E2E must not send hits to the real property)',
(host) => {
const { queryAllByTestId } = renderOn(host)
expect(queryAllByTestId('next-script')).toHaveLength(0)
}
)
it('loads gtag on the production host', () => {
const { getAllByTestId } = renderOn('gen.nomadkaraoke.com')
const scripts = getAllByTestId('next-script')
expect(scripts.some((s) => (s.getAttribute('data-src') ?? '').includes('googletagmanager.com/gtag/js'))).toBe(true)
})
})
+12
View File
@@ -1,10 +1,22 @@
'use client'
import { useEffect, useState } from 'react'
import Script from 'next/script'
import { isLocalPage } from '@/lib/local-host'
const GA_MEASUREMENT_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID || 'G-D0E63LB9FY'
export function GoogleAnalytics() {
// Decided after mount from the page's real host (static export has no server to ask), so a
// local stack, nomad-mobile's E2E in an emulator's Chrome, or CI never sends hits to the real
// property. Server and first client render agree (nothing), so hydration matches.
const [enabled, setEnabled] = useState(false)
useEffect(() => {
setEnabled(!isLocalPage())
}, [])
if (!enabled) return null
return (
<>
<Script
@@ -117,6 +117,7 @@ interface ApiClient {
getWaveformData?: (numPoints?: number) => Promise<{ amplitudes: number[]; duration_seconds?: number; duration?: number }>
// Optional: separation-status poll for stems that land after page load (cloud mode).
getInstrumentalState?: LyricsReviewApiClient['getInstrumentalState']
setSyncReference?: LyricsReviewApiClient['setSyncReference']
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
// Review session methods (optional - available in cloud mode)
saveReviewSession?: LyricsReviewApiClient['saveReviewSession']
@@ -1151,7 +1152,9 @@ export default function LyricsAnalyzer({
}, [saveSession])
// Submit to server (save corrections, don't complete review yet)
const handleSubmitToServer = useCallback(async () => {
const handleSubmitToServer = useCallback(async (
opts?: { syncReference?: { verified: boolean; notes?: string } },
) => {
if (!apiClient) return
// Block submission of lyrics that still have no timing (e.g. custom lyrics
@@ -1172,6 +1175,17 @@ export default function LyricsAnalyzer({
// 1. Save corrections (not final submission yet), including current duet flag
await apiClient.submitCorrections(dataToSubmit, isDuet)
// 1b. Admin "perfectly synced" mark — only now that the timing it vouches for
// is saved. Best-effort: never blocks or fails the review.
if (opts?.syncReference && apiClient.setSyncReference) {
try {
await apiClient.setSyncReference(opts.syncReference.verified, opts.syncReference.notes)
} catch (error) {
console.error('Failed to save sync reference mark:', error)
toast.error(t('toasts.syncReferenceSaveFailed'))
}
}
// 2. Save edit log (non-blocking)
if (editLog.entries.length > 0) {
try {
@@ -0,0 +1,82 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ReviewChangesModal from '../modals/ReviewChangesModal'
import type { CorrectionData } from '@/lib/lyrics-review/types'
import { useAuth } from '@/lib/auth'
jest.mock('../PreviewVideoSection', () => {
const React = require('react')
return {
__esModule: true,
default: React.forwardRef(function MockPreview(_props: unknown, ref: unknown) {
React.useImperativeHandle(ref, () => ({ auditionInstrumental: jest.fn() }))
return <div data-testid="preview-video">Preview</div>
}),
}
})
const data = {
original_segments: [], reference_lyrics: {}, anchor_sequences: [], gap_sequences: [],
resized_segments: [], corrections_made: 0, confidence: 1, corrections: [], metadata: {},
corrected_segments: [{ text: 'Hello', words: [], start_time: 0, end_time: 1 }],
} as unknown as CorrectionData
function client() {
return { generatePreviewVideo: jest.fn(), getPreviewVideoStatus: jest.fn(), getPreviewVideoUrl: jest.fn() }
}
function setRole(role: string | null) {
useAuth.setState({ user: role ? ({ email: 'a@nomadkaraoke.com', role } as any) : null })
}
describe('ReviewChangesModal sync-reference mark (admin only)', () => {
afterEach(() => setRole(null))
it('is hidden for non-admin users', () => {
setRole('user')
render(<ReviewChangesModal open onClose={jest.fn()} onSubmit={jest.fn()} data={data} apiClient={client()} />)
expect(screen.queryByTestId('sync-reference')).not.toBeInTheDocument()
})
it('passes the mark with notes to onSubmit when an admin ticks it', async () => {
setRole('admin')
const onSubmit = jest.fn()
render(<ReviewChangesModal open onClose={jest.fn()} onSubmit={onSubmit} data={data} apiClient={client()} />)
await userEvent.click(screen.getByTestId('sync-reference-checkbox'))
await userEvent.type(screen.getByTestId('sync-reference-notes'), 'spot-checked')
await userEvent.click(screen.getByRole('button', { name: /proceed to instrumental/i }))
expect(onSubmit).toHaveBeenCalledWith({ syncReference: { verified: true, notes: 'spot-checked' } })
})
it('sends no mark when the admin leaves it unticked', async () => {
setRole('admin')
const onSubmit = jest.fn()
render(<ReviewChangesModal open onClose={jest.fn()} onSubmit={onSubmit} data={data} apiClient={client()} />)
expect(screen.getByTestId('sync-reference')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: /proceed to instrumental/i }))
expect(onSubmit).toHaveBeenCalledWith()
})
it('starts ticked from a saved mark and sends verified=false when revoked', async () => {
setRole('admin')
const onSubmit = jest.fn()
const marked = { ...data, sync_reference: { verified: true, notes: 'old note' } } as CorrectionData
render(<ReviewChangesModal open onClose={jest.fn()} onSubmit={onSubmit} data={marked} apiClient={client()} />)
const box = screen.getByTestId('sync-reference-checkbox') as HTMLInputElement
expect(box.checked).toBe(true)
await userEvent.click(box)
await userEvent.click(screen.getByRole('button', { name: /proceed to instrumental/i }))
expect(onSubmit).toHaveBeenCalledWith({ syncReference: { verified: false, notes: 'old note' } })
})
it('sends verified=false once touched, even with no saved mark', async () => {
setRole('admin')
const onSubmit = jest.fn()
render(<ReviewChangesModal open onClose={jest.fn()} onSubmit={onSubmit} data={data} apiClient={client()} />)
const box = screen.getByTestId('sync-reference-checkbox')
await userEvent.click(box)
await userEvent.click(box)
await userEvent.click(screen.getByRole('button', { name: /proceed to instrumental/i }))
expect(onSubmit).toHaveBeenCalledWith({ syncReference: { verified: false, notes: undefined } })
})
})
@@ -9,6 +9,7 @@ import { AlertTriangle, ArrowLeft, ArrowRight, Loader2 } from 'lucide-react'
import PreviewVideoSection, { PreviewVideoHandle } from '../PreviewVideoSection'
import BackingVocalsWaveform from '../BackingVocalsWaveform'
import type { LateInstrumentalStatus } from '@/lib/lyrics-review/hooks/useLateInstrumentalStems'
import { useAuth } from '@/lib/auth'
interface WaveformDataResult {
amplitudes: number[]
@@ -41,7 +42,9 @@ interface ReviewChangesModalProps {
/** Late-stems poll state: `waiting` = audio separation still running, so the
* instrumental choice isn't available yet; `gave_up` = it didn't arrive in time. */
stemsStatus?: LateInstrumentalStatus
onSubmit: () => void
/** `syncReference` is set only for admins who ticked (or un-ticked a previously
* saved) "perfectly synced" mark; the caller saves it after the timing is saved. */
onSubmit: (opts?: { syncReference?: { verified: boolean; notes?: string } }) => void
isSubmitting?: boolean
apiClient?: ApiClient | null
timingOffsetMs?: number
@@ -152,9 +155,24 @@ export default function ReviewChangesModal({
)
}
// Admin-only "perfectly synced" mark: verified jobs join the word-timing reference
// set used to train and evaluate the aligner. Unticked = unverified. Starts from
// the saved mark so a re-review can see and revoke it.
const isAdmin = useAuth((s) => s.user?.role === 'admin')
const savedVerified = !!data.sync_reference?.verified
const [syncVerified, setSyncVerified] = useState(savedVerified)
const [syncNotes, setSyncNotes] = useState(data.sync_reference?.notes || '')
// Once touched, always send the current state: a mark saved earlier in this
// session (then a failed submit) must still be revocable by un-ticking.
const [syncTouched, setSyncTouched] = useState(false)
const handleSubmit = () => {
if (isSubmitting) return
onSubmit()
if (isAdmin && (syncVerified || savedVerified || syncTouched)) {
onSubmit({ syncReference: { verified: syncVerified, notes: syncNotes.trim() || undefined } })
} else {
onSubmit()
}
}
return (
@@ -304,6 +322,34 @@ export default function ReviewChangesModal({
</div>
)}
{isAdmin && (
<div className="rounded-md border border-dashed p-3 text-sm space-y-2" data-testid="sync-reference">
<label className="flex items-start gap-2 cursor-pointer">
<input
type="checkbox"
className="mt-1"
checked={syncVerified}
onChange={(e) => { setSyncVerified(e.target.checked); setSyncTouched(true) }}
data-testid="sync-reference-checkbox"
/>
<span>
<span className="font-medium">{t('syncReferenceLabel')}</span>
<span className="block text-muted-foreground text-xs">{t('syncReferenceHelp')}</span>
</span>
</label>
{syncVerified && (
<input
type="text"
value={syncNotes}
onChange={(e) => setSyncNotes(e.target.value)}
placeholder={t('syncReferenceNotesPlaceholder')}
className="w-full rounded border bg-background px-2 py-1 text-xs"
data-testid="sync-reference-notes"
/>
)}
</div>
)}
<DialogFooter className="border-t pt-4">
<Button variant="ghost" onClick={onClose} disabled={isSubmitting} className="text-primary">
<ArrowLeft className="h-4 w-4 mr-2" />
@@ -330,4 +330,111 @@ describe('useManualSync — tap-to-sync end times', () => {
// …and the segment end grew to include it (no hard cut at 3.00).
expect(segment.end_time).toBeGreaterThanOrEqual(lastWord.end_time as number)
})
describe('a pass that stops before the last word', () => {
// gen's fake fixture line (backend/services/fake_workers/lyrics.py): five words with OLD
// timings 15.5..19.5; the next line starts at 20.0. Tapping only the first four words, later
// than their old starts, leaves "transcribed" at a stale 18.74 BEFORE "ever" (19.6).
const fixtureLine = () =>
makeSegment([
w('w0', 'Nothing', 15.5, 16.26),
w('w1', 'here', 16.31, 17.07),
w('w2', 'was', 17.12, 17.88),
w('w3', 'ever', 17.93, 18.69),
w('w4', 'transcribed', 18.74, 19.5),
])
function tapFourWords() {
let segment = fixtureLine()
let currentTime = 15.0
const { result, rerender } = renderHook(
({ seg, time }) =>
useManualSync({
editedSegment: seg,
currentTime: time,
onPlaySegment: () => {},
updateSegment: (newWords: Word[]) => {
segment = recompute(segment, newWords)
},
}),
{ initialProps: { seg: segment, time: currentTime } }
)
act(() => result.current.startManualSync())
;[16.0, 17.2, 18.4, 19.6].forEach((t) => {
currentTime = t
rerender({ seg: segment, time: currentTime })
tap(result)
rerender({ seg: segment, time: currentTime })
})
return {
result,
get segment() {
return segment
},
// A fresh segment object re-runs the auto-stop effect, which checks immediately.
rerender: (time: number) => rerender({ seg: { ...segment }, time }),
}
}
function expectInOrderWithTranscribedUntimed(words: Word[]) {
const transcribed = words[4]
expect(transcribed.start_time).toBeNull()
expect(transcribed.end_time).toBeNull()
const timed = words.filter((x) => x.start_time !== null)
expect(timed.map((x) => x.text)).toEqual(['Nothing', 'here', 'was', 'ever'])
for (let i = 1; i < timed.length; i++) {
expect(timed[i].start_time as number).toBeGreaterThanOrEqual(timed[i - 1].end_time as number)
}
expect(words[3].start_time).toBeCloseTo(19.6, 5)
}
it('clears the stale untapped word on auto-stop instead of leaving it out of order', () => {
const h = tapFourWords()
expect(h.result.current.isManualSyncing).toBe(true)
// Playback runs on a full lead-out past the (grown) segment end, then auto-stops.
window.isAudioPlaying = true
h.rerender((h.segment.end_time as number) + 3.5)
expect(h.result.current.isManualSyncing).toBe(false)
expectInOrderWithTranscribedUntimed(h.segment.words)
})
it('clears the stale untapped word when the user stops the pass', () => {
const h = tapFourWords()
act(() => h.result.current.startManualSync()) // the Stop button toggles the pass off
expect(h.result.current.isManualSyncing).toBe(false)
expectInOrderWithTranscribedUntimed(h.segment.words)
})
it('keeps untapped words that still start after the last tapped word, capping the tapped end', () => {
// Taps land EARLIER than the old timings: "transcribed" (18.74) is still after "ever" (18.3),
// so it keeps its timing, and "ever" must end before it.
let segment = fixtureLine()
let currentTime = 15.0
const { result, rerender } = renderHook(
({ seg, time }) =>
useManualSync({
editedSegment: seg,
currentTime: time,
onPlaySegment: () => {},
updateSegment: (newWords: Word[]) => {
segment = recompute(segment, newWords)
},
}),
{ initialProps: { seg: segment, time: currentTime } }
)
act(() => result.current.startManualSync())
;[15.4, 16.2, 17.0, 18.3].forEach((t) => {
currentTime = t
rerender({ seg: segment, time: currentTime })
tap(result)
rerender({ seg: segment, time: currentTime })
})
act(() => result.current.startManualSync())
const [, , , ever, transcribed] = segment.words
expect(transcribed.start_time).toBeCloseTo(18.74, 5)
expect(transcribed.end_time).toBeCloseTo(19.5, 5)
expect(ever.end_time as number).toBeLessThan(18.74)
expect(ever.end_time as number).toBeGreaterThanOrEqual(ever.start_time as number)
})
})
})
+58
View File
@@ -79,6 +79,50 @@ export function adjustPreviousWordEnd(previousWord: Word, nextStart: number, was
}
}
/**
* Close out a Tap To Sync pass that stopped before the last word (auto-stop after the line, or the
* user pressing Stop mid-line). The untapped words after the last tapped one still carry their OLD
* timings, which can now start BEFORE the last tapped word (gen's fake fixture: taps at 16.0, 17.2,
* 18.4, 19.6 leave "ever" at 19.6 but "transcribed" at a stale 18.74) and would render out of order.
*
* - Every untapped word after the last tapped one whose start is before the last tapped word's
* start is cleared (null start/end), so the untimed-lyrics guard blocks finishing and points the
* user at it, instead of saving words that highlight out of order.
* - The last tapped word's end is then capped before the next still-timed word in the line.
*
* Mirrors nomad-mobile's review-core `commitTapSync`. Returns a new words array, or null when
* nothing changed. Pure; `synced` is the set of word indices tapped this pass.
*/
export function commitPartialSyncPass(words: Word[], synced: Set<number>): Word[] | null {
if (synced.size === 0) return null
const last = Math.max(...synced)
const lastWord = words[last]
if (!lastWord || lastWord.start_time === null || lastWord.end_time === null) return null
const tappedStart = lastWord.start_time
let changed = false
const next = words.map((word, j) => {
if (j > last && word.start_time !== null && word.start_time < tappedStart) {
changed = true
return { ...word, start_time: null, end_time: null }
}
return word
})
const nextTimed = next.slice(last + 1).find((word) => word.start_time !== null)
if (nextTimed && nextTimed.start_time !== null) {
const cappedEnd = Math.max(
Math.min(lastWord.end_time, nextTimed.start_time - OVERLAP_BUFFER),
tappedStart
)
if (cappedEnd !== lastWord.end_time) {
changed = true
next[last] = { ...lastWord, end_time: cappedEnd }
}
}
return changed ? next : null
}
export default function useManualSync({
editedSegment,
currentTime,
@@ -134,7 +178,21 @@ export default function useManualSync({
}
}, [updateSegment, syncWordIndex]) // Only update when syncWordIndex changes
// Latest updateSegment, so the stable cleanupManualSync can commit the pass with it.
const updateSegmentRef = useRef(updateSegment)
useEffect(() => {
updateSegmentRef.current = updateSegment
}, [updateSegment])
const cleanupManualSync = useCallback(() => {
// A pass stopped mid-line (auto-stop or Stop): clear stale untapped words that now start before
// the last tapped one, and cap that word before the next timed word (see commitPartialSyncPass).
const committed = commitPartialSyncPass(wordsRef.current, syncedIndicesRef.current)
if (committed) {
wordsRef.current = committed
updateSegmentRef.current(committed)
}
setIsManualSyncing(false)
setIsPaused(false)
setSyncWordIndex(-1)
+20 -5
View File
@@ -13,15 +13,16 @@ import {
markBackendReachable,
} from './backend-status';
import { ApiError } from './api-error';
import { isLocalPage, localApiOverride } from './local-host';
import { putFileToSignedUrl, uploadFilesToSignedUrls, type UploadProgress } from './upload';
// In development, use relative URLs to go through Next.js proxy (avoids CORS)
// In production (static export), use the full backend URL
// For local mode (localhost or 127.0.0.1), use relative URLs
const isLocalHostname = typeof window !== 'undefined' &&
(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
export const API_BASE_URL = isLocalHostname
? new URLSearchParams(location.search).get('baseApiUrl') || ('' /* Relative URL - goes to the local server */)
// For local mode (localhost, 127.0.0.1, or the Android emulator's 10.0.2.2), use relative URLs.
// Every client that builds API URLs (lib/api/*) must use API_BASE_URL, so a local page never
// sends its bearer token to production.
export const API_BASE_URL = isLocalPage()
? localApiOverride(location.search) || ('' /* Relative URL - goes to the local server */)
: (process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com');
// Token management - stored in localStorage (client-side only)
@@ -4294,6 +4295,8 @@ export interface LyricsReviewApiClient {
refreshInstrumentalUrls: () => Promise<InstrumentalOption[]>
getInstrumentalState?: () => Promise<InstrumentalState>
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
/** Admin only: mark the reviewed timing "perfectly synced" (word-timing reference set). */
setSyncReference?: (verified: boolean, notes?: string) => Promise<void>
// Review session methods
saveReviewSession: (data: CorrectionData, editCount: number, trigger: string, summary: ReviewSessionSummary) => Promise<{ status: string; session_id?: string; reason?: string }>
listReviewSessions: () => Promise<{ sessions: ReviewSession[] }>
@@ -4514,6 +4517,18 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
* modal still calls this on an audio load error (e.g. a transient network blip), and
* it's cheap and harmless. Resolved to absolute token URLs like getCorrectionData.
*/
async setSyncReference(verified: boolean, notes?: string): Promise<void> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/sync-reference`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ verified, notes: notes || null }),
})
await handleResponse<unknown>(response)
},
async refreshInstrumentalUrls(): Promise<InstrumentalOption[]> {
const response = await apiFetch(
`${API_BASE_URL}/api/review/${jobId}/instrumental-urls`,
@@ -0,0 +1,76 @@
/**
* The AI review clients (auto-correct, custom lyrics) must pick their API base the same way as
* lib/api.ts: a page served from a local host (the local stack, nomad-mobile's E2E in an emulator's
* Chrome) talks to its own backend through relative URLs, never to production with its bearer token.
*/
const PROD = 'https://api.nomadkaraoke.com'
function setHostname(hostname: string, search = '') {
delete (window as unknown as { location?: Location }).location
Object.defineProperty(window, 'location', { value: { hostname, search, href: `http://${hostname}/${search}`, pathname: '/' } as Location, configurable: true, writable: true })
}
async function capturePostedUrl(hostname: string, client: 'autoCorrect' | 'customLyrics', search = ''): Promise<string> {
const original = window.location
setHostname(hostname, search)
let url = ''
const originalFetch = global.fetch
global.fetch = jest.fn(async (u: RequestInfo) => {
url = String(u)
return { ok: true, status: 200, json: async () => ({ suggestions: [], lines: [] }) } as unknown as Response
}) as unknown as typeof fetch
try {
await jest.isolateModulesAsync(async () => {
if (client === 'autoCorrect') {
const mod = await import('../autoCorrect')
await mod
.fetchAutoCorrectSuggestions('job-1', {
segments: [],
referenceLyrics: {},
settings: mod.DEFAULT_AUTO_CORRECT_SETTINGS,
})
.catch(() => {})
} else {
const mod = await import('../customLyrics')
await mod
.generateCustomLyrics('job-1', {
existingLines: ['a'],
customText: 'x',
settings: mod.DEFAULT_GENERATION_SETTINGS,
} as never)
.catch(() => {})
}
})
} finally {
global.fetch = originalFetch
Object.defineProperty(window, 'location', { value: original, configurable: true, writable: true })
}
return url
}
describe.each(['autoCorrect', 'customLyrics'] as const)('%s API base', (client) => {
it.each(['localhost', '127.0.0.1', '10.0.2.2'])('uses a relative URL on local host %s', async (host) => {
const url = await capturePostedUrl(host, client)
expect(url).toMatch(/^\/api\/review\/job-1\//)
expect(url).not.toContain(PROD)
})
it('honours a local ?baseApiUrl= override (another lane\'s stack)', async () => {
const url = await capturePostedUrl('127.0.0.1', client, '?baseApiUrl=http://127.0.0.1:8110')
expect(url.startsWith('http://127.0.0.1:8110/api/review/job-1/')).toBe(true)
})
it.each(['https://example.com', 'https://api.nomadkaraoke.com', 'javascript:alert(1)', 'not a url'])(
'ignores a non-local ?baseApiUrl=%s (the bearer token must not leave the machine)',
async (override) => {
const url = await capturePostedUrl('10.0.2.2', client, `?baseApiUrl=${encodeURIComponent(override)}`)
expect(url).toMatch(/^\/api\/review\/job-1\//)
},
)
it('uses the production API on the production host', async () => {
const url = await capturePostedUrl('gen.nomadkaraoke.com', client)
expect(url.startsWith(`${PROD}/api/review/job-1/`)).toBe(true)
})
})
@@ -137,13 +137,16 @@ describe('generateCustomLyrics', () => {
}), { status: 200 })
}) as unknown as typeof fetch
// On a local host (jsdom is localhost) the URL is relative, so apiFetch manages it and wraps
// the caller's signal in its own controller: assert the caller's abort reaches fetch.
const ac = new AbortController()
ac.abort()
await generateCustomLyrics(
'job-1',
{ existingLines: ['a'], customText: 'x', settings: DEFAULT_GENERATION_SETTINGS },
ac.signal,
'tok',
)
expect(captured.init!.signal).toBe(ac.signal)
expect((captured.init!.signal as AbortSignal).aborted).toBe(true)
})
})
+1 -4
View File
@@ -9,10 +9,7 @@
* flows through the existing corrections/complete paths.
*/
import type { LyricsSegment, ReferenceSource } from '@/lib/lyrics-review/types'
import { apiFetch } from '@/lib/api'
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
import { API_BASE_URL as API_BASE, apiFetch } from '@/lib/api'
export type AiSuggestionOp = 'replace' | 'delete' | 'insert_after'
+1 -4
View File
@@ -7,10 +7,7 @@
* preview. Persistence still flows through the existing replace-segments
* Save path.
*/
import { apiFetch } from '@/lib/api'
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
import { API_BASE_URL as API_BASE, apiFetch } from '@/lib/api'
export type StrictnessLevel = 'verbatim' | 'loose' | 'balanced' | 'tight' | 'strict'
export type StopReason =
+35
View File
@@ -0,0 +1,35 @@
/**
* Hostnames that mean "this page is served by a local stack, not production": a developer's
* `next dev`, gen's scripts/local-stack.sh, and nomad-mobile's E2E, which loads gen web in an
* emulator's Chrome (127.0.0.1 through adb reverse, or 10.0.2.2, the Android emulator's alias for
* the host machine). Pages on these hosts must never talk to production services: API calls go
* relative (lib/api.ts API_BASE_URL) and Google Analytics is not loaded.
*/
export const LOCAL_HOSTNAMES: readonly string[] = ['localhost', '127.0.0.1', '10.0.2.2']
export function isLocalHostname(hostname: string | null | undefined): boolean {
return !!hostname && LOCAL_HOSTNAMES.includes(hostname)
}
/** True in a browser whose page host is local. False during SSR / static export. */
export function isLocalPage(): boolean {
return typeof window !== 'undefined' && isLocalHostname(window.location?.hostname)
}
/**
* A local page's `?baseApiUrl=` override (pointing the page at another local stack, e.g. another E2E
* lane's gen), only when it is an http(s) URL on a local host. Anything else is ignored (''), so a
* crafted link can't send the page's bearer token to another origin.
*/
export function localApiOverride(search: string): string {
const raw = new URLSearchParams(search).get('baseApiUrl')
if (!raw) return ''
try {
const url = new URL(raw)
return (url.protocol === 'http:' || url.protocol === 'https:') && isLocalHostname(url.hostname)
? raw.replace(/\/+$/, '')
: ''
} catch {
return ''
}
}
@@ -86,4 +86,36 @@ describe('sanitizeSegmentTimings', () => {
expect(out.words[1].start_time).toBe(4)
expect(out.words[1].end_time).toBe(5)
})
it('moves a word that starts before the previous word ends to after it (mirrors timing_sanitizer.py)', () => {
// A Tap To Sync pass that stopped before the last word: "ever" re-tapped at 19.6, but
// "transcribed" kept its stale 18.74 start, so it would highlight out of order.
const seg: LyricsSegment = {
id: 's', text: 'was ever transcribed', start_time: 18.4, end_time: 20.1,
words: [
{ id: 'w2', text: 'was', start_time: 18.4, end_time: 19.3 },
{ id: 'w3', text: 'ever', start_time: 19.6, end_time: 20.1 },
{ id: 'w4', text: 'transcribed', start_time: 18.74, end_time: 19.5 },
],
}
const { segment, changes } = sanitizeSegmentTimings(seg)
expect(segment.words[0]).toBe(seg.words[0])
expect(segment.words[1]).toBe(seg.words[1])
expect(segment.words[2].start_time).toBe(20.1)
expect(segment.words[2].end_time).toBe(20.1)
expect(changes.map((c) => c.wordText)).toEqual(['transcribed', 'transcribed'])
})
it('leaves a small overlap with the previous word untouched (common in AI transcriptions)', () => {
const seg: LyricsSegment = {
id: 's', text: 'a b', start_time: 1, end_time: 3,
words: [
{ id: 'w0', text: 'a', start_time: 1, end_time: 2 },
{ id: 'w1', text: 'b', start_time: 1.98, end_time: 3 },
],
}
const { segment, changes } = sanitizeSegmentTimings(seg)
expect(changes).toEqual([])
expect(segment).toBe(seg)
})
})
@@ -18,14 +18,18 @@ export interface TimingChange {
* segment bounds are a separate concern.)
* - Each word's `start_time` and `end_time` are clamped into
* `[segment.start_time, segment.end_time]`.
* - Words whose `start_time` is missing or non-finite are placed at the previous
* word's (repaired) end time, keeping repaired words in order within the window.
* - Words whose `start_time` is missing, non-finite, or before the previous word's
* (repaired) START (out of order, e.g. a stale untapped word left behind a partial Tap
* To Sync pass) are placed at the previous word's end, keeping words in order. A start
* between the previous word's start and end (a small overlap, common in AI
* transcriptions) is left as-is.
* - `word.end_time` is forced `>= word.start_time` (after clamping).
* - Already-valid in-bounds word timings are left as-is; only out-of-window or
* missing values are corrected.
*
* These semantics intentionally mirror the shipped backend
* `SegmentResizer._sanitize_segment_timings`. Returns a NEW segment object plus the
* These semantics intentionally mirror the backend `services/timing_sanitizer.py`
* (`sanitize_corrections`), which runs on every submitted correction. The render-time
* `SegmentResizer._sanitize_segment_timings` shares the window clamping but not the ordering rule. Returns a NEW segment object plus the
* list of clamps applied so callers can warn. A clean segment returns the same word
* objects and `changes: []`.
*/
@@ -46,13 +50,15 @@ export function sanitizeSegmentTimings(segment: LyricsSegment): {
// Hoist clamp once — segStart/segEnd are constant for the whole segment.
const clamp = (v: number) => Math.min(Math.max(v, segStart), segEnd)
let prevStart = segStart
let prevEnd = segStart
const words: Word[] = segment.words.map((w) => {
const start = isFiniteNumber(w.start_time) ? (w.start_time as number) : null
const end = isFiniteNumber(w.end_time) ? (w.end_time as number) : null
// Invalid start = non-finite OR outside the segment window -> place at previous word's end.
const newStart = start !== null && start >= segStart && start <= segEnd
// Invalid start = non-finite, outside the segment window, OR before the previous word's start
// (out of order) -> place at previous word's end. Small overlaps are left alone.
const newStart = start !== null && start >= segStart && start <= segEnd && start >= prevStart
? start
: clamp(Math.max(prevEnd, segStart))
// Invalid end = non-finite, before start, or past segment end.
@@ -73,6 +79,7 @@ export function sanitizeSegmentTimings(segment: LyricsSegment): {
changes.push({ wordId: w.id, wordText: w.text, field: 'end_time', from: w.end_time, to: newEnd })
next = { ...next, end_time: newEnd }
}
prevStart = newStart
prevEnd = newEnd
return next
})
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more