mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 09:14:03 +09:00
36b331f3d7411ecf97c05bf15146e83161ab94de
12
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d39dfd6778 |
Encoding worker infra/auth failures: retry instead of terminal-failing the job (#972)
## Why Prod alert burst (2026-08-31): a paying customer's job (`6452888e`) was **terminally failed** — its render worker error was: > Encoding job 6452888e failed: Failed to retrieve `https://metadata.google.internal/.../service-accounts/default/` … **Compute Engine Metadata server unavailable** … `SSLCertVerificationError` Root cause: the c4d primary pair was in a zonal stockout (503 on start), so the render fell back to `encoding-worker-fallback-c4a`. That fallback VM **booted and accepted the job** but then couldn't reach the GCE metadata server to fetch its service-account token, so it couldn't touch GCS and died mid-encode. This surfaced as a bare `RuntimeError`, hit `render_video_worker`'s generic `except Exception` → `fail_job`, and lost the job with **no retry** — even though the exact same work succeeds on any healthy worker. The same alert burst also included the daily E2E happy-path failure (the encoder being offline made the preview step flaky) and a benign `match-judge AI call failed; returning no-suggestion` red-error page. All three are addressed here. ## What **1. Encoding infra/auth failures are now recoverable (primary fix)** - `encoding_errors.py`: `is_worker_infra_error()` classifier (metadata / SSL-cert / missing-credentials markers, deliberately specific so a real ffmpeg/input error never matches) + new `EncodingWorkerInfraError` — a **subclass of `EncodingWorkerStartError`** so it flows through the existing park-for-auto-retry path with zero changes to the render worker's `except` (and the final-encode Cloud Run Job retries too). - `encoding_service.wait_for_completion()`: on a worker-reported infra/auth failure, **demote the broken worker + invalidate the URL cache**, then raise the recoverable typed error instead of `RuntimeError`. - `encoding_worker_manager.demote_active_worker()`: records a capacity-state cooldown for the serving fallback's `machine_type@zone` and clears `active_override`, so the retry re-selects a *different, healthy* VM. Scoped to **fallbacks only** — it never family-demotes the fast c4d primary on a rare blip. **2. match-judge noise** — the two graceful-degradation `logger.exception` calls become `logger.warning(exc_info=True)`, so a transient Vertex/Gemini blip that safely returns no-suggestion stops paging as a red "new error pattern". **3. Happy-path E2E robustness** — tolerate slow encoder cold-starts at the preview step: scope the alert check to the modal (kills the spurious empty-`[role=alert]` "Preview error:" from run #151) and recover the "Proceed to Instrumental" button via reload+reopen. The final assertion stays authoritative, so genuinely broken generation still fails the smoke test. ## Testing - New unit coverage: classifier positive/negative + subclass (`test_encoding_errors.py`), `demote_active_worker` (fallback demote+clear, primary no-op, never-raises), `wait_for_completion` infra classification (+ demote/invalidate, and no-manager path), and render worker **parks** (not fails) on `EncodingWorkerInfraError`. - `python -m pytest` across the encoding / worker / match-judge suites: **177 passed** locally. ## Not in this PR (infra, needs Andrew / GCP write) - **Fault A**: `encoding-worker-a` (c4d, us-central1-c) is chronically 503 on start (zonal stockout) — that's why the "Encoder offline" footer showed in the E2E. This change makes the fallback path robust to it, but the underlying c4d capacity/zone choice is an infra decision (secret/VM change; my GCP access is read-only). Worth deciding whether to repin the primary family/zone or promote a fallback. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Detects infrastructure and authentication failures on encoding workers. * Demotes affected workers and retries jobs using alternate capacity when available. * **Bug Fixes** * Prevents recoverable worker failures from becoming terminal job errors. * Reduces misleading error-level logging for gracefully handled match-judge failures. * Improves preview-flow recovery by waiting for actions to become enabled. * **Documentation** * Clarified that retries prefer, but do not guarantee, a different worker. * **Chores** * Updated the application version to 0.217.0. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
c7959ea2d5 |
feat(encoding): mature multi-instance-type pool with availability-aware selection (#911)
## Summary - Replaces "c4d primary + single n2 fallback family" with a **ranked pool of 6 x86_64 / 32-vCPU / ≥32 GB highcpu types** across 4 silicon lineages (c4d, c4, n4d, c2d, n2d, n2), selected **fastest-first** but **availability-aware** — a type that stocks out is demoted for a 15-min cooldown then re-probed. c4d stays the top pick whenever it can start; a render no longer stalls even if 2+ types are fully stocked out in us-central1. - One **pure preference module** (`encoding_worker_preference.ordered_candidates`) is now the single source of truth for candidate ranking, driving **both** runtime selection and deploy green selection so they can't drift. - Keeps the per-VM start/stop model (MIG deferred with documented triggers; no reservation). Full plan + rollout in `docs/archive/2026-08-15-encoding-instance-type-diversity-plan.md`. ## Changes - **New** `backend/services/encoding_worker_preference.py` — speed-rank + Firestore `capacity_state` cooldown; stdlib-only so `deploy_promote` imports it (with a shadow-proof by-path fallback). - **Runtime** (`encoding_service`, `encoding_worker_manager`): builder ranks primary + fallbacks; manager records/clears per-(type,zone) stockout; override routing now keys off an explicit `is_primary` flag instead of list position. - **Deploy** (`deploy_promote`, `ci.yml`): green selection uses the shared ranker + threads `capacity_state`. - **IaC** (`config.py`, tests): `FALLBACKS` broadened to 6 types (additive-only) with family-correct disk types (Titanium c4/c4d/n4/n4d = hyperdisk-balanced; c2d/n2/n2d = pd-balanced); secret schema gains optional `machine_type`. - **Packer** (`provision.sh`, `startup.sh`): bake full dep tree with **CPU-only torch** so fresh type VMs boot self-sufficient; build-time import verify. - **New** `benchmark_types.py` to measure per-type encode wall-time and refine the seeded `SPEED_RANK`. ## Testing - [x] Full backend unit suite: **3871 passed, 36 skipped** (emulator tests need external services) - [x] New/updated tests: preference module (16), capacity_state + `is_primary` manager tests, builder-ordering + non-list-JSON service tests, deploy ranking tests, infra disk-capability + pool-breadth invariants - [ ] Operator rollout (needs write creds): `pulumi up` (verify +8 create, 0 replace) → rebuild image (dep-bake) → grow fallback secret with `machine_type` → run `benchmark_types.py` ## Review - [x] Local CodeRabbit review completed (4 major findings fixed; cycle 2 clean) - [x] Review feedback addressed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
51dbf1cbfd |
fix(encoding): serialize heavy encodes (OOM-proof) + auto-resubmit lost renders (#908)
## Problem Three Arctic Monkeys renders (`a3f340a2`, `374dec26`, `590630c0`) failed within ~2 min on 2026-08-15 with `lost contact with worker after 5 consecutive poll failures: Encoding job … not found`. **Root cause (confirmed from live forensics):** Both 60 GB c4d primary encoding workers were down (Spot stockout), so all render traffic funneled onto the single 32 GB `n2-highcpu-32` fallback. The worker ran `ThreadPoolExecutor(max_workers=4)`, so the batch put **3 concurrent 4K ffmpeg encodes** (~30 GB) on it → **kernel OOM-killer fired** → `encoding-worker` service restarted → in-memory `jobs` registry wiped → every poll `404`'d → all three failed. ffmpeg already saturates all cores for one job, so the parallelism bought **no throughput**, only multiplied peak RAM. ## Fix **Worker — serialize the heavy lane** (`backend/services/gce_encoding/main.py`) - Split the single pool into `heavy_executor` (`max_workers=ENCODING_HEAVY_CONCURRENCY`, default **1**, clamped to `[1,4]`) for renders/encodes and `light_executor` (previews + wheel installs). One heavy ffmpeg at a time = OOM-proof on any machine type; extras queue as `pending`. - `/status` now exposes `queue_position` (+ `restart_failure_code`); jobs tagged by `kind`. **Client + workers — auto-resubmit a lost job** - `wait_for_completion` raises the typed `EncodingJobLostError` on a **404-after-the-job-was-seen** (a pinned poll can only 404 if the worker lost it) or a terminal failure carrying `restart_failure_code`. 404 is now a typed `EncodingJobNotFoundError` (no message parsing). - Time spent `pending` counts against a generous `queue_timeout`, not the per-run `timeout`. - `run_with_lost_job_resubmit` resubmits a lost job as `<id>_retry_<hex8>` (bounded, `ENCODING_RESUBMIT_MAX=2`), wired into `render_video_worker`, `video_worker`, and `video_worker_orchestrator` (incl. the stale-cache path). Idempotent by deterministic output paths (overwrite, no dupes). - `GCEEncodingBackend.encode` re-raises the lost error instead of flattening it to `success=False`, so the resubmit actually fires. ## Testing - New tests: worker lane serialization + `queue_position`; concurrency-clamp matrix; client lost-job detection (404-after-seen, restart code, pending-not-timeout); resubmit wrapper (fresh id, bounded, non-retry of other errors); backend re-raise; preview queue-timeout cap. - Full backend suite: **3766 passed, 139 skipped**. - Local CodeRabbit review completed; feedback addressed (typed 404, bounded env parsing, preview queue cap, idempotency doc). ## Deploy note `main.py` ships in the wheel, but the running uvicorn process only picks up worker-side changes on a **service restart** — the CI deploy / blue-green swap handles this. Post-deploy verification: re-render the 3 failed jobs **concurrently** (the exact OOM trigger) and confirm no OOM (`journalctl -k`), `NRestarts` doesn't increase, and all three complete. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a0b94f95a2 |
fix(encoding): pin in-flight render polls to the submission worker (#840)
## Problem A blue-green encoding-worker deploy that swaps the Firestore primary pointer (`active_url`) **mid-render** caused in-flight status polls to migrate from the worker actually encoding the job to the just-swapped new primary, which returns 404 `Encoding job <ID> not found`. After 5 consecutive poll failures the render was failed — even though the original worker finished the encode fine. **Incident 2026-06-16, job `d3af33ae`** (error-monitor alert). Confirmed from logs + Firestore: - 04:31:39 render submitted to worker-a; encoding begins - 04:33:46.985 deploy swaps `primary_vm` worker-a → worker-b (`last_swap_at`) - 04:33:53–04:34:33 polls hit worker-b (never had the job) → 404 ×5 → render failed - worker-a was alive and finished the encode the whole time; user retried 12 min later and it succeeded The 4 poll failures happened **before** worker-a was stopped (04:34:33), proving the orphaning is at the **poll layer** — the 2026-06-15 drain fix (which keeps the old VM alive) can't catch it. ## Fix Pin in-flight polls to the worker that accepted the job — the poll follows the job, not the floating primary pointer. - `_request_with_retry(..., allow_failover=True)` — gates the fallback-VM warmup + URL re-resolution (default `True` keeps capacity fallback unchanged). - `get_job_status(job_id, worker_url=None)` — pinned polls target the given worker with `allow_failover=False` (never re-route / never spin up a fallback VM — a fresh VM can't have the in-flight job). - `wait_for_completion(..., worker_url=None)` — threads the pinned URL into every poll. - `render_video_on_gce` / `encode_videos` / `encode_preview_video` — capture the worker URL **after** submit (reflects a capacity-fallback re-route, precedes any later swap) and pin the wait to it. URL re-resolution stays correct for capacity fallback (dead primary, fresh submission); it's only suppressed for in-flight polls. ## Tests New `TestWorkerUrlPinning` in `test_encoding_service.py`, including an **end-to-end swap regression** where `active_url` has swapped to a 404'ing worker and the render still completes by polling the submission worker (fails before the fix, passes after). Plus pinned-vs-active resolution, failover suppression, and poll threading. `391 passed` across encoding / render-worker / review suites. No regressions. ## Docs / version - `docs/LESSONS-LEARNED.md` + `docs/TROUBLESHOOTING.md` (runbook note) + plan doc in `docs/archive/` - version `0.184.1 → 0.184.2` @coderabbitai ignore Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
952302f8f3 |
fix(render): re-resolve encoding worker URL between retry attempts (#752)
## Summary Bug observed on job `fae3eadc` 2026-05-06: multi-zone fallback successfully routed to fallback-a in us-central1-a — set `active_override` in Firestore, invalidated the URL cache — but `_request_with_retry` had already captured the original (primary, dead) URL **before** the retry loop started, and used it for all 8 retry attempts. Every attempt timed out, the retry loop re-raised `TimeoutError()` (not a typed start error), and the render worker's `except EncodingWorkerStartError` didn't catch it → job hard-failed instead of being parked for auto-retry. Without this fix, the scheduler's auto-retry can't actually recover a job once the URL gets stuck on a dead VM, even though all the multi-zone plumbing engages correctly. ## Fix `_request_with_retry` now accepts an optional `path` parameter (e.g. `/render-video`) and re-resolves the full URL via `_get_worker_url() + path` on retry attempts **after** the warmup has fired. Updated all four call sites: `submit_encoding_job`, `get_job_status`, `submit_preview_encoding_job`, `submit_render_video_job`. The `_health` callsite uses `aiohttp.ClientSession` directly without `_request_with_retry`, so no change needed there. ## Trace from the affected job ``` 21:15:39 Trying candidate 1/3: VM encoding-worker-b in us-central1-c (status TERMINATED) 21:15:41 Candidate encoding-worker-b in us-central1-c start failed (503), trying next candidate 21:15:41 Set active_override to encoding-worker-fallback-a in us-central1-a (capacity fallback) 21:15:41 [job:fae3eadc] Encoding worker unreachable — VM encoding-worker-fallback-a already running/starting 21:15:41 [job:fae3eadc] GCE worker connection failed (attempt 1/8): TimeoutError. Retrying in 5.0s... 21:16:17 [job:fae3eadc] GCE worker connection failed (attempt 2/8): TimeoutError. Retrying in 10.0s... ... (all 8 attempts to dead primary URL — should have hit fallback-a from attempt 2 onwards) 21:20:48 [job:fae3eadc] WORKER_END worker=render-video status=error duration=341.6s error=TimeoutError() 21:20:49 Job fae3eadc failed: Video render failed: TimeoutError() ``` After this fix, attempt 2 onwards will resolve to `http://34.55.231.54:8080/render-video` (fallback-a) instead of the dead primary, and the request will succeed. ## Test plan - [x] New regression test `test_url_reresolves_after_warmup_so_fallback_takes_effect` — first attempt to dead URL fails, warmup updates override, second attempt re-resolves to live URL and succeeds. Asserts both URLs were actually requested (in order) - [x] All 84 capacity-related tests pass locally - [ ] After merge: monitor for any new \"TimeoutError after warmup\" patterns — should disappear @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
b321f56568 |
fix(render): zone-aware readiness wait + index-free retry + fallback env on encoding job (#751)
## Summary Three issues observed after #750 deployed and the parked jobs were re-triggered. All blocking real renders. ### 1. `wait_for_worker_ready` looks in the wrong zone Multi-zone fallback successfully started a VM in `us-central1-a`, but `wait_for_worker_ready` then polled `get_vm_status` against the manager's default zone (`us-central1-c`), got 404 (\"instance not found\"), gave up, and the next HTTP retry hit a still-booting VM and timed out. ``` [job:6b0bf198] Encoding worker unreachable — started VM encoding-worker-fallback-a as fallback [job:6b0bf198] Cold-start readiness wait failed (non-fatal): NotFound: 404 ... zones/us-central1-c/instances/encoding-worker-fallback-a [job:6b0bf198] GCE worker connection failed (attempt 1/8): TimeoutError. Retrying in 5.0s... ``` Fix: thread the candidate's `zone` through `wait_for_worker_ready` so the VM-status poll targets the right zone. Also include zone in `ensure_primary_running`'s return for consistency. ### 2. /retry-pending-render-jobs returns 500 (Firestore composite index) ``` status = StatusCode.FAILED_PRECONDITION details = "The query requires an index. ..." ``` The Cloud Scheduler-driven endpoint's query (`status == X` + `order_by updated_at`) needs a composite index that doesn't exist. Fix: drop the server-side `order_by`, stream by status alone (small result set), sort in Python by `first_seen_at`. No index ceremony, matches the existing `recover-stuck-jobs` pattern. ### 3. video-encoding-job Cloud Run Job missing `ENCODING_WORKER_FALLBACK_VMS` The final encoding stage runs in a Cloud Run Job (separate from the main service). Its IaC was missing the `ENCODING_WORKER_FALLBACK_VMS` env var, so when it hit `503 SERVICE_UNAVAILABLE` starting the primary VM in `us-central1-c`, it couldn't fall through to alt-zone fallbacks and the job died. Observed for `549cdf90`, `6b0bf198`: render succeeded via fallback, then encoding stage failed at progress 0 with: ``` Video generation failed: Encoding failed: VM encoding-worker-b start failed in us-central1-c: 503 — SERVICE UNAVAILABLE ``` Fix: add the `ENCODING_WORKER_FALLBACK_VMS` secret-mount to the Cloud Run Job in IaC. ## Test plan - [x] Unit: `_patch_endpoint_dependencies` no longer mocks `order_by` chain (matches new query) - [x] Unit: `wait_for_worker_ready` accepts `zone` parameter and threads to `get_vm_status` - [x] All 83 capacity-related tests pass locally - [x] `pulumi up` applied locally — Cloud Run Job updated with new env var (1 resource updated) - [ ] After merge: confirm parked jobs unstick (the auto-retry endpoint should now actually work, and the Cloud Run Job should fall through to fallback-a/b instead of dying on 503) @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
20fae2c579 |
Encoding worker capacity resilience: real errors, auto-retry, multi-zone failover (#748)
## Summary
Investigation of two failed jobs (`fbc651be`, `bee150fd`) revealed both
failed at the GCE encoding-worker render stage with empty error messages
(`Video render failed: `). Root cause: the GCP `compute.instances.start`
API was returning `ZONE_RESOURCE_POOL_EXHAUSTED` (us-central1-c out of
`c4d-highcpu-32` capacity), but the application's fire-and-forget call
swallowed the error. Users saw 7-minute timeouts with no useful message,
and there was no mechanism to retry once capacity returned.
This PR delivers all three phases of the capacity-resilience plan
([docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md](docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md)):
### Phase 1 — Surface real errors (commit `56e5968e`)
- New `EncodingWorkerCapacityError` / `EncodingWorkerStartError` typed
exceptions
- `EncodingWorkerManager.start_vm` now waits for the operation result
and raises the right typed error on `ZONE_RESOURCE_POOL_EXHAUSTED` /
`STOCKOUT` / `QUOTA_EXCEEDED`
- Capacity errors propagate through the warmup-fallback path; the HTTP
retry loop bails out fast (instead of hammering an unreachable VM for 7
min)
- Render worker catches capacity errors and parks the job in new state
`RENDER_PENDING_CAPACITY` with a user-friendly message: *"Encoding
capacity is temporarily unavailable. Your job will retry automatically —
no action needed. Most jobs recover within 5–30 minutes."*
- Repeat capacity hits accumulate `attempt_count` while preserving
`first_seen_at`
- `repr()` fallback in the generic exception handler so empty-string
errors no longer produce blank `Video render failed: ` messages
### Phase 2 — Auto-retry scheduler (commit `9d6d2161`)
- New endpoint `POST /api/internal/retry-pending-render-jobs`
(admin-auth)
- Cloud Scheduler fires it every 5 min — picks the oldest
`RENDER_PENDING_CAPACITY` job, clears its error state, re-triggers the
render worker
- 24h hard deadline: jobs older than that fail permanently with a clear
"retry manually or contact support" message
- Processes 1 job per tick (the GCE worker is single-tenant per render)
### Phase 3 — Multi-zone failover (commit `6d6b1376`)
- IaC: new fallback VMs `encoding-worker-fallback-a` (us-central1-a) and
`encoding-worker-fallback-f` (us-central1-f). All four zones support
`c4d-highcpu-32`. Provisioned stopped — ~$10/mo idle each
- New `EncodingWorkerManager.ensure_any_running(candidates)` iterates
VMs in order, catching capacity errors per-zone, falling through to the
next; returns the active VM info
- New `active_override_*` fields on the Firestore config doc track the
active fallback URL; `EncodingWorkerConfig.active_url` returns the
override if set, else primary; `EncodingService._get_worker_url`
consults `active_url` so in-flight requests after fallback hit the right
VM
- Gated by env var `ENCODING_WORKER_FALLBACK_VMS` (JSON list) — empty
default = single-zone behavior unchanged
## Operational rollout
Phases 1 & 2 ship as code only — no manual steps. Phase 3 needs:
1. `pulumi up` from `infrastructure/` — provisions the 2 fallback VMs
(stopped)
2. Capture Pulumi-output IPs (`encoding_worker_fallback_a_ip`,
`encoding_worker_fallback_f_ip`)
3. Set env var on `karaoke-backend` Cloud Run:
```
ENCODING_WORKER_FALLBACK_VMS=[{"vm":"encoding-worker-fallback-a","zone":"us-central1-a","ip":"<ip-a>"},{"vm":"encoding-worker-fallback-f","zone":"us-central1-f","ip":"<ip-f>"}]
```
4. Until step 3 is done the application uses single-zone behavior;
fallback VMs are inert
Plan doc:
[docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md](docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md)
## Test plan
- [x] Unit: `EncodingWorkerManager.start_vm` raises
`EncodingWorkerCapacityError` for `ZONE_RESOURCE_POOL_EXHAUSTED`,
generic `EncodingWorkerStartError` for other codes, surfaces `result()`
failures
- [x] Unit: `_warmup_encoding_worker_fallback` propagates capacity
errors, swallows generic warmup failures
- [x] Unit: `_request_with_retry` aborts immediately on capacity error
from warmup (no 7-min retry loop)
- [x] Unit: render worker transitions to `RENDER_PENDING_CAPACITY` on
capacity error, NOT `FAILED`; preserves `first_seen_at`; increments
`attempt_count`
- [x] Unit: render worker non-capacity exceptions still fail with a
useful message (no more blank `Video render failed: `)
- [x] Unit: `/api/internal/retry-pending-render-jobs` retries 1 job per
tick (oldest first), times out 24h+ jobs, no-op on empty queue, clears
error state before retry
- [x] Unit: `ensure_any_running` happy path, falls through on capacity
error, raises when all candidates exhausted, clears stale override on
primary success
- [x] Unit: `EncodingWorkerConfig.active_url` returns override if set,
else primary
- [x] Full backend suite passes (3114 tests; 5 pre-existing failures in
`test_internal_api.py` are unrelated and present on `main`)
- [ ] Manual prod test: trigger a render during a confirmed capacity
outage, observe job parks in `RENDER_PENDING_CAPACITY`, scheduler picks
it up next tick, completes when capacity returns
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
52b4ac1abc |
fix(encoding): GCE worker cold-start resilience (#736)
## Summary - Fixes render/preview-encode jobs that fail when the GCE encoding worker VM is cold (TERMINATED). The existing 90s connection retry window (sized for `systemctl restart` during deploys) was too short for a 2-5 min cold boot. - Adds an active readiness gate (`EncodingWorkerManager.wait_for_worker_ready`) that's awaited only when `ensure_primary_running()` reports `started=True` (VM was actually TERMINATED). The deploy-restart fast path (`started=False`) is unchanged. - Fixes the empty error message that made the original incident hard to diagnose: `_format_exception()` helper always includes the exception type when `str(e)` is empty. ## Background Job `2c577535` failed on 2026-04-24 at 02:25 UTC after 8 retry attempts over 338s, with an empty log message: ``` [job:2c577535] GCE worker connection failed after 8 attempts: ``` `encoding-worker-a` was TERMINATED (auto-shutdown for cost savings), the backend's `_warmup_encoding_worker_fallback` kicked the start API and returned, and the retry loop's ~90s window exhausted before the VM finished cold-booting (typical 2-5 min). Empty `str(aiohttp.ClientConnectorError)` silently swallowed the failure mode. ## Changes - **`backend/services/encoding_worker_manager.py`** — new `async wait_for_worker_ready(vm_name, health_url, *, vm_timeout=120, health_timeout=180, poll_interval=5)`. Two-phase poll: VM status → `/health` 200. Raises `TimeoutError` on either phase exhausting its budget. - **`backend/services/encoding_service.py`** — `_warmup_encoding_worker_fallback` is now `async`. When `started=True`, it `await`s the readiness gate before returning so the next retry attempt hits a healthy worker. When `started=False`, behavior is unchanged. The single caller in `_request_with_retry` was updated to `await`. - **`backend/services/encoding_service.py`** — new `_format_exception(e)` helper used in both retry log calls so empty exception messages still produce diagnostic logs. - **`backend/tests/`** — 17 new tests across `test_encoding_worker_manager.py` and `test_encoding_service.py`: 5 readiness-gate unit tests, 7 warmup-fallback tests covering all branches (including the new cold-start path and exception swallowing), 3 `_format_exception` tests, 1 cold-start integration regression guard, 1 `attempt == 0` guard test. - **`docs/TROUBLESHOOTING.md`** — runbook for verifying the fix in production (stop the primary VM, submit a job, watch for the new log sequence). - **`docs/LESSONS-LEARNED.md`** — entry complementing the existing "Encoding Worker Warmup Must Cover All Paths" lesson. - **`docs/README.md`** — top-of-list "Recent Changes" entry. - **`docs/archive/`** — design and implementation plan docs. - **`pyproject.toml`** — bump `0.172.2` → `0.172.3`. ## Testing - [x] Backend unit tests: 3017 passed, 36 skipped (`make test`) - [x] Frontend unit tests: 849 passed - [x] Backend integration regression test: simulates the 2026-04-24 incident path end-to-end and asserts no retry exhaustion - [ ] Manual production verification: planned post-deploy per the new runbook entry — stop `encoding-worker-a`, submit a test render, confirm `Waiting for VM ...` → `VM ... reached RUNNING` → `Worker at ... is healthy` → `Cold-started VM ... is now ready` log sequence ## Review - [x] Per-task spec + code quality reviews via subagent-driven flow - [x] Final whole-branch code review - [x] CodeRabbit CLI run locally (1 cycle: 1 real issue fixed in TROUBLESHOOTING.md timing math, 2 false positives skipped) @coderabbitai ignore ## Out of scope - **Stale GCE worker cache** (when `cached=True` is returned but no GCS artifacts exist): already handled gracefully by `worker_service` via `_retry_<hash>` re-encoding. Track separately as a worker-side cache bug. - **Pre-warm on review-page open**: option C from the design doc; better UX but doesn't replace the safety net. Possible follow-up. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
8c7627b7ec |
fix: prevent video worker race condition and add encoding worker warmup (#619)
## Summary - Fix race condition where Cloud Run Job `max_retries` + manual retry launched concurrent video workers that corrupted each other's state transitions (job 13b8adcf) - Add encoding worker VM warmup to all paths that trigger video encoding, not just the frontend happy path - Defense in depth: frontend warmup → worker dispatch warmup → encoding retry warmup ## Changes - **job_health_service.py**: Remove `GENERATING_VIDEO`/`RENDERING_VIDEO` from valid video_worker startup states — if a job is already in those states, another worker is processing it - **video_worker.py**: Make `_validate_prerequisites` a hard failure on wrong status (was warn-and-continue) - **worker_service.py**: Add `_warmup_encoding_worker()` called from both `trigger_video_worker` and `trigger_render_video_worker` - **encoding_service.py**: Add `_warmup_encoding_worker_fallback()` called on first connection failure in retry loop - **docs/LESSONS-LEARNED.md**: Document both findings ## Testing - [x] 7 new unit tests covering race condition fix, warmup dispatch, and fallback behavior - [x] Full backend suite passes (2817 passed) - [x] Full frontend suite passes (712 passed) ## Review - [x] Local CodeRabbit review completed (0 code issues) - [x] Review feedback addressed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
19efa269a8 |
feat: blue-green encoding worker deployment with deep health checks (#595)
## Summary - Replaces single encoding worker VM with a blue-green pair (a/b) for zero-downtime deployments - VMs auto-start on demand (JIT warmup when user opens lyrics review) and auto-shutdown after 15 min idle - CI deploys to secondary VM, runs a real encode test, then swaps the Firestore pointer atomically - Deep health check catches issues like PR #587's pip crash before they reach users - Cloud Function checks idle VMs every 5 minutes and stops them to minimize cost (~$10-15/mo idle vs $800/mo always-on) ## Architecture - **Firestore config doc** (`config/encoding-worker`) is single source of truth for primary/secondary routing - **Backend** reads primary IP from Firestore (30s TTL cache), starts VM on demand via Compute API - **CI workflow** handles blue-green swap: deploy → health check → real encode test → atomic Firestore swap → drain & stop old - **Cloud Function** auto-stops idle VMs based on active jobs, user activity, and deploy status - **Frontend** sends warmup signal on lyrics review page load + heartbeat on interactions ## Changes ### New Files - `backend/services/encoding_worker_manager.py` — VM lifecycle + Firestore config management - `backend/api/routes/encoding_worker.py` — Warmup and heartbeat API endpoints - `infrastructure/functions/encoding_worker_idle/` — Idle shutdown Cloud Function - `infrastructure/modules/encoding_worker_manager.py` — Pulumi module for Cloud Function + Scheduler - `scripts/seed-encoding-worker-config.py` — Firestore config seeding script - `infrastructure/encoding-worker/test-assets/test-preview.ass` — Test file for deploy health check ### Modified Files - `infrastructure/compute/encoding_worker_vm.py` — Single VM → blue-green pair - `infrastructure/__main__.py` — Wire up new VMs, Cloud Function, IAM - `backend/services/encoding_service.py` — Dynamic URL from Firestore, warmup-aware retry - `.github/workflows/ci.yml` — Blue-green deploy flow - `frontend/` — Warmup signal on lyrics review, heartbeat, warming-up UI state - `docs/` — Architecture, development, troubleshooting, lessons learned ## Test plan - [x] 47 new backend tests pass (EncodingWorkerManager, routes, dynamic URL resolution) - [x] 9 Cloud Function unit tests pass - [x] All 2808 existing backend tests pass (1 pre-existing failure unrelated) - [x] All 1116 existing unit tests pass (3 pre-existing failures unrelated) - [ ] Pulumi preview shows expected resource changes - [ ] Pulumi up applied locally before merge - [ ] Firestore config seeded with VM IPs - [ ] End-to-end verification after deployment ## Migration Steps (post-merge) 1. `pulumi up` creates 2 VMs, removes old VM 2. Seed Firestore: `python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>` 3. Start VM A, verify health 4. First CI deploy exercises the blue-green flow ## Design Docs - Spec: `docs/superpowers/specs/2026-03-24-blue-green-encoding-worker-design.md` - Plan: `docs/superpowers/plans/2026-03-24-blue-green-encoding-worker.md` @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> |
||
|
|
7eecbe8382 |
fix: make encoding pipeline resilient to deployment restarts (#473)
## Summary - Encoding jobs no longer fail when CI deploys restart the GCE encoding worker mid-job - Three-layer defense: CI graceful drain + extended client retries + poll failure tolerance - Root cause: Job `25173cb3` failed 2026-03-04 because the retry window (~14s) was too short for a worker restart (~30-90s) ## Changes ### CI Workflow (`.github/workflows/ci.yml`) - New "Drain active encoding jobs before restart" step polls `/health` for `active_jobs` - Waits up to 10 minutes for active jobs to finish before restarting the worker - Falls through gracefully if the worker is already down or drain timeout expires ### Encoding Service (`backend/services/encoding_service.py`) - **Extended retries:** MAX_RETRIES 3→7, INITIAL_BACKOFF 2s→5s, MAX_BACKOFF 10s→15s (total window ~90s) - **Poll failure tolerance:** `wait_for_completion()` now tolerates up to 5 consecutive poll failures instead of failing immediately on a single network error - Follows same pattern as flacfetch status polling (PR #446) ### Tests (`backend/tests/test_encoding_service.py`) - 8 new tests: retry config validation, poll tolerance, counter reset, error propagation - Config guard test mathematically verifies retry window exceeds 60s minimum ### Documentation - `docs/LESSONS-LEARNED.md`: New section documenting the three-layer defense pattern - `docs/TROUBLESHOOTING.md`: Added prevention note to "Job stuck at encoding" runbook ## Testing - [x] All 19 encoding service tests pass - [x] Full test suite passes (178 passed, 7 skipped) - [x] CodeRabbit CLI review: no findings ## Review - [x] Local CodeRabbit review completed - [x] Documentation updated @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
f404a25328 |
Make GCE encoding pipeline resilient to deployment interruptions (#413)
## Summary - Make `/encode` endpoint idempotent on GCE worker — return cached/in_progress instead of hard 409 reject (mirrors existing `/encode-preview` pattern) - Handle cached/in_progress/409 responses in `encoding_service.py` — `submit_encoding_job()` falls back to status check on 409, `encode_videos()` returns immediately on cached results - Detect jobs stuck in `encoding` status >50 min in health service (encoding timeout is 1 hour) **Context:** A Cloud Run deployment (PR #411) killed an instance that was polling the GCE encoding worker for job `a03ad39c`. The encoding completed on GCE but nobody received the result — the job got permanently stuck. Recovery required SSH to restart the worker because `/encode` rejected re-submission with a hard 409. ## Test plan - [x] 11 new tests for encoding_service.py (cached/in_progress passthrough, 409 fallback with 5 sub-scenarios, encode_videos short-circuit) - [x] 5 new tests for encoding-stuck detection (boundary timing, non-encoding status, naive datetime handling) - [x] All 42 new + existing tests pass - [x] `make test` passes (2055 backend tests, 170 frontend tests) - [ ] After deploy: restart encoding worker (`sudo systemctl restart encoding-worker`) to pick up new wheel - [ ] Verify idempotent behavior: submit same job_id twice to `/encode` <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |