mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +09:00
Compare commits
15
Commits
No files matched your search
@@ -181,6 +181,12 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: npx playwright test smoke.spec.ts --project=chromium --reporter=line
|
||||
|
||||
# Offline (fixture pages + stub LLM) tests for the self-healing Stripe
|
||||
# Checkout runner used by the daily production E2E.
|
||||
- name: Run self-healing Stripe runner tests
|
||||
working-directory: frontend
|
||||
run: npx playwright test --config=playwright.selfheal.config.ts --reporter=line
|
||||
|
||||
- name: Upload Playwright report
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -33,6 +33,11 @@ on:
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
self_heal_force_llm:
|
||||
description: 'Self-healing test: comma-separated Stripe step ids to force through the LLM fallback (e.g. selectCard). Learned recipes still open an auto-merge PR.'
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -46,10 +51,16 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # keyless GCP auth, only to read the Gemini key for self-healing
|
||||
|
||||
outputs:
|
||||
session_token: ${{ steps.extract_token.outputs.token }}
|
||||
result: ${{ steps.test_result.outputs.result }}
|
||||
healed: ${{ steps.self_heal.outputs.healed }}
|
||||
env:
|
||||
HAS_GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY != '' }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
@@ -74,6 +85,48 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
# ── Self-healing Stripe Checkout: LLM fallback key ───────────────────
|
||||
# The Stripe step runner (frontend/e2e/helpers/self-healing) falls back
|
||||
# to Gemini when every deterministic variant of a step fails. The key is
|
||||
# the AI Studio key (billed outside the nomadkaraoke project). Prefer a
|
||||
# GEMINI_API_KEY repo secret; otherwise read it from Secret Manager via
|
||||
# keyless auth. All of this is best-effort: without a key the test runs
|
||||
# deterministic-only, exactly as before.
|
||||
- name: Authenticate to Google Cloud (Gemini key)
|
||||
id: gcp_auth
|
||||
if: ${{ env.HAS_GEMINI_SECRET != 'true' }}
|
||||
continue-on-error: true
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Set up Cloud SDK
|
||||
if: steps.gcp_auth.outcome == 'success'
|
||||
continue-on-error: true
|
||||
uses: google-github-actions/setup-gcloud@v2
|
||||
|
||||
- name: Load Gemini key for self-healing fallback
|
||||
continue-on-error: true
|
||||
env:
|
||||
GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY }}
|
||||
GCP_AUTHED: ${{ steps.gcp_auth.outcome == 'success' }}
|
||||
run: |
|
||||
KEY="$GEMINI_SECRET"
|
||||
if [ -z "$KEY" ] && [ "$GCP_AUTHED" = "true" ]; then
|
||||
KEY=$(gcloud secrets versions access latest --secret=gemini-api-key --project=nomadkaraoke 2>/dev/null || true)
|
||||
fi
|
||||
# Drop the deployer credentials before any test code runs.
|
||||
if [ -n "${GOOGLE_GHA_CREDS_PATH:-}" ]; then rm -f "$GOOGLE_GHA_CREDS_PATH"; fi
|
||||
if [ -n "${CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE:-}" ]; then rm -f "$CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE"; fi
|
||||
if [ -n "$KEY" ]; then
|
||||
echo "::add-mask::$KEY"
|
||||
echo "GEMINI_API_KEY=$KEY" >> "$GITHUB_ENV"
|
||||
echo "Self-healing LLM fallback: enabled"
|
||||
else
|
||||
echo "::warning::Self-healing LLM fallback disabled (no Gemini key) — Stripe steps run deterministic-only"
|
||||
fi
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
@@ -93,6 +146,8 @@ jobs:
|
||||
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
|
||||
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
|
||||
E2E_STRIPE_CARDHOLDER_NAME: ${{ secrets.E2E_STRIPE_CARDHOLDER_NAME }}
|
||||
E2E_STRIPE_ZIP: ${{ secrets.E2E_STRIPE_ZIP }}
|
||||
E2E_SELF_HEAL_FORCE_LLM: ${{ inputs.self_heal_force_llm || '' }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
|
||||
@@ -117,6 +172,37 @@ jobs:
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Detect self-healed Stripe steps
|
||||
id: self_heal
|
||||
if: always()
|
||||
working-directory: frontend
|
||||
run: |
|
||||
REPORT=test-results/self-heal/self-heal-report.json
|
||||
LEARNED=test-results/self-heal/learned-variants.json
|
||||
if [ -f "$REPORT" ]; then
|
||||
{
|
||||
echo "### Stripe Checkout self-healing"
|
||||
echo '```json'
|
||||
jq '{flowVerified, llmCalls, learnedWritten, added, outcomes: [.outcomes[] | {stepId, status, via, variant, model, reason}]}' "$REPORT"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
# Only promote recipes from a run whose purchase was verified server-side.
|
||||
if [ "${{ steps.test_result.outputs.result }}" = "success" ] && [ -f "$LEARNED" ]; then
|
||||
echo "healed=true" >> "$GITHUB_OUTPUT"
|
||||
echo "::warning::Stripe Checkout changed — LLM fallback healed it; an auto-merge PR will record the new variant"
|
||||
else
|
||||
echo "healed=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Upload self-heal learned variants
|
||||
if: steps.self_heal.outputs.healed == 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: self-heal-learned-${{ github.run_number }}
|
||||
path: frontend/test-results/self-heal/
|
||||
retention-days: 30
|
||||
|
||||
- name: Extract session token
|
||||
id: extract_token
|
||||
if: steps.test_result.outputs.result == 'success'
|
||||
@@ -153,6 +239,165 @@ jobs:
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
|
||||
# =========================================================================
|
||||
# Self-heal: record LLM-discovered Stripe variants via an auto-merging PR
|
||||
# =========================================================================
|
||||
# One Stripe layout change → one LLM-healed run → one data-only PR (only
|
||||
# learned-variants.json) that auto-merges, so the next run replays the
|
||||
# recipe deterministically. No human in the loop.
|
||||
#
|
||||
# Merge gates for a bot PR (all verified live with #1117, 2026-10-03):
|
||||
# - its `pull_request` CI run is created "action_required" and, until run,
|
||||
# supersedes other CI Gate results → we approve it via the API;
|
||||
# - the `protect main` ruleset's require_extra_approval_for_unattributed_changes
|
||||
# (GitHub default true since ~Aug 2026) would demand a human review for
|
||||
# bot-authored changes → set to false on ruleset 11423976;
|
||||
# - review threads must be resolved → `@coderabbitai ignore` in the body.
|
||||
self-heal-pr:
|
||||
name: "Self-heal: auto-merge PR"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
needs: e2e-credit-purchase
|
||||
# Only learn from main — branch runs (e.g. testing self_heal_force_llm on a
|
||||
# feature branch) must not open PRs against main.
|
||||
if: always() && needs.e2e-credit-purchase.outputs.healed == 'true' && github.ref == 'refs/heads/main'
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
actions: write
|
||||
outputs:
|
||||
pr_url: ${{ steps.pr.outputs.pr_url }}
|
||||
unchanged: ${{ steps.pr.outputs.unchanged }}
|
||||
steps:
|
||||
- name: Checkout main
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
|
||||
- name: Download learned variants
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: self-heal-learned-${{ github.run_number }}
|
||||
path: /tmp/self-heal
|
||||
|
||||
- name: Open auto-merge PR
|
||||
id: pr
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TARGET=frontend/e2e/helpers/self-healing/learned-variants.json
|
||||
|
||||
# A bot-authored PR's `pull_request` CI run is created as
|
||||
# "action_required" (awaiting approval) and, until it runs, supersedes
|
||||
# any other CI Gate result for the ruleset. Approve it; succeed once a
|
||||
# pull_request run exists that is past approval.
|
||||
approve_ci() {
|
||||
local branch=$1 runs pending active
|
||||
for _ in $(seq 1 18); do
|
||||
runs=$(gh run list --workflow ci.yml --branch "$branch" --event pull_request --json databaseId,status,conclusion) || { sleep 10; continue; }
|
||||
pending=$(jq -r '.[] | select(.conclusion == "action_required" or .status == "waiting" or .status == "action_required") | .databaseId' <<<"$runs") || pending=""
|
||||
active=$(jq '[.[] | select(.conclusion != "action_required" and .status != "waiting" and .status != "action_required")] | length' <<<"$runs") || active=0
|
||||
for id in $pending; do
|
||||
if gh api -X POST "repos/${{ github.repository }}/actions/runs/$id/approve" >/dev/null; then
|
||||
echo "Approved CI run $id"
|
||||
else
|
||||
echo "::warning::Could not approve CI run $id with GITHUB_TOKEN"
|
||||
fi
|
||||
done
|
||||
if [ -z "$pending" ] && [ "$active" -gt 0 ]; then
|
||||
echo "CI is running for $branch"
|
||||
return 0
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
return 1
|
||||
}
|
||||
REPORT=/tmp/self-heal/self-heal-report.json
|
||||
|
||||
OPEN=$(gh pr list --label e2e-self-heal --state open --json url --jq '.[0].url // ""')
|
||||
if [ -n "$OPEN" ]; then
|
||||
echo "A self-heal PR is already open ($OPEN) — not opening another; making sure its CI can run"
|
||||
echo "pr_url=$OPEN" >> "$GITHUB_OUTPUT"
|
||||
OPEN_BRANCH=$(gh pr view "$OPEN" --json headRefName --jq .headRefName || true)
|
||||
if [ -z "$OPEN_BRANCH" ] || ! approve_ci "$OPEN_BRANCH"; then
|
||||
echo "ci_needs_approval=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
cp /tmp/self-heal/learned-variants.json "$TARGET"
|
||||
if git diff --quiet -- "$TARGET"; then
|
||||
echo "learned-variants.json unchanged vs main — nothing to do"
|
||||
echo "unchanged=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
STEPS=$(jq -r '[.outcomes[] | select(.status == "healed") | .stepId] | unique | join(", ")' "$REPORT")
|
||||
BRANCH="self-heal/stripe-checkout-${{ github.run_id }}"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git checkout -b "$BRANCH"
|
||||
git add "$TARGET"
|
||||
git commit -m "test(e2e): self-heal Stripe Checkout steps: $STEPS" -m "Learned by the LLM fallback in $RUN_URL (purchase verified server-side)."
|
||||
git push origin "$BRANCH"
|
||||
|
||||
gh label create e2e-self-heal --color FBCA04 --description "Auto-generated by the self-healing Stripe E2E" 2>/dev/null || true
|
||||
{
|
||||
echo "## 🩹 Stripe Checkout self-heal"
|
||||
echo
|
||||
echo "Stripe changed its hosted checkout page. In [run #${{ github.run_number }}]($RUN_URL) every deterministic variant of **$STEPS** failed; the Gemini fallback completed the step(s), and the purchase was then **verified server-side** (credit granted)."
|
||||
echo
|
||||
echo "This PR only adds the recipe(s) to \`learned-variants.json\`, so future runs replay them deterministically (no LLM). It auto-merges once CI passes."
|
||||
echo
|
||||
echo "### Learned recipes"
|
||||
echo '```json'
|
||||
jq '[.outcomes[] | select(.status == "healed") | {stepId, model, llmCalls, actions}]' "$REPORT"
|
||||
echo '```'
|
||||
echo
|
||||
echo "@coderabbitai ignore"
|
||||
echo
|
||||
echo "🤖 Generated by the E2E Daily self-healing workflow"
|
||||
} > /tmp/pr-body.md
|
||||
|
||||
PR_URL=$(gh pr create --base main --head "$BRANCH" --label e2e-self-heal \
|
||||
--title "test(e2e): self-heal Stripe Checkout ($STEPS)" --body-file /tmp/pr-body.md)
|
||||
echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
|
||||
gh pr merge "$PR_URL" --auto --squash
|
||||
|
||||
if approve_ci "$BRANCH"; then
|
||||
echo "Opened $PR_URL (auto-merge enabled, CI approved)"
|
||||
else
|
||||
# Fallback: dispatched CI (allowed from GITHUB_TOKEN) puts a CI Gate
|
||||
# check on the head SHA if no pull_request run ever appears.
|
||||
gh workflow run ci.yml --ref "$BRANCH"
|
||||
echo "ci_needs_approval=true" >> "$GITHUB_OUTPUT"
|
||||
echo "::warning::CI for $PR_URL may need a one-click approval (PR → Checks → Approve and run)"
|
||||
fi
|
||||
|
||||
- name: Discord notification (self-heal)
|
||||
# Recipe already on main (e.g. merged between checkout and now) → nothing to report.
|
||||
if: always() && steps.pr.outputs.unchanged != 'true'
|
||||
run: |
|
||||
PR="${{ steps.pr.outputs.pr_url }}"
|
||||
if [ -n "$PR" ] && [ "${{ steps.pr.outputs.ci_needs_approval }}" = "true" ]; then
|
||||
TITLE="🩹 E2E self-healed Stripe — PR needs a CI approval click"
|
||||
DESC="LLM fallback healed a Stripe Checkout change. The auto-merge PR's CI run awaits approval (open the PR → Checks → Approve and run): $PR"
|
||||
COLOR=16776960
|
||||
elif [ -n "$PR" ]; then
|
||||
TITLE="🩹 E2E self-healed a Stripe Checkout change"
|
||||
DESC="Stripe changed its checkout page; the LLM fallback got through and the purchase was verified. Auto-merge PR: $PR"
|
||||
COLOR=16776960
|
||||
else
|
||||
TITLE="⚠️ E2E self-heal PR could not be opened"
|
||||
DESC="The LLM fallback healed a Stripe step but opening the PR failed — see the run."
|
||||
COLOR=15105570
|
||||
fi
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"$TITLE\", \"description\": \"$DESC\n\n**Run:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": $COLOR}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
# =========================================================================
|
||||
# Stage 2: Happy Path (uses credit from Stage 1)
|
||||
# =========================================================================
|
||||
@@ -309,7 +554,7 @@ jobs:
|
||||
notify:
|
||||
name: "Notify"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [e2e-credit-purchase, e2e-happy-path]
|
||||
needs: [e2e-credit-purchase, e2e-happy-path, self-heal-pr]
|
||||
if: always()
|
||||
|
||||
steps:
|
||||
@@ -338,6 +583,7 @@ jobs:
|
||||
|
||||
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
|
||||
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
|
||||
Stripe self-heal: ${{ needs.e2e-credit-purchase.outputs.healed == 'true' && format('Stripe changed its checkout; LLM fallback healed it. Auto-merge PR: {0}', needs.self-heal-pr.outputs.pr_url || (needs.self-heal-pr.outputs.unchanged == 'true' && '(already on main)' || '(failed to open — see run)')) || 'not needed' }}
|
||||
|
||||
Run: #${{ github.run_number }}
|
||||
Trigger: ${{ github.event_name }}
|
||||
|
||||
@@ -73,6 +73,18 @@ RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install --upgrade pip && \
|
||||
pip install -e .
|
||||
|
||||
# Pre-build matplotlib's font cache at BUILD time. Without it, the first
|
||||
# `import matplotlib.pyplot` on every new Cloud Run instance scanned all the
|
||||
# Noto fonts above (20-40s of GIL-holding CPU) and froze the API's event loop
|
||||
# — prod logged "Matplotlib is building the font cache" in 17 of 28
|
||||
# "servers unavailable" banner episodes (2026-10-03 analysis). The cache lives
|
||||
# in MPLCONFIGDIR so it ships in the image instead of the in-memory $HOME.
|
||||
ENV MPLCONFIGDIR=/opt/mplconfig
|
||||
RUN mkdir -p /opt/mplconfig && \
|
||||
python -c "import matplotlib; matplotlib.use('Agg'); import matplotlib.font_manager as fm; print(len(fm.fontManager.ttflist), 'fonts cached')" && \
|
||||
ls /opt/mplconfig/fontlist-*.json && \
|
||||
chmod -R a+rwX /opt/mplconfig
|
||||
|
||||
# Now copy actual source code (AFTER deps installed, so code changes don't
|
||||
# invalidate the expensive pip install layer in registry cache)
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
|
||||
+85
-36
@@ -463,7 +463,7 @@ class CacheStatsResponse(BaseModel):
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/audio-searches", response_model=AudioSearchListResponse)
|
||||
async def list_audio_searches(
|
||||
def list_audio_searches(
|
||||
limit: int = 50,
|
||||
status_filter: Optional[str] = None,
|
||||
exclude_test: bool = True,
|
||||
@@ -670,7 +670,7 @@ async def clear_audio_search_cache(
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/reset-worker-state")
|
||||
async def reset_worker_state(
|
||||
def reset_worker_state(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -880,7 +880,7 @@ def _extract_files_recursive(
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/files", response_model=JobFilesResponse)
|
||||
async def get_job_files(
|
||||
def get_job_files(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -1075,7 +1075,7 @@ async def update_job(
|
||||
f"Auto-deleting outputs for job {job_id} (toggled to private by {admin_email})"
|
||||
)
|
||||
# Call the delete-outputs endpoint directly (same module)
|
||||
await delete_job_outputs(job_id, auth_data)
|
||||
await asyncio.to_thread(delete_job_outputs, job_id, auth_data)
|
||||
auto_deleted = True
|
||||
except HTTPException:
|
||||
# delete_job_outputs raises HTTPException on validation failures,
|
||||
@@ -1588,7 +1588,7 @@ ALL_WORKER_PROGRESS_KEYS = [
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/clear-workers", response_model=ClearWorkersResponse)
|
||||
async def clear_worker_state(
|
||||
def clear_worker_state(
|
||||
job_id: str,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -1676,7 +1676,7 @@ TERMINAL_STATES = {"complete", "prep_complete", "failed", "cancelled"}
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/delete-outputs", response_model=DeleteOutputsResponse)
|
||||
async def delete_job_outputs(
|
||||
def delete_job_outputs(
|
||||
job_id: str,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -1881,7 +1881,7 @@ class OrphanedOutputsCleanupRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post("/orphaned-outputs/cleanup")
|
||||
async def cleanup_orphaned_outputs(
|
||||
def cleanup_orphaned_outputs(
|
||||
req: OrphanedOutputsCleanupRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
) -> dict:
|
||||
@@ -1999,7 +1999,7 @@ async def cleanup_orphaned_outputs(
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/completion-message", response_model=CompletionMessageResponse)
|
||||
async def get_job_completion_message(
|
||||
def get_job_completion_message(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -2063,7 +2063,7 @@ async def get_job_completion_message(
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/send-completion-email", response_model=SendCompletionEmailResponse)
|
||||
async def send_job_completion_email(
|
||||
def send_job_completion_email(
|
||||
job_id: str,
|
||||
request: SendCompletionEmailRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -2141,7 +2141,7 @@ class MintLoginLinkRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post("/users/{email}/login-link")
|
||||
async def mint_user_login_link(
|
||||
def mint_user_login_link(
|
||||
email: str,
|
||||
request: MintLoginLinkRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2180,7 +2180,7 @@ class ImpersonateUserResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/users/{email}/impersonate", response_model=ImpersonateUserResponse)
|
||||
async def impersonate_user(
|
||||
def impersonate_user(
|
||||
email: str,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -2398,6 +2398,55 @@ async def regenerate_screens(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Regenerate (storage retention) Endpoint
|
||||
# =============================================================================
|
||||
|
||||
class AdminRegenerateRequest(BaseModel):
|
||||
"""Request body for POST /api/admin/jobs/{job_id}/regenerate."""
|
||||
notify_customer: bool = Field(
|
||||
False, description="Email/push the customer when the regenerate completes",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/regenerate")
|
||||
async def admin_regenerate_job(
|
||||
job_id: str,
|
||||
body: Optional[AdminRegenerateRequest] = None,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Rebuild a completed job's GCS outputs (storage retention), admin only.
|
||||
|
||||
Re-separates stems first if they were purged, then regenerates screens,
|
||||
the lyrics video, every final and the packages in GCS. Unlike
|
||||
``/rerender`` nothing is deleted or re-published (YouTube/Dropbox/GDrive
|
||||
untouched, same brand code). No rate limit.
|
||||
"""
|
||||
from backend.services.regenerate_service import RegenerateService
|
||||
from backend.services.theme_rerender_service import RerenderError
|
||||
|
||||
body = body or AdminRegenerateRequest()
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
job_manager = JobManager()
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
try:
|
||||
result = await RegenerateService(job_manager).start(
|
||||
job, requested_by=admin_email, source="admin", notify_customer=body.notify_customer,
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
return {
|
||||
"status": "processing",
|
||||
"job_id": job_id,
|
||||
"needs_stems": result["needs_stems"],
|
||||
"notify_customer": body.notify_customer,
|
||||
"message": "Regenerate started (GCS only; nothing re-published).",
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Re-render Endpoint
|
||||
# =============================================================================
|
||||
@@ -2863,7 +2912,7 @@ OVERRIDE_AUDIO_ALLOWED_STATES = {
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/override-audio-source", response_model=OverrideAudioSourceResponse)
|
||||
async def override_audio_source(
|
||||
def override_audio_source(
|
||||
job_id: str,
|
||||
request: OverrideAudioSourceRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -3168,7 +3217,7 @@ class WebhookEventItem(BaseModel):
|
||||
|
||||
|
||||
@router.get("/payments/summary", response_model=RevenueSummaryResponse)
|
||||
async def get_payment_summary(
|
||||
def get_payment_summary(
|
||||
days: int = 30,
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -3183,7 +3232,7 @@ async def get_payment_summary(
|
||||
|
||||
|
||||
@router.get("/payments/revenue-chart", response_model=List[RevenueChartPoint])
|
||||
async def get_revenue_chart(
|
||||
def get_revenue_chart(
|
||||
days: int = 30,
|
||||
group_by: str = "day",
|
||||
exclude_test: bool = True,
|
||||
@@ -3196,7 +3245,7 @@ async def get_revenue_chart(
|
||||
|
||||
|
||||
@router.get("/payments", response_model=PaymentListResponse)
|
||||
async def list_payments(
|
||||
def list_payments(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
order_type: Optional[str] = None,
|
||||
@@ -3216,7 +3265,7 @@ async def list_payments(
|
||||
|
||||
|
||||
@router.get("/payments/balance", response_model=StripeBalanceResponse)
|
||||
async def get_stripe_balance(
|
||||
def get_stripe_balance(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get current Stripe account balance."""
|
||||
@@ -3226,7 +3275,7 @@ async def get_stripe_balance(
|
||||
|
||||
|
||||
@router.get("/payments/payouts", response_model=List[PayoutItem])
|
||||
async def get_payouts(
|
||||
def get_payouts(
|
||||
limit: int = 20,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -3237,7 +3286,7 @@ async def get_payouts(
|
||||
|
||||
|
||||
@router.get("/payments/disputes", response_model=List[DisputeItem])
|
||||
async def get_disputes(
|
||||
def get_disputes(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get open and recent disputes."""
|
||||
@@ -3247,7 +3296,7 @@ async def get_disputes(
|
||||
|
||||
|
||||
@router.get("/payments/webhook-events", response_model=List[WebhookEventItem])
|
||||
async def get_webhook_events(
|
||||
def get_webhook_events(
|
||||
limit: int = 50,
|
||||
event_type: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
@@ -3260,7 +3309,7 @@ async def get_webhook_events(
|
||||
|
||||
|
||||
@router.get("/payments/by-user/{email}")
|
||||
async def get_user_payments(
|
||||
def get_user_payments(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -3271,7 +3320,7 @@ async def get_user_payments(
|
||||
|
||||
|
||||
@router.get("/users/{email}/emails")
|
||||
async def get_user_emails(
|
||||
def get_user_emails(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -3282,7 +3331,7 @@ async def get_user_emails(
|
||||
|
||||
|
||||
@router.get("/emails/{message_id}")
|
||||
async def get_email_detail(
|
||||
def get_email_detail(
|
||||
message_id: str,
|
||||
source: str = "postmark",
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -3302,7 +3351,7 @@ async def get_email_detail(
|
||||
|
||||
|
||||
@router.get("/payments/{session_id}")
|
||||
async def get_payment_detail(
|
||||
def get_payment_detail(
|
||||
session_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -3316,7 +3365,7 @@ async def get_payment_detail(
|
||||
|
||||
|
||||
@router.post("/payments/{session_id}/refund", response_model=RefundResponse)
|
||||
async def refund_payment(
|
||||
def refund_payment(
|
||||
session_id: str,
|
||||
request: RefundRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -3374,7 +3423,7 @@ async def refund_payment(
|
||||
|
||||
|
||||
@router.post("/payments/normalize-emails")
|
||||
async def normalize_payment_emails(
|
||||
def normalize_payment_emails(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""One-time backfill: lowercase all customer_email values in stripe_payments."""
|
||||
@@ -3384,7 +3433,7 @@ async def normalize_payment_emails(
|
||||
|
||||
|
||||
@router.post("/backfill/user-stats")
|
||||
async def backfill_user_stats(
|
||||
def backfill_user_stats(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""One-time backfill: recalculate total_jobs_completed and total_spent for all users."""
|
||||
@@ -3877,7 +3926,7 @@ async def get_audio_edit_review_detail(
|
||||
|
||||
|
||||
@router.get("/abuse/related/{email}")
|
||||
async def find_related_accounts(
|
||||
def find_related_accounts(
|
||||
email: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -3927,7 +3976,7 @@ async def find_related_accounts(
|
||||
|
||||
|
||||
@router.get("/abuse/correlations")
|
||||
async def find_account_correlations(
|
||||
def find_account_correlations(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -3977,7 +4026,7 @@ async def find_account_correlations(
|
||||
|
||||
|
||||
@router.get("/abuse/suspicious")
|
||||
async def find_suspicious_accounts(
|
||||
def find_suspicious_accounts(
|
||||
min_jobs: int = 2,
|
||||
max_spend: int = 0,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
@@ -4016,7 +4065,7 @@ async def find_suspicious_accounts(
|
||||
|
||||
|
||||
@router.get("/abuse/by-ip/{ip_address:path}")
|
||||
async def find_users_by_ip(
|
||||
def find_users_by_ip(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -4041,7 +4090,7 @@ async def find_users_by_ip(
|
||||
|
||||
|
||||
@router.get("/abuse/by-fingerprint/{fingerprint}")
|
||||
async def find_users_by_fingerprint(
|
||||
def find_users_by_fingerprint(
|
||||
fingerprint: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -4066,7 +4115,7 @@ async def find_users_by_fingerprint(
|
||||
|
||||
|
||||
@router.post("/abuse/backfill-ips")
|
||||
async def backfill_signup_ips(
|
||||
def backfill_signup_ips(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -4165,7 +4214,7 @@ class IpBatchRequest(BaseModel):
|
||||
|
||||
|
||||
@router.get("/abuse/ip-info/{ip_address:path}")
|
||||
async def get_ip_info(
|
||||
def get_ip_info(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -4175,7 +4224,7 @@ async def get_ip_info(
|
||||
|
||||
|
||||
@router.post("/abuse/ip-info/batch")
|
||||
async def get_ip_info_batch(
|
||||
def get_ip_info_batch(
|
||||
request: IpBatchRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -4317,7 +4366,7 @@ class CommunityRequestListResponse(BaseModel):
|
||||
|
||||
|
||||
@router.get("/community-requests", response_model=CommunityRequestListResponse)
|
||||
async def list_community_requests(
|
||||
def list_community_requests(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Full history of requests-board submissions across every status — who asked,
|
||||
@@ -4371,7 +4420,7 @@ class CommunityReviewActionResponse(BaseModel):
|
||||
|
||||
|
||||
@router.get("/community-reviews", response_model=CommunityReviewListResponse)
|
||||
async def list_community_reviews(
|
||||
def list_community_reviews(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""List requests-board picks the daily picker flagged because an existing
|
||||
|
||||
@@ -1111,7 +1111,7 @@ async def search_audio_standalone(
|
||||
|
||||
|
||||
@router.get("/audio-search/{job_id}/results")
|
||||
async def get_audio_search_results(
|
||||
def get_audio_search_results(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
@@ -1436,7 +1436,7 @@ async def provide_url_for_job(
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/attach-upload-url", response_model=AttachUploadUrlsResponse)
|
||||
async def attach_upload_url(
|
||||
def attach_upload_url(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
body: AttachUploadUrlsRequest,
|
||||
@@ -1471,7 +1471,7 @@ async def attach_upload_url(
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/attach-upload-complete", response_model=AttachResponse)
|
||||
async def attach_upload_complete(
|
||||
def attach_upload_complete(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
|
||||
@@ -91,7 +91,7 @@ class CredentialValidationResponse(BaseModel):
|
||||
# ===========================================================================
|
||||
|
||||
@router.get("/status", response_model=AllCredentialsStatusResponse)
|
||||
async def get_credentials_status():
|
||||
def get_credentials_status():
|
||||
"""
|
||||
Get the status of all OAuth credentials.
|
||||
|
||||
@@ -126,7 +126,7 @@ async def get_credentials_status():
|
||||
|
||||
|
||||
@router.get("/status/{service}", response_model=CredentialStatusResponse)
|
||||
async def get_service_credential_status(service: str, request: Request):
|
||||
def get_service_credential_status(service: str, request: Request):
|
||||
"""
|
||||
Get the status of a specific service's OAuth credentials.
|
||||
|
||||
@@ -155,7 +155,7 @@ async def get_service_credential_status(service: str, request: Request):
|
||||
|
||||
|
||||
@router.post("/validate", response_model=CredentialValidationResponse)
|
||||
async def validate_credentials(request: CredentialValidationRequest, http_request: Request):
|
||||
def validate_credentials(request: CredentialValidationRequest, http_request: Request):
|
||||
"""
|
||||
Validate that credentials are available for requested services.
|
||||
|
||||
@@ -200,7 +200,7 @@ async def validate_credentials(request: CredentialValidationRequest, http_reques
|
||||
# ===========================================================================
|
||||
|
||||
@router.post("/youtube/device", response_model=DeviceAuthStartResponse)
|
||||
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
"""
|
||||
Start YouTube device authorization flow.
|
||||
|
||||
@@ -238,7 +238,7 @@ async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] =
|
||||
|
||||
|
||||
@router.get("/youtube/device/{device_code}", response_model=DeviceAuthPollResponse)
|
||||
async def poll_youtube_device_auth(device_code: str):
|
||||
def poll_youtube_device_auth(device_code: str):
|
||||
"""
|
||||
Poll for YouTube device authorization completion.
|
||||
|
||||
@@ -263,7 +263,7 @@ async def poll_youtube_device_auth(device_code: str):
|
||||
|
||||
|
||||
@router.post("/gdrive/device", response_model=DeviceAuthStartResponse)
|
||||
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
"""
|
||||
Start Google Drive device authorization flow.
|
||||
|
||||
@@ -296,7 +296,7 @@ async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = N
|
||||
|
||||
|
||||
@router.get("/gdrive/device/{device_code}", response_model=DeviceAuthPollResponse)
|
||||
async def poll_gdrive_device_auth(device_code: str):
|
||||
def poll_gdrive_device_auth(device_code: str):
|
||||
"""
|
||||
Poll for Google Drive device authorization completion.
|
||||
"""
|
||||
@@ -316,7 +316,7 @@ async def poll_gdrive_device_auth(device_code: str):
|
||||
# ===========================================================================
|
||||
|
||||
@router.post("/test-alert")
|
||||
async def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
|
||||
def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
|
||||
"""
|
||||
Test the credential alert mechanism.
|
||||
|
||||
|
||||
@@ -445,7 +445,7 @@ def _bucket(status: str, pending_search: bool) -> str:
|
||||
|
||||
|
||||
@router.get("/{batch_id}", response_model=BulkBatchResponse)
|
||||
async def bulk_batch(
|
||||
def bulk_batch(
|
||||
request: Request,
|
||||
batch_id: str,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
|
||||
@@ -10,6 +10,17 @@ metadata to review frequency and context later. Two sinks per event:
|
||||
2. A Firestore doc in ``client_events`` — survives log retention, cheap to
|
||||
aggregate for "how often are users seeing this?" reviews.
|
||||
|
||||
Identity (2026-10-03): the client sends its session token (if any) and the
|
||||
server resolves ``user_email`` / ``is_admin`` / ``is_internal`` / ``is_test``
|
||||
from it — a client-supplied email is never trusted (and is ignored). Each
|
||||
event also carries the FingerprintJS ``device_fingerprint`` (same visitorId the
|
||||
magic-link abuse checks use), a per-tab ``tab_id`` and an ``episode_id`` that
|
||||
groups one degradation episode (first banner → ``banner_recovered``).
|
||||
|
||||
The watchdog in ``backend/services/loop_watchdog.py`` writes server-side
|
||||
``server_loop_stall`` docs into the same collection; clients cannot submit
|
||||
that type.
|
||||
|
||||
Unauthenticated (review-token users must be able to report) and rate-limited
|
||||
per IP, mirroring /api/client-errors. The limiter is process-local, so the
|
||||
effective ceiling is 120/min/IP × live instances — acceptable for this threat
|
||||
@@ -23,10 +34,12 @@ import logging
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Literal, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from backend.utils.test_data import is_internal_email, is_test_email
|
||||
from backend.services.error_monitor.frontend_ingestion import (
|
||||
RateLimiter,
|
||||
is_bot_user_agent,
|
||||
@@ -48,6 +61,7 @@ EventType = Literal[
|
||||
"banner_reconnecting",
|
||||
"banner_unavailable",
|
||||
"banner_waking",
|
||||
"banner_recovered",
|
||||
"lyrics_load_failed",
|
||||
"waveform_slow",
|
||||
"waveform_failed",
|
||||
@@ -67,7 +81,12 @@ class ClientEventPayload(BaseModel):
|
||||
type: EventType
|
||||
url: str = Field("", max_length=2048)
|
||||
job_id: Optional[str] = Field(None, max_length=64)
|
||||
# Legacy field from pre-2026-10-03 frontends — accepted but IGNORED (the
|
||||
# server resolves identity from the bearer token instead).
|
||||
user_email: Optional[str] = Field(None, max_length=320)
|
||||
device_fingerprint: Optional[str] = Field(None, max_length=128)
|
||||
tab_id: Optional[str] = Field(None, max_length=64)
|
||||
episode_id: Optional[str] = Field(None, max_length=64)
|
||||
locale: str = Field("en", max_length=10)
|
||||
release: str = Field("", max_length=64)
|
||||
# Small free-form context (stall age, http status, elapsed ms, probe state…).
|
||||
@@ -94,6 +113,51 @@ def _capped_detail(detail: Optional[dict]) -> dict[str, Any]:
|
||||
return out
|
||||
|
||||
|
||||
_TENANT_HOST_EXCLUDE = {"gen", "www", "api", "app", "decide", "localhost"}
|
||||
|
||||
|
||||
def _tenant_from_url(url: str) -> Optional[str]:
|
||||
"""``randy-vild.nomadkaraoke.com/...`` → ``randy-vild``; consumer hosts → None."""
|
||||
try:
|
||||
host = (urlparse(url).hostname or "").lower()
|
||||
except ValueError:
|
||||
return None
|
||||
if not host.endswith(".nomadkaraoke.com"):
|
||||
return None
|
||||
sub = host[: -len(".nomadkaraoke.com")]
|
||||
if not sub or "." in sub or sub in _TENANT_HOST_EXCLUDE:
|
||||
return None
|
||||
return sub
|
||||
|
||||
|
||||
def _resolve_identity(request: Request) -> dict[str, Any]:
|
||||
"""Resolve the caller from its bearer token. Never raises; anonymous on failure."""
|
||||
identity: dict[str, Any] = {
|
||||
"user_email": None, "is_admin": False, "is_internal": False, "is_test": False,
|
||||
}
|
||||
auth = request.headers.get("authorization", "")
|
||||
if not auth.lower().startswith("bearer "):
|
||||
return identity
|
||||
token = auth[7:].strip()
|
||||
if not token:
|
||||
return identity
|
||||
try:
|
||||
from backend.services.auth_service import get_auth_service
|
||||
|
||||
result = get_auth_service().validate_token_full(token)
|
||||
except Exception:
|
||||
logger.debug("client_event token resolution failed", exc_info=True)
|
||||
return identity
|
||||
if not result.is_valid:
|
||||
return identity
|
||||
email = result.user_email
|
||||
identity["user_email"] = email
|
||||
identity["is_admin"] = bool(result.is_admin)
|
||||
identity["is_internal"] = bool(email and is_internal_email(email))
|
||||
identity["is_test"] = bool(email and is_test_email(email))
|
||||
return identity
|
||||
|
||||
|
||||
@router.post("", status_code=202)
|
||||
def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
@@ -104,11 +168,20 @@ def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
|
||||
if is_bot_user_agent(user_agent):
|
||||
return {"status": "ignored"}
|
||||
|
||||
# Sync handler → runs in FastAPI's threadpool, so the token lookup
|
||||
# (Firestore) never touches the event loop.
|
||||
identity = _resolve_identity(request)
|
||||
|
||||
event = {
|
||||
"type": payload.type,
|
||||
"source": "client",
|
||||
"url": sanitize_url(payload.url),
|
||||
"tenant": _tenant_from_url(payload.url),
|
||||
"job_id": payload.job_id,
|
||||
"user_email": payload.user_email,
|
||||
**identity,
|
||||
"device_fingerprint": payload.device_fingerprint,
|
||||
"tab_id": payload.tab_id,
|
||||
"episode_id": payload.episode_id,
|
||||
"locale": payload.locale,
|
||||
"release": payload.release,
|
||||
"user_agent": user_agent,
|
||||
@@ -118,10 +191,13 @@ def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
|
||||
|
||||
# Sink 1: structured log line — correlate with backend symptoms in Logging.
|
||||
logger.info(
|
||||
"client_event type=%s job_id=%s user=%s url=%s release=%s detail=%s",
|
||||
"client_event type=%s job_id=%s user=%s admin=%s fp=%s episode=%s url=%s release=%s detail=%s",
|
||||
event["type"],
|
||||
event["job_id"],
|
||||
event["user_email"],
|
||||
event["is_admin"],
|
||||
event["device_fingerprint"],
|
||||
event["episode_id"],
|
||||
event["url"],
|
||||
event["release"],
|
||||
event["detail"],
|
||||
|
||||
@@ -1652,6 +1652,20 @@ async def mark_uploads_complete(
|
||||
logger.warning(f"Duration validation failed with error: {e}. Proceeding without validation.")
|
||||
# Don't block the job if we can't validate - the video worker will fail more gracefully
|
||||
|
||||
# uploads/ expires after 7 days: keep the user's instrumental at the job
|
||||
# root (where the video pipeline stages it anyway) so later re-renders,
|
||||
# regenerates and edits still have it.
|
||||
if (update_data.get('existing_instrumental_gcs_path') or '').startswith('uploads/'):
|
||||
from backend.utils.existing_instrumental import persistent_instrumental_path
|
||||
source = update_data['existing_instrumental_gcs_path']
|
||||
dest = persistent_instrumental_path(job_id, source)
|
||||
try:
|
||||
storage_service.copy_blob(source, dest)
|
||||
update_data['existing_instrumental_gcs_path'] = dest
|
||||
logger.info(f"Job {job_id}: persisted existing instrumental {source} -> {dest}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: couldn't persist existing instrumental {source}: {e}")
|
||||
|
||||
# Add style assets to update if any
|
||||
if style_assets:
|
||||
update_data['style_assets'] = style_assets
|
||||
@@ -1885,7 +1899,7 @@ class ValidateUrlResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/jobs/validate-url", response_model=ValidateUrlResponse)
|
||||
async def validate_job_url(
|
||||
def validate_job_url(
|
||||
request: Request,
|
||||
body: ValidateUrlRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
@@ -2239,7 +2253,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
|
||||
|
||||
|
||||
@router.post("/jobs/create-finalise-only")
|
||||
async def create_finalise_only_job(
|
||||
def create_finalise_only_job(
|
||||
request: Request,
|
||||
body: CreateFinaliseOnlyJobRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -2476,7 +2490,7 @@ async def create_finalise_only_job(
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/finalise-uploads-complete")
|
||||
async def mark_finalise_uploads_complete(
|
||||
def mark_finalise_uploads_complete(
|
||||
job_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: UploadsCompleteRequest,
|
||||
@@ -2702,7 +2716,7 @@ async def mark_finalise_uploads_complete(
|
||||
# ============================================================================
|
||||
|
||||
@router.post("/jobs/{job_id}/style-upload-urls")
|
||||
async def get_style_upload_urls(
|
||||
def get_style_upload_urls(
|
||||
job_id: str,
|
||||
body: StyleUploadUrlsRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
@@ -2782,7 +2796,7 @@ async def get_style_upload_urls(
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/style-uploads-complete")
|
||||
async def complete_style_uploads(
|
||||
def complete_style_uploads(
|
||||
job_id: str,
|
||||
body: StyleUploadsCompleteRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Health check routes.
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import logging
|
||||
import subprocess
|
||||
@@ -217,7 +218,7 @@ async def check_flacfetch_service_status() -> Dict[str, Any]:
|
||||
|
||||
async def check_encoding_worker_status() -> Dict[str, Any]:
|
||||
"""Check if GCE encoding worker is available and healthy."""
|
||||
encoding_service = get_encoding_service()
|
||||
encoding_service = await asyncio.to_thread(get_encoding_service)
|
||||
|
||||
if not encoding_service.is_configured:
|
||||
return {
|
||||
@@ -335,7 +336,7 @@ def check_audio_separator_status() -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
Return audio separation status (installed audio-separator package version).
|
||||
|
||||
@@ -546,7 +547,7 @@ async def detailed_health_check() -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/health/preload-status")
|
||||
async def preload_status() -> Dict[str, Any]:
|
||||
def preload_status() -> Dict[str, Any]:
|
||||
"""
|
||||
Check status of preloaded resources for performance optimization.
|
||||
|
||||
@@ -608,7 +609,7 @@ async def preload_status() -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/health/job-consistency")
|
||||
async def job_consistency_check(
|
||||
def job_consistency_check(
|
||||
status: Optional[str] = None,
|
||||
limit: int = 50
|
||||
) -> Dict[str, Any]:
|
||||
|
||||
+153
-12
@@ -141,7 +141,7 @@ async def sync_disposable_domains_endpoint(
|
||||
|
||||
|
||||
@router.post("/workers/audio", response_model=WorkerResponse)
|
||||
async def trigger_audio_worker(
|
||||
def trigger_audio_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -225,7 +225,7 @@ async def analyze_vocal_gaps_endpoint(
|
||||
|
||||
|
||||
@router.post("/workers/lyrics", response_model=WorkerResponse)
|
||||
async def trigger_lyrics_worker(
|
||||
def trigger_lyrics_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -338,19 +338,41 @@ async def trigger_screens_worker(
|
||||
add_span_event("worker_skipped", {"reason": skip_response.status})
|
||||
return skip_response
|
||||
|
||||
# Add task to background tasks
|
||||
background_tasks.add_task(generate_screens, job_id)
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
if not get_settings().enable_cloud_tasks:
|
||||
# Direct-HTTP mode (local dev): the caller uses a 30s timeout, so keep
|
||||
# the fire-and-forget background task there.
|
||||
background_tasks.add_task(generate_screens, job_id)
|
||||
add_span_event("worker_started")
|
||||
return WorkerResponse(
|
||||
status="started",
|
||||
job_id=job_id,
|
||||
message="Screens generation worker started"
|
||||
)
|
||||
|
||||
# Cloud Tasks mode (prod): run the worker INLINE and respond when it's done.
|
||||
# As a post-response BackgroundTask it ran on throttled CPU
|
||||
# (--cpu-throttling only allocates CPU while a request is open) and
|
||||
# its sync work blocked the event loop for every other request; inline,
|
||||
# the open request keeps CPU allocated and the heavy steps run in worker
|
||||
# threads. generate_screens handles its own failures (marks the job
|
||||
# failed), so always 200 — a non-2xx would make Cloud Tasks re-run it.
|
||||
add_span_event("worker_started")
|
||||
try:
|
||||
ok = await generate_screens(job_id)
|
||||
except Exception as e: # noqa: BLE001 — never trigger a Cloud Tasks retry storm
|
||||
logger.exception(f"[job:{job_id}] screens worker raised: {e}")
|
||||
ok = False
|
||||
return WorkerResponse(
|
||||
status="started",
|
||||
status="completed" if ok else "failed",
|
||||
job_id=job_id,
|
||||
message="Screens generation worker started"
|
||||
message="Screens generation finished" if ok else "Screens generation failed",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workers/video", response_model=WorkerResponse)
|
||||
async def trigger_video_worker(
|
||||
def trigger_video_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -391,7 +413,7 @@ async def trigger_video_worker(
|
||||
|
||||
|
||||
@router.post("/workers/render-video", response_model=WorkerResponse)
|
||||
async def trigger_render_video_worker(
|
||||
def trigger_render_video_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -563,7 +585,7 @@ async def check_idle_reminder(
|
||||
|
||||
|
||||
@router.post("/youtube-queue/process")
|
||||
async def process_youtube_upload_queue(
|
||||
def process_youtube_upload_queue(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
@@ -603,7 +625,7 @@ async def process_youtube_upload_queue(
|
||||
|
||||
|
||||
@router.post("/process-stale-reviews")
|
||||
async def process_stale_reviews_endpoint(
|
||||
def process_stale_reviews_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
@@ -649,7 +671,7 @@ async def process_stale_reviews_endpoint(
|
||||
|
||||
|
||||
@router.post("/youtube-backfill/run")
|
||||
async def youtube_backfill_run_endpoint(
|
||||
def youtube_backfill_run_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
max_updates: Optional[int] = None,
|
||||
@@ -685,6 +707,75 @@ async def youtube_backfill_run_endpoint(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/storage-retention/run")
|
||||
async def storage_retention_run_endpoint(
|
||||
dry_run: Optional[bool] = None,
|
||||
job_ids: Optional[str] = None,
|
||||
min_age_days: Optional[int] = None,
|
||||
max_jobs: Optional[int] = None,
|
||||
include_orphans: bool = False,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Purge regenerable files of old completed jobs (storage retention).
|
||||
|
||||
Called daily by Cloud Scheduler. DRY-RUN unless STORAGE_RETENTION_DRY_RUN is
|
||||
false: it then only writes a report to GCS (path returned). See
|
||||
backend/services/storage_retention.py for the policy.
|
||||
|
||||
Manual/testing params:
|
||||
- ``job_ids=a,b`` scopes the pass to those jobs and runs synchronously
|
||||
(returns the full report). Only a scoped pass may override ``dry_run=false``
|
||||
or ``min_age_days`` — a global real purge only happens via the setting.
|
||||
- ``max_jobs`` caps the jobs planned/purged; ``include_orphans`` adds a
|
||||
report section on jobs/ folders with no Firestore doc (report only).
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from backend.config import get_settings
|
||||
from backend.services.storage_retention import StorageRetentionService
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.storage_retention_enabled:
|
||||
return {"status": "disabled", "message": "STORAGE_RETENTION_ENABLED is false"}
|
||||
|
||||
scoped = [j.strip() for j in (job_ids or "").split(",") if j.strip()]
|
||||
if not scoped:
|
||||
if dry_run is False and settings.storage_retention_dry_run:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="A global real purge needs STORAGE_RETENTION_DRY_RUN=false; pass job_ids to scope a real run.",
|
||||
)
|
||||
if min_age_days is not None:
|
||||
raise HTTPException(status_code=400, detail="min_age_days can only be overridden with job_ids")
|
||||
effective_dry_run = settings.storage_retention_dry_run if dry_run is None else dry_run
|
||||
|
||||
if scoped:
|
||||
report = await asyncio.to_thread(
|
||||
StorageRetentionService().run,
|
||||
dry_run=effective_dry_run, job_ids=scoped, min_age_days=min_age_days, max_jobs=max_jobs,
|
||||
)
|
||||
return {"status": "complete", "report": report}
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
report_path = StorageRetentionService.default_report_path(now, effective_dry_run)
|
||||
|
||||
# A full pass takes minutes: run it as the storage-retention-job Cloud Run
|
||||
# Job. (The API service throttles CPU outside requests, which starves a
|
||||
# BackgroundTask, and Cloudflare cuts requests at 100s.)
|
||||
from backend.services.worker_service import get_worker_service
|
||||
started = await get_worker_service().trigger_storage_retention_job(
|
||||
dry_run=effective_dry_run, report_path=report_path,
|
||||
max_jobs=max_jobs, include_orphans=include_orphans,
|
||||
)
|
||||
if not started:
|
||||
raise HTTPException(status_code=503, detail="Couldn't start the storage-retention job")
|
||||
return {
|
||||
"status": "started",
|
||||
"dry_run": effective_dry_run,
|
||||
"report_path": f"gs://{settings.gcs_bucket_name}/{report_path}",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/community-daily-pick")
|
||||
async def community_daily_pick_endpoint(
|
||||
http_request: Request,
|
||||
@@ -1143,6 +1234,54 @@ async def recover_stuck_jobs(
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] screens re-trigger failed: {e}")
|
||||
|
||||
# --- Storage-retention stems restore whose audio job died silently ---
|
||||
# (hard-killed GPU task: no except block ran, the job sits at
|
||||
# lyrics_complete with stems_restore=running forever). Fail it so the
|
||||
# customer/admin gets a Retry button; the retry re-runs the restore.
|
||||
stems_restore_failed = []
|
||||
from backend.services.stems_restore import restore_stalled
|
||||
lc_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.LYRICS_COMPLETE.value)
|
||||
).limit(SCREENS_RECOVERY_SCAN_LIMIT).stream()
|
||||
regen_screens_retriggered = []
|
||||
for doc in lc_query:
|
||||
data = doc.to_dict() or {}
|
||||
sd = data.get("state_data") or {}
|
||||
job_id = data.get("job_id", doc.id)
|
||||
# A re-render / regenerate / visibility flow parks the job at
|
||||
# lyrics_complete only until its screens dispatch starts (which moves it
|
||||
# to generating_screens within seconds). Still here after 10 min with no
|
||||
# stems restore running = the dispatch was lost (or skipped by a stale
|
||||
# screens_progress mark): clear the mark and re-trigger.
|
||||
if sd.get("regen_restore_status") and not sd.get("stems_restore"):
|
||||
if len(regen_screens_retriggered) >= SCREENS_RETRIGGERS_PER_TICK:
|
||||
continue
|
||||
job = job_manager.get_job(job_id)
|
||||
age = _job_updated_age_seconds(job) if job else None
|
||||
if job and age is not None and age > PREP_SCREENS_STALL_SECONDS:
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD as _DEL
|
||||
logger.warning(f"[job:{job_id}] Re-render parked at lyrics_complete >10 min — re-triggering screens")
|
||||
job_manager.update_job(job_id, {"state_data.screens_progress": _DEL})
|
||||
try:
|
||||
if await worker_service.trigger_screens_worker(job_id):
|
||||
regen_screens_retriggered.append(job_id)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] re-render screens re-trigger failed: {e}")
|
||||
continue
|
||||
if not sd.get("stems_restore"):
|
||||
continue
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job or not restore_stalled(job):
|
||||
continue
|
||||
logger.warning(f"[job:{job_id}] Stems restore stalled >60 min — failing for retry")
|
||||
job_manager.update_job(job_id, {"state_data.stems_restore.status": "failed"})
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id,
|
||||
error_message="Restoring this track's audio stems timed out. Retry the job to try again.",
|
||||
error_details={"stage": "stems_restore", "reason": "stalled"},
|
||||
)
|
||||
stems_restore_failed.append(job_id)
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
@@ -1171,6 +1310,8 @@ async def recover_stuck_jobs(
|
||||
"render_retriggered_count": len(render_retriggered),
|
||||
"screens_retriggered_jobs": screens_retriggered,
|
||||
"screens_retriggered_count": len(screens_retriggered),
|
||||
"stems_restore_failed_jobs": stems_restore_failed,
|
||||
"regen_screens_retriggered_jobs": regen_screens_retriggered,
|
||||
}
|
||||
|
||||
|
||||
|
||||
+198
-26
@@ -36,6 +36,7 @@ from backend.services.tempo_label import apply_tempo_to_title
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.services.theme_rerender_service import RerenderError
|
||||
from backend.config import get_settings
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
@@ -76,7 +77,7 @@ async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
|
||||
|
||||
@router.post("", response_model=JobResponse)
|
||||
async def create_job(
|
||||
def create_job(
|
||||
request: URLSubmissionRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -210,7 +211,7 @@ async def create_job(
|
||||
|
||||
|
||||
@router.get("/{job_id}", response_model=Job)
|
||||
async def get_job(
|
||||
def get_job(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -275,7 +276,7 @@ class EditTrackResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/{job_id}/edit", response_model=EditTrackResponse)
|
||||
async def edit_completed_track(
|
||||
def edit_completed_track(
|
||||
job_id: str,
|
||||
request: EditTrackRequest,
|
||||
http_request: Request,
|
||||
@@ -311,6 +312,11 @@ async def edit_completed_track(
|
||||
detail=t(locale, "jobs.notCompleted", status=job.status)
|
||||
)
|
||||
|
||||
# Storage retention is deleting this job's files right now (seconds).
|
||||
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
|
||||
if purge_in_progress(job):
|
||||
raise HTTPException(status_code=409, detail=PURGE_IN_PROGRESS_MESSAGE)
|
||||
|
||||
# Prevent editing if outputs already deleted (edit already in progress)
|
||||
if job.outputs_deleted_at:
|
||||
raise HTTPException(
|
||||
@@ -471,7 +477,11 @@ async def edit_completed_track(
|
||||
job_ref.update(update_payload)
|
||||
|
||||
# --- Phase 4: Transition state ---
|
||||
if metadata_updated:
|
||||
# Storage retention archived this track's stems: review needs them, so go
|
||||
# through the screens worker, which re-separates them before review opens.
|
||||
from backend.services.regenerate_service import stems_need_restore
|
||||
stems_restore_needed = stems_need_restore(job)
|
||||
if metadata_updated or stems_restore_needed:
|
||||
# Metadata changed → screens need regeneration.
|
||||
# Transition to LYRICS_COMPLETE so screens worker can run
|
||||
# (LYRICS_COMPLETE → GENERATING_SCREENS is a valid transition;
|
||||
@@ -480,7 +490,10 @@ async def edit_completed_track(
|
||||
job_id,
|
||||
JobStatus.LYRICS_COMPLETE,
|
||||
progress=55,
|
||||
message="Regenerating screens with updated metadata",
|
||||
message=(
|
||||
"Regenerating screens with updated metadata" if metadata_updated
|
||||
else "Restoring audio stems before review"
|
||||
),
|
||||
)
|
||||
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
|
||||
else:
|
||||
@@ -536,6 +549,9 @@ _SUMMARY_STATE_DATA_KEYS = {
|
||||
'batch_id',
|
||||
'bulk_auto_selected',
|
||||
'awaiting_upload',
|
||||
'regenerate',
|
||||
'stems_restore',
|
||||
'instrumental_selection',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
|
||||
@@ -612,7 +628,7 @@ def _search_filter_jobs(jobs: List[Dict[str, Any]], search: str) -> List[Dict[st
|
||||
|
||||
|
||||
@router.get("", response_model=None)
|
||||
async def list_jobs(
|
||||
def list_jobs(
|
||||
request: Request,
|
||||
status: Optional[JobStatus] = None,
|
||||
environment: Optional[str] = None,
|
||||
@@ -762,7 +778,7 @@ async def list_jobs(
|
||||
|
||||
|
||||
@router.delete("/{job_id}")
|
||||
async def delete_job(
|
||||
def delete_job(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
delete_files: bool = True,
|
||||
@@ -834,7 +850,7 @@ async def delete_job(
|
||||
|
||||
|
||||
@router.delete("")
|
||||
async def bulk_delete_jobs(
|
||||
def bulk_delete_jobs(
|
||||
request: Request,
|
||||
environment: Optional[str] = None,
|
||||
client_id: Optional[str] = None,
|
||||
@@ -946,7 +962,7 @@ async def bulk_delete_jobs(
|
||||
# ============================================================================
|
||||
|
||||
@router.get("/{job_id}/review-data")
|
||||
async def get_review_data(
|
||||
def get_review_data(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -1011,7 +1027,7 @@ async def get_review_data(
|
||||
|
||||
|
||||
@router.post("/{job_id}/start-review")
|
||||
async def start_review(
|
||||
def start_review(
|
||||
job_id: str,
|
||||
request: StartReviewRequest,
|
||||
http_request: Request,
|
||||
@@ -1049,7 +1065,7 @@ async def start_review(
|
||||
|
||||
|
||||
@router.post("/{job_id}/corrections")
|
||||
async def submit_corrections(
|
||||
def submit_corrections(
|
||||
job_id: str,
|
||||
submission: CorrectionsSubmission,
|
||||
http_request: Request,
|
||||
@@ -1151,7 +1167,7 @@ async def submit_corrections(
|
||||
|
||||
|
||||
@router.post("/{job_id}/edit-log")
|
||||
async def submit_edit_log(
|
||||
def submit_edit_log(
|
||||
job_id: str,
|
||||
edit_log: Dict[str, Any],
|
||||
request: Request,
|
||||
@@ -1561,7 +1577,7 @@ async def _get_audio_duration_ffprobe_signed(job_id: str, job, storage: StorageS
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete-review")
|
||||
async def complete_review(
|
||||
def complete_review(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -1655,7 +1671,7 @@ async def complete_review(
|
||||
|
||||
|
||||
@router.post("/{job_id}/select-instrumental")
|
||||
async def select_instrumental(
|
||||
def select_instrumental(
|
||||
job_id: str,
|
||||
selection: InstrumentalSelection,
|
||||
request: Request,
|
||||
@@ -1725,7 +1741,7 @@ async def select_instrumental(
|
||||
|
||||
|
||||
@router.get("/{job_id}/download-urls")
|
||||
async def get_download_urls(
|
||||
def get_download_urls(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -1784,6 +1800,31 @@ DOWNLOAD_FILENAME_SUFFIXES = {
|
||||
}
|
||||
|
||||
|
||||
def _archived_output(job, category: str, file_key: str) -> bool:
|
||||
"""True if storage retention purged this download (recorded in the job's manifest)."""
|
||||
if not (getattr(job, 'renders_purged_at', None) or getattr(job, 'stems_purged_at', None)):
|
||||
return False
|
||||
manifest = getattr(job, 'storage_purge', None) or {}
|
||||
for entry in manifest.get('files') or []:
|
||||
path = (entry or {}).get('path') or ''
|
||||
rel = path.split('/', 2)[-1] if path.startswith('jobs/') else path
|
||||
if rel.startswith(f"{category}/{file_key}.") or rel == f"{category}/{file_key}":
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _archived_error(job, locale: str) -> HTTPException:
|
||||
"""410 Gone with a machine-readable code so clients can offer/trigger a regenerate."""
|
||||
return HTTPException(
|
||||
status_code=410,
|
||||
detail={
|
||||
"code": "output_archived",
|
||||
"message": t(locale, "jobs.fileNoLongerAvailable"),
|
||||
"regenerate_url": f"/api/jobs/{job.job_id}/regenerate",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _cleanup_temp_file(path: Optional[str]) -> None:
|
||||
"""Best-effort removal of a temp file created for a download that failed
|
||||
before streaming started (so it never reaches the iterator's cleanup)."""
|
||||
@@ -1796,7 +1837,7 @@ def _cleanup_temp_file(path: Optional[str]) -> None:
|
||||
|
||||
|
||||
@router.get("/{job_id}/download/{category}/{file_key}")
|
||||
async def download_file(
|
||||
def download_file(
|
||||
job_id: str,
|
||||
category: str,
|
||||
file_key: str,
|
||||
@@ -1823,16 +1864,21 @@ async def download_file(
|
||||
|
||||
file_urls = job.file_urls or {}
|
||||
category_files = file_urls.get(category)
|
||||
|
||||
if not category_files:
|
||||
raise HTTPException(status_code=404, detail=f"Category '{category}' not found")
|
||||
|
||||
|
||||
if isinstance(category_files, dict):
|
||||
gcs_path = category_files.get(file_key)
|
||||
else:
|
||||
elif category_files:
|
||||
gcs_path = category_files if file_key == category else None
|
||||
|
||||
else:
|
||||
gcs_path = None
|
||||
|
||||
if not gcs_path:
|
||||
# Archived by storage retention: tell clients (UI, kjbox) it can be
|
||||
# regenerated rather than a plain 404.
|
||||
if _archived_output(job, category, file_key):
|
||||
raise _archived_error(job, locale)
|
||||
if not category_files:
|
||||
raise HTTPException(status_code=404, detail=f"Category '{category}' not found")
|
||||
raise HTTPException(status_code=404, detail=f"File '{file_key}' not found in '{category}'")
|
||||
|
||||
# Determine content type based on file extension
|
||||
@@ -1915,6 +1961,8 @@ async def download_file(
|
||||
# doesn't trip the error-monitor.
|
||||
_cleanup_temp_file(tmp_path)
|
||||
logger.warning(f"Download requested for missing object {gcs_path}")
|
||||
if getattr(job, 'renders_purged_at', None) or getattr(job, 'stems_purged_at', None):
|
||||
raise _archived_error(job, locale)
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.fileNoLongerAvailable"))
|
||||
except Exception as e:
|
||||
_cleanup_temp_file(tmp_path)
|
||||
@@ -1923,7 +1971,7 @@ async def download_file(
|
||||
|
||||
|
||||
@router.post("/{job_id}/cancel")
|
||||
async def cancel_job(
|
||||
def cancel_job(
|
||||
job_id: str,
|
||||
request: CancelJobRequest,
|
||||
http_request: Request,
|
||||
@@ -2075,6 +2123,53 @@ async def retry_job(
|
||||
"retry_stage": "admin_rerender",
|
||||
}
|
||||
|
||||
# A failed storage-retention regenerate: re-run it (re-claims the job and
|
||||
# restores purged stems first) until its screens exist; after that the
|
||||
# branches below resume it (the marker keeps the run GCS-only).
|
||||
from backend.services.regenerate_service import active_regenerate, stems_need_restore, RegenerateService
|
||||
from backend.services.theme_rerender_service import RerenderError
|
||||
regenerate = active_regenerate(job)
|
||||
if (regenerate and original_status in (JobStatus.FAILED, JobStatus.CANCELLED)
|
||||
and (not _has_title_screen(file_urls) or stems_need_restore(job))):
|
||||
try:
|
||||
await RegenerateService(job_manager).start(
|
||||
job,
|
||||
requested_by=auth_result.user_email or "unknown",
|
||||
source=regenerate.get('source') or 'retry',
|
||||
notify_customer=bool(regenerate.get('notify_customer', True)),
|
||||
after=regenerate.get('after'),
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "lyrics_complete",
|
||||
"message": "Job retry: re-running the regenerate",
|
||||
"retry_stage": "regenerate",
|
||||
}
|
||||
|
||||
# Stems archived by storage retention (e.g. an Edit whose stems restore
|
||||
# failed): go back through the screens worker, which restores them first.
|
||||
if stems_need_restore(job) and file_urls.get('lyrics', {}).get('corrections'):
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD as _DEL
|
||||
# A manual retry gets a fresh set of automatic restore attempts.
|
||||
job_manager.update_job(job_id, {'error_message': None, 'error_details': None,
|
||||
'state_data.stems_restore': _DEL})
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.LYRICS_COMPLETE,
|
||||
progress=45,
|
||||
message="Retrying: restoring audio stems",
|
||||
):
|
||||
raise HTTPException(status_code=500, detail="Failed to transition job status for retry")
|
||||
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "lyrics_complete",
|
||||
"message": "Job retry started: restoring audio stems",
|
||||
"retry_stage": "stems_restore",
|
||||
}
|
||||
|
||||
# If we have a video with vocals and instrumental selection, retry video generation
|
||||
if (file_urls.get('videos', {}).get('with_vocals') and
|
||||
state_data.get('instrumental_selection')):
|
||||
@@ -2323,7 +2418,7 @@ async def retry_job(
|
||||
|
||||
|
||||
@router.post("/{job_id}/choose-different-audio")
|
||||
async def choose_different_audio(
|
||||
def choose_different_audio(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -2370,7 +2465,7 @@ async def choose_different_audio(
|
||||
|
||||
|
||||
@router.get("/{job_id}/logs")
|
||||
async def get_worker_logs(
|
||||
def get_worker_logs(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
since_index: int = 0,
|
||||
@@ -2598,7 +2693,7 @@ def _run_distribution_cleanup(job_id: str, job) -> dict:
|
||||
|
||||
|
||||
@router.post("/{job_id}/cleanup-distribution")
|
||||
async def cleanup_distribution(
|
||||
def cleanup_distribution(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
delete_job: bool = True,
|
||||
@@ -2953,11 +3048,88 @@ async def change_visibility(
|
||||
reprocessing_required=result["reprocessing_required"],
|
||||
)
|
||||
|
||||
except RerenderError as e:
|
||||
# Old track whose finals were archived and can't be regenerated right now.
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Error changing visibility for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Regenerate (storage retention) Endpoint
|
||||
# =============================================================================
|
||||
|
||||
@router.post("/{job_id}/regenerate")
|
||||
async def regenerate_job_outputs(
|
||||
job_id: str,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Regenerate a finished track's video files after storage retention archived them.
|
||||
|
||||
Old tracks keep their 720p video and CDG/TXT packages; the other formats
|
||||
(4K, lossless, with-vocals, ...) and, for some, the separated audio stems
|
||||
are archived after 30 days. This rebuilds them in storage — re-running audio
|
||||
separation first if needed — from the track's existing reviewed lyrics,
|
||||
instrumental choice and style. Nothing is re-published (YouTube, Dropbox,
|
||||
Google Drive stay as they are). The owner is emailed when it's ready.
|
||||
Rate-limited per track and per user (admins exempt).
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job_manager = JobManager()
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
from backend.services.regenerate_service import (
|
||||
RegenerateService,
|
||||
check_and_record_rate_limit,
|
||||
renders_missing,
|
||||
validate_regenerate,
|
||||
)
|
||||
|
||||
reason = validate_regenerate(job)
|
||||
if not reason and not auth_result.is_admin and not renders_missing(job):
|
||||
reason = "This track's video files are all available — there's nothing to regenerate."
|
||||
if reason:
|
||||
conflict = any(marker in reason for marker in ("already", "right now", "in progress"))
|
||||
raise HTTPException(status_code=409 if conflict else 400, detail=reason)
|
||||
|
||||
requested_by = auth_result.user_email or "unknown"
|
||||
if not auth_result.is_admin:
|
||||
refusal = await asyncio.to_thread(
|
||||
check_and_record_rate_limit, job_manager.firestore.db, job, requested_by, get_settings(),
|
||||
)
|
||||
if refusal:
|
||||
raise HTTPException(status_code=429, detail=refusal)
|
||||
|
||||
source = "admin" if auth_result.is_admin else "customer"
|
||||
client_id = (http_request.headers.get("X-Client-Id") or "").strip().lower()
|
||||
if client_id == "kjbox":
|
||||
source = "kjbox"
|
||||
try:
|
||||
result = await RegenerateService(job_manager).start(
|
||||
job, requested_by=requested_by, source=source,
|
||||
# The owner is always told when their track is ready again (kjbox /
|
||||
# admin triggers too — the files are theirs).
|
||||
notify_customer=True,
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
|
||||
logger.info(f"[job:{job_id}] Regenerate started by {requested_by} (source={source}, needs_stems={result['needs_stems']})")
|
||||
return {
|
||||
"status": "processing",
|
||||
"job_id": job_id,
|
||||
"needs_stems": result["needs_stems"],
|
||||
"message": "Regenerating your video files. This usually takes 10-30 minutes; we'll email you when they're ready.",
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Re-render With Current Theme Endpoint
|
||||
# =============================================================================
|
||||
|
||||
@@ -147,7 +147,7 @@ def _pretend_sent() -> SendCodeResponse:
|
||||
# ------------------------------------------------------------------ endpoints
|
||||
|
||||
@router.post("/auth/send-code", response_model=SendCodeResponse)
|
||||
async def send_code(
|
||||
def send_code(
|
||||
body: SendCodeRequest,
|
||||
http_request: Request,
|
||||
svc: KjboxPartnerService = Depends(get_kjbox_service),
|
||||
@@ -221,7 +221,7 @@ async def send_code(
|
||||
|
||||
|
||||
@router.post("/auth/verify-code", response_model=VerifyCodeResponse)
|
||||
async def verify_code(
|
||||
def verify_code(
|
||||
body: VerifyCodeRequest,
|
||||
http_request: Request,
|
||||
svc: KjboxPartnerService = Depends(get_kjbox_service),
|
||||
@@ -296,7 +296,7 @@ async def verify_code(
|
||||
|
||||
|
||||
@router.post("/credits/show-credit", response_model=ShowCreditResponse)
|
||||
async def show_credit(
|
||||
def show_credit(
|
||||
body: ShowCreditRequest,
|
||||
svc: KjboxPartnerService = Depends(get_kjbox_service),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
|
||||
@@ -88,7 +88,7 @@ class TestNotificationResponse(BaseModel):
|
||||
# Routes
|
||||
|
||||
@router.get("/vapid-public-key", response_model=VapidPublicKeyResponse)
|
||||
async def get_vapid_public_key():
|
||||
def get_vapid_public_key():
|
||||
"""
|
||||
Get the VAPID public key for push subscription.
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ class SuccessResponse(BaseModel):
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/blocklists", response_model=BlocklistsResponse)
|
||||
async def get_blocklists(
|
||||
def get_blocklists(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Get all blocklist data with domain source separation."""
|
||||
@@ -98,7 +98,7 @@ async def get_blocklists(
|
||||
|
||||
|
||||
@router.post("/blocklists/disposable-domains", response_model=SuccessResponse)
|
||||
async def add_disposable_domain(
|
||||
def add_disposable_domain(
|
||||
request: DomainRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -118,7 +118,7 @@ async def add_disposable_domain(
|
||||
|
||||
|
||||
@router.delete("/blocklists/disposable-domains/{domain}", response_model=SuccessResponse)
|
||||
async def remove_disposable_domain(
|
||||
def remove_disposable_domain(
|
||||
domain: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -136,7 +136,7 @@ async def remove_disposable_domain(
|
||||
|
||||
|
||||
@router.post("/blocklists/allowlisted-domains", response_model=SuccessResponse)
|
||||
async def add_allowlisted_domain(
|
||||
def add_allowlisted_domain(
|
||||
request: DomainRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -150,7 +150,7 @@ async def add_allowlisted_domain(
|
||||
|
||||
|
||||
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
|
||||
async def remove_allowlisted_domain(
|
||||
def remove_allowlisted_domain(
|
||||
domain: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -187,7 +187,7 @@ async def trigger_sync(
|
||||
|
||||
|
||||
@router.post("/blocklists/blocked-emails", response_model=SuccessResponse)
|
||||
async def add_blocked_email(
|
||||
def add_blocked_email(
|
||||
request: EmailRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -207,7 +207,7 @@ async def add_blocked_email(
|
||||
|
||||
|
||||
@router.delete("/blocklists/blocked-emails/{email}", response_model=SuccessResponse)
|
||||
async def remove_blocked_email(
|
||||
def remove_blocked_email(
|
||||
email: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -225,7 +225,7 @@ async def remove_blocked_email(
|
||||
|
||||
|
||||
@router.post("/blocklists/blocked-ips", response_model=SuccessResponse)
|
||||
async def add_blocked_ip(
|
||||
def add_blocked_ip(
|
||||
request: IPRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -245,7 +245,7 @@ async def add_blocked_ip(
|
||||
|
||||
|
||||
@router.delete("/blocklists/blocked-ips/{ip_address}", response_model=SuccessResponse)
|
||||
async def remove_blocked_ip(
|
||||
def remove_blocked_ip(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -267,7 +267,7 @@ async def remove_blocked_ip(
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/youtube-queue", response_model=YouTubeQueueListResponse)
|
||||
async def get_youtube_queue(
|
||||
def get_youtube_queue(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
@@ -288,7 +288,7 @@ async def get_youtube_queue(
|
||||
|
||||
|
||||
@router.post("/youtube-queue/{job_id}/retry", response_model=SuccessResponse)
|
||||
async def retry_youtube_upload(
|
||||
def retry_youtube_upload(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
|
||||
@@ -41,7 +41,7 @@ class GenerateFlyerRequest(BaseModel):
|
||||
|
||||
|
||||
@router.get("/r/{code}", response_model=ReferralInterstitialResponse)
|
||||
async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
"""
|
||||
Public endpoint: get interstitial data for a referral link.
|
||||
|
||||
@@ -76,14 +76,14 @@ async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_my_dashboard(auth=Depends(require_auth)):
|
||||
def get_my_dashboard(auth=Depends(require_auth)):
|
||||
"""Get referral dashboard data for the authenticated user."""
|
||||
service = get_referral_service()
|
||||
return service.get_dashboard_data(auth.user_email)
|
||||
|
||||
|
||||
@router.put("/me")
|
||||
async def update_my_link(
|
||||
def update_my_link(
|
||||
updates: UpdateReferralLinkRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
@@ -108,7 +108,7 @@ async def update_my_link(
|
||||
|
||||
|
||||
@router.post("/me/connect")
|
||||
async def start_stripe_connect(auth=Depends(require_auth)):
|
||||
def start_stripe_connect(auth=Depends(require_auth)):
|
||||
"""Start Stripe Connect onboarding for the authenticated user."""
|
||||
# Check if user already has a Connect account
|
||||
from backend.services.user_service import get_user_service
|
||||
@@ -129,7 +129,7 @@ async def start_stripe_connect(auth=Depends(require_auth)):
|
||||
|
||||
|
||||
@router.post("/me/connect/dashboard-link")
|
||||
async def get_connect_dashboard_link(auth=Depends(require_auth)):
|
||||
def get_connect_dashboard_link(auth=Depends(require_auth)):
|
||||
"""Get a login link to the Stripe Express dashboard for managing payout settings."""
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(auth.user_email)
|
||||
@@ -145,7 +145,7 @@ async def get_connect_dashboard_link(auth=Depends(require_auth)):
|
||||
|
||||
|
||||
@router.post("/me/connect/update-link")
|
||||
async def get_connect_update_link(auth=Depends(require_auth)):
|
||||
def get_connect_update_link(auth=Depends(require_auth)):
|
||||
"""Get a link to update Stripe Connect account info (re-onboarding)."""
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(auth.user_email)
|
||||
@@ -165,7 +165,7 @@ class VanityRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post("/me/vanity-request")
|
||||
async def request_vanity_url(
|
||||
def request_vanity_url(
|
||||
request: VanityRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
@@ -215,7 +215,7 @@ async def request_vanity_url(
|
||||
|
||||
|
||||
@router.post("/me/flyer")
|
||||
async def generate_flyer(
|
||||
def generate_flyer(
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
@@ -249,7 +249,7 @@ async def generate_flyer(
|
||||
|
||||
|
||||
@router.post("/admin/vanity")
|
||||
async def create_vanity_link(
|
||||
def create_vanity_link(
|
||||
request: CreateReferralLinkRequest,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
@@ -276,7 +276,7 @@ async def create_vanity_link(
|
||||
|
||||
|
||||
@router.get("/admin/vanity-requests")
|
||||
async def list_vanity_requests(
|
||||
def list_vanity_requests(
|
||||
status: str = Query("pending", pattern="^(pending|approved|denied)$"),
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
@@ -293,7 +293,7 @@ async def list_vanity_requests(
|
||||
|
||||
|
||||
@router.post("/admin/vanity-requests/{request_id}/approve")
|
||||
async def approve_vanity_request(
|
||||
def approve_vanity_request(
|
||||
request_id: str,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
@@ -332,7 +332,7 @@ async def approve_vanity_request(
|
||||
|
||||
|
||||
@router.post("/admin/vanity-requests/{request_id}/deny")
|
||||
async def deny_vanity_request(
|
||||
def deny_vanity_request(
|
||||
request_id: str,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
@@ -346,7 +346,7 @@ async def deny_vanity_request(
|
||||
|
||||
|
||||
@router.get("/admin/links")
|
||||
async def list_links(
|
||||
def list_links(
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
offset: int = Query(0, ge=0),
|
||||
auth=Depends(require_admin),
|
||||
@@ -406,7 +406,7 @@ async def admin_apply_discount(
|
||||
|
||||
|
||||
@router.put("/admin/links/{code}")
|
||||
async def update_link(
|
||||
def update_link(
|
||||
code: str,
|
||||
updates: UpdateReferralLinkRequest,
|
||||
auth=Depends(require_admin),
|
||||
@@ -429,7 +429,7 @@ async def update_link(
|
||||
|
||||
|
||||
@router.post("/admin/links/{code}/flyer")
|
||||
async def admin_generate_flyer(
|
||||
def admin_generate_flyer(
|
||||
code: str,
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_admin),
|
||||
|
||||
@@ -79,7 +79,7 @@ def _to_public(req: SongRequest, your_vote: Optional[int] = None) -> SongRequest
|
||||
|
||||
|
||||
@router.get("/requests", response_model=BoardResponse)
|
||||
async def list_requests(
|
||||
def list_requests(
|
||||
viewer_email: Optional[str] = Depends(optional_user_email),
|
||||
):
|
||||
"""The ranked board: active requests + recently published, with the caller's vote."""
|
||||
@@ -134,7 +134,7 @@ async def submit_request(
|
||||
|
||||
|
||||
@router.post("/requests/{request_id}/vote", response_model=SongRequestPublic)
|
||||
async def vote(
|
||||
def vote(
|
||||
request_id: str,
|
||||
body: VoteBody,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
@@ -158,7 +158,7 @@ async def vote(
|
||||
|
||||
|
||||
@router.get("/me", response_model=DailyVoteStatus)
|
||||
async def my_daily_status(
|
||||
def my_daily_status(
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""The caller's daily-vote status (has today's vote been used, and on what)."""
|
||||
|
||||
@@ -512,7 +512,7 @@ async def _run_preview_encode(
|
||||
"""GCE encode → local fallback → error marker (the cancellable inner body)."""
|
||||
job_id = job.job_id
|
||||
storage = StorageService()
|
||||
encoding_service = get_encoding_service()
|
||||
encoding_service = await asyncio.to_thread(get_encoding_service)
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
|
||||
with job_log_context(job_id, worker="preview"):
|
||||
@@ -546,7 +546,7 @@ async def _run_preview_encode(
|
||||
# Cross-job search endpoint MUST be registered before {job_id} routes
|
||||
# to avoid FastAPI matching "sessions" as a job_id path parameter.
|
||||
@router.get("/sessions/search")
|
||||
async def search_review_sessions(
|
||||
def search_review_sessions(
|
||||
q: str = "",
|
||||
limit: int = 20,
|
||||
auth_info: Tuple[str, str] = Depends(require_auth)
|
||||
@@ -1621,7 +1621,7 @@ async def auto_correct_suggestions(
|
||||
|
||||
|
||||
@router.post("/{job_id}/handlers")
|
||||
async def update_handlers(
|
||||
def update_handlers(
|
||||
job_id: str,
|
||||
enabled_handlers: list,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -1637,7 +1637,7 @@ async def update_handlers(
|
||||
|
||||
|
||||
@router.post("/{job_id}/add-lyrics")
|
||||
async def add_lyrics(
|
||||
def add_lyrics(
|
||||
job_id: str,
|
||||
data: Dict[str, str],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -1755,7 +1755,7 @@ async def add_lyrics(
|
||||
|
||||
|
||||
@router.post("/{job_id}/search-lyrics")
|
||||
async def search_lyrics(
|
||||
def search_lyrics(
|
||||
job_id: str,
|
||||
data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -1919,7 +1919,7 @@ async def generate_preview_video(
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
settings = get_settings()
|
||||
encoding_service = get_encoding_service()
|
||||
encoding_service = await asyncio.to_thread(get_encoding_service)
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
@@ -2092,7 +2092,7 @@ async def generate_preview_video(
|
||||
|
||||
|
||||
@router.get("/{job_id}/preview-video/{preview_hash}")
|
||||
async def get_preview_video(
|
||||
def get_preview_video(
|
||||
job_id: str,
|
||||
preview_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -2131,7 +2131,7 @@ async def get_preview_video(
|
||||
|
||||
|
||||
@router.get("/{job_id}/preview-video/{preview_hash}/status")
|
||||
async def get_preview_video_status(
|
||||
def get_preview_video_status(
|
||||
job_id: str,
|
||||
preview_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -2166,7 +2166,7 @@ async def get_preview_video_status(
|
||||
|
||||
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(
|
||||
def submit_annotation(
|
||||
job_id: str,
|
||||
payload: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -2206,7 +2206,7 @@ async def submit_annotation(
|
||||
|
||||
|
||||
@router.get("/{job_id}/v1/annotations/stats")
|
||||
async def get_annotation_stats(
|
||||
def get_annotation_stats(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
@@ -2463,7 +2463,7 @@ async def get_waveform_data(
|
||||
|
||||
|
||||
@router.post("/{job_id}/sessions")
|
||||
async def save_review_session(
|
||||
def save_review_session(
|
||||
job_id: str,
|
||||
data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -2541,7 +2541,7 @@ async def save_review_session(
|
||||
|
||||
|
||||
@router.get("/{job_id}/sessions")
|
||||
async def list_review_sessions(
|
||||
def list_review_sessions(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
@@ -2573,7 +2573,7 @@ async def list_review_sessions(
|
||||
|
||||
|
||||
@router.get("/{job_id}/sessions/{session_id}")
|
||||
async def get_review_session(
|
||||
def get_review_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -2614,7 +2614,7 @@ async def get_review_session(
|
||||
|
||||
|
||||
@router.delete("/{job_id}/sessions/{session_id}")
|
||||
async def delete_review_session(
|
||||
def delete_review_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
@@ -2646,7 +2646,7 @@ async def delete_review_session(
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit-sessions")
|
||||
async def save_audio_edit_session(
|
||||
def save_audio_edit_session(
|
||||
job_id: str,
|
||||
data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
@@ -2706,7 +2706,7 @@ async def save_audio_edit_session(
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio-edit-sessions")
|
||||
async def list_audio_edit_sessions(
|
||||
def list_audio_edit_sessions(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
@@ -2719,7 +2719,7 @@ async def list_audio_edit_sessions(
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio-edit-sessions/{session_id}")
|
||||
async def get_audio_edit_session(
|
||||
def get_audio_edit_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
@@ -2747,7 +2747,7 @@ async def get_audio_edit_session(
|
||||
|
||||
|
||||
@router.delete("/{job_id}/audio-edit-sessions/{session_id}")
|
||||
async def delete_audio_edit_session(
|
||||
def delete_audio_edit_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
@@ -2836,7 +2836,7 @@ def _build_audio_edit_response(
|
||||
|
||||
|
||||
@router.get("/{job_id}/input-audio-info")
|
||||
async def get_input_audio_info(
|
||||
def get_input_audio_info(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
@@ -3059,7 +3059,7 @@ async def apply_audio_edit(
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit/undo")
|
||||
async def undo_audio_edit(
|
||||
def undo_audio_edit(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
@@ -3110,7 +3110,7 @@ async def undo_audio_edit(
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit/redo")
|
||||
async def redo_audio_edit(
|
||||
def redo_audio_edit(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
|
||||
@@ -20,7 +20,7 @@ router = APIRouter(prefix="/api/tenant", tags=["tenant"])
|
||||
|
||||
|
||||
@router.get("/config", response_model=TenantConfigResponse)
|
||||
async def get_tenant_config(
|
||||
def get_tenant_config(
|
||||
request: Request,
|
||||
tenant: Optional[str] = Query(
|
||||
None,
|
||||
@@ -81,7 +81,7 @@ async def get_tenant_config(
|
||||
|
||||
|
||||
@router.get("/config/{tenant_id}", response_model=TenantConfigResponse)
|
||||
async def get_tenant_config_by_id(tenant_id: str):
|
||||
def get_tenant_config_by_id(tenant_id: str):
|
||||
"""
|
||||
Get tenant configuration by explicit tenant ID.
|
||||
|
||||
@@ -102,7 +102,7 @@ async def get_tenant_config_by_id(tenant_id: str):
|
||||
|
||||
|
||||
@router.get("/asset/{tenant_id}/{asset_name}")
|
||||
async def get_tenant_asset(tenant_id: str, asset_name: str):
|
||||
def get_tenant_asset(tenant_id: str, asset_name: str):
|
||||
"""
|
||||
Get a signed URL for a tenant asset (logo, favicon, etc.).
|
||||
|
||||
|
||||
@@ -169,13 +169,13 @@ async def _read_asset(upload: Optional[UploadFile], label: str) -> Optional[Tupl
|
||||
|
||||
|
||||
@router.get("", response_model=TenantListResponse)
|
||||
async def admin_list_tenants(auth_data: AuthResult = Depends(require_admin)):
|
||||
def admin_list_tenants(auth_data: AuthResult = Depends(require_admin)):
|
||||
"""List all white-label tenants."""
|
||||
return TenantListResponse(tenants=[TenantSummary(**t) for t in list_tenants()])
|
||||
|
||||
|
||||
@router.get("/_template", response_model=TenantTemplateResponse)
|
||||
async def admin_tenant_theme_template(auth_data: AuthResult = Depends(require_admin)):
|
||||
def admin_tenant_theme_template(auth_data: AuthResult = Depends(require_admin)):
|
||||
"""Return the default Nomad theme's full style_params as an editing starting point."""
|
||||
try:
|
||||
return TenantTemplateResponse(style_params=get_default_style_params())
|
||||
|
||||
@@ -22,7 +22,7 @@ router = APIRouter(prefix="/themes", tags=["themes"])
|
||||
|
||||
|
||||
@router.get("", response_model=ThemesListResponse)
|
||||
async def list_themes(request: Request) -> ThemesListResponse:
|
||||
def list_themes(request: Request) -> ThemesListResponse:
|
||||
"""
|
||||
List all available themes.
|
||||
|
||||
@@ -74,7 +74,7 @@ async def get_translation_preview(language: str, request: Request) -> dict:
|
||||
|
||||
|
||||
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
|
||||
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
"""
|
||||
Get detailed information about a specific theme.
|
||||
|
||||
@@ -113,7 +113,7 @@ async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
|
||||
|
||||
@router.get("/{theme_id}/preview")
|
||||
async def get_theme_preview(theme_id: str, request: Request) -> dict:
|
||||
def get_theme_preview(theme_id: str, request: Request) -> dict:
|
||||
"""
|
||||
Get a signed URL for the theme's preview image.
|
||||
|
||||
@@ -158,7 +158,7 @@ async def get_theme_preview(theme_id: str, request: Request) -> dict:
|
||||
|
||||
|
||||
@router.get("/{theme_id}/youtube-description")
|
||||
async def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
|
||||
def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
|
||||
"""
|
||||
Get the YouTube description template for a theme.
|
||||
|
||||
|
||||
+20
-20
@@ -215,7 +215,7 @@ def _precompute_credit_eval(token: str, email: str, collection: Optional[str] =
|
||||
|
||||
|
||||
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
|
||||
async def send_magic_link(
|
||||
def send_magic_link(
|
||||
request: SendMagicLinkRequest,
|
||||
http_request: Request,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -504,7 +504,7 @@ def complete_verified_login(
|
||||
|
||||
|
||||
@router.get("/auth/verify", response_model=VerifyMagicLinkResponse)
|
||||
async def verify_magic_link(
|
||||
def verify_magic_link(
|
||||
token: str,
|
||||
http_request: Request,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -628,7 +628,7 @@ class ClaimWelcomeCreditResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/claim-welcome-credit", response_model=ClaimWelcomeCreditResponse)
|
||||
async def claim_welcome_credit(
|
||||
def claim_welcome_credit(
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -658,7 +658,7 @@ class MagicLinkStatusResponse(BaseModel):
|
||||
|
||||
|
||||
@router.get("/auth/link-status", response_model=MagicLinkStatusResponse)
|
||||
async def magic_link_status(
|
||||
def magic_link_status(
|
||||
token: str,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -680,7 +680,7 @@ async def magic_link_status(
|
||||
|
||||
|
||||
@router.post("/auth/resend-from-token", response_model=ResendFromTokenResponse)
|
||||
async def resend_magic_link_from_token(
|
||||
def resend_magic_link_from_token(
|
||||
request: ResendFromTokenRequest,
|
||||
http_request: Request,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -831,7 +831,7 @@ async def resend_magic_link_from_token(
|
||||
|
||||
|
||||
@router.post("/auth/logout", response_model=LogoutResponse)
|
||||
async def logout(
|
||||
def logout(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -856,7 +856,7 @@ async def logout(
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/me", response_model=UserProfileResponse)
|
||||
async def get_current_user(
|
||||
def get_current_user(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -913,7 +913,7 @@ async def get_current_user(
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/credits/packages", response_model=CreditPackagesResponse)
|
||||
async def list_credit_packages():
|
||||
def list_credit_packages():
|
||||
"""
|
||||
List available credit packages for purchase.
|
||||
|
||||
@@ -934,7 +934,7 @@ async def list_credit_packages():
|
||||
|
||||
|
||||
@router.post("/credits/checkout", response_model=CreateCheckoutResponse)
|
||||
async def create_checkout(
|
||||
def create_checkout(
|
||||
request: CreateCheckoutRequest,
|
||||
stripe_service: StripeService = Depends(get_stripe_service),
|
||||
):
|
||||
@@ -975,7 +975,7 @@ async def create_checkout(
|
||||
|
||||
|
||||
@router.post("/made-for-you/checkout", response_model=CreateCheckoutResponse)
|
||||
async def create_made_for_you_checkout(
|
||||
def create_made_for_you_checkout(
|
||||
request: MadeForYouCheckoutRequest,
|
||||
http_request: Request,
|
||||
stripe_service: StripeService = Depends(get_stripe_service),
|
||||
@@ -1701,7 +1701,7 @@ async def stripe_webhook(
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
|
||||
async def check_feedback_eligibility(
|
||||
def check_feedback_eligibility(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -1741,7 +1741,7 @@ async def check_feedback_eligibility(
|
||||
|
||||
|
||||
@router.post("/feedback", response_model=UserFeedbackResponse)
|
||||
async def submit_user_feedback(
|
||||
def submit_user_feedback(
|
||||
http_request: Request,
|
||||
request: UserFeedbackRequest,
|
||||
authorization: Optional[str] = Header(None),
|
||||
@@ -1965,7 +1965,7 @@ class UserDetailResponse(BaseModel):
|
||||
|
||||
|
||||
@router.get("/admin/users", response_model=UserListResponsePaginated)
|
||||
async def list_users(
|
||||
def list_users(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
search: Optional[str] = None,
|
||||
@@ -2063,7 +2063,7 @@ async def list_users(
|
||||
|
||||
|
||||
@router.get("/admin/users/{email}/detail", response_model=UserDetailResponse)
|
||||
async def get_user_detail(
|
||||
def get_user_detail(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -2166,7 +2166,7 @@ async def get_user_detail(
|
||||
|
||||
|
||||
@router.post("/admin/users", response_model=AdminCreateUserResponse, status_code=201)
|
||||
async def admin_create_user(
|
||||
def admin_create_user(
|
||||
request: AdminCreateUserRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -2228,7 +2228,7 @@ async def admin_create_user(
|
||||
|
||||
|
||||
@router.post("/admin/credits", response_model=AddCreditsResponse)
|
||||
async def add_credits_to_user(
|
||||
def add_credits_to_user(
|
||||
request: AddCreditsRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -2265,7 +2265,7 @@ async def add_credits_to_user(
|
||||
|
||||
|
||||
@router.post("/admin/users/{email}/disable")
|
||||
async def disable_user(
|
||||
def disable_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2286,7 +2286,7 @@ async def disable_user(
|
||||
|
||||
|
||||
@router.post("/admin/users/{email}/enable")
|
||||
async def enable_user(
|
||||
def enable_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2307,7 +2307,7 @@ async def enable_user(
|
||||
|
||||
|
||||
@router.delete("/admin/users/{email}")
|
||||
async def delete_user(
|
||||
def delete_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2333,7 +2333,7 @@ async def delete_user(
|
||||
|
||||
|
||||
@router.post("/admin/users/{email}/role")
|
||||
async def set_user_role(
|
||||
def set_user_role(
|
||||
email: str,
|
||||
role: UserRole,
|
||||
request: Request,
|
||||
|
||||
@@ -67,6 +67,10 @@ class Settings(BaseSettings):
|
||||
|
||||
# Application
|
||||
environment: str = os.getenv("ENVIRONMENT", "development")
|
||||
# Event-loop stall watchdog (backend/services/loop_watchdog.py): logs the
|
||||
# blocking stack when the single uvicorn loop stops ticking for >1s, and
|
||||
# records stalls >=5s to Firestore client_events (production only).
|
||||
loop_watchdog_enabled: bool = os.getenv("LOOP_WATCHDOG_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
log_level: str = os.getenv("LOG_LEVEL", "INFO")
|
||||
|
||||
# Processing
|
||||
@@ -409,6 +413,23 @@ class Settings(BaseSettings):
|
||||
# Where the daily progress + completion emails are sent.
|
||||
youtube_backfill_report_email: str = os.getenv("YOUTUBE_BACKFILL_REPORT_EMAIL", "andrew@nomadkaraoke.com")
|
||||
|
||||
# Storage retention (backend/services/storage_retention.py): a daily job purges
|
||||
# regenerable files (big finals, rendered videos, stems, ...) from jobs
|
||||
# completed more than `storage_retention_min_age_days` ago. DRY-RUN BY DEFAULT:
|
||||
# it only writes a report until STORAGE_RETENTION_DRY_RUN=false is set after a
|
||||
# human has reviewed one.
|
||||
storage_retention_enabled: bool = os.getenv("STORAGE_RETENTION_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
storage_retention_dry_run: bool = os.getenv("STORAGE_RETENTION_DRY_RUN", "true").lower() not in ("false", "0", "no")
|
||||
storage_retention_min_age_days: int = int(os.getenv("STORAGE_RETENTION_MIN_AGE_DAYS", "30"))
|
||||
# Real (non-dry) runs purge at most this many jobs per run, resuming from a cursor.
|
||||
storage_retention_max_jobs_per_run: int = int(os.getenv("STORAGE_RETENTION_MAX_JOBS_PER_RUN", "50"))
|
||||
# Comma-separated tenant ids whose jobs are never purged.
|
||||
storage_retention_excluded_tenants: str = os.getenv("STORAGE_RETENTION_EXCLUDED_TENANTS", "")
|
||||
|
||||
# Customer "Regenerate video" limits (per job / per user, rolling 24h).
|
||||
regenerate_max_per_job_per_day: int = int(os.getenv("REGENERATE_MAX_PER_JOB_PER_DAY", "3"))
|
||||
regenerate_max_per_user_per_day: int = int(os.getenv("REGENERATE_MAX_PER_USER_PER_DAY", "10"))
|
||||
|
||||
# Default CDG/TXT generation settings
|
||||
# When True, CDG and TXT packages are generated by default (when a theme is set)
|
||||
# These can be overridden per-request via explicit enable_cdg/enable_txt parameters
|
||||
|
||||
@@ -4,6 +4,7 @@ FastAPI application entry point for karaoke generation backend.
|
||||
(Trivial comment touch to trigger backend CI on ephemeral runners after
|
||||
the 2026-05-17 dispatcher e2 fix; safe to remove on next backend edit.)
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
@@ -103,6 +104,16 @@ def _run_background_warmup():
|
||||
except Exception as e:
|
||||
logger.warning(f"Langfuse preload failed (will initialize lazily): {e}")
|
||||
|
||||
# 4. Encoding service singleton — its first construction imports
|
||||
# google.cloud.compute_v1 (~10s on a fresh instance). Build it here, off the
|
||||
# event loop, before /api/health/detailed or a preview encode needs it.
|
||||
try:
|
||||
from backend.services.encoding_service import get_encoding_service
|
||||
|
||||
get_encoding_service()
|
||||
except Exception as e:
|
||||
logger.warning(f"Encoding service warmup failed (will build lazily): {e}")
|
||||
|
||||
# Validate OAuth credentials (alerting only, nothing depends on it)
|
||||
try:
|
||||
validate_credentials_on_startup()
|
||||
@@ -133,8 +144,32 @@ async def lifespan(app: FastAPI):
|
||||
target=_run_background_warmup, name="startup-warmup", daemon=True
|
||||
).start()
|
||||
|
||||
# asyncio.to_thread's default executor is min(32, cpu+4) ≈ 6 threads on our
|
||||
# 2 vCPUs. The screens worker, stale-review cron, auto-correct and many
|
||||
# review endpoints all offload into it (mostly I/O-bound), so size it up —
|
||||
# otherwise review-page requests queue behind a few long-running jobs.
|
||||
import concurrent.futures
|
||||
|
||||
asyncio.get_running_loop().set_default_executor(
|
||||
concurrent.futures.ThreadPoolExecutor(max_workers=48, thread_name_prefix="to-thread")
|
||||
)
|
||||
|
||||
# Event-loop stall watchdog: makes "every request froze for 30s" episodes
|
||||
# self-diagnosing (logs the blocking stack; records >=5s stalls in prod).
|
||||
watchdog = None
|
||||
if settings.loop_watchdog_enabled:
|
||||
from backend.services.loop_watchdog import LoopWatchdog, firestore_stall_recorder
|
||||
|
||||
watchdog = LoopWatchdog(
|
||||
recorder=firestore_stall_recorder if settings.environment == "production" else None,
|
||||
)
|
||||
watchdog.start()
|
||||
|
||||
yield
|
||||
|
||||
if watchdog is not None:
|
||||
await watchdog.stop()
|
||||
|
||||
# Shutdown - best-effort parking of any still-registered workers.
|
||||
#
|
||||
# Reality check (incident 2026-09-13, job 41e06b90): Cloud Run services
|
||||
|
||||
@@ -391,6 +391,14 @@ class Job(BaseModel):
|
||||
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
|
||||
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
|
||||
|
||||
# Storage retention (backend/services/storage_retention.py): set when the
|
||||
# daily purge deleted this job's regenerable renders / separated stems.
|
||||
# Cleared when they're rebuilt (regenerate / re-render / stems restore).
|
||||
renders_purged_at: Optional[datetime] = None
|
||||
stems_purged_at: Optional[datetime] = None
|
||||
renders_regenerated_at: Optional[datetime] = None # last GCS-only regenerate
|
||||
storage_purge: Optional[Dict[str, Any]] = None # manifest of the last purge
|
||||
|
||||
# Credit refund tracking (prevents double-refund on cancel→delete or fail→delete)
|
||||
credit_refunded: bool = False
|
||||
|
||||
|
||||
@@ -187,10 +187,17 @@ def claim_with_youtube_queue(
|
||||
|
||||
|
||||
def clear_admin_rerender_update(job) -> Dict[str, Any]:
|
||||
"""Firestore update that drops the marker (empty if there is none)."""
|
||||
"""Firestore update that drops the marker (empty if there is none).
|
||||
|
||||
Also drops a storage-retention regenerate marker: every caller (admin
|
||||
reset/restart, Edit, visibility change, delete outputs) starts a new run.
|
||||
"""
|
||||
update: Dict[str, Any] = {}
|
||||
if raw_admin_rerender_marker(job):
|
||||
return {f"state_data.{ADMIN_RERENDER_MARKER}": DELETE_FIELD}
|
||||
return {}
|
||||
update[f"state_data.{ADMIN_RERENDER_MARKER}"] = DELETE_FIELD
|
||||
from backend.services.regenerate_service import clear_regenerate_update
|
||||
update.update(clear_regenerate_update(job))
|
||||
return update
|
||||
|
||||
|
||||
def suppress_customer_notifications(job) -> bool:
|
||||
@@ -200,7 +207,11 @@ def suppress_customer_notifications(job) -> bool:
|
||||
suppresses them; normal jobs and the tenant theme re-render always notify.
|
||||
"""
|
||||
marker = active_admin_rerender(job)
|
||||
return bool(marker) and not marker.get("notify_customer", False)
|
||||
if marker:
|
||||
return not marker.get("notify_customer", False)
|
||||
# A storage-retention regenerate notifies unless it was started quietly.
|
||||
from backend.services.regenerate_service import regenerate_suppresses_notifications
|
||||
return regenerate_suppresses_notifications(job)
|
||||
|
||||
|
||||
def admin_rerender_brand_code(job) -> Optional[str]:
|
||||
@@ -228,6 +239,9 @@ def validate_admin_rerender(job) -> Optional[str]:
|
||||
return f"Only completed jobs can be re-rendered (current status: {job.status})."
|
||||
if getattr(job, "outputs_deleted_at", None):
|
||||
return "This job's outputs were deleted, so it can't be re-rendered."
|
||||
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
|
||||
if purge_in_progress(job):
|
||||
return PURGE_IN_PROGRESS_MESSAGE
|
||||
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
|
||||
return "Prep-only / finalise-only jobs can't be re-rendered."
|
||||
state_data = job.state_data or {}
|
||||
|
||||
@@ -154,8 +154,9 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
elif not audio_complete:
|
||||
timing_info = {"status": "pending_audio"}
|
||||
else:
|
||||
signals = _compute_timing_signals(
|
||||
job_id, corrections, ai_suggestions, stems, storage
|
||||
signals = await asyncio.to_thread(
|
||||
_compute_timing_signals,
|
||||
job_id, corrections, ai_suggestions, stems, storage,
|
||||
)
|
||||
if signals is None:
|
||||
timing_info = {"status": "no_lead_stem"}
|
||||
|
||||
@@ -19,6 +19,7 @@ its existing client-side on-load auto-apply. Auto-approval must never strand a j
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
@@ -51,32 +52,33 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
|
||||
storage = StorageService()
|
||||
|
||||
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
|
||||
if not storage.file_exists(corrections_path):
|
||||
# All GCS/Firestore calls below are sync — run them off the event loop.
|
||||
if not await asyncio.to_thread(storage.file_exists, corrections_path):
|
||||
return {"outcome": "skipped", "reason": "no_corrections"}
|
||||
|
||||
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
|
||||
if storage.file_exists(updated_path):
|
||||
if await asyncio.to_thread(storage.file_exists, updated_path):
|
||||
# Already applied once (executor auto-complete, a prior pre-apply run,
|
||||
# or a human edit). Never clobber existing corrections_updated.json.
|
||||
try:
|
||||
existing = storage.download_json(updated_path)
|
||||
existing = await asyncio.to_thread(storage.download_json, updated_path)
|
||||
if ((existing.get("metadata") or {}).get("auto_approval")):
|
||||
return {"outcome": "skipped", "reason": "already_applied"}
|
||||
except Exception:
|
||||
pass
|
||||
return {"outcome": "skipped", "reason": "corrections_updated_exists"}
|
||||
|
||||
corrections = storage.download_json(corrections_path)
|
||||
corrections = await asyncio.to_thread(storage.download_json, corrections_path)
|
||||
|
||||
# 1) Ensure the proactive suggestion cache exists (generate on miss, unless
|
||||
# the caller — e.g. the load-time path — asked to only apply an existing
|
||||
# cache so the request doesn't block on an LLM call).
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
ai_suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
|
||||
if ai_suggestions is None and generate_on_miss and settings.auto_correct_proactive_enabled:
|
||||
logger.info(f"[job:{job_id}] pre-apply: cache miss, generating suggestions synchronously")
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
await process_proactive_auto_correct(job_id) # bounded (180s) + best-effort
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
ai_suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
|
||||
|
||||
if ai_suggestions is None:
|
||||
# Unknown suggestion set (proactive disabled or generation failed) —
|
||||
@@ -84,7 +86,7 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
|
||||
return {"outcome": "skipped", "reason": "no_suggestions_cache"}
|
||||
|
||||
# 2) Apply with the executor's sanity gates.
|
||||
result = build_applied_segments(corrections, ai_suggestions)
|
||||
result = await asyncio.to_thread(build_applied_segments, corrections, ai_suggestions)
|
||||
if result.get("aborted"):
|
||||
logger.info(f"[job:{job_id}] pre-apply aborted ({result['aborted']}) — UI will apply client-side")
|
||||
return {"outcome": "skipped", "reason": result["aborted"]}
|
||||
@@ -115,11 +117,13 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
|
||||
except Exception: # pragma: no cover - google libs always present in prod
|
||||
PreconditionFailed = () # type: ignore[assignment]
|
||||
try:
|
||||
storage.upload_json(updated_path, updated, if_generation_match=0)
|
||||
await asyncio.to_thread(storage.upload_json, updated_path, updated, if_generation_match=0)
|
||||
except PreconditionFailed:
|
||||
logger.info(f"[job:{job_id}] pre-apply raced a concurrent write — theirs wins")
|
||||
return {"outcome": "skipped", "reason": "raced_concurrent_write"}
|
||||
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
|
||||
await asyncio.to_thread(
|
||||
JobManager().update_file_url, job_id, "lyrics", "corrections_updated", updated_path
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"[job:{job_id}] pre-apply saved corrections_updated.json "
|
||||
|
||||
@@ -17,6 +17,7 @@ Usage:
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
@@ -1381,25 +1382,49 @@ class EncodingService:
|
||||
_encoding_service: Optional[EncodingService] = None
|
||||
|
||||
|
||||
_encoding_service_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_encoding_service() -> EncodingService:
|
||||
"""Get the singleton encoding service instance."""
|
||||
"""Get the singleton encoding service instance.
|
||||
|
||||
First construction imports ``google.cloud.compute_v1`` (a ~10s import on a
|
||||
fresh Cloud Run instance) — the startup warmup thread builds it in the
|
||||
background, and async callers should use ``asyncio.to_thread`` so a cold
|
||||
call can't freeze the event loop (watchdog caught a 9.9s stall here in
|
||||
/api/health/detailed, 2026-10-03).
|
||||
"""
|
||||
global _encoding_service
|
||||
if _encoding_service is None:
|
||||
_encoding_service = EncodingService()
|
||||
# Wire up worker manager for dynamic URL resolution
|
||||
try:
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from google.cloud import compute_v1, firestore
|
||||
settings = get_settings()
|
||||
db = firestore.Client(project=settings.google_cloud_project)
|
||||
compute_client = compute_v1.InstancesClient()
|
||||
manager = EncodingWorkerManager(
|
||||
db=db,
|
||||
compute_client=compute_client,
|
||||
project_id=settings.google_cloud_project,
|
||||
)
|
||||
_encoding_service.set_worker_manager(manager)
|
||||
except Exception:
|
||||
# Fallback to static URL if worker manager setup fails
|
||||
pass
|
||||
if _encoding_service is not None:
|
||||
return _encoding_service
|
||||
with _encoding_service_lock:
|
||||
if _encoding_service is not None:
|
||||
return _encoding_service
|
||||
_build_encoding_service()
|
||||
return _encoding_service
|
||||
|
||||
|
||||
def _build_encoding_service() -> None:
|
||||
"""Construct + wire the singleton; publish it only once fully wired, so the
|
||||
lock-free fast path in get_encoding_service never sees a half-built one."""
|
||||
global _encoding_service
|
||||
if _encoding_service is not None:
|
||||
return
|
||||
service = EncodingService()
|
||||
# Wire up worker manager for dynamic URL resolution
|
||||
try:
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from google.cloud import compute_v1, firestore
|
||||
settings = get_settings()
|
||||
db = firestore.Client(project=settings.google_cloud_project)
|
||||
compute_client = compute_v1.InstancesClient()
|
||||
manager = EncodingWorkerManager(
|
||||
db=db,
|
||||
compute_client=compute_client,
|
||||
project_id=settings.google_cloud_project,
|
||||
)
|
||||
service.set_worker_manager(manager)
|
||||
except Exception:
|
||||
# Fallback to static URL if worker manager setup fails
|
||||
pass
|
||||
_encoding_service = service
|
||||
@@ -256,6 +256,8 @@ class FirestoreService:
|
||||
'job_id', 'status', 'progress', 'created_at', 'updated_at', 'artist', 'title',
|
||||
'error_message', 'error_details.code', 'error_details.stage',
|
||||
'error_details.stall_minutes', 'error_details.keep_trying', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'renders_purged_at', 'stems_purged_at', 'finalise_only', 'prep_only',
|
||||
'state_data.regenerate', 'state_data.stems_restore', 'state_data.instrumental_selection',
|
||||
'made_for_you', 'customer_email', 'locale',
|
||||
'url', 'filename', 'existing_instrumental_gcs_path',
|
||||
'audio_search_artist', 'audio_search_title',
|
||||
|
||||
@@ -856,21 +856,20 @@ def resolve_instrumental(work_dir: Path, config: dict):
|
||||
"*custom_instrumental*.aac", "*Instrumental Custom*",
|
||||
)
|
||||
elif instrumental_selection == "with_backing":
|
||||
# User selected instrumental with backing vocals
|
||||
# User selected instrumental with backing vocals. NO generic fallback:
|
||||
# "*instrumental*.flac" used to match instrumental_clean.flac (or a kept
|
||||
# custom_instrumental.flac) whenever the with-backing stem was missing,
|
||||
# silently shipping the wrong instrumental. Missing => fail loudly.
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*instrumental_with_backing*.flac", "*Instrumental Backing*.flac",
|
||||
"*with_backing*.flac", "*Backing*.flac",
|
||||
"*instrumental*.flac", "*Instrumental*.flac",
|
||||
"*instrumental*.wav"
|
||||
)
|
||||
else:
|
||||
# Default to clean instrumental
|
||||
# Default to clean instrumental — never fall back to a with-backing or
|
||||
# custom/user instrumental (same silent-wrong-instrumental risk).
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*instrumental_clean*.flac", "*Instrumental Clean*.flac",
|
||||
"*instrumental*.flac", "*Instrumental*.flac",
|
||||
"*instrumental*.wav"
|
||||
)
|
||||
|
||||
return instrumental
|
||||
|
||||
@@ -20,6 +20,7 @@ from backend.models.worker_log import WorkerLogEntry
|
||||
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.utils.keyed_lock import job_lock
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -487,7 +488,18 @@ class JobManager:
|
||||
|
||||
return True
|
||||
|
||||
def transition_to_state(
|
||||
def transition_to_state(self, job_id: str, *args, **kwargs) -> bool:
|
||||
"""Validate + apply a status transition (see _transition_to_state_unlocked).
|
||||
|
||||
Serialized per job within this instance: route handlers run in the
|
||||
threadpool, so two concurrent requests (e.g. a double-clicked Complete)
|
||||
could otherwise both pass validation and both transition/trigger
|
||||
workers. (They used to be serialized by running on the event loop.)
|
||||
"""
|
||||
with job_lock(job_id):
|
||||
return self._transition_to_state_unlocked(job_id, *args, **kwargs)
|
||||
|
||||
def _transition_to_state_unlocked(
|
||||
self,
|
||||
job_id: str,
|
||||
new_status: JobStatus,
|
||||
@@ -1034,6 +1046,12 @@ class JobManager:
|
||||
# default to 1. payment_bypassed admin/no-email jobs have
|
||||
# credits_charged=0 and must not be refunded.
|
||||
state_data = job.state_data or {}
|
||||
# A re-run of an already-delivered track (storage-retention
|
||||
# regenerate, admin/theme re-render) was paid for when it first
|
||||
# completed — cancelling the re-run must not refund that credit.
|
||||
if any(state_data.get(k) for k in ("regenerate", "admin_rerender", "theme_rerender")):
|
||||
logger.info(f"Job {job_id}: cancelled re-run of a delivered track, skipping refund")
|
||||
return False
|
||||
credits_charged = int(state_data.get("credits_charged", 1))
|
||||
|
||||
if credits_charged == 0:
|
||||
@@ -1312,8 +1330,13 @@ class JobManager:
|
||||
"""
|
||||
Cancel a job.
|
||||
|
||||
Only jobs in non-terminal states can be cancelled.
|
||||
Only jobs in non-terminal states can be cancelled. Serialized per job
|
||||
within this instance so a double-clicked Cancel can't refund twice.
|
||||
"""
|
||||
with job_lock(job_id):
|
||||
return self._cancel_job_unlocked(job_id, reason)
|
||||
|
||||
def _cancel_job_unlocked(self, job_id: str, reason: Optional[str]) -> bool:
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
"""Event-loop stall watchdog.
|
||||
|
||||
The API runs ONE uvicorn process with ONE asyncio event loop per Cloud Run
|
||||
instance. Any synchronous work executed on that loop (sync Firestore/GCS/HTTP
|
||||
calls, PIL/ffmpeg, a first ``import matplotlib.pyplot``…) freezes *every*
|
||||
request on the instance — including ``/api/health`` — which users see as the
|
||||
"Reconnecting" pill / "temporarily unavailable" banner. (Analysis 2026-10-03:
|
||||
docs/archive/2026-10-03-backend-loop-freezes-telemetry-plan.md.)
|
||||
|
||||
This module makes such freezes self-diagnosing:
|
||||
|
||||
* an asyncio heartbeat task stamps ``last_tick`` every ``tick_s``;
|
||||
* a daemon thread notices when the stamp goes stale (> ``stall_threshold_s``)
|
||||
and captures the *event-loop thread's* Python stack via
|
||||
``sys._current_frames()`` — i.e. the exact line that is blocking — resampling
|
||||
at ``sample_at_s`` so a long freeze shows where it actually spent its time;
|
||||
* when the loop resumes it logs ``EVENT_LOOP_STALL ended duration_ms=…``
|
||||
(WARNING, or ERROR at ``error_threshold_s`` — the alerting log metric keys on
|
||||
that), and for stalls ≥ ``record_threshold_s`` hands a summary to
|
||||
``recorder`` (Firestore ``client_events`` type ``server_loop_stall`` in prod),
|
||||
so server-side cause and user-visible impact live in one collection.
|
||||
|
||||
The thread only reads frames and a float; it never touches the loop, so it is
|
||||
safe to run alongside it. Recording happens on the watchdog thread (sync
|
||||
Firestore is fine there).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Frames from these path fragments are "ours" — the innermost one is reported
|
||||
# as the culprit (the stdlib/library frame below it is usually just the I/O).
|
||||
_OWN_CODE_MARKERS = ("/backend/", "/karaoke_gen/")
|
||||
_MAX_STACK_FRAMES = 30
|
||||
_MAX_STACK_CHARS = 8000
|
||||
|
||||
Recorder = Callable[[dict], None]
|
||||
|
||||
# Innermost frames that mean "the loop is idle, waiting for I/O" — not blocked.
|
||||
_IDLE_FUNCS = {"select", "poll", "epoll", "kqueue", "control", "_run_once"}
|
||||
_IDLE_FILES = ("selectors.py", "base_events.py")
|
||||
|
||||
|
||||
def _is_idle_frame(frame) -> bool:
|
||||
"""True when the loop thread is parked in the selector (idle), not running code."""
|
||||
if frame is None:
|
||||
return False
|
||||
code = frame.f_code
|
||||
return code.co_name in _IDLE_FUNCS and code.co_filename.endswith(_IDLE_FILES)
|
||||
|
||||
|
||||
def _format_stack(frame) -> tuple[str, str]:
|
||||
"""Return (stack_text, culprit) for a frame; culprit = innermost own-code frame."""
|
||||
if frame is None:
|
||||
return "", ""
|
||||
summary = traceback.extract_stack(frame)[-_MAX_STACK_FRAMES:]
|
||||
culprit = ""
|
||||
for fs in reversed(summary):
|
||||
if any(m in fs.filename for m in _OWN_CODE_MARKERS) and "loop_watchdog" not in fs.filename:
|
||||
short = fs.filename.split("/app/")[-1]
|
||||
culprit = f"{short}:{fs.lineno} in {fs.name}"
|
||||
break
|
||||
if not culprit and summary:
|
||||
fs = summary[-1]
|
||||
culprit = f"{fs.filename}:{fs.lineno} in {fs.name}"
|
||||
text = "".join(traceback.format_list(summary))[-_MAX_STACK_CHARS:]
|
||||
return text, culprit
|
||||
|
||||
|
||||
class LoopWatchdog:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
tick_s: float = 0.25,
|
||||
stall_threshold_s: float = 1.0,
|
||||
error_threshold_s: float = 10.0,
|
||||
record_threshold_s: float = 5.0,
|
||||
sample_at_s: tuple[float, ...] = (1.0, 5.0, 15.0),
|
||||
recorder: Optional[Recorder] = None,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
) -> None:
|
||||
self.tick_s = tick_s
|
||||
self.stall_threshold_s = stall_threshold_s
|
||||
self.error_threshold_s = error_threshold_s
|
||||
self.record_threshold_s = record_threshold_s
|
||||
self.sample_at_s = tuple(sorted(sample_at_s))
|
||||
self.recorder = recorder
|
||||
self._clock = clock
|
||||
|
||||
self._last_tick = clock()
|
||||
self._loop_thread_id: Optional[int] = None
|
||||
self._heartbeat_task: Optional[asyncio.Task] = None
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._stop = threading.Event()
|
||||
|
||||
# Current-stall state (only touched by the watchdog thread).
|
||||
self._in_stall = False
|
||||
self._stall_started_tick = 0.0
|
||||
self._samples: list[dict[str, Any]] = []
|
||||
self._next_sample_idx = 0
|
||||
|
||||
# ----- lifecycle -------------------------------------------------------
|
||||
def start(self) -> None:
|
||||
"""Start heartbeat + watchdog thread. Must be called from inside the loop."""
|
||||
if self._thread is not None:
|
||||
return
|
||||
self._loop_thread_id = threading.get_ident()
|
||||
self._last_tick = self._clock()
|
||||
self._heartbeat_task = asyncio.get_running_loop().create_task(self._heartbeat())
|
||||
self._stop.clear()
|
||||
self._thread = threading.Thread(target=self._run, name="loop-watchdog", daemon=True)
|
||||
self._thread.start()
|
||||
logger.info(
|
||||
"Event-loop watchdog started (stall>=%.1fs logged, >=%.1fs recorded, >=%.1fs error)",
|
||||
self.stall_threshold_s, self.record_threshold_s, self.error_threshold_s,
|
||||
)
|
||||
|
||||
async def stop(self) -> None:
|
||||
self._stop.set()
|
||||
if self._heartbeat_task is not None:
|
||||
self._heartbeat_task.cancel()
|
||||
try:
|
||||
await self._heartbeat_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
self._heartbeat_task = None
|
||||
self._thread = None
|
||||
|
||||
async def _heartbeat(self) -> None:
|
||||
while True:
|
||||
self._last_tick = self._clock()
|
||||
await asyncio.sleep(self.tick_s)
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.wait(self.tick_s):
|
||||
try:
|
||||
self.check()
|
||||
except Exception: # pragma: no cover — must never kill the thread
|
||||
logger.exception("loop watchdog check failed")
|
||||
|
||||
# ----- detection (called from the watchdog thread; unit-testable) ------
|
||||
def _sample(self, age: float) -> None:
|
||||
frame = sys._current_frames().get(self._loop_thread_id) if self._loop_thread_id else None
|
||||
if _is_idle_frame(frame):
|
||||
# Loop is parked in select(): not blocked. This is what a CPU-throttled
|
||||
# idle Cloud Run instance looks like when CPU returns (the watchdog
|
||||
# thread can wake before the heartbeat does). Record it so _finish
|
||||
# can drop an all-idle "stall" as a false positive.
|
||||
self._samples.append({"at_s": round(age, 1), "culprit": "", "stack": "", "idle": True})
|
||||
return
|
||||
stack, culprit = _format_stack(frame)
|
||||
if self._samples and self._samples[-1]["stack"] == stack:
|
||||
return # identical to the previous sample — nothing new to learn
|
||||
self._samples.append({"at_s": round(age, 1), "culprit": culprit, "stack": stack, "idle": False})
|
||||
level = logging.ERROR if age >= self.error_threshold_s else logging.WARNING
|
||||
logger.log(
|
||||
level,
|
||||
"EVENT_LOOP_STALL in progress age_ms=%d culprit=%s\n%s",
|
||||
int(age * 1000), culprit, stack,
|
||||
extra={"loop_stall_age_ms": int(age * 1000), "loop_stall_culprit": culprit},
|
||||
)
|
||||
|
||||
def check(self, now: Optional[float] = None) -> None:
|
||||
now = self._clock() if now is None else now
|
||||
last = self._last_tick
|
||||
age = now - last
|
||||
|
||||
if not self._in_stall:
|
||||
if age >= self.stall_threshold_s:
|
||||
self._in_stall = True
|
||||
self._stall_started_tick = last
|
||||
self._samples = []
|
||||
self._next_sample_idx = 0
|
||||
else:
|
||||
return
|
||||
|
||||
# In a stall: has the heartbeat resumed?
|
||||
if last > self._stall_started_tick:
|
||||
# The heartbeat that ended the stall fired one tick_s after the
|
||||
# previous one would have, so subtract the nominal sleep.
|
||||
duration = max(0.0, last - self._stall_started_tick - self.tick_s)
|
||||
self._finish(duration)
|
||||
return
|
||||
|
||||
while (
|
||||
self._next_sample_idx < len(self.sample_at_s)
|
||||
and age >= self.sample_at_s[self._next_sample_idx]
|
||||
):
|
||||
self._next_sample_idx += 1
|
||||
self._sample(age)
|
||||
|
||||
def _finish(self, duration: float) -> None:
|
||||
samples = self._samples
|
||||
self._in_stall = False
|
||||
self._samples = []
|
||||
if duration < self.stall_threshold_s:
|
||||
return
|
||||
if samples and all(s.get("idle") for s in samples):
|
||||
# Every sample saw the loop idle in select() — a throttled/idle gap
|
||||
# (no CPU allocated between requests), not a blocking call.
|
||||
logger.debug("loop watchdog: ignored idle gap of %dms", int(duration * 1000))
|
||||
return
|
||||
samples = [s for s in samples if not s.get("idle")]
|
||||
culprits = [s["culprit"] for s in samples if s["culprit"]]
|
||||
# The longest-lived sample is the most representative of the freeze.
|
||||
main_culprit = culprits[-1] if culprits else ""
|
||||
level = logging.ERROR if duration >= self.error_threshold_s else logging.WARNING
|
||||
logger.log(
|
||||
level,
|
||||
"EVENT_LOOP_STALL ended duration_ms=%d culprit=%s",
|
||||
int(duration * 1000), main_culprit,
|
||||
extra={
|
||||
"loop_stall_duration_ms": int(duration * 1000),
|
||||
"loop_stall_culprit": main_culprit,
|
||||
"loop_stall_culprits": culprits,
|
||||
},
|
||||
)
|
||||
if self.recorder is not None and duration >= self.record_threshold_s:
|
||||
try:
|
||||
self.recorder({
|
||||
"duration_ms": int(duration * 1000),
|
||||
"culprit": main_culprit,
|
||||
"culprits": culprits,
|
||||
"stack": samples[-1]["stack"] if samples else "",
|
||||
})
|
||||
except Exception:
|
||||
logger.exception("Failed to record loop stall (non-fatal)")
|
||||
|
||||
|
||||
# ----- production recorder ---------------------------------------------------
|
||||
_instance_id: Optional[str] = None
|
||||
|
||||
|
||||
def _cloud_run_instance_id() -> str:
|
||||
"""Best-effort Cloud Run instance id from the metadata server (cached)."""
|
||||
global _instance_id
|
||||
if _instance_id is not None:
|
||||
return _instance_id
|
||||
_instance_id = ""
|
||||
try:
|
||||
import requests
|
||||
|
||||
resp = requests.get(
|
||||
"http://metadata.google.internal/computeMetadata/v1/instance/id",
|
||||
headers={"Metadata-Flavor": "Google"},
|
||||
timeout=1,
|
||||
)
|
||||
if resp.ok:
|
||||
_instance_id = resp.text.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return _instance_id
|
||||
|
||||
|
||||
def firestore_stall_recorder(stall: dict) -> None:
|
||||
"""Persist a stall as a ``client_events`` doc (type ``server_loop_stall``)."""
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
from backend.version import VERSION
|
||||
|
||||
doc = {
|
||||
"type": "server_loop_stall",
|
||||
"source": "server",
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
"release": VERSION,
|
||||
"revision": os.getenv("K_REVISION", ""),
|
||||
"instance_id": _cloud_run_instance_id(),
|
||||
"detail": {
|
||||
"duration_ms": stall["duration_ms"],
|
||||
"culprit": stall["culprit"][:300],
|
||||
},
|
||||
"culprits": [c[:300] for c in stall.get("culprits", [])][:5],
|
||||
"stack": stall.get("stack", "")[:_MAX_STACK_CHARS],
|
||||
}
|
||||
firestore.Client(project="nomadkaraoke").collection("client_events").add(doc)
|
||||
@@ -0,0 +1,367 @@
|
||||
"""
|
||||
Regenerate a completed job's GCS outputs on demand (storage retention).
|
||||
|
||||
The storage-retention job (backend/services/storage_retention.py) purges the big
|
||||
regenerable files of jobs completed >30 days ago — every final except the 720p,
|
||||
the rendered lyrics video, previews and (where the input audio is kept) the
|
||||
separated stems. This service brings them back:
|
||||
|
||||
1. claim the job atomically: COMPLETE -> LYRICS_COMPLETE with
|
||||
``state_data.regen_restore_status = "review_complete"`` (the mechanism shared
|
||||
with the admin/theme re-render and the private->public visibility flow) and
|
||||
the ``state_data.regenerate`` marker;
|
||||
2. trigger the screens worker. If the job's stems were purged
|
||||
(``stems_purged_at``), the screens worker first re-runs audio separation from
|
||||
the job's input (``input_media_gcs_path``, i.e. ``input/edited.flac`` for
|
||||
audio-edited jobs) — see ``backend/workers/screens_worker.py`` stems gate and
|
||||
the audio worker's restore mode;
|
||||
3. screens -> render -> video worker, using the job's EXISTING reviewed lyrics,
|
||||
instrumental selection (custom/uploaded instrumentals are never purged) and
|
||||
style snapshot.
|
||||
|
||||
Unlike the admin re-render this is GCS-ONLY: the video worker skips the whole
|
||||
distribution stage (no YouTube/Dropbox/Google Drive changes, no new brand code,
|
||||
no Discord post) while the marker is active, and keeps the job's published links.
|
||||
The customer is emailed/pushed on completion unless ``notify_customer`` is False.
|
||||
|
||||
``after="change_to_private"`` chains a public->private visibility change once
|
||||
the finals are back (redistribution needs the full finals set).
|
||||
|
||||
Like the admin re-render the marker records the job's ``review_token`` at claim,
|
||||
so a later trip through review retires it; a FAILED regenerate keeps it, so
|
||||
``POST /api/jobs/{id}/retry`` (or another regenerate) resumes it.
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.firestore_service import log_to_job
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_rerender_service import (
|
||||
RerenderConflictError,
|
||||
RerenderError,
|
||||
claim_for_rerender,
|
||||
delete_regenerated_artifacts,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
REGENERATE_MARKER = "regenerate"
|
||||
_LOG_SOURCE = "regenerate"
|
||||
RATE_LIMIT_COLLECTION = "regenerate_rate_limits"
|
||||
AFTER_CHANGE_TO_PRIVATE = "change_to_private"
|
||||
_ALLOWED_AFTER = {None, AFTER_CHANGE_TO_PRIVATE}
|
||||
|
||||
# Finals the UI / redistribution need; any missing => renders must be regenerated.
|
||||
_REQUIRED_FINAL_KEYS = ("lossy_4k_mp4", "lossy_720p_mp4")
|
||||
|
||||
|
||||
# --- Marker helpers ------------------------------------------------------------
|
||||
|
||||
def raw_regenerate_marker(job) -> Dict[str, Any]:
|
||||
state_data = getattr(job, "state_data", None)
|
||||
marker = state_data.get(REGENERATE_MARKER) if isinstance(state_data, dict) else None
|
||||
return marker if isinstance(marker, dict) else {}
|
||||
|
||||
|
||||
def active_regenerate(job) -> Dict[str, Any]:
|
||||
"""The marker if it belongs to the job's current run (same review_token), else ``{}``."""
|
||||
marker = raw_regenerate_marker(job)
|
||||
if marker and "review_token" in marker:
|
||||
if marker["review_token"] != getattr(job, "review_token", None):
|
||||
return {}
|
||||
return marker
|
||||
|
||||
|
||||
def clear_regenerate_update(job) -> Dict[str, Any]:
|
||||
if raw_regenerate_marker(job):
|
||||
return {f"state_data.{REGENERATE_MARKER}": DELETE_FIELD}
|
||||
return {}
|
||||
|
||||
|
||||
def regenerate_brand_code(job) -> Optional[str]:
|
||||
return active_regenerate(job).get("brand_code") or None
|
||||
|
||||
|
||||
def regenerate_suppresses_notifications(job) -> bool:
|
||||
marker = active_regenerate(job)
|
||||
return bool(marker) and not marker.get("notify_customer", True)
|
||||
|
||||
|
||||
def is_gcs_only_run(job) -> bool:
|
||||
"""True while a regenerate is rebuilding this job's GCS outputs (no distribution)."""
|
||||
return bool(active_regenerate(job))
|
||||
|
||||
|
||||
def renders_missing(job) -> bool:
|
||||
"""True if the job's big finals are gone (purged, or never recorded)."""
|
||||
if getattr(job, "renders_purged_at", None):
|
||||
return True
|
||||
finals = (getattr(job, "file_urls", None) or {}).get("finals") or {}
|
||||
if not isinstance(finals, dict):
|
||||
return True
|
||||
return not all(finals.get(key) for key in _REQUIRED_FINAL_KEYS)
|
||||
|
||||
|
||||
def stems_need_restore(job) -> bool:
|
||||
"""True if the job's separated stems were purged and must be re-separated first.
|
||||
|
||||
Bring-your-own-instrumental and finalise-only jobs never had separated
|
||||
stems to restore.
|
||||
"""
|
||||
if getattr(job, "existing_instrumental_gcs_path", None):
|
||||
return False
|
||||
if getattr(job, "finalise_only", False):
|
||||
return False
|
||||
return bool(getattr(job, "stems_purged_at", None))
|
||||
|
||||
|
||||
# --- Validation ------------------------------------------------------------------
|
||||
|
||||
def _claimable_statuses(job) -> set:
|
||||
statuses = {JobStatus.COMPLETE.value}
|
||||
if active_regenerate(job):
|
||||
statuses.update({JobStatus.FAILED.value, JobStatus.CANCELLED.value})
|
||||
return statuses
|
||||
|
||||
|
||||
def validate_regenerate(job, after: Optional[str] = None) -> Optional[str]:
|
||||
"""Return a reason the job can't be regenerated, or None if it can."""
|
||||
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
|
||||
|
||||
status = job.status.value if hasattr(job.status, "value") else job.status
|
||||
if status not in _claimable_statuses(job):
|
||||
return f"Only finished tracks can be regenerated (current status: {status})."
|
||||
if getattr(job, "outputs_deleted_at", None):
|
||||
return "This track's outputs were deleted, so it can't be regenerated."
|
||||
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
|
||||
return "This track type can't be regenerated."
|
||||
state_data = job.state_data or {}
|
||||
if state_data.get("visibility_change_in_progress") and after != AFTER_CHANGE_TO_PRIVATE:
|
||||
return "A visibility change is in progress for this track."
|
||||
from backend.services.admin_rerender_service import active_admin_rerender
|
||||
if active_admin_rerender(job) or state_data.get("theme_rerender"):
|
||||
return "This track is already being re-rendered."
|
||||
if purge_in_progress(job):
|
||||
return PURGE_IN_PROGRESS_MESSAGE
|
||||
if not state_data.get("instrumental_selection"):
|
||||
return "This track has no instrumental selection to regenerate with."
|
||||
if not ((job.file_urls or {}).get("lyrics") or {}).get("corrections"):
|
||||
return "This track has no reviewed lyrics to regenerate with."
|
||||
if not getattr(job, "input_media_gcs_path", None):
|
||||
return "This track's original audio is no longer available, so it can't be regenerated."
|
||||
if not getattr(job, "theme_id", None):
|
||||
return "This track has no video style to regenerate with."
|
||||
return None
|
||||
|
||||
|
||||
# --- Rate limiting ------------------------------------------------------------------
|
||||
|
||||
def _recent(timestamps: List[str], now: datetime, window: timedelta) -> List[str]:
|
||||
out = []
|
||||
for ts in timestamps or []:
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
continue
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
if now - dt < window:
|
||||
out.append(dt.isoformat())
|
||||
return out
|
||||
|
||||
|
||||
def check_and_record_rate_limit(db, job, user_email: str, settings, now: Optional[datetime] = None) -> Optional[str]:
|
||||
"""Customer limits: N regenerations per job and M per user in a rolling 24h.
|
||||
|
||||
Returns a refusal message, or None (and records the request) if allowed.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = settings or get_settings()
|
||||
now = now or datetime.now(timezone.utc)
|
||||
window = timedelta(hours=24)
|
||||
|
||||
job_recent = _recent((job.state_data or {}).get("regenerate_requests") or [], now, window)
|
||||
if len(job_recent) >= settings.regenerate_max_per_job_per_day:
|
||||
return "This track was regenerated recently. Please try again tomorrow."
|
||||
|
||||
key = hashlib.sha256((user_email or "unknown").strip().lower().encode()).hexdigest()[:32]
|
||||
user_ref = db.collection(RATE_LIMIT_COLLECTION).document(key)
|
||||
|
||||
@firestore.transactional
|
||||
def record(transaction):
|
||||
snap = user_ref.get(transaction=transaction)
|
||||
user_recent = _recent((snap.to_dict() or {}).get("requests") if snap.exists else [], now, window)
|
||||
if len(user_recent) >= settings.regenerate_max_per_user_per_day:
|
||||
return False
|
||||
transaction.set(user_ref, {"requests": user_recent + [now.isoformat()], "updated_at": now})
|
||||
return True
|
||||
|
||||
if not record(db.transaction()):
|
||||
return "You've regenerated several tracks today. Please try again tomorrow."
|
||||
return None
|
||||
|
||||
|
||||
# --- Service ---------------------------------------------------------------------
|
||||
|
||||
class RegenerateService:
|
||||
def __init__(
|
||||
self,
|
||||
job_manager: Optional[JobManager] = None,
|
||||
storage: Optional[StorageService] = None,
|
||||
):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
self.storage = storage or StorageService()
|
||||
|
||||
async def start(
|
||||
self,
|
||||
job,
|
||||
requested_by: str,
|
||||
source: str = "customer",
|
||||
notify_customer: bool = True,
|
||||
after: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Claim the job and kick off the GCS-only regenerate.
|
||||
|
||||
Raises RerenderError (400/500/503) or RerenderConflictError (409).
|
||||
Returns ``{"needs_stems": bool, "brand_code": ...}``.
|
||||
"""
|
||||
if after not in _ALLOWED_AFTER:
|
||||
raise RerenderError(f"Unknown follow-up action: {after}")
|
||||
reason = validate_regenerate(job, after=after)
|
||||
if reason:
|
||||
raise RerenderError(reason)
|
||||
|
||||
job_id = job.job_id
|
||||
input_path = getattr(job, "input_media_gcs_path", None)
|
||||
if not await asyncio.to_thread(self.storage.file_exists, input_path):
|
||||
raise RerenderError(
|
||||
"This track's original audio is no longer available, so it can't be regenerated."
|
||||
)
|
||||
update, context = self._build_claim(job, requested_by, source, notify_customer, after)
|
||||
await asyncio.to_thread(
|
||||
claim_for_rerender, self.job_manager.firestore.db, job_id, update, _claimable_statuses(job),
|
||||
)
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(self._after_claim, job, context)
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_screens_worker(job_id)
|
||||
except Exception as e:
|
||||
logger.exception(f"[job:{job_id}] Regenerate failed after claim")
|
||||
await asyncio.to_thread(self._fail_run, job_id, f"Regenerate failed to start: {e}", "start_error")
|
||||
raise RerenderError(
|
||||
"The regeneration failed to start. Please try again.", status_code=500,
|
||||
) from e
|
||||
if not triggered:
|
||||
await asyncio.to_thread(
|
||||
self._fail_run, job_id, "Regenerate couldn't start the screens worker.", "screens_trigger_failed",
|
||||
)
|
||||
raise RerenderError("Couldn't start the regeneration. Please try again.", status_code=503)
|
||||
|
||||
await asyncio.to_thread(
|
||||
log_to_job, job_id, _LOG_SOURCE, "INFO",
|
||||
f"Regenerate started by {requested_by} ({source}); stems restore first: {context['needs_stems']}",
|
||||
)
|
||||
return {"needs_stems": context["needs_stems"], "brand_code": context["brand_code"]}
|
||||
|
||||
def _build_claim(self, job, requested_by, source, notify_customer, after):
|
||||
state_data = job.state_data or {}
|
||||
previous = active_regenerate(job)
|
||||
brand_code = state_data.get("brand_code") or previous.get("brand_code")
|
||||
needs_stems = stems_need_restore(job)
|
||||
now = datetime.now(timezone.utc)
|
||||
message = (
|
||||
f"Regenerate requested by {requested_by} ({source}): rebuilding GCS outputs only "
|
||||
f"(no YouTube/Dropbox/Google Drive changes){'; re-separating stems first' if needs_stems else ''}"
|
||||
)
|
||||
# Only customer-triggered runs count towards the customer's daily limit.
|
||||
requests = _recent(state_data.get("regenerate_requests") or [], now, timedelta(hours=24))
|
||||
if source == "customer":
|
||||
requests = requests + [now.isoformat()]
|
||||
update: Dict[str, Any] = {
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"progress": 50,
|
||||
"error_message": None,
|
||||
"error_details": None,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"state_data.stems_restore": DELETE_FIELD,
|
||||
"state_data.regenerate_requests": requests,
|
||||
f"state_data.{REGENERATE_MARKER}": {
|
||||
"requested_by": requested_by,
|
||||
"requested_at": now.isoformat(),
|
||||
"source": source,
|
||||
"notify_customer": bool(notify_customer),
|
||||
"brand_code": brand_code,
|
||||
"after": after,
|
||||
"needs_stems": needs_stems,
|
||||
"review_token": getattr(job, "review_token", None),
|
||||
},
|
||||
# Stale screens/lyrics video are deleted below; drop their file_urls.
|
||||
"file_urls.screens": DELETE_FIELD,
|
||||
"file_urls.videos.with_vocals": DELETE_FIELD,
|
||||
"updated_at": now,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"timestamp": now.isoformat(),
|
||||
"message": message,
|
||||
"metadata": {
|
||||
"action": "regenerate_initiated",
|
||||
"initiated_by": requested_by,
|
||||
"source": source,
|
||||
"needs_stems": needs_stems,
|
||||
"after": after,
|
||||
},
|
||||
}]),
|
||||
}
|
||||
if after == AFTER_CHANGE_TO_PRIVATE:
|
||||
update["state_data.visibility_change_in_progress"] = True
|
||||
return update, {"brand_code": brand_code, "needs_stems": needs_stems, "message": message}
|
||||
|
||||
def _after_claim(self, job, context) -> None:
|
||||
log_to_job(job.job_id, _LOG_SOURCE, "INFO", context["message"])
|
||||
delete_regenerated_artifacts(self.storage, job.job_id)
|
||||
|
||||
def _fail_run(self, job_id: str, error: str, reason: str) -> None:
|
||||
logger.error(f"[job:{job_id}] {error}")
|
||||
try:
|
||||
self.job_manager.update_job(job_id, {
|
||||
"status": JobStatus.FAILED.value,
|
||||
"error_message": error,
|
||||
"error_details": {"stage": "regenerate", "reason": reason},
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
})
|
||||
log_to_job(job_id, _LOG_SOURCE, "ERROR", error)
|
||||
except Exception:
|
||||
logger.exception(f"[job:{job_id}] Failed to mark regenerate as failed")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"REGENERATE_MARKER",
|
||||
"RegenerateService",
|
||||
"RerenderConflictError",
|
||||
"RerenderError",
|
||||
"active_regenerate",
|
||||
"check_and_record_rate_limit",
|
||||
"clear_regenerate_update",
|
||||
"is_gcs_only_run",
|
||||
"regenerate_brand_code",
|
||||
"regenerate_suppresses_notifications",
|
||||
"renders_missing",
|
||||
"stems_need_restore",
|
||||
"validate_regenerate",
|
||||
]
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
Restore a job's separated stems after storage retention purged them.
|
||||
|
||||
The storage-retention job deletes the separated stems of old jobs (they're
|
||||
regenerable: re-run separation on the kept input audio) and stamps
|
||||
``stems_purged_at``. Every flow that rebuilds a completed job goes through the
|
||||
screens worker — regenerate, admin re-render, theme re-render, private->public
|
||||
visibility change, Edit — so the screens worker gates on this module: if the
|
||||
job's stems were purged it starts the audio-separation Cloud Run Job in RESTORE
|
||||
mode instead of generating screens, and the audio worker re-triggers the screens
|
||||
worker once the stems are back. Review (Edit flow) and the encoder then find the
|
||||
stems exactly where they always were.
|
||||
|
||||
``state_data.stems_restore = {status: running|failed, attempts, started_at}``
|
||||
tracks the restore; ``attempts`` bounds automatic re-runs.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STEMS_RESTORE_KEY = "stems_restore"
|
||||
MAX_AUTO_ATTEMPTS = 3
|
||||
STALE_RUNNING_SECONDS = 60 * 60
|
||||
|
||||
NOT_NEEDED = "not_needed"
|
||||
STARTED = "started"
|
||||
IN_PROGRESS = "in_progress"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
def restore_marker(job) -> dict:
|
||||
marker = (getattr(job, "state_data", None) or {}).get(STEMS_RESTORE_KEY)
|
||||
return marker if isinstance(marker, dict) else {}
|
||||
|
||||
|
||||
def _age_seconds(iso: Optional[str]) -> Optional[float]:
|
||||
if not iso:
|
||||
return None
|
||||
try:
|
||||
started = datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
if started.tzinfo is None:
|
||||
started = started.replace(tzinfo=timezone.utc)
|
||||
return (datetime.now(timezone.utc) - started).total_seconds()
|
||||
|
||||
|
||||
def is_restore_run(job) -> bool:
|
||||
"""True when the audio worker was started to restore purged stems.
|
||||
|
||||
Keyed on the marker existing (any status), not just ``running``: when a
|
||||
restore attempt fails, Cloud Run retries the task after the worker already
|
||||
marked it failed — that retry must still run in restore mode.
|
||||
"""
|
||||
from backend.services.regenerate_service import stems_need_restore
|
||||
return stems_need_restore(job) and bool(restore_marker(job))
|
||||
|
||||
|
||||
async def maybe_start_stems_restore(job, job_manager, job_log=None) -> str:
|
||||
"""Screens-worker gate. Returns NOT_NEEDED, STARTED, IN_PROGRESS or FAILED."""
|
||||
from backend.services.regenerate_service import stems_need_restore
|
||||
|
||||
if not stems_need_restore(job):
|
||||
return NOT_NEEDED
|
||||
job_id = job.job_id
|
||||
marker = restore_marker(job)
|
||||
if marker.get("status") == "running":
|
||||
age = _age_seconds(marker.get("started_at"))
|
||||
if age is not None and age < STALE_RUNNING_SECONDS:
|
||||
logger.info(f"[job:{job_id}] Stems restore already running; skipping duplicate screens dispatch")
|
||||
job_manager.update_job(job_id, {"state_data.screens_progress": DELETE_FIELD})
|
||||
return IN_PROGRESS
|
||||
attempts = int(marker.get("attempts") or 0)
|
||||
if attempts >= MAX_AUTO_ATTEMPTS:
|
||||
message = (
|
||||
"Couldn't restore this track's audio stems (archived to save space) after "
|
||||
f"{attempts} attempts. Retry the job to try again."
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.screens_progress": DELETE_FIELD})
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id, error_message=message,
|
||||
error_details={"stage": "stems_restore", "attempts": attempts},
|
||||
)
|
||||
return FAILED
|
||||
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
job_manager.update_job(job_id, {
|
||||
f"state_data.{STEMS_RESTORE_KEY}": {
|
||||
"status": "running", "attempts": attempts + 1, "started_at": now,
|
||||
},
|
||||
# This screens dispatch ends here (the restore re-triggers screens), so
|
||||
# drop the "running" idempotency mark /api/internal/workers/screens set —
|
||||
# otherwise the re-trigger is skipped as "already running". Duplicate
|
||||
# dispatches meanwhile are absorbed by the stems_restore marker.
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"message": "Restoring audio stems",
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
if job_log is not None:
|
||||
job_log.info("Stems were archived by storage retention: re-running audio separation first")
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_audio_worker(job_id)
|
||||
if not triggered:
|
||||
job_manager.update_job(job_id, {f"state_data.{STEMS_RESTORE_KEY}.status": "failed",
|
||||
"state_data.screens_progress": DELETE_FIELD})
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id,
|
||||
error_message="Couldn't start audio separation to restore this track's stems. Retry the job.",
|
||||
error_details={"stage": "stems_restore", "reason": "audio_trigger_failed"},
|
||||
)
|
||||
return FAILED
|
||||
logger.info(f"[job:{job_id}] Stems restore started (attempt {attempts + 1})")
|
||||
return STARTED
|
||||
|
||||
|
||||
async def complete_stems_restore(job_id: str, job_manager) -> bool:
|
||||
"""Audio worker (restore mode) finished: clear the markers and resume screens."""
|
||||
update = {
|
||||
"stems_purged_at": None,
|
||||
f"state_data.{STEMS_RESTORE_KEY}": DELETE_FIELD,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
}
|
||||
# A Cloud Run task retry succeeded after an earlier attempt marked the job
|
||||
# FAILED: put it back where the restore started so screens can continue.
|
||||
job = job_manager.get_job(job_id)
|
||||
status = getattr(getattr(job, "status", None), "value", getattr(job, "status", None))
|
||||
if status == "failed" and ((getattr(job, "error_details", None) or {}).get("stage")
|
||||
in ("audio_separation", "download_audio", "stems_restore")):
|
||||
update.update({"status": "lyrics_complete", "error_message": None, "error_details": None})
|
||||
job_manager.update_job(job_id, update)
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_screens_worker(job_id)
|
||||
if not triggered:
|
||||
logger.error(f"[job:{job_id}] Stems restored but the screens worker couldn't be triggered")
|
||||
return triggered
|
||||
|
||||
|
||||
def restore_stalled(job, now: Optional[datetime] = None) -> bool:
|
||||
"""A ``running`` restore whose audio job died without reporting back."""
|
||||
marker = restore_marker(job)
|
||||
if marker.get("status") != "running":
|
||||
return False
|
||||
age = _age_seconds(marker.get("started_at"))
|
||||
return age is not None and age > STALE_RUNNING_SECONDS
|
||||
|
||||
|
||||
def mark_restore_failed(job_id: str, job_manager) -> None:
|
||||
try:
|
||||
job_manager.update_job(job_id, {f"state_data.{STEMS_RESTORE_KEY}.status": "failed"})
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception(f"[job:{job_id}] Couldn't mark stems restore failed")
|
||||
@@ -0,0 +1,675 @@
|
||||
"""
|
||||
Storage retention: purge regenerable files from old completed jobs.
|
||||
|
||||
Policy (docs/archive/2026-10-03-gen-storage-retention-plan.md, approved by
|
||||
Andrew 2026-10-03). For jobs completed more than ``min_age_days`` (30) ago:
|
||||
|
||||
KEEP forever
|
||||
- ``input/*`` (incl. ``input/edited.flac``), ``lyrics/**``, ``style/**``,
|
||||
``review_sessions/**``, ``audio_edit*/**``, ``uploads/**``
|
||||
- the 720p final (``finals/*(Final Karaoke Lossy 720p).mp4`` and the
|
||||
canonical ``finals/lossy_720p_mp4.mp4`` copy) — the one ready-made download
|
||||
- ``packages/*`` (CDG/TXT zips), ``screens/*.png|jpg``, ``analysis/*``
|
||||
- user-made instrumentals: ``stems/custom_instrumental.*`` and the staged
|
||||
copies at the job root (``custom_instrumental.*`` / ``existing_instrumental.*``)
|
||||
— they hold user mute edits / uploads, which aren't stored anywhere else
|
||||
- ``stems/vocals_derived.*`` (cheap waveform helper of bring-your-own-
|
||||
instrumental jobs; separation doesn't recreate it)
|
||||
- anything not explicitly on the purge list (unknown files are kept)
|
||||
|
||||
PURGE (regenerated on demand by backend/services/regenerate_service.py)
|
||||
- every other ``finals/*``, ``videos/*``, ``previews/*``, ``encoded/*``,
|
||||
``quick/*.mp4``, ``screens/*.mov``, ``review-audio/*``
|
||||
- separated stems (``stems/*`` apart from the kept ones above) — only when the
|
||||
input audio is still in ``jobs/{id}/`` so separation can be re-run
|
||||
|
||||
Never touched
|
||||
- finalise-only jobs (their videos/screens/stems are user-uploaded SOURCES and
|
||||
they can't be regenerated), jobs whose input audio is gone (nothing could be
|
||||
re-rendered), jobs mid-edit / re-render / visibility change, jobs with a
|
||||
pending deferred YouTube upload, excluded tenants
|
||||
- anything outside ``jobs/{job_id}/``
|
||||
|
||||
The job walks Firestore (it knows each job's type) rather than using a bucket
|
||||
lifecycle rule. It is DRY-RUN by default (settings.storage_retention_dry_run):
|
||||
it then only writes a report (GCS JSON + log summary). Real runs record
|
||||
``renders_purged_at`` / ``stems_purged_at`` + a ``storage_purge`` manifest on the
|
||||
job and drop the purged entries from ``file_urls`` so the UI offers
|
||||
"Regenerate video". Idempotent, batched (``max_jobs``) with a resumable cursor.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
POLICY_VERSION = 1
|
||||
REPORT_PREFIX = "storage-retention/reports"
|
||||
STATE_COLLECTION = "storage_retention"
|
||||
STATE_DOC = "state"
|
||||
SCAN_PAGE_SIZE = 200
|
||||
# A purge claims the job for this long; a regenerate/edit started meanwhile waits.
|
||||
PURGE_IN_PROGRESS_KEY = "storage_purge_in_progress"
|
||||
PURGE_CLAIM_STALE_SECONDS = 30 * 60
|
||||
|
||||
# Purge categories that count as "renders" (vs stems).
|
||||
RENDER_CATEGORIES = frozenset({
|
||||
"finals", "videos", "previews", "encoded", "quick", "screens_mov", "review_audio",
|
||||
})
|
||||
STEM_CATEGORIES = frozenset({"stems"})
|
||||
|
||||
KEEP = "keep"
|
||||
PURGE = "purge"
|
||||
|
||||
_KEEP_PREFIXES = (
|
||||
"input/", "lyrics/", "style/", "review_sessions/", "audio_edit", "uploads/",
|
||||
"packages/", "analysis/",
|
||||
)
|
||||
_KEPT_STEM_STEMS = ("custom_instrumental", "vocals_derived")
|
||||
_ROOT_INSTRUMENTAL_STEMS = ("custom_instrumental", "existing_instrumental")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------
|
||||
# Policy (pure functions)
|
||||
# --------------------------------------------------------------------------------
|
||||
|
||||
def classify_file(rel_path: str, finalise_only: bool = False, stems_purgeable: bool = True) -> Tuple[str, str]:
|
||||
"""Return ``(KEEP|PURGE, category)`` for a path relative to ``jobs/{job_id}/``."""
|
||||
rel = rel_path.lstrip("/")
|
||||
name = os.path.basename(rel)
|
||||
stem = os.path.splitext(name)[0].lower()
|
||||
ext = os.path.splitext(name)[1].lower()
|
||||
|
||||
if "/" not in rel:
|
||||
if stem in _ROOT_INSTRUMENTAL_STEMS:
|
||||
return KEEP, "user_instrumental"
|
||||
return KEEP, "other"
|
||||
|
||||
top = rel.split("/", 1)[0]
|
||||
if rel.startswith(_KEEP_PREFIXES):
|
||||
return KEEP, top
|
||||
|
||||
if top == "finals":
|
||||
from backend.services.encoding_interface import classify_encoded_output
|
||||
if classify_encoded_output(name) == "mp4_720p":
|
||||
return KEEP, "final_720p"
|
||||
return PURGE, "finals"
|
||||
if top == "videos":
|
||||
# Finalise-only: the user uploaded videos/with_vocals.* (a source file).
|
||||
return (KEEP, "source_video") if finalise_only else (PURGE, "videos")
|
||||
if top == "previews":
|
||||
return PURGE, "previews"
|
||||
if top == "encoded":
|
||||
return PURGE, "encoded"
|
||||
if top == "quick":
|
||||
return (PURGE, "quick") if ext == ".mp4" else (KEEP, "quick_other")
|
||||
if top == "review-audio":
|
||||
return PURGE, "review_audio"
|
||||
if top == "screens":
|
||||
if ext == ".mov":
|
||||
return (KEEP, "source_screen") if finalise_only else (PURGE, "screens_mov")
|
||||
return KEEP, "screens_image"
|
||||
if top == "stems":
|
||||
if stem.startswith(_KEPT_STEM_STEMS):
|
||||
return KEEP, "user_instrumental" if stem.startswith("custom_instrumental") else "stems_kept"
|
||||
if finalise_only:
|
||||
return KEEP, "source_stem"
|
||||
if not stems_purgeable:
|
||||
return KEEP, "stems_unrecoverable"
|
||||
return PURGE, "stems"
|
||||
return KEEP, "other"
|
||||
|
||||
|
||||
def _parse_ts(value: Any) -> Optional[datetime]:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def completed_at(job: Dict[str, Any]) -> Optional[datetime]:
|
||||
"""When the job last completed: the newest ``complete`` timeline entry.
|
||||
|
||||
Every re-render / regenerate / edit appends a new one, so the 30-day window
|
||||
restarts whenever fresh finals are made. Falls back to ``updated_at``.
|
||||
"""
|
||||
latest = None
|
||||
for entry in job.get("timeline") or []:
|
||||
if not isinstance(entry, dict) or entry.get("status") != "complete":
|
||||
continue
|
||||
ts = _parse_ts(entry.get("timestamp"))
|
||||
if ts and (latest is None or ts > latest):
|
||||
latest = ts
|
||||
return latest or _parse_ts(job.get("updated_at"))
|
||||
|
||||
|
||||
def _input_path(job: Dict[str, Any]) -> Optional[str]:
|
||||
# Only input_media_gcs_path: it's what separation, render and regenerate read.
|
||||
path = job.get("input_media_gcs_path")
|
||||
if not isinstance(path, str) or not path:
|
||||
return None
|
||||
if path.startswith("gs://"):
|
||||
path = path.split("/", 3)[-1]
|
||||
return path
|
||||
|
||||
|
||||
def regenerable_reason(job: Dict[str, Any]) -> Optional[str]:
|
||||
"""Why a regenerate of this job couldn't run (so its renders must be kept)."""
|
||||
state_data = job.get("state_data") or {}
|
||||
if not state_data.get("instrumental_selection"):
|
||||
return "no_instrumental_selection"
|
||||
if not ((job.get("file_urls") or {}).get("lyrics") or {}).get("corrections"):
|
||||
return "no_reviewed_lyrics"
|
||||
if not job.get("theme_id"):
|
||||
return "no_theme"
|
||||
return None
|
||||
|
||||
|
||||
def job_skip_reason(
|
||||
job: Dict[str, Any],
|
||||
now: datetime,
|
||||
min_age_days: int,
|
||||
excluded_tenants: Iterable[str] = (),
|
||||
) -> Optional[str]:
|
||||
"""Why this job must not be purged (or None if it's a candidate)."""
|
||||
if job.get("status") != "complete":
|
||||
return "not_complete"
|
||||
if job.get("finalise_only"):
|
||||
return "finalise_only"
|
||||
if job.get("prep_only"):
|
||||
return "prep_only"
|
||||
if job.get("outputs_deleted_at"):
|
||||
return "outputs_deleted"
|
||||
tenant = job.get("tenant_id") or ""
|
||||
if tenant and tenant in set(excluded_tenants):
|
||||
return "excluded_tenant"
|
||||
state_data = job.get("state_data") or {}
|
||||
for marker in ("visibility_change_in_progress", "admin_rerender", "theme_rerender", "regenerate"):
|
||||
if state_data.get(marker):
|
||||
return f"active_{marker}"
|
||||
if state_data.get("youtube_upload_queued"):
|
||||
return "youtube_upload_queued"
|
||||
claim = _parse_ts(state_data.get(PURGE_IN_PROGRESS_KEY))
|
||||
if claim and (now - claim).total_seconds() < PURGE_CLAIM_STALE_SECONDS:
|
||||
return "purge_in_progress"
|
||||
done = completed_at(job)
|
||||
if done is None:
|
||||
return "no_completion_time"
|
||||
if now - done < timedelta(days=min_age_days):
|
||||
return "too_recent"
|
||||
# Only purge what a regenerate could rebuild.
|
||||
reason = regenerable_reason(job)
|
||||
if reason:
|
||||
return f"not_regenerable_{reason}"
|
||||
return None
|
||||
|
||||
|
||||
def purge_in_progress(job) -> bool:
|
||||
"""True while the retention job is deleting this job's files (Job model or dict)."""
|
||||
state_data = job.get("state_data") if isinstance(job, dict) else getattr(job, "state_data", None)
|
||||
claim = _parse_ts((state_data or {}).get(PURGE_IN_PROGRESS_KEY)) if isinstance(state_data, dict) else None
|
||||
return bool(claim) and (datetime.now(timezone.utc) - claim).total_seconds() < PURGE_CLAIM_STALE_SECONDS
|
||||
|
||||
|
||||
PURGE_IN_PROGRESS_MESSAGE = "This track's files are being archived right now. Try again in a few minutes."
|
||||
|
||||
|
||||
@dataclass
|
||||
class JobPlan:
|
||||
job_id: str
|
||||
purge: List[Tuple[str, int, str]] = field(default_factory=list) # (blob path, bytes, category)
|
||||
kept_bytes: int = 0
|
||||
stems_purgeable: bool = True
|
||||
stems_note: Optional[str] = None
|
||||
skip_reason: Optional[str] = None
|
||||
|
||||
@property
|
||||
def purge_bytes(self) -> int:
|
||||
return sum(size for _, size, _ in self.purge)
|
||||
|
||||
def bytes_by_category(self) -> Dict[str, int]:
|
||||
out: Counter = Counter()
|
||||
for _, size, category in self.purge:
|
||||
out[category] += size
|
||||
return dict(out)
|
||||
|
||||
@property
|
||||
def purges_renders(self) -> bool:
|
||||
return any(c in RENDER_CATEGORIES for _, _, c in self.purge)
|
||||
|
||||
@property
|
||||
def purges_stems(self) -> bool:
|
||||
return any(c in STEM_CATEGORIES for _, _, c in self.purge)
|
||||
|
||||
|
||||
def plan_job(job: Dict[str, Any], listing: List[Tuple[str, int]]) -> JobPlan:
|
||||
"""Decide what to purge for one (already eligible) job from its GCS listing."""
|
||||
job_id = job["job_id"]
|
||||
prefix = f"jobs/{job_id}/"
|
||||
plan = JobPlan(job_id=job_id)
|
||||
names = {name for name, _ in listing}
|
||||
|
||||
# Re-rendering needs the input audio (render worker + separation). If it's
|
||||
# gone (e.g. pre-persistence jobs whose input expired from uploads/), nothing
|
||||
# could ever be regenerated: keep everything.
|
||||
input_path = _input_path(job)
|
||||
if not input_path or not input_path.startswith(prefix) or input_path not in names:
|
||||
plan.skip_reason = "input_unavailable"
|
||||
return plan
|
||||
|
||||
finalise_only = bool(job.get("finalise_only"))
|
||||
# Bring-your-own-instrumental jobs never ran separation, so "re-separate"
|
||||
# isn't part of their pipeline — leave whatever stems they have.
|
||||
if job.get("existing_instrumental_gcs_path"):
|
||||
plan.stems_purgeable = False
|
||||
plan.stems_note = "existing_instrumental"
|
||||
|
||||
for name, size in listing:
|
||||
if not name.startswith(prefix): # defence in depth: never outside jobs/{id}/
|
||||
continue
|
||||
action, category = classify_file(
|
||||
name[len(prefix):], finalise_only=finalise_only, stems_purgeable=plan.stems_purgeable,
|
||||
)
|
||||
if action == PURGE:
|
||||
plan.purge.append((name, size, category))
|
||||
else:
|
||||
plan.kept_bytes += size
|
||||
return plan
|
||||
|
||||
|
||||
def file_url_deletions(file_urls: Dict[str, Any], purged_paths: Iterable[str]) -> List[str]:
|
||||
"""Firestore field paths under ``file_urls`` that reference purged blobs."""
|
||||
purged = set(purged_paths)
|
||||
|
||||
def norm(value: str) -> str:
|
||||
return value.split("/", 3)[-1] if value.startswith("gs://") else value
|
||||
|
||||
out: List[str] = []
|
||||
for category, entries in (file_urls or {}).items():
|
||||
if isinstance(entries, dict):
|
||||
for key, value in entries.items():
|
||||
if isinstance(value, str) and norm(value) in purged and _safe_key(category) and _safe_key(key):
|
||||
out.append(f"file_urls.{category}.{key}")
|
||||
elif isinstance(entries, str) and norm(entries) in purged and _safe_key(category):
|
||||
out.append(f"file_urls.{category}")
|
||||
return out
|
||||
|
||||
|
||||
_SAFE_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
|
||||
|
||||
def _safe_key(key: str) -> bool:
|
||||
return bool(_SAFE_KEY.match(str(key)))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------
|
||||
# Service
|
||||
# --------------------------------------------------------------------------------
|
||||
|
||||
def _run_in_transaction(db, fn):
|
||||
"""Run ``fn(transaction)`` in a Firestore transaction (retried on contention)."""
|
||||
from google.cloud import firestore
|
||||
return firestore.transactional(fn)(db.transaction())
|
||||
|
||||
|
||||
_PROJECTION = [
|
||||
"job_id", "status", "timeline", "updated_at", "finalise_only", "prep_only", "theme_id",
|
||||
"storage_purge.status", "state_data.instrumental_selection",
|
||||
"outputs_deleted_at", "tenant_id", "input_media_gcs_path", "file_urls",
|
||||
"existing_instrumental_gcs_path", "renders_purged_at", "stems_purged_at",
|
||||
"state_data.visibility_change_in_progress", "state_data.admin_rerender",
|
||||
"state_data.theme_rerender", "state_data.regenerate",
|
||||
"state_data.youtube_upload_queued", f"state_data.{PURGE_IN_PROGRESS_KEY}",
|
||||
]
|
||||
|
||||
|
||||
class StorageRetentionService:
|
||||
def __init__(self, db=None, storage=None, settings=None, job_manager=None):
|
||||
from backend.config import get_settings
|
||||
self.settings = settings or get_settings()
|
||||
if storage is None:
|
||||
from backend.services.storage_service import StorageService
|
||||
storage = StorageService()
|
||||
self.storage = storage
|
||||
if db is None:
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
db = FirestoreService().db
|
||||
self.db = db
|
||||
self._job_manager = job_manager
|
||||
|
||||
@property
|
||||
def jobs_collection(self):
|
||||
return self.db.collection(self.settings.firestore_collection)
|
||||
|
||||
# --- run ----------------------------------------------------------------------
|
||||
|
||||
def run(
|
||||
self,
|
||||
dry_run: Optional[bool] = None,
|
||||
job_ids: Optional[List[str]] = None,
|
||||
max_jobs: Optional[int] = None,
|
||||
min_age_days: Optional[int] = None,
|
||||
include_orphans: bool = False,
|
||||
report_path: Optional[str] = None,
|
||||
now: Optional[datetime] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Plan (and unless dry-run, execute) one retention pass. Returns the report.
|
||||
|
||||
- ``dry_run`` defaults to settings.storage_retention_dry_run (True).
|
||||
- ``job_ids`` scopes the pass to those jobs (no cursor).
|
||||
- Dry runs without ``max_jobs`` cover every completed job (full report);
|
||||
real runs purge at most ``max_jobs`` (settings default) per pass,
|
||||
resuming from the stored cursor.
|
||||
"""
|
||||
started = time.time()
|
||||
now = now or datetime.now(timezone.utc)
|
||||
dry_run = self.settings.storage_retention_dry_run if dry_run is None else bool(dry_run)
|
||||
min_age = self.settings.storage_retention_min_age_days if min_age_days is None else int(min_age_days)
|
||||
excluded = [t.strip() for t in (self.settings.storage_retention_excluded_tenants or "").split(",") if t.strip()]
|
||||
if max_jobs is None and not dry_run and not job_ids:
|
||||
max_jobs = self.settings.storage_retention_max_jobs_per_run
|
||||
use_cursor = not job_ids and not dry_run
|
||||
|
||||
report: Dict[str, Any] = {
|
||||
"policy_version": POLICY_VERSION,
|
||||
"dry_run": dry_run,
|
||||
"started_at": now.isoformat(),
|
||||
"min_age_days": min_age,
|
||||
"max_jobs": max_jobs,
|
||||
"excluded_tenants": excluded,
|
||||
"scoped_job_ids": job_ids or None,
|
||||
"jobs": [],
|
||||
"skipped": Counter(),
|
||||
"errors": [],
|
||||
}
|
||||
totals: Counter = Counter()
|
||||
processed = 0
|
||||
scanned = 0
|
||||
last_id = None
|
||||
exhausted = True
|
||||
|
||||
for job in self._iter_jobs(job_ids, use_cursor):
|
||||
if max_jobs is not None and processed >= max_jobs:
|
||||
exhausted = False
|
||||
break
|
||||
scanned += 1
|
||||
last_id = job.get("job_id")
|
||||
reason = job_skip_reason(job, now, min_age, excluded)
|
||||
if reason is None and self._already_purged(job):
|
||||
reason = "already_purged"
|
||||
if reason:
|
||||
report["skipped"][reason] += 1
|
||||
continue
|
||||
try:
|
||||
listing = self.storage.list_files_with_sizes(f"jobs/{job['job_id']}/")
|
||||
plan = plan_job(job, listing)
|
||||
except Exception as e: # noqa: BLE001 - one bad job never stops the pass
|
||||
logger.exception(f"[job:{job.get('job_id')}] storage retention: planning failed")
|
||||
report["errors"].append({"job_id": job.get("job_id"), "error": str(e)})
|
||||
continue
|
||||
if plan.skip_reason:
|
||||
report["skipped"][plan.skip_reason] += 1
|
||||
continue
|
||||
if not plan.purge:
|
||||
report["skipped"]["nothing_to_purge"] += 1
|
||||
continue
|
||||
|
||||
entry = {
|
||||
"job_id": plan.job_id,
|
||||
"tenant_id": job.get("tenant_id") or None,
|
||||
"completed_at": (completed_at(job) or now).isoformat(),
|
||||
"purge_bytes": plan.purge_bytes,
|
||||
"kept_bytes": plan.kept_bytes,
|
||||
"bytes_by_category": plan.bytes_by_category(),
|
||||
"stems_kept_reason": plan.stems_note,
|
||||
"files": [{"path": p, "bytes": s, "category": c} for p, s, c in plan.purge],
|
||||
}
|
||||
if not dry_run:
|
||||
try:
|
||||
entry["result"] = self._execute(job["job_id"], plan, now, min_age, excluded)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception(f"[job:{plan.job_id}] storage retention: purge failed")
|
||||
entry["result"] = {"status": "error", "error": str(e)}
|
||||
report["errors"].append({"job_id": plan.job_id, "error": str(e)})
|
||||
report["jobs"].append(entry)
|
||||
if not dry_run and entry["result"].get("status") != "purged":
|
||||
continue
|
||||
processed += 1
|
||||
for category, size in plan.bytes_by_category().items():
|
||||
totals[category] += size
|
||||
|
||||
if use_cursor:
|
||||
self._save_cursor(None if exhausted else last_id)
|
||||
|
||||
report["skipped"] = dict(report["skipped"])
|
||||
report["summary"] = {
|
||||
"jobs_scanned": scanned,
|
||||
"jobs_to_purge" if dry_run else "jobs_purged": processed,
|
||||
"bytes_total": sum(totals.values()),
|
||||
"gib_total": round(sum(totals.values()) / 2**30, 2),
|
||||
"gib_by_category": {k: round(v / 2**30, 2) for k, v in sorted(totals.items())},
|
||||
"bytes_by_category": dict(totals),
|
||||
"duration_seconds": round(time.time() - started, 1),
|
||||
}
|
||||
if include_orphans:
|
||||
try:
|
||||
report["orphans"] = self.orphan_job_folders()
|
||||
except Exception as e: # noqa: BLE001
|
||||
report["orphans"] = {"error": str(e)}
|
||||
|
||||
report["report_path"] = report_path or self.default_report_path(now, dry_run)
|
||||
try:
|
||||
self.storage.upload_json(report["report_path"], report)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"storage retention: failed to write report {report['report_path']}: {e}")
|
||||
report["report_write_error"] = str(e)
|
||||
s = report["summary"]
|
||||
logger.info(
|
||||
f"STORAGE_RETENTION {'DRY-RUN' if dry_run else 'RUN'} complete: scanned={scanned} "
|
||||
f"{'would_purge' if dry_run else 'purged'}={processed} jobs, {s['gib_total']} GiB "
|
||||
f"by_category={s['gib_by_category']} skipped={report['skipped']} "
|
||||
f"errors={len(report['errors'])} report=gs://{self.settings.gcs_bucket_name}/{report['report_path']}"
|
||||
)
|
||||
return report
|
||||
|
||||
@staticmethod
|
||||
def default_report_path(now: datetime, dry_run: bool) -> str:
|
||||
return f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-{'dry-run' if dry_run else 'run'}.json"
|
||||
|
||||
# --- helpers ------------------------------------------------------------------
|
||||
|
||||
def _already_purged(self, job: Dict[str, Any]) -> bool:
|
||||
"""Skip the GCS listing for jobs already purged since their last completion."""
|
||||
if ((job.get("storage_purge") or {}).get("status")) == "pending":
|
||||
return False # an interrupted purge: finish it
|
||||
renders = _parse_ts(job.get("renders_purged_at"))
|
||||
if not renders:
|
||||
return False
|
||||
done = completed_at(job)
|
||||
if done and done > renders:
|
||||
return False # regenerated since — eligible again after its own window
|
||||
stems = _parse_ts(job.get("stems_purged_at"))
|
||||
stems_done = stems is not None or bool(job.get("existing_instrumental_gcs_path"))
|
||||
return stems_done
|
||||
|
||||
def _iter_jobs(self, job_ids: Optional[List[str]], use_cursor: bool):
|
||||
if job_ids:
|
||||
for job_id in job_ids:
|
||||
snap = self.jobs_collection.document(job_id).get()
|
||||
if snap.exists:
|
||||
data = snap.to_dict() or {}
|
||||
data.setdefault("job_id", snap.id)
|
||||
yield data
|
||||
return
|
||||
|
||||
from google.cloud.firestore_v1.base_query import FieldFilter
|
||||
|
||||
cursor = self._load_cursor() if use_cursor else None
|
||||
while True:
|
||||
query = (
|
||||
self.jobs_collection
|
||||
.where(filter=FieldFilter("status", "==", "complete"))
|
||||
.order_by("__name__")
|
||||
.select(_PROJECTION)
|
||||
.limit(SCAN_PAGE_SIZE)
|
||||
)
|
||||
if cursor:
|
||||
query = query.start_after({"__name__": self.jobs_collection.document(cursor)})
|
||||
docs = list(query.stream())
|
||||
for snap in docs:
|
||||
data = snap.to_dict() or {}
|
||||
data.setdefault("job_id", snap.id)
|
||||
data["job_id"] = data.get("job_id") or snap.id
|
||||
yield data
|
||||
if len(docs) < SCAN_PAGE_SIZE:
|
||||
return
|
||||
cursor = docs[-1].id
|
||||
|
||||
def _state_ref(self):
|
||||
return self.db.collection(STATE_COLLECTION).document(STATE_DOC)
|
||||
|
||||
def _load_cursor(self) -> Optional[str]:
|
||||
try:
|
||||
snap = self._state_ref().get()
|
||||
return (snap.to_dict() or {}).get("cursor_job_id") if snap.exists else None
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"storage retention: couldn't load cursor: {e}")
|
||||
return None
|
||||
|
||||
def _save_cursor(self, job_id: Optional[str]) -> None:
|
||||
try:
|
||||
self._state_ref().set(
|
||||
{"cursor_job_id": job_id, "updated_at": datetime.now(timezone.utc)}, merge=True,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"storage retention: couldn't save cursor: {e}")
|
||||
|
||||
def _claim(self, job_id: str, plan: "JobPlan", now: datetime, min_age: int, excluded: List[str]) -> bool:
|
||||
"""Atomically re-check eligibility on the live doc and mark the purge in progress.
|
||||
|
||||
The purge markers (``renders_purged_at`` / ``stems_purged_at``) and a
|
||||
PENDING manifest are written HERE, before anything is deleted: if the
|
||||
run dies mid-way, regenerate still knows to rebuild (and re-separate),
|
||||
and the next pass finishes the job (``storage_purge.status == pending``).
|
||||
"""
|
||||
ref = self.jobs_collection.document(job_id)
|
||||
|
||||
def claim(transaction):
|
||||
snap = ref.get(transaction=transaction)
|
||||
if not snap.exists:
|
||||
return False
|
||||
data = snap.to_dict() or {}
|
||||
data.setdefault("job_id", job_id)
|
||||
if job_skip_reason(data, now, min_age, excluded):
|
||||
return False
|
||||
update: Dict[str, Any] = {
|
||||
f"state_data.{PURGE_IN_PROGRESS_KEY}": now.isoformat(),
|
||||
"storage_purge": {
|
||||
"status": "pending",
|
||||
"started_at": now.isoformat(),
|
||||
"policy_version": POLICY_VERSION,
|
||||
"planned_bytes": plan.purge_bytes,
|
||||
"planned_files": len(plan.purge),
|
||||
},
|
||||
}
|
||||
if plan.purges_renders:
|
||||
update["renders_purged_at"] = now
|
||||
if plan.purges_stems:
|
||||
update["stems_purged_at"] = now
|
||||
transaction.update(ref, update)
|
||||
return True
|
||||
|
||||
return _run_in_transaction(self.db, claim)
|
||||
|
||||
def _execute(self, job_id: str, plan: JobPlan, now: datetime, min_age: int, excluded: List[str]) -> Dict[str, Any]:
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
if not self._claim(job_id, plan, now, min_age, excluded):
|
||||
return {"status": "skipped", "reason": "no_longer_eligible"}
|
||||
|
||||
ref = self.jobs_collection.document(job_id)
|
||||
deleted: List[Tuple[str, int, str]] = []
|
||||
failures: List[Dict[str, str]] = []
|
||||
try:
|
||||
for path, size, category in plan.purge:
|
||||
if not path.startswith(f"jobs/{job_id}/"):
|
||||
continue
|
||||
try:
|
||||
self.storage.delete_file(path, ignore_missing=True)
|
||||
deleted.append((path, size, category))
|
||||
except Exception as e: # noqa: BLE001
|
||||
failures.append({"path": path, "error": str(e)})
|
||||
|
||||
snap = ref.get()
|
||||
file_urls = (snap.to_dict() or {}).get("file_urls") or {} if snap.exists else {}
|
||||
update: Dict[str, Any] = {f"state_data.{PURGE_IN_PROGRESS_KEY}": DELETE_FIELD}
|
||||
for field_path in file_url_deletions(file_urls, [p for p, _, _ in deleted]):
|
||||
update[field_path] = DELETE_FIELD
|
||||
by_category: Counter = Counter()
|
||||
for _, size, category in deleted:
|
||||
by_category[category] += size
|
||||
if any(c in RENDER_CATEGORIES for _, _, c in deleted):
|
||||
update["renders_purged_at"] = now
|
||||
if any(c in STEM_CATEGORIES for _, _, c in deleted):
|
||||
update["stems_purged_at"] = now
|
||||
update["storage_purge"] = {
|
||||
"status": "complete",
|
||||
"purged_at": now.isoformat(),
|
||||
"policy_version": POLICY_VERSION,
|
||||
"bytes": sum(by_category.values()),
|
||||
"bytes_by_category": dict(by_category),
|
||||
"files": [{"path": p, "bytes": s, "category": c} for p, s, c in deleted],
|
||||
"failures": failures,
|
||||
}
|
||||
ref.update(update)
|
||||
except Exception:
|
||||
try:
|
||||
ref.update({f"state_data.{PURGE_IN_PROGRESS_KEY}": DELETE_FIELD})
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise
|
||||
|
||||
try:
|
||||
from backend.services.firestore_service import log_to_job
|
||||
log_to_job(
|
||||
job_id, "storage-retention", "INFO",
|
||||
f"Storage retention purged {len(deleted)} regenerable files "
|
||||
f"({sum(by_category.values()) / 2**20:.0f} MiB); regenerate on demand",
|
||||
{"bytes_by_category": dict(by_category), "failures": failures},
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return {
|
||||
"status": "purged" if deleted else "skipped",
|
||||
"deleted": len(deleted),
|
||||
"failures": failures,
|
||||
}
|
||||
|
||||
# --- orphans (report only, never deleted) -------------------------------------
|
||||
|
||||
def orphan_job_folders(self) -> Dict[str, Any]:
|
||||
"""``jobs/{id}/`` folders with no Firestore job doc (report only)."""
|
||||
known = {snap.id for snap in self.jobs_collection.select(["status"]).stream()}
|
||||
sizes: Counter = Counter()
|
||||
for name, size in self.storage.list_files_with_sizes("jobs/"):
|
||||
parts = name.split("/")
|
||||
if len(parts) > 2 and parts[1] not in known:
|
||||
sizes[parts[1]] += size
|
||||
total = sum(sizes.values())
|
||||
return {
|
||||
"folders": len(sizes),
|
||||
"gib_total": round(total / 2**30, 2),
|
||||
"largest": [{"job_id": k, "gib": round(v / 2**30, 2)} for k, v in sizes.most_common(20)],
|
||||
}
|
||||
@@ -365,6 +365,14 @@ class StorageService:
|
||||
logger.error(f"Error listing files with prefix {prefix}: {e}")
|
||||
raise
|
||||
|
||||
def list_files_with_sizes(self, prefix: str) -> list:
|
||||
"""List ``(name, size_bytes)`` for every object under ``prefix``."""
|
||||
try:
|
||||
return [(blob.name, int(blob.size or 0)) for blob in self.bucket.list_blobs(prefix=prefix)]
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing files with prefix {prefix}: {e}")
|
||||
raise
|
||||
|
||||
def get_file_size(self, blob_path: str) -> Optional[int]:
|
||||
"""Size in bytes of a GCS object, or None if it doesn't exist."""
|
||||
blob = self.bucket.get_blob(blob_path)
|
||||
|
||||
@@ -77,6 +77,9 @@ def validate_rerender(job) -> Optional[str]:
|
||||
return f"Only finished tracks can be re-rendered (current status: {job.status})."
|
||||
if getattr(job, "outputs_deleted_at", None):
|
||||
return "This track's outputs were deleted, so it can't be re-rendered."
|
||||
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
|
||||
if purge_in_progress(job):
|
||||
return PURGE_IN_PROGRESS_MESSAGE
|
||||
if not getattr(job, "theme_id", None):
|
||||
return "This track wasn't made from a theme, so there's nothing to re-apply."
|
||||
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
|
||||
@@ -109,7 +112,12 @@ def rerender_brand_code(job) -> Optional[str]:
|
||||
return code
|
||||
# Admin re-render (only while its marker belongs to the current run).
|
||||
from backend.services.admin_rerender_service import admin_rerender_brand_code
|
||||
return admin_rerender_brand_code(job)
|
||||
code = admin_rerender_brand_code(job)
|
||||
if code:
|
||||
return code
|
||||
# GCS-only regenerate (storage retention): same brand code, nothing re-published.
|
||||
from backend.services.regenerate_service import regenerate_brand_code
|
||||
return regenerate_brand_code(job)
|
||||
|
||||
|
||||
def delete_regenerated_artifacts(storage: StorageService, job_id: str) -> None:
|
||||
|
||||
@@ -19,6 +19,7 @@ from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from google.cloud.firestore_v1 import Increment
|
||||
|
||||
from backend.utils.keyed_lock import user_lock
|
||||
from backend.config import get_settings
|
||||
from backend.models.user import (
|
||||
User,
|
||||
@@ -1056,7 +1057,14 @@ class UserService:
|
||||
# Credit Operations
|
||||
# =========================================================================
|
||||
|
||||
def add_credits(
|
||||
def add_credits(self, email: str, *args, **kwargs) -> Tuple[bool, int, str]:
|
||||
"""Add credits (see _add_credits_unlocked). Serialized per user within this
|
||||
instance — the read-modify-write isn't transactional, and threadpool route
|
||||
handlers could otherwise interleave two grants and lose one."""
|
||||
with user_lock(email):
|
||||
return self._add_credits_unlocked(email, *args, **kwargs)
|
||||
|
||||
def _add_credits_unlocked(
|
||||
self,
|
||||
email: str,
|
||||
amount: int,
|
||||
|
||||
@@ -53,7 +53,7 @@ class VisibilityChangeService:
|
||||
|
||||
return None
|
||||
|
||||
async def change_to_private(self, job_id: str, job, user_email: str) -> dict:
|
||||
async def change_to_private(self, job_id: str, job, user_email: str, regenerate_if_missing: bool = True) -> dict:
|
||||
"""
|
||||
Change a public job to private (fast path).
|
||||
|
||||
@@ -70,6 +70,23 @@ class VisibilityChangeService:
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
|
||||
|
||||
# Storage retention may have purged the big finals of an old job. The
|
||||
# private archive needs the full set, so regenerate them (GCS-only) first;
|
||||
# the video worker runs this change again once they're back.
|
||||
from backend.services.regenerate_service import AFTER_CHANGE_TO_PRIVATE, RegenerateService
|
||||
if regenerate_if_missing and getattr(job, "renders_purged_at", None):
|
||||
logger.info(f"[job:{job_id}] Finals missing (storage retention): regenerating before going private")
|
||||
await RegenerateService(self.job_manager).start(
|
||||
job, requested_by=user_email, source="visibility_change",
|
||||
notify_customer=False, after=AFTER_CHANGE_TO_PRIVATE,
|
||||
)
|
||||
return {
|
||||
"status": "processing",
|
||||
"message": "This track's video files were archived. They're being regenerated first, "
|
||||
"then the track will move to private automatically (about 15-30 minutes).",
|
||||
"reprocessing_required": True,
|
||||
}
|
||||
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
|
||||
|
||||
@@ -453,6 +453,52 @@ class WorkerService:
|
||||
)
|
||||
return False
|
||||
|
||||
async def trigger_storage_retention_job(
|
||||
self,
|
||||
dry_run: bool,
|
||||
report_path: str,
|
||||
max_jobs: Optional[int] = None,
|
||||
include_orphans: bool = False,
|
||||
) -> bool:
|
||||
"""Start the storage-retention pass as the ``storage-retention-job`` Cloud Run Job.
|
||||
|
||||
A full pass takes minutes; the API service throttles CPU outside requests
|
||||
and Cloudflare cuts requests at 100s, so it can't run in the request.
|
||||
"""
|
||||
args = ["--dry-run", "true" if dry_run else "false", "--report-path", report_path]
|
||||
if max_jobs is not None:
|
||||
args += ["--max-jobs", str(int(max_jobs))]
|
||||
if include_orphans:
|
||||
args.append("--include-orphans")
|
||||
if not self._use_cloud_tasks and not is_production():
|
||||
return self._run_worker_module_locally("storage_retention_worker", args, log_prefix="[storage-retention]")
|
||||
try:
|
||||
from google.cloud import run_v2
|
||||
|
||||
project = self.settings.google_cloud_project
|
||||
if not project:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger storage-retention-job")
|
||||
return False
|
||||
job_name = f"projects/{project}/locations/{self.settings.cpu_jobs_region}/jobs/storage-retention-job"
|
||||
request = run_v2.RunJobRequest(
|
||||
name=job_name,
|
||||
overrides=run_v2.RunJobRequest.Overrides(
|
||||
container_overrides=[
|
||||
run_v2.RunJobRequest.Overrides.ContainerOverride(
|
||||
args=["python", "-m", "backend.workers.storage_retention_worker", *args],
|
||||
)
|
||||
]
|
||||
),
|
||||
)
|
||||
operation = await self._run_job_with_retry(
|
||||
run_v2.JobsClient(), request, log_prefix="[storage-retention]"
|
||||
)
|
||||
logger.info(f"[storage-retention] Started Cloud Run Job storage-retention-job: {operation.metadata}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"[storage-retention] Failed to trigger storage-retention-job: {e}", exc_info=True)
|
||||
return False
|
||||
|
||||
async def trigger_audio_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger audio separation worker.
|
||||
|
||||
@@ -101,6 +101,22 @@ async def test_matching_durations_do_not_cancel(mocks):
|
||||
await _call(_auth(email=None, is_admin=True))
|
||||
|
||||
mocks["job_manager"].cancel_job.assert_not_called()
|
||||
update = mocks["job_manager"].update_job.call_args[0][1]
|
||||
# uploads/ expires after 7 days: the instrumental is persisted at the job root.
|
||||
assert update["existing_instrumental_gcs_path"] == "jobs/job-1/custom_instrumental.wav"
|
||||
mocks["storage"].copy_blob.assert_any_call(
|
||||
"uploads/job-1/audio/existing_instrumental.wav", "jobs/job-1/custom_instrumental.wav"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_instrumental_persist_failure_keeps_upload_path(mocks):
|
||||
mocks["storage"].copy_blob.side_effect = RuntimeError("gcs down")
|
||||
with patch("backend.api.routes.file_upload._validate_audio_durations",
|
||||
new_callable=AsyncMock, return_value=(True, 200.0, 200.2)), \
|
||||
patch("backend.api.routes.file_upload.get_credential_manager"):
|
||||
await _call(_auth(email=None, is_admin=True))
|
||||
|
||||
update = mocks["job_manager"].update_job.call_args[0][1]
|
||||
assert update["existing_instrumental_gcs_path"] == "uploads/job-1/audio/existing_instrumental.wav"
|
||||
|
||||
@@ -119,7 +135,8 @@ async def test_alignable_mismatch_uses_conformed_instrumental(mocks):
|
||||
conform.assert_awaited_once()
|
||||
mocks["job_manager"].cancel_job.assert_not_called()
|
||||
update = mocks["job_manager"].update_job.call_args[0][1]
|
||||
assert update["existing_instrumental_gcs_path"] == conformed
|
||||
assert update["existing_instrumental_gcs_path"] == "jobs/job-1/custom_instrumental.flac"
|
||||
mocks["storage"].copy_blob.assert_any_call(conformed, "jobs/job-1/custom_instrumental.flac")
|
||||
mocks["job_manager"].update_state_data.assert_any_call("job-1", "instrumental_conformed", info)
|
||||
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ if 'FIRESTORE_EMULATOR_HOST' not in os.environ:
|
||||
os.environ.setdefault('GCS_BUCKET_NAME', 'test-bucket')
|
||||
os.environ.setdefault('FIRESTORE_COLLECTION', 'jobs')
|
||||
os.environ.setdefault('ENVIRONMENT', 'test')
|
||||
os.environ.setdefault('LOOP_WATCHDOG_ENABLED', 'false')
|
||||
# Gemini Developer API key: never let a test fall through to Secret Manager.
|
||||
os.environ.setdefault('GEMINI_API_KEY', 'test-gemini-key')
|
||||
|
||||
|
||||
@@ -281,8 +281,7 @@ class TestSubmitFeedbackEmailIntegration:
|
||||
)
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
result = (submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# Verify email notification was called with matching args
|
||||
@@ -338,8 +337,7 @@ class TestSubmitFeedbackEmailIntegration:
|
||||
)
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
result = (submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# User still gets credits even though email failed
|
||||
|
||||
@@ -32,7 +32,8 @@ def _make_job(
|
||||
title="Test Song",
|
||||
outputs_deleted_at=None,
|
||||
dropbox_path="/Tracks-Organized",
|
||||
file_urls={"finals": {"lossy_4k_mp4": "gs://test/4k.mp4"}},
|
||||
file_urls={"finals": {"lossy_4k_mp4": "gs://test/4k.mp4", "lossy_720p_mp4": "gs://test/720p.mp4"}},
|
||||
renders_purged_at=None,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -92,3 +92,118 @@ class TestReportClientEvent:
|
||||
assert all(len(v) <= 200 for v in capped.values())
|
||||
assert client_events._capped_detail(None) == {}
|
||||
assert client_events._capped_detail("not a dict") == {}
|
||||
|
||||
|
||||
class TestIdentityAndNewFields:
|
||||
"""2026-10-03: identity is resolved server-side from the bearer token."""
|
||||
|
||||
def _auth_result(self, email, is_admin=False, valid=True):
|
||||
r = MagicMock()
|
||||
r.is_valid = valid
|
||||
r.user_email = email
|
||||
r.is_admin = is_admin
|
||||
return r
|
||||
|
||||
def _post_with_token(self, client, auth_result, **overrides):
|
||||
svc = MagicMock()
|
||||
svc.validate_token_full.return_value = auth_result
|
||||
with patch("backend.services.auth_service.get_auth_service", return_value=svc):
|
||||
resp = client.post(
|
||||
"/api/client-events",
|
||||
json=_event(**overrides),
|
||||
headers={"Authorization": "Bearer sess-token"},
|
||||
)
|
||||
return resp, svc
|
||||
|
||||
def _doc(self, db):
|
||||
(doc,) = db.collection.return_value.add.call_args[0]
|
||||
return doc
|
||||
|
||||
def test_anonymous_has_no_identity(self, client, fresh_limiter_and_db):
|
||||
client.post("/api/client-events", json=_event())
|
||||
doc = self._doc(fresh_limiter_and_db)
|
||||
assert doc["user_email"] is None
|
||||
assert doc["is_admin"] is False
|
||||
assert doc["source"] == "client"
|
||||
|
||||
def test_client_supplied_email_is_ignored(self, client, fresh_limiter_and_db):
|
||||
client.post("/api/client-events", json=_event(user_email="spoof@example.com"))
|
||||
assert self._doc(fresh_limiter_and_db)["user_email"] is None
|
||||
|
||||
def test_token_resolves_customer(self, client, fresh_limiter_and_db):
|
||||
resp, svc = self._post_with_token(client, self._auth_result("fan@gmail.com"))
|
||||
assert resp.status_code == 202
|
||||
svc.validate_token_full.assert_called_once_with("sess-token")
|
||||
doc = self._doc(fresh_limiter_and_db)
|
||||
assert doc["user_email"] == "fan@gmail.com"
|
||||
assert (doc["is_admin"], doc["is_internal"], doc["is_test"]) == (False, False, False)
|
||||
|
||||
def test_token_resolves_admin_internal(self, client, fresh_limiter_and_db):
|
||||
self._post_with_token(client, self._auth_result("andrew@nomadkaraoke.com", is_admin=True))
|
||||
doc = self._doc(fresh_limiter_and_db)
|
||||
assert doc["is_admin"] is True
|
||||
assert doc["is_internal"] is True
|
||||
|
||||
def test_token_resolves_test_account(self, client, fresh_limiter_and_db):
|
||||
self._post_with_token(client, self._auth_result("k1.test-1@inbox.testmail.app"))
|
||||
assert self._doc(fresh_limiter_and_db)["is_test"] is True
|
||||
|
||||
def test_invalid_token_is_anonymous_not_error(self, client, fresh_limiter_and_db):
|
||||
resp, _ = self._post_with_token(client, self._auth_result(None, valid=False))
|
||||
assert resp.status_code == 202
|
||||
assert self._doc(fresh_limiter_and_db)["user_email"] is None
|
||||
|
||||
def test_auth_service_crash_is_anonymous_not_error(self, client, fresh_limiter_and_db):
|
||||
with patch("backend.services.auth_service.get_auth_service", side_effect=RuntimeError("x")):
|
||||
resp = client.post(
|
||||
"/api/client-events", json=_event(), headers={"Authorization": "Bearer t"}
|
||||
)
|
||||
assert resp.status_code == 202
|
||||
assert self._doc(fresh_limiter_and_db)["user_email"] is None
|
||||
|
||||
def test_fingerprint_tab_episode_and_tenant_persisted(self, client, fresh_limiter_and_db):
|
||||
client.post(
|
||||
"/api/client-events",
|
||||
json=_event(
|
||||
url="https://randy-vild.nomadkaraoke.com/en/app/",
|
||||
device_fingerprint="635a6066abc",
|
||||
tab_id="tab-1",
|
||||
episode_id="ep-1",
|
||||
),
|
||||
)
|
||||
doc = self._doc(fresh_limiter_and_db)
|
||||
assert doc["device_fingerprint"] == "635a6066abc"
|
||||
assert doc["tab_id"] == "tab-1"
|
||||
assert doc["episode_id"] == "ep-1"
|
||||
assert doc["tenant"] == "randy-vild"
|
||||
|
||||
def test_consumer_host_has_no_tenant(self, client, fresh_limiter_and_db):
|
||||
client.post("/api/client-events", json=_event())
|
||||
assert self._doc(fresh_limiter_and_db)["tenant"] is None
|
||||
|
||||
def test_banner_recovered_accepted(self, client, fresh_limiter_and_db):
|
||||
resp = client.post(
|
||||
"/api/client-events",
|
||||
json=_event(type="banner_recovered", detail={"duration_ms": 31000, "peak_status": "unavailable"}),
|
||||
)
|
||||
assert resp.status_code == 202
|
||||
assert self._doc(fresh_limiter_and_db)["type"] == "banner_recovered"
|
||||
|
||||
def test_server_loop_stall_rejected_from_clients(self, client):
|
||||
resp = client.post("/api/client-events", json=_event(type="server_loop_stall"))
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url,expected",
|
||||
[
|
||||
("https://randy-vild.nomadkaraoke.com/en/app/", "randy-vild"),
|
||||
("https://vocalstar.nomadkaraoke.com/x", "vocalstar"),
|
||||
("https://gen.nomadkaraoke.com/en/app/", None),
|
||||
("https://nomadkaraoke.com/", None),
|
||||
("https://evil.com/?x=.nomadkaraoke.com", None),
|
||||
("", None),
|
||||
],
|
||||
)
|
||||
def test_tenant_from_url(url, expected):
|
||||
assert client_events._tenant_from_url(url) == expected
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Unit tests for scripts/client_events_report.py (summary logic only)."""
|
||||
import importlib.util
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
_spec = importlib.util.spec_from_file_location(
|
||||
"client_events_report",
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "client_events_report.py",
|
||||
)
|
||||
report = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(report)
|
||||
|
||||
T = datetime(2026, 10, 3, 12, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def _ev(type_, **kw):
|
||||
return {"type": type_, "created_at": T, "source": "client", **kw}
|
||||
|
||||
|
||||
def test_excludes_admin_internal_test_by_default():
|
||||
events = [
|
||||
_ev("banner_unavailable", user_email="fan@gmail.com"),
|
||||
_ev("banner_unavailable", user_email="andrew@nomadkaraoke.com", is_admin=True, is_internal=True),
|
||||
_ev("banner_reconnecting", user_email="x@inbox.testmail.app", is_test=True),
|
||||
]
|
||||
out = report.summarise(events, include_noise=False)
|
||||
assert "excluded 2" in out
|
||||
assert "fan@gmail.com" in out
|
||||
assert "andrew@" not in out
|
||||
out_all = report.summarise(events, include_noise=True)
|
||||
assert "andrew@nomadkaraoke.com" in out_all
|
||||
|
||||
|
||||
def test_episode_durations_and_stall_culprits():
|
||||
events = [
|
||||
_ev("banner_recovered", detail={"duration_ms": 30000, "peak_status": "unavailable"}),
|
||||
_ev("banner_recovered", detail={"duration_ms": 12000, "peak_status": "reconnecting"}),
|
||||
{"type": "server_loop_stall", "source": "server", "created_at": T,
|
||||
"detail": {"duration_ms": 31000, "culprit": "backend/workers/screens_worker.py:774 in x"}},
|
||||
]
|
||||
out = report.summarise(events, include_noise=False)
|
||||
assert "2 recovered" in out
|
||||
assert "max 30.0s" in out
|
||||
assert "Server event-loop stalls >=5s: 1" in out
|
||||
assert "screens_worker.py:774" in out
|
||||
|
||||
|
||||
def test_anonymous_devices_grouped_by_fingerprint_and_legacy_tenant():
|
||||
events = [
|
||||
_ev("banner_unavailable", device_fingerprint="abcdef123456", url="https://randy-vild.nomadkaraoke.com/en/app/"),
|
||||
_ev("banner_unavailable", url="https://gen.nomadkaraoke.com/en/app/"),
|
||||
]
|
||||
out = report.summarise(events, include_noise=False)
|
||||
assert "fp:abcdef1234" in out
|
||||
assert "(anonymous)" in out
|
||||
assert "randy-vild=1" in out
|
||||
@@ -120,7 +120,7 @@ async def test_list_community_requests_maps_all_statuses():
|
||||
svc.list_all.return_value = [published, open_req]
|
||||
with patch("backend.services.song_request_service.get_song_request_service",
|
||||
MagicMock(return_value=svc)):
|
||||
res = await list_community_requests(auth_data=("admin", None, 0))
|
||||
res = list_community_requests(auth_data=("admin", None, 0))
|
||||
assert [r.id for r in res.requests] == ["pub", "op"]
|
||||
pub = res.requests[0]
|
||||
assert pub.status == "published"
|
||||
|
||||
@@ -332,3 +332,38 @@ class TestEditPreservesTempoLabel:
|
||||
_, payload = self._edit(client, mock_job_manager, complete_job, auth_headers,
|
||||
{"title": "Better Name"}, None, "Test Song")
|
||||
assert payload["title"] == "Better Name"
|
||||
|
||||
|
||||
class TestEditStemsPurgedTrack:
|
||||
"""Storage retention purged the stems: review needs them, so the edit goes
|
||||
through the screens worker (which re-separates first) instead of straight
|
||||
to AWAITING_REVIEW."""
|
||||
|
||||
def test_stems_purged_edit_restores_stems_before_review(
|
||||
self, client, complete_job, mock_job_manager, mock_worker_service, auth_headers
|
||||
):
|
||||
complete_job.stems_purged_at = datetime.now(UTC)
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["metadata_updated"] is False
|
||||
mock_job_manager.transition_to_state.assert_called_once_with(
|
||||
"test-edit-123",
|
||||
JobStatus.LYRICS_COMPLETE,
|
||||
progress=55,
|
||||
message="Restoring audio stems before review",
|
||||
)
|
||||
mock_worker_service.trigger_screens_worker.assert_called_once_with("test-edit-123")
|
||||
|
||||
def test_bring_your_own_instrumental_job_goes_straight_to_review(
|
||||
self, client, complete_job, mock_job_manager, auth_headers
|
||||
):
|
||||
complete_job.stems_purged_at = datetime.now(UTC)
|
||||
complete_job.existing_instrumental_gcs_path = "jobs/test-edit-123/custom_instrumental.wav"
|
||||
client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
assert mock_job_manager.transition_to_state.call_args.args[1] == JobStatus.AWAITING_REVIEW
|
||||
|
||||
|
||||
def test_edit_refused_while_purge_in_progress(self, client, complete_job, auth_headers):
|
||||
complete_job.state_data["storage_purge_in_progress"] = datetime.now(UTC).isoformat()
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 409
|
||||
@@ -0,0 +1,163 @@
|
||||
"""The heavy steps of the screens worker / stale-review cron must not block the loop.
|
||||
|
||||
Prod (2026-10-03 analysis): these ran synchronously on the single uvicorn event
|
||||
loop and froze every request on the instance for 20-45s, surfacing as the
|
||||
"servers unavailable" banner. Each test patches the heavy sync call with a
|
||||
``time.sleep`` and asserts a concurrent ticker keeps ticking meanwhile — i.e.
|
||||
the work really runs in a worker thread.
|
||||
"""
|
||||
import asyncio
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
BLOCK_S = 0.4
|
||||
|
||||
|
||||
async def _ticks_during(coro) -> int:
|
||||
"""Run coro while counting 20ms ticks; a blocked loop yields ~0 ticks."""
|
||||
ticks = 0
|
||||
done = asyncio.Event()
|
||||
|
||||
async def ticker():
|
||||
nonlocal ticks
|
||||
while not done.is_set():
|
||||
await asyncio.sleep(0.02)
|
||||
ticks += 1
|
||||
|
||||
t = asyncio.create_task(ticker())
|
||||
try:
|
||||
await coro
|
||||
finally:
|
||||
done.set()
|
||||
await t
|
||||
return ticks
|
||||
|
||||
|
||||
def _sleep(*_a, **_kw):
|
||||
time.sleep(BLOCK_S)
|
||||
return {}
|
||||
|
||||
|
||||
# Blocked for BLOCK_S → ~0-1 ticks; offloaded → ~BLOCK_S/0.02 = 20 ticks.
|
||||
MIN_TICKS = 8
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_screens_runs_off_loop(tmp_path):
|
||||
from backend.workers import screens_worker
|
||||
|
||||
title = tmp_path / "t.png"
|
||||
end = tmp_path / "e.png"
|
||||
title.write_bytes(b"x")
|
||||
end.write_bytes(b"x")
|
||||
storage = MagicMock()
|
||||
storage.upload_file.side_effect = _sleep
|
||||
ticks = await _ticks_during(
|
||||
screens_worker._upload_screens("j1", MagicMock(), storage, str(title), str(end))
|
||||
)
|
||||
assert storage.upload_file.call_count == 2
|
||||
assert ticks >= MIN_TICKS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_review_audio_transcode_runs_off_loop():
|
||||
from backend.workers import screens_worker
|
||||
|
||||
jm = MagicMock()
|
||||
job = MagicMock()
|
||||
job.file_urls = {}
|
||||
job.input_media_gcs_path = None
|
||||
jm.get_job.return_value = job
|
||||
with patch("backend.services.audio_transcoding_service.AudioTranscodingService") as svc, \
|
||||
patch("backend.utils.stems.vocals_stem_path", return_value=None):
|
||||
svc.return_value.prepare_review_audio_for_job.side_effect = _sleep
|
||||
ticks = await _ticks_during(
|
||||
screens_worker._transcode_review_audio("j1", jm, MagicMock())
|
||||
)
|
||||
svc.return_value.prepare_review_audio_for_job.assert_called_once()
|
||||
assert ticks >= MIN_TICKS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_title_screen_render_runs_off_loop(tmp_path):
|
||||
from backend.workers import screens_worker
|
||||
|
||||
gen = MagicMock()
|
||||
gen.create_title_video.side_effect = _sleep
|
||||
style = MagicMock()
|
||||
style.get_intro_format.return_value = {}
|
||||
job = MagicMock(artist="A", title="B")
|
||||
ticks = await _ticks_during(
|
||||
screens_worker._generate_title_screen("j1", job, gen, style, str(tmp_path))
|
||||
)
|
||||
gen.create_title_video.assert_called_once()
|
||||
assert ticks >= MIN_TICKS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_style_config_load_runs_off_loop(tmp_path):
|
||||
from backend.workers import style_helper
|
||||
|
||||
job = MagicMock(job_id="j1", style_assets={}, style_params_gcs_path=None)
|
||||
|
||||
def slow_load(**_kw):
|
||||
time.sleep(BLOCK_S)
|
||||
return (None, {})
|
||||
|
||||
with patch.object(style_helper, "load_styles_from_gcs", side_effect=slow_load):
|
||||
cfg = style_helper.StyleConfig(job, MagicMock(), str(tmp_path))
|
||||
ticks = await _ticks_during(cfg.load())
|
||||
assert ticks >= MIN_TICKS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_review_cron_runs_off_loop():
|
||||
from backend.workers import stale_review_processor
|
||||
|
||||
with patch.object(stale_review_processor, "process_stale_reviews_sync", side_effect=_sleep):
|
||||
ticks = await _ticks_during(stale_review_processor.process_stale_reviews())
|
||||
assert ticks >= MIN_TICKS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_health_encoding_status_builds_service_off_loop():
|
||||
"""A cold get_encoding_service() (imports compute_v1, ~10s) must not block the loop."""
|
||||
from backend.api.routes import health
|
||||
|
||||
def slow_build():
|
||||
time.sleep(BLOCK_S)
|
||||
svc = MagicMock()
|
||||
svc.is_enabled = False
|
||||
return svc
|
||||
|
||||
with patch.object(health, "get_encoding_service", side_effect=slow_build):
|
||||
ticks = await _ticks_during(health.check_encoding_worker_status())
|
||||
assert ticks >= MIN_TICKS
|
||||
|
||||
|
||||
def test_get_encoding_service_builds_once_under_concurrency():
|
||||
import threading
|
||||
|
||||
from backend.services import encoding_service as es
|
||||
|
||||
builds = []
|
||||
|
||||
class FakeService:
|
||||
def __init__(self):
|
||||
builds.append(1)
|
||||
time.sleep(0.05)
|
||||
|
||||
def set_worker_manager(self, m):
|
||||
pass
|
||||
|
||||
with patch.object(es, "_encoding_service", None), patch.object(es, "EncodingService", FakeService):
|
||||
results = []
|
||||
threads = [threading.Thread(target=lambda: results.append(es.get_encoding_service())) for _ in range(5)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
assert len(builds) == 1
|
||||
assert len({id(r) for r in results}) == 1
|
||||
@@ -1373,8 +1373,7 @@ class TestValidateJobUrlEndpoint:
|
||||
req = MagicMock()
|
||||
req.headers = {}
|
||||
with patch("backend.api.routes.file_upload.get_locale_from_request", return_value="en"):
|
||||
return asyncio.run(
|
||||
validate_job_url(
|
||||
return (validate_job_url(
|
||||
request=req,
|
||||
body=ValidateUrlRequest(url=url),
|
||||
auth_result=MagicMock(),
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
Instrumental resolution fixes (storage-retention work, 2026-10-03):
|
||||
|
||||
- the GCE encoder's with-backing / clean lookups fail loudly instead of
|
||||
silently falling back to another instrumental;
|
||||
- a user-supplied ("existing") instrumental recorded under uploads/ (7-day
|
||||
lifecycle) resolves to its kept job-root copy, repointing the job.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.gce_encoding.main import resolve_instrumental
|
||||
from backend.utils.existing_instrumental import persistent_instrumental_path, resolve_existing_instrumental
|
||||
|
||||
|
||||
def _touch(root: Path, *names):
|
||||
for name in names:
|
||||
path = root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"x")
|
||||
|
||||
|
||||
class TestEncoderLookupIsStrict:
|
||||
def test_with_backing_found(self, tmp_path):
|
||||
_touch(tmp_path, "stems/instrumental_clean.flac", "stems/instrumental_with_backing.flac")
|
||||
assert resolve_instrumental(tmp_path, {"instrumental_selection": "with_backing"}).name == \
|
||||
"instrumental_with_backing.flac"
|
||||
|
||||
def test_with_backing_missing_does_not_fall_back_to_clean(self, tmp_path):
|
||||
_touch(tmp_path, "stems/instrumental_clean.flac", "custom_instrumental.flac")
|
||||
assert resolve_instrumental(tmp_path, {"instrumental_selection": "with_backing"}) is None
|
||||
|
||||
def test_legacy_named_backing_file_still_found(self, tmp_path):
|
||||
_touch(tmp_path, "Artist - Title (Instrumental Backing).flac")
|
||||
assert resolve_instrumental(tmp_path, {"instrumental_selection": "with_backing"}) is not None
|
||||
|
||||
def test_clean_found(self, tmp_path):
|
||||
_touch(tmp_path, "stems/instrumental_clean.flac", "stems/instrumental_with_backing.flac")
|
||||
assert resolve_instrumental(tmp_path, {"instrumental_selection": "clean"}).name == "instrumental_clean.flac"
|
||||
|
||||
@pytest.mark.parametrize("other", [
|
||||
"stems/instrumental_with_backing.flac", "custom_instrumental.flac", "stems/custom_instrumental.flac",
|
||||
])
|
||||
def test_clean_missing_does_not_fall_back(self, tmp_path, other):
|
||||
_touch(tmp_path, other)
|
||||
assert resolve_instrumental(tmp_path, {"instrumental_selection": "clean"}) is None
|
||||
|
||||
def test_legacy_named_clean_file_still_found(self, tmp_path):
|
||||
_touch(tmp_path, "Artist - Title (Instrumental Clean).flac")
|
||||
assert resolve_instrumental(tmp_path, {"instrumental_selection": "clean"}) is not None
|
||||
|
||||
|
||||
class TestExistingInstrumentalResolution:
|
||||
def _job(self, path="uploads/job1/audio/existing_instrumental.wav"):
|
||||
return SimpleNamespace(job_id="job1", existing_instrumental_gcs_path=path)
|
||||
|
||||
def test_persistent_path(self):
|
||||
assert persistent_instrumental_path("job1", "uploads/job1/audio/existing_instrumental.wav") == \
|
||||
"jobs/job1/custom_instrumental.wav"
|
||||
assert persistent_instrumental_path("job1", "uploads/job1/conformed/existing_instrumental.flac") == \
|
||||
"jobs/job1/custom_instrumental.flac"
|
||||
|
||||
def test_recorded_path_used_when_present(self):
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = True
|
||||
jm = MagicMock()
|
||||
assert resolve_existing_instrumental(self._job(), storage, jm) == "uploads/job1/audio/existing_instrumental.wav"
|
||||
jm.update_job.assert_not_called()
|
||||
|
||||
def test_expired_upload_falls_back_to_staged_copy_and_repoints(self):
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = False
|
||||
storage.list_files.return_value = [
|
||||
"jobs/job1/input/song.flac", "jobs/job1/stems/custom_instrumental.flac",
|
||||
"jobs/job1/custom_instrumental.wav",
|
||||
]
|
||||
jm, log = MagicMock(), MagicMock()
|
||||
assert resolve_existing_instrumental(self._job(), storage, jm, log) == "jobs/job1/custom_instrumental.wav"
|
||||
jm.update_job.assert_called_once_with("job1", {"existing_instrumental_gcs_path": "jobs/job1/custom_instrumental.wav"})
|
||||
log.warning.assert_called_once()
|
||||
|
||||
def test_legacy_existing_instrumental_staged_name(self):
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = False
|
||||
storage.list_files.return_value = ["jobs/job1/existing_instrumental.mp3"]
|
||||
assert resolve_existing_instrumental(self._job(), storage) == "jobs/job1/existing_instrumental.mp3"
|
||||
|
||||
def test_nothing_staged_keeps_recorded_path(self):
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = False
|
||||
storage.list_files.return_value = ["jobs/job1/stems/custom_instrumental.flac"]
|
||||
jm = MagicMock()
|
||||
assert resolve_existing_instrumental(self._job(), storage, jm) == "uploads/job1/audio/existing_instrumental.wav"
|
||||
jm.update_job.assert_not_called()
|
||||
|
||||
def test_no_existing_instrumental(self):
|
||||
assert resolve_existing_instrumental(self._job(path=None), MagicMock()) is None
|
||||
|
||||
|
||||
class TestOrchestratorStagingRepoints:
|
||||
@pytest.mark.asyncio
|
||||
async def test_staging_from_uploads_repoints_job(self):
|
||||
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
|
||||
|
||||
config = OrchestratorConfig(
|
||||
job_id="job1", artist="A", title="T", title_video_path="", karaoke_video_path="",
|
||||
instrumental_audio_path="", existing_instrumental_gcs_path="uploads/job1/audio/existing_instrumental.wav",
|
||||
)
|
||||
jm, storage = MagicMock(), MagicMock()
|
||||
orch = VideoWorkerOrchestrator(config=config, job_manager=jm, storage=storage)
|
||||
backend = MagicMock()
|
||||
backend.name = "gce"
|
||||
backend.encode = MagicMock(side_effect=RuntimeError("stop after staging"))
|
||||
orch._get_encoding_backend = MagicMock(return_value=backend)
|
||||
|
||||
async def boom(*args, **kwargs):
|
||||
raise RuntimeError("stop after staging")
|
||||
|
||||
from unittest.mock import patch
|
||||
with patch("backend.services.encoding_service.run_with_lost_job_resubmit", side_effect=boom):
|
||||
with pytest.raises(RuntimeError):
|
||||
await orch._run_encoding()
|
||||
storage.copy_blob.assert_called_once_with(
|
||||
"uploads/job1/audio/existing_instrumental.wav", "jobs/job1/custom_instrumental.wav")
|
||||
jm.update_job.assert_any_call("job1", {"existing_instrumental_gcs_path": "jobs/job1/custom_instrumental.wav"})
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_already_persisted_path_is_not_recopied(self):
|
||||
from unittest.mock import patch
|
||||
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
|
||||
|
||||
config = OrchestratorConfig(
|
||||
job_id="job1", artist="A", title="T", title_video_path="", karaoke_video_path="",
|
||||
instrumental_audio_path="", existing_instrumental_gcs_path="jobs/job1/custom_instrumental.wav",
|
||||
)
|
||||
jm, storage = MagicMock(), MagicMock()
|
||||
orch = VideoWorkerOrchestrator(config=config, job_manager=jm, storage=storage)
|
||||
backend = MagicMock()
|
||||
backend.name = "gce"
|
||||
orch._get_encoding_backend = MagicMock(return_value=backend)
|
||||
|
||||
async def boom(*args, **kwargs):
|
||||
raise RuntimeError("stop")
|
||||
|
||||
with patch("backend.services.encoding_service.run_with_lost_job_resubmit", side_effect=boom):
|
||||
with pytest.raises(RuntimeError):
|
||||
await orch._run_encoding()
|
||||
storage.copy_blob.assert_not_called()
|
||||
@@ -167,6 +167,60 @@ class TestScreensWorkerEndpoint:
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
class TestScreensWorkerInlineInCloudTasksMode:
|
||||
"""Prod (Cloud Tasks) runs screens INLINE so CPU stays allocated and the
|
||||
heavy steps run in worker threads instead of a post-response BackgroundTask."""
|
||||
|
||||
def _settings(self, enable_cloud_tasks):
|
||||
s = MagicMock()
|
||||
s.enable_cloud_tasks = enable_cloud_tasks
|
||||
return s
|
||||
|
||||
def test_cloud_tasks_mode_awaits_worker_inline(self, client, auth_headers):
|
||||
import backend.api.routes.internal as internal_mod
|
||||
with patch('backend.config.get_settings', return_value=self._settings(True)):
|
||||
internal_mod.generate_screens.reset_mock()
|
||||
internal_mod.generate_screens.return_value = True
|
||||
response = client.post(
|
||||
"/api/internal/workers/screens", headers=auth_headers, json={"job_id": "test123"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "completed"
|
||||
internal_mod.generate_screens.assert_awaited_once_with("test123")
|
||||
|
||||
def test_cloud_tasks_mode_worker_failure_still_200(self, client, auth_headers):
|
||||
"""A handled failure must not return non-2xx (Cloud Tasks would re-run it)."""
|
||||
import backend.api.routes.internal as internal_mod
|
||||
with patch('backend.config.get_settings', return_value=self._settings(True)):
|
||||
internal_mod.generate_screens.return_value = False
|
||||
response = client.post(
|
||||
"/api/internal/workers/screens", headers=auth_headers, json={"job_id": "test123"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "failed"
|
||||
|
||||
def test_cloud_tasks_mode_worker_exception_still_200(self, client, auth_headers):
|
||||
import backend.api.routes.internal as internal_mod
|
||||
with patch('backend.config.get_settings', return_value=self._settings(True)):
|
||||
internal_mod.generate_screens.side_effect = RuntimeError("boom")
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/internal/workers/screens", headers=auth_headers, json={"job_id": "test123"}
|
||||
)
|
||||
finally:
|
||||
internal_mod.generate_screens.side_effect = None
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "failed"
|
||||
|
||||
def test_direct_http_mode_keeps_background_task(self, client, auth_headers):
|
||||
with patch('backend.config.get_settings', return_value=self._settings(False)):
|
||||
response = client.post(
|
||||
"/api/internal/workers/screens", headers=auth_headers, json={"job_id": "test123"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "started"
|
||||
|
||||
|
||||
class TestVideoWorkerEndpoint:
|
||||
"""Tests for POST /api/internal/workers/video."""
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Per-key locks restore per-instance serialization for threadpool route handlers."""
|
||||
import threading
|
||||
import time
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from backend.utils.keyed_lock import KeyedLocks
|
||||
|
||||
|
||||
def test_same_key_serializes_different_keys_dont():
|
||||
locks = KeyedLocks()
|
||||
order = []
|
||||
|
||||
def worker(key, tag):
|
||||
with locks.hold(key):
|
||||
order.append(f"{tag}-in")
|
||||
time.sleep(0.1)
|
||||
order.append(f"{tag}-out")
|
||||
|
||||
t1 = threading.Thread(target=worker, args=("job1", "a"))
|
||||
t2 = threading.Thread(target=worker, args=("job1", "b"))
|
||||
t1.start(); time.sleep(0.02); t2.start()
|
||||
t1.join(); t2.join()
|
||||
assert order == ["a-in", "a-out", "b-in", "b-out"]
|
||||
|
||||
start = time.monotonic()
|
||||
t3 = threading.Thread(target=worker, args=("x", "c"))
|
||||
t4 = threading.Thread(target=worker, args=("y", "d"))
|
||||
t3.start(); t4.start(); t3.join(); t4.join()
|
||||
assert time.monotonic() - start < 0.18 # ran in parallel
|
||||
|
||||
|
||||
def test_reentrant_and_cleans_up():
|
||||
locks = KeyedLocks()
|
||||
with locks.hold("k"):
|
||||
with locks.hold("k"):
|
||||
pass
|
||||
assert locks._locks == {} and locks._refs == {}
|
||||
|
||||
|
||||
def test_concurrent_cancel_refunds_once():
|
||||
"""Two threads cancelling the same job: the second must see CANCELLED and no-op."""
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services import job_manager as jm_mod
|
||||
|
||||
state = {"status": JobStatus.AWAITING_REVIEW}
|
||||
jm = jm_mod.JobManager.__new__(jm_mod.JobManager)
|
||||
|
||||
def get_job(_id):
|
||||
time.sleep(0.05) # widen the check-then-write window
|
||||
job = MagicMock()
|
||||
job.status = state["status"]
|
||||
return job
|
||||
|
||||
def update_job_status(job_id, status, message):
|
||||
state["status"] = status
|
||||
|
||||
jm.get_job = get_job
|
||||
jm.update_job_status = update_job_status
|
||||
jm._refund_credit_for_job = MagicMock()
|
||||
|
||||
results = []
|
||||
threads = [threading.Thread(target=lambda: results.append(jm.cancel_job("j1"))) for _ in range(2)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
assert sorted(results) == [False, True]
|
||||
jm._refund_credit_for_job.assert_called_once()
|
||||
@@ -44,7 +44,7 @@ async def _call_summary(auth: AuthResult):
|
||||
patch("backend.api.routes.jobs.job_manager") as mock_jm:
|
||||
# Return a fresh copy each call so pruning doesn't mutate shared state.
|
||||
mock_jm.list_jobs_summary.return_value = [dict(j) for j in JOBS]
|
||||
return await list_jobs(request, fields="summary", auth_result=auth)
|
||||
return list_jobs(request, fields="summary", auth_result=auth)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Tests for the event-loop stall watchdog (backend/services/loop_watchdog.py)."""
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.services.loop_watchdog import LoopWatchdog, _format_stack
|
||||
|
||||
|
||||
def _blocking_culprit_function(seconds: float) -> None:
|
||||
time.sleep(seconds) # deliberately blocks the event loop
|
||||
|
||||
|
||||
class FakeClock:
|
||||
def __init__(self):
|
||||
self.t = 1000.0
|
||||
|
||||
def __call__(self):
|
||||
return self.t
|
||||
|
||||
|
||||
class TestCheckStateMachine:
|
||||
"""Drive check() with a fake clock — no threads, fully deterministic."""
|
||||
|
||||
def _wd(self, **kw):
|
||||
clock = FakeClock()
|
||||
recorded = []
|
||||
wd = LoopWatchdog(clock=clock, recorder=recorded.append, **kw)
|
||||
wd._loop_thread_id = None # no real frames in these tests
|
||||
return wd, clock, recorded
|
||||
|
||||
def test_no_stall_when_ticking(self, caplog):
|
||||
wd, clock, recorded = self._wd()
|
||||
for _ in range(10):
|
||||
clock.t += 0.25
|
||||
wd._last_tick = clock.t
|
||||
wd.check()
|
||||
assert not wd._in_stall
|
||||
assert recorded == []
|
||||
assert "EVENT_LOOP_STALL" not in caplog.text
|
||||
|
||||
def test_short_stall_logged_not_recorded(self, caplog):
|
||||
caplog.set_level(logging.WARNING)
|
||||
wd, clock, recorded = self._wd()
|
||||
wd._last_tick = clock.t
|
||||
clock.t += 2.0
|
||||
wd.check()
|
||||
assert wd._in_stall
|
||||
clock.t += 0.25
|
||||
wd._last_tick = clock.t # heartbeat resumes
|
||||
wd.check()
|
||||
assert not wd._in_stall
|
||||
assert "EVENT_LOOP_STALL ended duration_ms=2000" in caplog.text
|
||||
assert recorded == [] # below 5s record threshold
|
||||
ended = [r for r in caplog.records if "ended" in r.getMessage()]
|
||||
assert ended[0].levelno == logging.WARNING
|
||||
|
||||
def test_long_stall_recorded_and_error(self, caplog):
|
||||
caplog.set_level(logging.WARNING)
|
||||
wd, clock, recorded = self._wd()
|
||||
wd._last_tick = clock.t
|
||||
for step in (1.0, 5.0, 12.0):
|
||||
clock.t = 1000.0 + step
|
||||
wd.check()
|
||||
clock.t = 1000.0 + 12.25
|
||||
wd._last_tick = clock.t
|
||||
wd.check()
|
||||
assert len(recorded) == 1
|
||||
assert recorded[0]["duration_ms"] == 12000
|
||||
ended = [r for r in caplog.records if "ended" in r.getMessage()]
|
||||
assert ended[0].levelno == logging.ERROR
|
||||
|
||||
def test_sub_threshold_gap_ignored(self, caplog):
|
||||
wd, clock, recorded = self._wd()
|
||||
wd._last_tick = clock.t
|
||||
clock.t += 0.9
|
||||
wd.check()
|
||||
assert not wd._in_stall
|
||||
|
||||
|
||||
class TestRealLoop:
|
||||
"""End-to-end: a real blocking call on the loop is detected with its stack."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_detects_blocking_call_with_stack(self, caplog):
|
||||
caplog.set_level(logging.WARNING, logger="backend.services.loop_watchdog")
|
||||
recorded = []
|
||||
wd = LoopWatchdog(
|
||||
tick_s=0.05,
|
||||
stall_threshold_s=0.3,
|
||||
record_threshold_s=0.5,
|
||||
error_threshold_s=5.0,
|
||||
sample_at_s=(0.3,),
|
||||
recorder=recorded.append,
|
||||
)
|
||||
wd.start()
|
||||
try:
|
||||
await asyncio.sleep(0.15) # let the heartbeat run
|
||||
_blocking_culprit_function(0.8)
|
||||
await asyncio.sleep(0.3) # let the loop resume and the thread notice
|
||||
finally:
|
||||
await wd.stop()
|
||||
|
||||
assert "_blocking_culprit_function" in caplog.text
|
||||
assert len(recorded) == 1
|
||||
assert recorded[0]["duration_ms"] >= 500
|
||||
assert "_blocking_culprit_function" in recorded[0]["culprit"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_quiet_when_loop_stays_responsive(self, caplog):
|
||||
caplog.set_level(logging.WARNING, logger="backend.services.loop_watchdog")
|
||||
wd = LoopWatchdog(tick_s=0.05, stall_threshold_s=0.3)
|
||||
wd.start()
|
||||
try:
|
||||
await asyncio.to_thread(time.sleep, 0.6) # offloaded — loop free
|
||||
finally:
|
||||
await wd.stop()
|
||||
assert "EVENT_LOOP_STALL" not in caplog.text
|
||||
|
||||
|
||||
def test_format_stack_none():
|
||||
assert _format_stack(None) == ("", "")
|
||||
|
||||
|
||||
class TestIdleGapSuppression:
|
||||
"""CPU-throttled idle instances: the watchdog thread can wake before the
|
||||
heartbeat, see a big gap, but the loop is parked in select() — not blocked."""
|
||||
|
||||
def _run_gap(self, idle: bool, caplog):
|
||||
caplog.set_level(logging.DEBUG, logger="backend.services.loop_watchdog")
|
||||
clock = FakeClock()
|
||||
recorded = []
|
||||
wd = LoopWatchdog(clock=clock, recorder=recorded.append)
|
||||
wd._loop_thread_id = 12345
|
||||
with patch("backend.services.loop_watchdog._is_idle_frame", return_value=idle), \
|
||||
patch("backend.services.loop_watchdog.sys._current_frames", return_value={12345: None}):
|
||||
wd._last_tick = clock.t
|
||||
for step in (1.0, 5.0, 15.0, 40.0):
|
||||
clock.t = 1000.0 + step
|
||||
wd.check()
|
||||
clock.t = 1000.0 + 40.25
|
||||
wd._last_tick = clock.t
|
||||
wd.check()
|
||||
return recorded
|
||||
|
||||
def test_all_idle_samples_are_not_a_stall(self, caplog):
|
||||
recorded = self._run_gap(idle=True, caplog=caplog)
|
||||
assert recorded == []
|
||||
assert "EVENT_LOOP_STALL ended" not in caplog.text
|
||||
assert "ignored idle gap" in caplog.text
|
||||
|
||||
def test_non_idle_samples_are_a_stall(self, caplog):
|
||||
recorded = self._run_gap(idle=False, caplog=caplog)
|
||||
assert len(recorded) == 1
|
||||
assert "EVENT_LOOP_STALL ended" in caplog.text
|
||||
|
||||
|
||||
def test_is_idle_frame_detects_parked_selector():
|
||||
"""A thread blocked in selectors' select() is classified idle; a busy one isn't."""
|
||||
import selectors
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
|
||||
from backend.services.loop_watchdog import _is_idle_frame
|
||||
|
||||
a, b = socket.socketpair()
|
||||
sel = selectors.DefaultSelector()
|
||||
sel.register(a, selectors.EVENT_READ)
|
||||
started = threading.Event()
|
||||
|
||||
def park():
|
||||
started.set()
|
||||
sel.select(timeout=2)
|
||||
|
||||
t = threading.Thread(target=park)
|
||||
t.start()
|
||||
started.wait()
|
||||
time.sleep(0.2)
|
||||
try:
|
||||
assert _is_idle_frame(sys._current_frames()[t.ident]) is True
|
||||
assert _is_idle_frame(sys._current_frames()[threading.get_ident()]) is False
|
||||
finally:
|
||||
b.send(b"x")
|
||||
t.join()
|
||||
sel.close()
|
||||
a.close()
|
||||
b.close()
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Guard: no FastAPI route may be ``async def`` without awaiting anything.
|
||||
|
||||
The API runs one uvicorn process with one event loop per Cloud Run instance.
|
||||
An ``async def`` handler runs ON that loop, so every sync Firestore / GCS /
|
||||
HTTP / email / LLM call inside it freezes every other request on the instance
|
||||
(users see the "Reconnecting" / "servers unavailable" banner). A plain ``def``
|
||||
handler is run by FastAPI in its threadpool instead. On 2026-10-03, 168
|
||||
handlers were async-without-await; 161 were converted (trivial no-call ones like health checks stay async) and this test keeps it
|
||||
that way.
|
||||
|
||||
Fix a failure by making the handler a plain ``def`` (FastAPI then runs it in
|
||||
the threadpool), or, if it genuinely needs to be async, ``await`` its blocking
|
||||
work via ``asyncio.to_thread(...)``.
|
||||
"""
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
ROUTE_FILES = sorted((BACKEND / "api" / "routes").glob("*.py")) + [BACKEND / "main.py"]
|
||||
|
||||
HTTP_VERBS = {"get", "post", "put", "patch", "delete", "head", "options", "api_route"}
|
||||
|
||||
|
||||
def _awaits_directly(fn: ast.AsyncFunctionDef) -> bool:
|
||||
"""True if fn's own body (excluding nested function scopes) awaits."""
|
||||
stack = list(fn.body)
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if isinstance(node, (ast.Await, ast.AsyncFor, ast.AsyncWith)):
|
||||
return True
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
|
||||
continue
|
||||
stack.extend(ast.iter_child_nodes(node))
|
||||
return False
|
||||
|
||||
|
||||
_LOOP_APIS = {"create_task", "ensure_future", "get_running_loop", "get_event_loop"}
|
||||
|
||||
|
||||
def _uses_loop_api(fn) -> bool:
|
||||
"""True if fn's own body calls a running-loop API (asyncio.create_task etc.).
|
||||
|
||||
Such a handler genuinely needs to run ON the loop: in FastAPI's threadpool
|
||||
there is no running loop, so create_task raises (or, if the RuntimeError is
|
||||
swallowed, the work is silently dropped).
|
||||
"""
|
||||
stack = list(fn.body)
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
|
||||
continue
|
||||
if isinstance(node, ast.Attribute) and node.attr in _LOOP_APIS:
|
||||
return True
|
||||
stack.extend(ast.iter_child_nodes(node))
|
||||
return False
|
||||
|
||||
|
||||
def _is_route(fn) -> bool:
|
||||
return any(
|
||||
isinstance(d, ast.Call)
|
||||
and isinstance(d.func, ast.Attribute)
|
||||
and d.func.attr in HTTP_VERBS
|
||||
for d in fn.decorator_list
|
||||
)
|
||||
|
||||
|
||||
def _is_trivial(fn) -> bool:
|
||||
"""No calls at all in the body (e.g. a health check returning a literal dict) —
|
||||
can't block, and keeping it async means it never waits for a threadpool slot."""
|
||||
return not any(isinstance(c, ast.Call) for stmt in fn.body for c in ast.walk(stmt))
|
||||
|
||||
|
||||
def find_offenders(source: str) -> list[str]:
|
||||
"""async routes that never await (and don't need the loop, and aren't trivial)."""
|
||||
tree = ast.parse(source)
|
||||
return [
|
||||
n.name
|
||||
for n in ast.walk(tree)
|
||||
if isinstance(n, ast.AsyncFunctionDef)
|
||||
and _is_route(n)
|
||||
and not _awaits_directly(n)
|
||||
and not _uses_loop_api(n)
|
||||
and not _is_trivial(n)
|
||||
]
|
||||
|
||||
|
||||
def find_loopless_sync_routes(source: str) -> list[str]:
|
||||
"""Plain-def routes that call a running-loop API — broken in the threadpool."""
|
||||
tree = ast.parse(source)
|
||||
return [
|
||||
n.name
|
||||
for n in ast.walk(tree)
|
||||
if isinstance(n, ast.FunctionDef) and _is_route(n) and _uses_loop_api(n)
|
||||
]
|
||||
|
||||
|
||||
def test_no_async_route_without_await():
|
||||
offenders = []
|
||||
for path in ROUTE_FILES:
|
||||
for name in find_offenders(path.read_text()):
|
||||
offenders.append(f"{path.relative_to(BACKEND.parent)}::{name}")
|
||||
assert not offenders, (
|
||||
"These routes are `async def` but never await, so their sync work blocks the "
|
||||
"event loop for every request. Make them plain `def` (FastAPI runs them in "
|
||||
"its threadpool) or await blocking work via asyncio.to_thread:\n "
|
||||
+ "\n ".join(offenders)
|
||||
)
|
||||
|
||||
|
||||
def test_no_sync_route_uses_running_loop_apis():
|
||||
offenders = []
|
||||
for path in ROUTE_FILES:
|
||||
for name in find_loopless_sync_routes(path.read_text()):
|
||||
offenders.append(f"{path.relative_to(BACKEND.parent)}::{name}")
|
||||
assert not offenders, (
|
||||
"These plain-`def` routes call asyncio.create_task/get_running_loop, which "
|
||||
"fails (or silently no-ops) in FastAPI's threadpool. Keep them `async def`:\n "
|
||||
+ "\n ".join(offenders)
|
||||
)
|
||||
|
||||
|
||||
def find_awaited_sync_routes(source: str) -> list[str]:
|
||||
"""`await some_sync_route(...)` within the same module — a TypeError at runtime
|
||||
(awaiting the return value), usually swallowed by a broad except."""
|
||||
tree = ast.parse(source)
|
||||
sync_routes = {
|
||||
n.name for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and _is_route(n)
|
||||
}
|
||||
hits = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Await) and isinstance(node.value, ast.Call):
|
||||
fn = node.value.func
|
||||
# Bare names only: `await svc.health_check()` is a different object's
|
||||
# (async) method that merely shares a route's name.
|
||||
if isinstance(fn, ast.Name) and fn.id in sync_routes:
|
||||
hits.append(fn.id)
|
||||
return hits
|
||||
|
||||
|
||||
def test_no_await_of_sync_route_handlers():
|
||||
offenders = []
|
||||
for path in ROUTE_FILES:
|
||||
for name in find_awaited_sync_routes(path.read_text()):
|
||||
offenders.append(f"{path.relative_to(BACKEND.parent)}::await {name}(...)")
|
||||
assert not offenders, (
|
||||
"These code paths `await` a plain-`def` route handler (TypeError at runtime). "
|
||||
"Call it via `await asyncio.to_thread(handler, ...)` instead:\n "
|
||||
+ "\n ".join(offenders)
|
||||
)
|
||||
|
||||
|
||||
def test_detector_flags_and_allows_correctly():
|
||||
src = '''
|
||||
@router.get("/a")
|
||||
async def bad(): return db.get()
|
||||
|
||||
@router.get("/b")
|
||||
async def good():
|
||||
return await asyncio.to_thread(db.get)
|
||||
|
||||
@router.post("/c")
|
||||
def sync_ok(): return db.get()
|
||||
|
||||
@router.get("/health")
|
||||
async def trivial(): return {"status": "ok"}
|
||||
|
||||
@router.post("/d")
|
||||
async def nested_only():
|
||||
async def _bg():
|
||||
await x()
|
||||
tasks.add_task(_bg)
|
||||
|
||||
async def not_a_route(): return 1
|
||||
|
||||
@router.post("/e")
|
||||
async def spawns_task():
|
||||
async def _bg():
|
||||
await x()
|
||||
asyncio.create_task(_bg())
|
||||
|
||||
@router.post("/f")
|
||||
def sync_spawns_task():
|
||||
asyncio.get_running_loop().create_task(x())
|
||||
'''
|
||||
assert sorted(find_offenders(src)) == ["bad", "nested_only"]
|
||||
assert find_loopless_sync_routes(src) == ["sync_spawns_task"]
|
||||
caller = src + '''
|
||||
async def helper():
|
||||
await sync_ok()
|
||||
await asyncio.to_thread(sync_ok)
|
||||
await client.sync_ok()
|
||||
'''
|
||||
assert find_awaited_sync_routes(caller) == ["sync_ok"]
|
||||
@@ -69,10 +69,11 @@ def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=
|
||||
where.stream.side_effect = [
|
||||
iter(downloading or []), iter(rendering or []), iter(review_complete or []),
|
||||
]
|
||||
# Two .limit().stream() calls in order: download_pending_retry, then downloading
|
||||
# (lost-screens-trigger sweep, bounded by SCREENS_RECOVERY_SCAN_LIMIT)
|
||||
# Three .limit().stream() calls in order: download_pending_retry, then downloading
|
||||
# (lost-screens-trigger sweep, bounded by SCREENS_RECOVERY_SCAN_LIMIT), then
|
||||
# lyrics_complete (stalled storage-retention stems restore)
|
||||
where.limit.return_value.stream.side_effect = [
|
||||
iter(pending or []), iter(downloading_prep or []),
|
||||
iter(pending or []), iter(downloading_prep or []), iter([]),
|
||||
]
|
||||
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
|
||||
@@ -0,0 +1,991 @@
|
||||
"""
|
||||
Tests for the storage-retention "Regenerate video" flow.
|
||||
|
||||
Covers backend/services/regenerate_service.py (validation, atomic claim, marker,
|
||||
rate limits, trigger/failure handling), the stems-restore gate
|
||||
(backend/services/stems_restore.py) and the audio worker's restore hand-off,
|
||||
the GCS-only video pipeline (orchestrator + video worker completion), the
|
||||
customer/admin endpoints, the archived-download 410, the internal retention
|
||||
endpoint guards, the public->private visibility chain and the edit/retry
|
||||
handling of stems-purged jobs.
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services import regenerate_service as rs
|
||||
from backend.services.regenerate_service import (
|
||||
RegenerateService,
|
||||
active_regenerate,
|
||||
check_and_record_rate_limit,
|
||||
clear_regenerate_update,
|
||||
is_gcs_only_run,
|
||||
renders_missing,
|
||||
stems_need_restore,
|
||||
validate_regenerate,
|
||||
)
|
||||
from backend.services.theme_rerender_service import RerenderConflictError, RerenderError, rerender_brand_code
|
||||
|
||||
PURGED = datetime(2026, 9, 1, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def _job(**overrides):
|
||||
fields = dict(
|
||||
job_id="job123",
|
||||
status="complete",
|
||||
tenant_id=None,
|
||||
user_email="customer@example.com",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
is_private=False,
|
||||
outputs_deleted_at=None,
|
||||
prep_only=False,
|
||||
finalise_only=False,
|
||||
review_token="tok-1",
|
||||
input_media_gcs_path="jobs/job123/input/song.flac",
|
||||
existing_instrumental_gcs_path=None,
|
||||
theme_id="nomad",
|
||||
renders_purged_at=PURGED,
|
||||
stems_purged_at=PURGED,
|
||||
state_data={
|
||||
"instrumental_selection": "with_backing",
|
||||
"brand_code": "NOMAD-1234",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=abc",
|
||||
},
|
||||
file_urls={
|
||||
"lyrics": {"corrections": "jobs/job123/lyrics/corrections.json"},
|
||||
"finals": {"lossy_720p_mp4": "jobs/job123/finals/lossy_720p_mp4.mp4"},
|
||||
},
|
||||
)
|
||||
fields.update(overrides)
|
||||
return SimpleNamespace(**fields)
|
||||
|
||||
|
||||
# --- helpers ------------------------------------------------------------------------
|
||||
|
||||
class TestHelpers:
|
||||
def test_renders_missing(self):
|
||||
assert renders_missing(_job())
|
||||
full = {"lossy_4k_mp4": "a", "lossy_720p_mp4": "b"}
|
||||
assert not renders_missing(_job(renders_purged_at=None, file_urls={"finals": full}))
|
||||
assert renders_missing(_job(renders_purged_at=None, file_urls={"finals": {"lossy_720p_mp4": "b"}}))
|
||||
assert renders_missing(_job(renders_purged_at=None, file_urls={}))
|
||||
|
||||
def test_stems_need_restore(self):
|
||||
assert stems_need_restore(_job())
|
||||
assert not stems_need_restore(_job(stems_purged_at=None))
|
||||
assert not stems_need_restore(_job(existing_instrumental_gcs_path="jobs/job123/custom_instrumental.wav"))
|
||||
assert not stems_need_restore(_job(finalise_only=True))
|
||||
|
||||
def test_marker_is_scoped_to_review_token(self):
|
||||
job = _job(state_data={"regenerate": {"review_token": "tok-1", "brand_code": "NOMAD-1"}})
|
||||
assert active_regenerate(job) and is_gcs_only_run(job)
|
||||
assert rerender_brand_code(job) == "NOMAD-1"
|
||||
stale = _job(review_token="tok-2", state_data={"regenerate": {"review_token": "tok-1"}})
|
||||
assert active_regenerate(stale) == {} and not is_gcs_only_run(stale)
|
||||
assert clear_regenerate_update(stale) == {"state_data.regenerate": DELETE_FIELD}
|
||||
assert clear_regenerate_update(_job()) == {}
|
||||
|
||||
def test_admin_marker_clear_also_drops_regenerate(self):
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
job = _job(state_data={"regenerate": {"review_token": "tok-1"}})
|
||||
assert clear_admin_rerender_update(job) == {"state_data.regenerate": DELETE_FIELD}
|
||||
|
||||
def test_notification_suppression(self):
|
||||
from backend.services.admin_rerender_service import suppress_customer_notifications
|
||||
quiet = _job(state_data={"regenerate": {"review_token": "tok-1", "notify_customer": False}})
|
||||
loud = _job(state_data={"regenerate": {"review_token": "tok-1", "notify_customer": True}})
|
||||
assert suppress_customer_notifications(quiet)
|
||||
assert not suppress_customer_notifications(loud)
|
||||
assert not suppress_customer_notifications(_job())
|
||||
|
||||
|
||||
class TestValidate:
|
||||
def test_valid(self):
|
||||
assert validate_regenerate(_job()) is None
|
||||
|
||||
@pytest.mark.parametrize("overrides, fragment", [
|
||||
({"status": "in_review"}, "Only finished tracks"),
|
||||
({"status": "failed"}, "Only finished tracks"),
|
||||
({"outputs_deleted_at": "2026-09-29"}, "outputs were deleted"),
|
||||
({"prep_only": True}, "can't be regenerated"),
|
||||
({"finalise_only": True}, "can't be regenerated"),
|
||||
({"state_data": {"instrumental_selection": "clean", "visibility_change_in_progress": True}}, "visibility change"),
|
||||
({"state_data": {"instrumental_selection": "clean", "admin_rerender": {"brand_code": "X"}}}, "already being re-rendered"),
|
||||
({"state_data": {"instrumental_selection": "clean", "theme_rerender": {"theme_id": "t"}}}, "already being re-rendered"),
|
||||
({"state_data": {"instrumental_selection": "clean",
|
||||
"storage_purge_in_progress": datetime.now(timezone.utc).isoformat()}}, "being archived"),
|
||||
({"state_data": {}}, "instrumental selection"),
|
||||
({"file_urls": {}}, "reviewed lyrics"),
|
||||
({"input_media_gcs_path": None}, "original audio"),
|
||||
({"theme_id": None}, "video style"),
|
||||
])
|
||||
def test_rejections(self, overrides, fragment):
|
||||
assert fragment in validate_regenerate(_job(**overrides))
|
||||
|
||||
def test_failed_regenerate_can_resume(self):
|
||||
job = _job(status="failed", state_data={"instrumental_selection": "clean",
|
||||
"regenerate": {"review_token": "tok-1"}})
|
||||
assert validate_regenerate(job) is None
|
||||
|
||||
def test_change_to_private_chain_allowed_during_visibility_change(self):
|
||||
job = _job(state_data={"instrumental_selection": "clean", "visibility_change_in_progress": True})
|
||||
assert validate_regenerate(job, after="change_to_private") is None
|
||||
|
||||
|
||||
# --- service ------------------------------------------------------------------------
|
||||
|
||||
def _service(claim_status="complete", trigger_ok=True, input_exists=True):
|
||||
job_manager = MagicMock()
|
||||
ref = MagicMock()
|
||||
snapshot = MagicMock(exists=True)
|
||||
snapshot.to_dict.return_value = {"status": claim_status}
|
||||
ref.get.return_value = snapshot
|
||||
job_manager.firestore.db.collection.return_value.document.return_value = ref
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = input_exists
|
||||
storage.list_files.return_value = ["jobs/job123/finals/title_mov.mov", "jobs/job123/finals/lossy_720p_mp4.mp4"]
|
||||
worker_service = MagicMock()
|
||||
worker_service.trigger_screens_worker = AsyncMock(return_value=trigger_ok)
|
||||
return RegenerateService(job_manager=job_manager, storage=storage), storage, worker_service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def no_tx():
|
||||
with patch("backend.services.theme_rerender_service.firestore.transactional", lambda fn: fn), \
|
||||
patch("google.cloud.firestore.transactional", lambda fn: fn), \
|
||||
patch.object(rs, "log_to_job"):
|
||||
yield
|
||||
|
||||
|
||||
async def _start(service, worker_service, job, **kwargs):
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
return await service.start(job, requested_by="customer@example.com", **kwargs)
|
||||
|
||||
|
||||
def _claim(service):
|
||||
tx = service.job_manager.firestore.db.transaction.return_value
|
||||
updates = [c.args[1] for c in tx.update.call_args_list]
|
||||
assert len(updates) == 1
|
||||
return updates[0]
|
||||
|
||||
|
||||
class TestRegenerateService:
|
||||
@pytest.mark.asyncio
|
||||
async def test_claims_and_triggers_screens(self, no_tx):
|
||||
service, storage, worker = _service()
|
||||
result = await _start(service, worker, _job())
|
||||
assert result == {"needs_stems": True, "brand_code": "NOMAD-1234"}
|
||||
update = _claim(service)
|
||||
assert update["status"] == JobStatus.LYRICS_COMPLETE.value
|
||||
assert update["state_data.regen_restore_status"] == "review_complete"
|
||||
marker = update["state_data.regenerate"]
|
||||
assert marker["brand_code"] == "NOMAD-1234"
|
||||
assert marker["notify_customer"] is True
|
||||
assert marker["review_token"] == "tok-1"
|
||||
assert marker["needs_stems"] is True
|
||||
assert marker["source"] == "customer"
|
||||
# nothing published is touched: links stay, no YouTube/Dropbox keys cleared
|
||||
assert not any(k.startswith("state_data.youtube") or k.startswith("state_data.dropbox") for k in update)
|
||||
assert update["file_urls.videos.with_vocals"] is DELETE_FIELD
|
||||
assert update["state_data.stems_restore"] is DELETE_FIELD
|
||||
assert len(update["state_data.regenerate_requests"]) == 1 # customer run counts
|
||||
worker.trigger_screens_worker.assert_awaited_once_with("job123")
|
||||
# stale title/end MOVs removed so the encoder can't reuse them; 720p kept
|
||||
deleted = [c.args[0] for c in storage.delete_file.call_args_list]
|
||||
assert "jobs/job123/finals/title_mov.mov" in deleted
|
||||
assert "jobs/job123/finals/lossy_720p_mp4.mp4" not in deleted
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stems_not_needed_when_kept(self, no_tx):
|
||||
service, storage, worker = _service()
|
||||
result = await _start(service, worker, _job(stems_purged_at=None))
|
||||
assert result["needs_stems"] is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_quiet_admin_regenerate(self, no_tx):
|
||||
service, storage, worker = _service()
|
||||
await _start(service, worker, _job(), source="admin", notify_customer=False)
|
||||
update = _claim(service)
|
||||
assert update["state_data.regenerate"]["notify_customer"] is False
|
||||
# system/admin runs don't eat the customer's daily allowance
|
||||
assert update["state_data.regenerate_requests"] == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_change_to_private_chain_sets_visibility_guard(self, no_tx):
|
||||
service, storage, worker = _service()
|
||||
await _start(service, worker, _job(), after="change_to_private")
|
||||
update = _claim(service)
|
||||
assert update["state_data.regenerate"]["after"] == "change_to_private"
|
||||
assert update["state_data.visibility_change_in_progress"] is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_after_rejected(self, no_tx):
|
||||
service, storage, worker = _service()
|
||||
with pytest.raises(RerenderError):
|
||||
await _start(service, worker, _job(), after="nope")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_input_rejected_before_claim(self, no_tx):
|
||||
service, storage, worker = _service(input_exists=False)
|
||||
with pytest.raises(RerenderError, match="original audio"):
|
||||
await _start(service, worker, _job())
|
||||
service.job_manager.firestore.db.transaction.return_value.update.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_conflict_when_no_longer_complete(self, no_tx):
|
||||
service, storage, worker = _service(claim_status="lyrics_complete")
|
||||
with pytest.raises(RerenderConflictError):
|
||||
await _start(service, worker, _job())
|
||||
worker.trigger_screens_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_failure_fails_job_keeping_marker(self, no_tx):
|
||||
service, storage, worker = _service(trigger_ok=False)
|
||||
with pytest.raises(RerenderError) as exc:
|
||||
await _start(service, worker, _job())
|
||||
assert exc.value.status_code == 503
|
||||
failed = service.job_manager.update_job.call_args[0][1]
|
||||
assert failed["status"] == JobStatus.FAILED.value
|
||||
assert "state_data.regenerate" not in failed
|
||||
|
||||
|
||||
class TestRateLimit:
|
||||
def _db(self, existing=None):
|
||||
db = MagicMock()
|
||||
snap = MagicMock(exists=existing is not None)
|
||||
snap.to_dict.return_value = {"requests": existing or []}
|
||||
db.collection.return_value.document.return_value.get.return_value = snap
|
||||
return db
|
||||
|
||||
def _settings(self):
|
||||
return SimpleNamespace(regenerate_max_per_job_per_day=3, regenerate_max_per_user_per_day=2)
|
||||
|
||||
def test_allows_and_records(self, no_tx):
|
||||
db = self._db()
|
||||
assert check_and_record_rate_limit(db, _job(), "a@b.com", self._settings()) is None
|
||||
db.transaction.return_value.set.assert_called_once()
|
||||
|
||||
def test_per_job_limit(self, no_tx):
|
||||
now = datetime.now(timezone.utc)
|
||||
job = _job(state_data={"regenerate_requests": [now.isoformat()] * 3, "instrumental_selection": "clean"})
|
||||
assert "recently" in check_and_record_rate_limit(self._db(), job, "a@b.com", self._settings())
|
||||
|
||||
def test_per_user_limit_and_window(self, no_tx):
|
||||
now = datetime.now(timezone.utc)
|
||||
recent = [now.isoformat(), now.isoformat()]
|
||||
assert "several tracks" in check_and_record_rate_limit(self._db(recent), _job(), "a@b.com", self._settings())
|
||||
old = [(now - timedelta(days=2)).isoformat()] * 5
|
||||
assert check_and_record_rate_limit(self._db(old), _job(), "a@b.com", self._settings()) is None
|
||||
|
||||
|
||||
# --- stems restore gate -------------------------------------------------------------
|
||||
|
||||
class TestStemsRestoreGate:
|
||||
@pytest.mark.asyncio
|
||||
async def test_not_needed(self):
|
||||
from backend.services.stems_restore import NOT_NEEDED, maybe_start_stems_restore
|
||||
assert await maybe_start_stems_restore(_job(stems_purged_at=None), MagicMock()) == NOT_NEEDED
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_starts_audio_worker(self):
|
||||
from backend.services.stems_restore import STARTED, maybe_start_stems_restore
|
||||
jm, ws = MagicMock(), MagicMock()
|
||||
ws.trigger_audio_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
|
||||
assert await maybe_start_stems_restore(_job(), jm) == STARTED
|
||||
payload = jm.update_job.call_args[0][1]
|
||||
marker = payload["state_data.stems_restore"]
|
||||
assert marker["status"] == "running" and marker["attempts"] == 1
|
||||
# the screens idempotency mark is dropped so the restore's re-trigger runs
|
||||
from backend.services import stems_restore
|
||||
assert payload["state_data.screens_progress"] is stems_restore.DELETE_FIELD
|
||||
ws.trigger_audio_worker.assert_awaited_once_with("job123")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_duplicate_dispatch_while_running(self):
|
||||
from backend.services.stems_restore import IN_PROGRESS, maybe_start_stems_restore
|
||||
running = {"status": "running", "attempts": 1, "started_at": datetime.now(timezone.utc).isoformat()}
|
||||
job = _job(state_data={"instrumental_selection": "clean", "stems_restore": running})
|
||||
assert await maybe_start_stems_restore(job, MagicMock()) == IN_PROGRESS
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_run_is_restarted(self):
|
||||
from backend.services.stems_restore import STARTED, maybe_start_stems_restore
|
||||
stale = {"status": "running", "attempts": 1,
|
||||
"started_at": (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()}
|
||||
jm, ws = MagicMock(), MagicMock()
|
||||
ws.trigger_audio_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
|
||||
job = _job(state_data={"instrumental_selection": "clean", "stems_restore": stale})
|
||||
assert await maybe_start_stems_restore(job, jm) == STARTED
|
||||
assert jm.update_job.call_args[0][1]["state_data.stems_restore"]["attempts"] == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gives_up_after_max_attempts(self):
|
||||
from backend.services.stems_restore import FAILED, maybe_start_stems_restore
|
||||
job = _job(state_data={"instrumental_selection": "clean",
|
||||
"stems_restore": {"status": "failed", "attempts": 3}})
|
||||
jm = MagicMock()
|
||||
assert await maybe_start_stems_restore(job, jm) == FAILED
|
||||
jm.mark_job_failed.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_audio_trigger_failure_fails_job(self):
|
||||
from backend.services.stems_restore import FAILED, maybe_start_stems_restore
|
||||
jm, ws = MagicMock(), MagicMock()
|
||||
ws.trigger_audio_worker = AsyncMock(return_value=False)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
|
||||
assert await maybe_start_stems_restore(_job(), jm) == FAILED
|
||||
jm.mark_job_failed.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_complete_heals_job_failed_by_earlier_attempt(self):
|
||||
from backend.services.stems_restore import complete_stems_restore
|
||||
jm, ws = MagicMock(), MagicMock()
|
||||
jm.get_job.return_value = _job(status="failed", error_details={"stage": "audio_separation"})
|
||||
ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
|
||||
await complete_stems_restore("job123", jm)
|
||||
update = jm.update_job.call_args[0][1]
|
||||
assert update["status"] == "lyrics_complete" and update["error_message"] is None
|
||||
|
||||
def test_restore_stalled(self):
|
||||
from backend.services.stems_restore import restore_stalled
|
||||
old = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
|
||||
fresh = datetime.now(timezone.utc).isoformat()
|
||||
assert restore_stalled(_job(state_data={"stems_restore": {"status": "running", "started_at": old}}))
|
||||
assert not restore_stalled(_job(state_data={"stems_restore": {"status": "running", "started_at": fresh}}))
|
||||
assert not restore_stalled(_job(state_data={"stems_restore": {"status": "failed", "started_at": old}}))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_complete_clears_marker_and_resumes_screens(self):
|
||||
from backend.services.stems_restore import complete_stems_restore
|
||||
jm, ws = MagicMock(), MagicMock()
|
||||
jm.get_job.return_value = _job(status="lyrics_complete")
|
||||
ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
|
||||
assert await complete_stems_restore("job123", jm) is True
|
||||
from backend.services import stems_restore
|
||||
update = jm.update_job.call_args[0][1]
|
||||
assert update["stems_purged_at"] is None
|
||||
assert "status" not in update
|
||||
assert "state_data.screens_progress" in update
|
||||
# compare with the module's own sentinel (other suites stub firestore_v1)
|
||||
assert update["state_data.stems_restore"] is stems_restore.DELETE_FIELD
|
||||
ws.trigger_screens_worker.assert_awaited_once_with("job123")
|
||||
|
||||
def test_is_restore_run(self):
|
||||
from backend.services.stems_restore import is_restore_run
|
||||
running = _job(state_data={"stems_restore": {"status": "running"}})
|
||||
assert is_restore_run(running)
|
||||
# a Cloud Run task retry after a failed attempt still restores
|
||||
assert is_restore_run(_job(state_data={"stems_restore": {"status": "failed"}}))
|
||||
assert not is_restore_run(_job())
|
||||
assert not is_restore_run(_job(stems_purged_at=None, state_data={"stems_restore": {"status": "running"}}))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_screens_worker_defers_to_restore(self):
|
||||
from backend.workers import screens_worker
|
||||
job = _job(status=JobStatus.LYRICS_COMPLETE, state_data={"instrumental_selection": "clean",
|
||||
"audio_complete": True, "lyrics_complete": True})
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = job
|
||||
with patch.object(screens_worker, "JobManager", return_value=jm), \
|
||||
patch.object(screens_worker, "StorageService"), \
|
||||
patch.object(screens_worker, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(screens_worker, "_validate_prerequisites", return_value=True), \
|
||||
patch("backend.services.stems_restore.maybe_start_stems_restore",
|
||||
new=AsyncMock(return_value="started")) as gate:
|
||||
assert await screens_worker.generate_screens("job123") is True
|
||||
gate.assert_awaited_once()
|
||||
# did not claim GENERATING_SCREENS
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
# --- GCS-only pipeline ----------------------------------------------------------------
|
||||
|
||||
class TestOrchestratorGcsOnly:
|
||||
@pytest.mark.asyncio
|
||||
async def test_gcs_only_skips_distribution(self):
|
||||
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
|
||||
config = OrchestratorConfig(
|
||||
job_id="job123", artist="A", title="T", title_video_path="", karaoke_video_path="",
|
||||
instrumental_audio_path="", gcs_only=True, keep_brand_code="NOMAD-1234",
|
||||
dropbox_path="/x", brand_prefix="NOMAD", gdrive_folder_id="g", enable_youtube_upload=True,
|
||||
)
|
||||
orch = VideoWorkerOrchestrator(config=config, job_manager=MagicMock(), storage=MagicMock())
|
||||
orch._run_encoding = AsyncMock()
|
||||
orch._run_organization = AsyncMock()
|
||||
orch._run_distribution = AsyncMock()
|
||||
orch._run_notifications = AsyncMock()
|
||||
orch._trigger_gdrive_validation = AsyncMock()
|
||||
result = await orch.run()
|
||||
assert result.success and result.brand_code == "NOMAD-1234"
|
||||
orch._run_encoding.assert_awaited_once()
|
||||
for stage in (orch._run_organization, orch._run_distribution, orch._run_notifications,
|
||||
orch._trigger_gdrive_validation):
|
||||
stage.assert_not_awaited()
|
||||
|
||||
def test_config_flag_follows_marker(self):
|
||||
from backend.workers.video_worker_orchestrator import create_orchestrator_config_from_job
|
||||
job = MagicMock()
|
||||
job.job_id = "job123"
|
||||
job.artist, job.title = "A", "T"
|
||||
job.review_token = "tok-1"
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.file_urls = {"screens": {}, "videos": {}}
|
||||
job.state_data = {"instrumental_selection": "clean", "regenerate": {"review_token": "tok-1",
|
||||
"brand_code": "NOMAD-9"}}
|
||||
with patch("backend.services.job_defaults_service.get_effective_distribution_for_job"):
|
||||
config = create_orchestrator_config_from_job(job, "/tmp/x")
|
||||
assert config.gcs_only is True and config.keep_brand_code == "NOMAD-9"
|
||||
|
||||
|
||||
async def _run_video_worker(state_data, result=None):
|
||||
from backend.workers import video_worker
|
||||
from backend.tests.test_admin_rerender import _orchestrator_result
|
||||
|
||||
job = MagicMock()
|
||||
job.job_id = "job123"
|
||||
job.artist, job.title = "A", "T"
|
||||
job.tenant_id = None
|
||||
job.edit_count = 0
|
||||
job.review_token = "tok-1"
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.state_data = state_data
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
orchestrator = MagicMock()
|
||||
orchestrator.run = AsyncMock(return_value=result or _orchestrator_result(
|
||||
youtube_url=None, dropbox_link=None, gdrive_files={}))
|
||||
style = MagicMock()
|
||||
style.get_cdg_styles.return_value = None
|
||||
native = AsyncMock()
|
||||
chained = AsyncMock()
|
||||
with patch.object(video_worker, "JobManager", return_value=job_manager), \
|
||||
patch.object(video_worker, "StorageService", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "setup_job_logging", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "_validate_prerequisites", return_value=True), \
|
||||
patch("backend.services.job_health_service.validate_worker_can_run", return_value=None), \
|
||||
patch.object(video_worker, "_setup_working_directory", new=AsyncMock()), \
|
||||
patch.object(video_worker, "load_style_config", new=AsyncMock(return_value=style)), \
|
||||
patch("backend.workers.video_worker_orchestrator.create_orchestrator_config_from_job", return_value=MagicMock()), \
|
||||
patch("backend.workers.video_worker_orchestrator.VideoWorkerOrchestrator", return_value=orchestrator), \
|
||||
patch.object(video_worker, "_handle_native_distribution", new=native), \
|
||||
patch.object(video_worker, "_upload_results", new=AsyncMock()), \
|
||||
patch.object(video_worker, "_store_video_processing_metadata"), \
|
||||
patch.object(video_worker, "_run_chained_change_to_private", new=chained), \
|
||||
patch("backend.services.community_publish.notify_community_publish", new=AsyncMock()):
|
||||
assert await video_worker.generate_video_orchestrated("job123") is True
|
||||
return job_manager, native, chained
|
||||
|
||||
|
||||
def _complete(jm):
|
||||
calls = [c for c in jm.transition_to_state.call_args_list if c.kwargs.get("new_status") == JobStatus.COMPLETE]
|
||||
assert len(calls) == 1
|
||||
return calls[0]
|
||||
|
||||
|
||||
class TestVideoWorkerRegenerate:
|
||||
@pytest.mark.asyncio
|
||||
async def test_regenerate_keeps_published_links_and_notifies(self):
|
||||
jm, native, chained = await _run_video_worker({
|
||||
"instrumental_selection": "clean",
|
||||
"regenerate": {"review_token": "tok-1", "notify_customer": True, "source": "customer"},
|
||||
})
|
||||
native.assert_not_awaited()
|
||||
chained.assert_not_awaited()
|
||||
payloads = [c.args[1] for c in jm.update_job.call_args_list]
|
||||
final = next(p for p in payloads if "renders_purged_at" in p)
|
||||
assert final["renders_purged_at"] is None
|
||||
assert not any(k in final for k in ("state_data.youtube_url", "state_data.brand_code",
|
||||
"state_data.dropbox_link", "state_data.gdrive_files"))
|
||||
call = _complete(jm)
|
||||
assert call.kwargs["notify"] is True
|
||||
assert call.kwargs["count_completion"] is False
|
||||
assert call.kwargs["extra_updates"]["state_data.regenerate"] is DELETE_FIELD
|
||||
assert "renders_regenerated_at" in call.kwargs["extra_updates"]
|
||||
assert call.kwargs["timeline_metadata"]["regenerate"] is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_quiet_regenerate(self):
|
||||
jm, _, _ = await _run_video_worker({
|
||||
"instrumental_selection": "clean",
|
||||
"regenerate": {"review_token": "tok-1", "notify_customer": False},
|
||||
})
|
||||
assert _complete(jm).kwargs["notify"] is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chained_change_to_private(self):
|
||||
jm, _, chained = await _run_video_worker({
|
||||
"instrumental_selection": "clean",
|
||||
"regenerate": {"review_token": "tok-1", "after": "change_to_private", "requested_by": "u@x.com"},
|
||||
})
|
||||
chained.assert_awaited_once()
|
||||
final = next(c.args[1] for c in jm.update_job.call_args_list if "renders_purged_at" in c.args[1])
|
||||
assert "state_data.visibility_change_in_progress" not in final
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_normal_completion_also_clears_purge_marker(self):
|
||||
jm, native, _ = await _run_video_worker({"instrumental_selection": "clean"})
|
||||
native.assert_awaited_once()
|
||||
final = next(c.args[1] for c in jm.update_job.call_args_list if "renders_purged_at" in c.args[1])
|
||||
assert final["renders_purged_at"] is None and "state_data.youtube_url" in final
|
||||
assert _complete(jm).kwargs["count_completion"] is True
|
||||
|
||||
|
||||
# --- routes ----------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
from backend.main import app
|
||||
yield TestClient(app), app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def _auth(email="customer@example.com", is_admin=False):
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
return AuthResult(is_valid=True, user_type=UserType.ADMIN if is_admin else UserType.UNLIMITED,
|
||||
remaining_uses=-1, message="Valid", user_email=email, is_admin=is_admin)
|
||||
|
||||
|
||||
def _as(app, auth):
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
|
||||
async def override():
|
||||
return auth
|
||||
|
||||
app.dependency_overrides[require_auth] = override
|
||||
app.dependency_overrides.pop(require_admin, None)
|
||||
|
||||
|
||||
class TestRegenerateRoute:
|
||||
def _post(self, client, auth, job, rate=None, start=None, headers=None):
|
||||
test_client, app = client
|
||||
_as(app, auth)
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = job
|
||||
start = start or AsyncMock(return_value={"needs_stems": True, "brand_code": "NOMAD-1"})
|
||||
with patch("backend.api.routes.jobs.JobManager", return_value=jm), \
|
||||
patch.object(rs, "check_and_record_rate_limit", return_value=rate) as limiter, \
|
||||
patch.object(RegenerateService, "start", start):
|
||||
resp = test_client.post("/api/jobs/job123/regenerate", headers=headers or {})
|
||||
return resp, start, limiter
|
||||
|
||||
def test_owner_can_regenerate(self, client):
|
||||
resp, start, limiter = self._post(client, _auth(), _job())
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["needs_stems"] is True
|
||||
assert start.await_args.kwargs["source"] == "customer"
|
||||
assert start.await_args.kwargs["notify_customer"] is True
|
||||
limiter.assert_called_once()
|
||||
|
||||
def test_other_user_forbidden(self, client):
|
||||
resp, start, _ = self._post(client, _auth(email="other@example.com"), _job())
|
||||
assert resp.status_code == 403
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_rate_limited(self, client):
|
||||
resp, start, _ = self._post(client, _auth(), _job(), rate="Please try again tomorrow.")
|
||||
assert resp.status_code == 429
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_admin_skips_rate_limit_and_kjbox_source(self, client):
|
||||
resp, start, limiter = self._post(client, _auth(email="admin@x.com", is_admin=True), _job(),
|
||||
headers={"X-Client-Id": "kjbox"})
|
||||
assert resp.status_code == 200
|
||||
limiter.assert_not_called()
|
||||
assert start.await_args.kwargs["source"] == "kjbox"
|
||||
|
||||
def test_customer_cannot_regenerate_a_complete_set(self, client):
|
||||
full = _job(renders_purged_at=None, file_urls={
|
||||
"lyrics": {"corrections": "c.json"},
|
||||
"finals": {"lossy_4k_mp4": "a", "lossy_720p_mp4": "b"}})
|
||||
resp, start, _ = self._post(client, _auth(), full)
|
||||
assert resp.status_code == 400
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_admin_can_regenerate_a_complete_set(self, client):
|
||||
full = _job(renders_purged_at=None, file_urls={
|
||||
"lyrics": {"corrections": "c.json"},
|
||||
"finals": {"lossy_4k_mp4": "a", "lossy_720p_mp4": "b"}})
|
||||
resp, start, _ = self._post(client, _auth(email="admin@x.com", is_admin=True), full)
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_invalid_job_400(self, client):
|
||||
resp, start, _ = self._post(client, _auth(), _job(status="in_review"))
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_visibility_change_in_progress_is_409(self, client):
|
||||
job = _job(state_data={"instrumental_selection": "clean", "visibility_change_in_progress": True})
|
||||
resp, start, _ = self._post(client, _auth(), job)
|
||||
assert resp.status_code == 409
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_conflict_409(self, client):
|
||||
resp, _, _ = self._post(client, _auth(), _job(),
|
||||
start=AsyncMock(side_effect=RerenderConflictError("busy")))
|
||||
assert resp.status_code == 409
|
||||
|
||||
def test_admin_endpoint(self, client):
|
||||
test_client, app = client
|
||||
_as(app, _auth(email="admin@x.com", is_admin=True))
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = _job()
|
||||
start = AsyncMock(return_value={"needs_stems": False, "brand_code": "NOMAD-1"})
|
||||
with patch("backend.api.routes.admin.JobManager", return_value=jm), \
|
||||
patch.object(RegenerateService, "start", start):
|
||||
resp = test_client.post("/api/admin/jobs/job123/regenerate", json={"notify_customer": True})
|
||||
assert resp.status_code == 200
|
||||
assert start.await_args.kwargs == {"requested_by": "admin@x.com", "source": "admin", "notify_customer": True}
|
||||
|
||||
def test_admin_endpoint_requires_admin(self, client):
|
||||
test_client, app = client
|
||||
_as(app, _auth())
|
||||
resp = test_client.post("/api/admin/jobs/job123/regenerate")
|
||||
assert resp.status_code in (401, 403)
|
||||
|
||||
|
||||
class TestArchivedDownload:
|
||||
def _get(self, client, job, key="lossy_4k_mp4"):
|
||||
test_client, app = client
|
||||
_as(app, _auth())
|
||||
with patch("backend.api.routes.jobs.job_manager") as jm:
|
||||
jm.get_job.return_value = job
|
||||
return test_client.get(f"/api/jobs/job123/download/finals/{key}")
|
||||
|
||||
def test_purged_final_is_410_with_regenerate_hint(self, client):
|
||||
job = _job(storage_purge={"files": [{"path": "jobs/job123/finals/lossy_4k_mp4.mp4", "bytes": 1}]})
|
||||
resp = self._get(client, job)
|
||||
assert resp.status_code == 410
|
||||
detail = resp.json()["detail"]
|
||||
assert detail["code"] == "output_archived"
|
||||
assert detail["regenerate_url"] == "/api/jobs/job123/regenerate"
|
||||
|
||||
def test_unknown_key_still_404(self, client):
|
||||
job = _job(storage_purge={"files": [{"path": "jobs/job123/finals/lossy_4k_mp4.mp4", "bytes": 1}]})
|
||||
assert self._get(client, job, key="nope").status_code == 404
|
||||
|
||||
def test_not_purged_job_404(self, client):
|
||||
job = _job(renders_purged_at=None, stems_purged_at=None, storage_purge=None)
|
||||
assert self._get(client, job).status_code == 404
|
||||
|
||||
|
||||
class TestInternalRetentionEndpoint:
|
||||
def _post(self, client, url, dry_run_setting=True):
|
||||
test_client, app = client
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
async def admin():
|
||||
return _auth(email="admin@x.com", is_admin=True)
|
||||
|
||||
app.dependency_overrides[require_admin] = admin
|
||||
settings = MagicMock(storage_retention_enabled=True, storage_retention_dry_run=dry_run_setting,
|
||||
gcs_bucket_name="bucket")
|
||||
svc = MagicMock()
|
||||
svc.run.return_value = {"summary": {}, "jobs": []}
|
||||
with patch("backend.config.get_settings", return_value=settings), \
|
||||
patch("backend.services.storage_retention.StorageRetentionService", return_value=svc) as cls:
|
||||
cls.default_report_path.return_value = "storage-retention/reports/x-dry-run.json"
|
||||
resp = test_client.post(url)
|
||||
return resp, svc
|
||||
|
||||
def test_global_real_run_refused_while_setting_is_dry(self, client):
|
||||
resp, svc = self._post(client, "/api/internal/storage-retention/run?dry_run=false")
|
||||
assert resp.status_code == 400
|
||||
svc.run.assert_not_called()
|
||||
|
||||
def test_min_age_override_needs_scope(self, client):
|
||||
resp, _ = self._post(client, "/api/internal/storage-retention/run?min_age_days=0")
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_scheduled_run_starts_the_cloud_run_job(self, client):
|
||||
# The full pass runs as the storage-retention-job Cloud Run Job (CPU is
|
||||
# throttled outside requests and Cloudflare cuts requests at 100s).
|
||||
ws = MagicMock()
|
||||
ws.trigger_storage_retention_job = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
|
||||
resp, svc = self._post(client, "/api/internal/storage-retention/run?include_orphans=true")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["status"] == "started" and body["dry_run"] is True
|
||||
assert body["report_path"].startswith("gs://bucket/storage-retention/reports/")
|
||||
svc.run.assert_not_called()
|
||||
kwargs = ws.trigger_storage_retention_job.await_args.kwargs
|
||||
assert kwargs["dry_run"] is True and kwargs["include_orphans"] is True
|
||||
assert kwargs["report_path"] == body["report_path"].removeprefix("gs://bucket/")
|
||||
|
||||
def test_job_trigger_failure_is_503(self, client):
|
||||
ws = MagicMock()
|
||||
ws.trigger_storage_retention_job = AsyncMock(return_value=False)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
|
||||
resp, _ = self._post(client, "/api/internal/storage-retention/run")
|
||||
assert resp.status_code == 503
|
||||
|
||||
def test_scoped_real_run_is_synchronous(self, client):
|
||||
resp, svc = self._post(client, "/api/internal/storage-retention/run?job_ids=job123&dry_run=false&min_age_days=0")
|
||||
assert resp.status_code == 200 and resp.json()["status"] == "complete"
|
||||
kwargs = svc.run.call_args.kwargs
|
||||
assert kwargs["dry_run"] is False and kwargs["job_ids"] == ["job123"] and kwargs["min_age_days"] == 0
|
||||
|
||||
|
||||
# --- visibility / edit / retry -------------------------------------------------------
|
||||
|
||||
class TestVisibilityChain:
|
||||
@pytest.mark.asyncio
|
||||
async def test_change_to_private_regenerates_missing_finals_first(self):
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
start = AsyncMock(return_value={"needs_stems": True, "brand_code": "NOMAD-1"})
|
||||
with patch.object(RegenerateService, "start", start), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new=AsyncMock()) as redistribute:
|
||||
result = await VisibilityChangeService(job_manager=MagicMock()).change_to_private(
|
||||
"job123", _job(), "customer@example.com")
|
||||
assert result["status"] == "processing" and result["reprocessing_required"] is True
|
||||
assert start.await_args.kwargs["after"] == "change_to_private"
|
||||
assert start.await_args.kwargs["notify_customer"] is False
|
||||
redistribute.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_never_purged_job_missing_finals_redistributes_as_before(self):
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
start = AsyncMock()
|
||||
job = _job(renders_purged_at=None) # no 4K in file_urls, but nothing was purged
|
||||
with patch.object(RegenerateService, "start", start), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new=AsyncMock(return_value=False)):
|
||||
with pytest.raises(RuntimeError):
|
||||
await VisibilityChangeService(job_manager=MagicMock()).change_to_private("job123", job, "u@x.com")
|
||||
start.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chained_call_does_not_loop(self):
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
start = AsyncMock()
|
||||
with patch.object(RegenerateService, "start", start), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new=AsyncMock(return_value=False)):
|
||||
with pytest.raises(RuntimeError):
|
||||
await VisibilityChangeService(job_manager=MagicMock()).change_to_private(
|
||||
"job123", _job(), "u@x.com", regenerate_if_missing=False)
|
||||
start.assert_not_awaited()
|
||||
|
||||
|
||||
class TestAudioWorkerRestoreMode:
|
||||
@pytest.mark.asyncio
|
||||
async def test_restore_run_hands_back_to_screens(self):
|
||||
from backend.workers import audio_worker
|
||||
job = _job(state_data={"instrumental_selection": "clean", "stems_restore": {"status": "running"}},
|
||||
clean_instrumental_model=None, backing_vocals_models=None, other_stems_models=None,
|
||||
url=None, filename="song.flac")
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = job
|
||||
processor = MagicMock()
|
||||
processor.process_audio_separation.return_value = {"clean_instrumental": {}}
|
||||
complete = AsyncMock(return_value=True)
|
||||
quick = MagicMock()
|
||||
with patch.object(audio_worker, "JobManager", return_value=jm), \
|
||||
patch.object(audio_worker, "StorageService"), \
|
||||
patch.object(audio_worker, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(audio_worker, "setup_job_logging", return_value=MagicMock()), \
|
||||
patch.object(audio_worker, "worker_registry", MagicMock(register=AsyncMock(), unregister=AsyncMock())), \
|
||||
patch.object(audio_worker, "download_audio", new=AsyncMock(return_value="/tmp/song.flac")), \
|
||||
patch.object(audio_worker, "_store_audio_source_metadata"), \
|
||||
patch.object(audio_worker, "create_audio_processor", return_value=processor), \
|
||||
patch.object(audio_worker, "upload_separation_results", new=AsyncMock()), \
|
||||
patch.object(audio_worker, "_transcode_review_stems", new=AsyncMock()), \
|
||||
patch.object(audio_worker, "start_quick_version", quick), \
|
||||
patch("backend.workers.screens_worker._analyze_backing_vocals", new=AsyncMock()), \
|
||||
patch("backend.services.stems_restore.complete_stems_restore", new=complete), \
|
||||
patch.dict("os.environ", {"MODEL_DIR": "/models"}):
|
||||
assert await audio_worker.process_audio_separation("job123") is True
|
||||
complete.assert_awaited_once_with("job123", jm)
|
||||
quick.assert_not_called()
|
||||
jm.mark_audio_complete.assert_not_called()
|
||||
jm.advance_to_screens_if_ready.assert_not_called()
|
||||
meta_keys = [c.args[1] for c in jm.update_processing_metadata.call_args_list]
|
||||
assert "separation_restore" in meta_keys and "separation" not in meta_keys
|
||||
|
||||
|
||||
class TestRetry:
|
||||
def _retry(self, client, job, start=None):
|
||||
test_client, app = client
|
||||
_as(app, _auth())
|
||||
job.error_details = {"stage": "stems_restore"}
|
||||
job.error_message = "x"
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = job
|
||||
jm.transition_to_state.return_value = True
|
||||
start = start or AsyncMock(return_value={"needs_stems": True, "brand_code": "NOMAD-1"})
|
||||
worker = MagicMock()
|
||||
worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.api.routes.jobs.job_manager", jm), \
|
||||
patch("backend.api.routes.jobs.worker_service", worker), \
|
||||
patch.object(RegenerateService, "start", start):
|
||||
resp = test_client.post("/api/jobs/job123/retry")
|
||||
return resp, start, jm, worker
|
||||
|
||||
def test_failed_regenerate_is_rerun_by_owner(self, client):
|
||||
job = _job(status="failed", state_data={
|
||||
"instrumental_selection": "clean",
|
||||
"regenerate": {"review_token": "tok-1", "source": "customer", "notify_customer": True, "after": None},
|
||||
})
|
||||
resp, start, _, _ = self._retry(client, job)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["retry_stage"] == "regenerate"
|
||||
assert start.await_args.kwargs["source"] == "customer"
|
||||
|
||||
def test_stems_purged_edit_failure_goes_back_through_screens(self, client):
|
||||
job = _job(status="failed", state_data={"instrumental_selection": "clean"},
|
||||
file_urls={"lyrics": {"corrections": "c.json"},
|
||||
"screens": {"title_png": "t.png"}})
|
||||
resp, start, jm, worker = self._retry(client, job)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["retry_stage"] == "stems_restore"
|
||||
start.assert_not_awaited()
|
||||
assert jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.LYRICS_COMPLETE
|
||||
worker.trigger_screens_worker.assert_called_once_with("job123")
|
||||
|
||||
|
||||
|
||||
class TestRefundGuard:
|
||||
@pytest.mark.parametrize("marker", ["regenerate", "admin_rerender", "theme_rerender"])
|
||||
def test_cancelling_a_rerun_of_a_delivered_track_does_not_refund(self, marker):
|
||||
from backend.services.job_manager import JobManager
|
||||
jm = JobManager.__new__(JobManager)
|
||||
job = SimpleNamespace(credit_refunded=False, user_email="customer@example.com",
|
||||
state_data={marker: {"source": "customer"}, "credits_charged": 1})
|
||||
with patch("backend.services.auth_service.is_admin_email", return_value=False), \
|
||||
patch("backend.services.user_service.get_user_service") as users:
|
||||
assert jm._refund_credit_for_job("job123", job, reason="job_cancelled") is False
|
||||
users.return_value.add_credits.assert_not_called()
|
||||
|
||||
|
||||
class TestStemsRestoreWatchdog:
|
||||
def test_recover_stuck_jobs_fails_stalled_restore(self, client):
|
||||
test_client, app = client
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
async def admin():
|
||||
return _auth(email="admin@x.com", is_admin=True)
|
||||
|
||||
app.dependency_overrides[require_admin] = admin
|
||||
old = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
|
||||
stalled = _job(status="lyrics_complete",
|
||||
state_data={"stems_restore": {"status": "running", "started_at": old}})
|
||||
doc = SimpleNamespace(id="job123", to_dict=lambda: {"job_id": "job123", "state_data": stalled.state_data})
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = stalled
|
||||
|
||||
def where(filter=None):
|
||||
q = MagicMock()
|
||||
status = getattr(filter, "value", None)
|
||||
docs = [doc] if status == "lyrics_complete" else []
|
||||
q.stream.return_value = docs
|
||||
q.limit.return_value.stream.return_value = docs
|
||||
return q
|
||||
|
||||
jm.firestore.db.collection.return_value.where.side_effect = where
|
||||
with patch("backend.api.routes.internal.JobManager", return_value=jm), \
|
||||
patch("google.cloud.firestore_v1.FieldFilter",
|
||||
side_effect=lambda field, op, value: SimpleNamespace(value=value)), \
|
||||
patch("backend.services.worker_service.get_worker_service"):
|
||||
resp = test_client.post("/api/internal/recover-stuck-jobs")
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["stems_restore_failed_jobs"] == ["job123"]
|
||||
jm.mark_job_failed.assert_called_once()
|
||||
|
||||
|
||||
|
||||
class TestStorageRetentionWorker:
|
||||
def test_cli_runs_service_with_args(self):
|
||||
from backend.workers import storage_retention_worker
|
||||
svc = MagicMock()
|
||||
svc.run.return_value = {"summary": {}}
|
||||
with patch("backend.services.storage_retention.StorageRetentionService", return_value=svc):
|
||||
code = storage_retention_worker.main(
|
||||
["--dry-run", "false", "--max-jobs", "5", "--include-orphans", "--report-path", "r.json"])
|
||||
assert code == 0
|
||||
assert svc.run.call_args.kwargs == {"dry_run": False, "max_jobs": 5, "include_orphans": True,
|
||||
"report_path": "r.json"}
|
||||
|
||||
def test_cli_defaults_to_dry_run(self):
|
||||
from backend.workers import storage_retention_worker
|
||||
svc = MagicMock()
|
||||
svc.run.return_value = {}
|
||||
with patch("backend.services.storage_retention.StorageRetentionService", return_value=svc):
|
||||
storage_retention_worker.main([])
|
||||
assert svc.run.call_args.kwargs["dry_run"] is True
|
||||
|
||||
def test_cli_job_errors_exit_nonzero(self):
|
||||
from backend.workers import storage_retention_worker
|
||||
svc = MagicMock()
|
||||
svc.run.return_value = {"errors": [{"job_id": "x", "error": "boom"}]}
|
||||
with patch("backend.services.storage_retention.StorageRetentionService", return_value=svc):
|
||||
assert storage_retention_worker.main([]) == 1
|
||||
|
||||
def test_cli_crash_exit_code(self):
|
||||
from backend.workers import storage_retention_worker
|
||||
with patch("backend.services.storage_retention.StorageRetentionService", side_effect=RuntimeError("x")):
|
||||
assert storage_retention_worker.main([]) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_builds_job_args(self):
|
||||
from backend.services.worker_service import WorkerService
|
||||
ws = WorkerService.__new__(WorkerService)
|
||||
ws._use_cloud_tasks = True
|
||||
ws.settings = SimpleNamespace(google_cloud_project="p", cpu_jobs_region="us-east4")
|
||||
ws._run_job_with_retry = AsyncMock(return_value=MagicMock(metadata={}))
|
||||
with patch("google.cloud.run_v2.JobsClient"):
|
||||
assert await ws.trigger_storage_retention_job(False, "r.json", max_jobs=3, include_orphans=True)
|
||||
request = ws._run_job_with_retry.await_args.args[1]
|
||||
assert request.name == "projects/p/locations/us-east4/jobs/storage-retention-job"
|
||||
args = list(request.overrides.container_overrides[0].args)
|
||||
assert args[:3] == ["python", "-m", "backend.workers.storage_retention_worker"]
|
||||
assert args[3:] == ["--dry-run", "false", "--report-path", "r.json", "--max-jobs", "3", "--include-orphans"]
|
||||
|
||||
|
||||
|
||||
class TestLostRerenderScreensDispatch:
|
||||
def test_parked_rerender_is_retriggered(self, client):
|
||||
test_client, app = client
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
async def admin():
|
||||
return _auth(email="admin@x.com", is_admin=True)
|
||||
|
||||
app.dependency_overrides[require_admin] = admin
|
||||
state = {"regen_restore_status": "review_complete", "screens_progress": {"stage": "running"},
|
||||
"regenerate": {"review_token": "tok-1"}}
|
||||
parked = _job(status="lyrics_complete", state_data=state,
|
||||
updated_at=datetime.now(timezone.utc) - timedelta(minutes=20))
|
||||
fresh = _job(job_id="job456", status="lyrics_complete", state_data=dict(state),
|
||||
updated_at=datetime.now(timezone.utc))
|
||||
docs = [SimpleNamespace(id=j.job_id, to_dict=(lambda j=j: {"job_id": j.job_id, "state_data": j.state_data}))
|
||||
for j in (parked, fresh)]
|
||||
jm = MagicMock()
|
||||
jm.get_job.side_effect = lambda jid: {"job123": parked, "job456": fresh}[jid]
|
||||
|
||||
def where(filter=None):
|
||||
q = MagicMock()
|
||||
selected = docs if getattr(filter, "value", None) == "lyrics_complete" else []
|
||||
q.stream.return_value = []
|
||||
q.limit.return_value.stream.return_value = selected
|
||||
return q
|
||||
|
||||
jm.firestore.db.collection.return_value.where.side_effect = where
|
||||
ws = MagicMock()
|
||||
ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.api.routes.internal.JobManager", return_value=jm), \
|
||||
patch("google.cloud.firestore_v1.FieldFilter",
|
||||
side_effect=lambda field, op, value: SimpleNamespace(value=value)), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=ws):
|
||||
resp = test_client.post("/api/internal/recover-stuck-jobs")
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["regen_screens_retriggered_jobs"] == ["job123"]
|
||||
ws.trigger_screens_worker.assert_awaited_once_with("job123")
|
||||
@@ -1087,7 +1087,7 @@ class TestCorrectionsDuetFlag:
|
||||
mock_request.headers = {}
|
||||
|
||||
async def _run():
|
||||
return await submit_corrections(
|
||||
return submit_corrections(
|
||||
job_id=mock_job.job_id,
|
||||
submission=submission,
|
||||
http_request=mock_request,
|
||||
@@ -1219,7 +1219,7 @@ class TestCorrectionsFirestoreDocSize:
|
||||
mock_request.headers = {}
|
||||
|
||||
async def _run():
|
||||
return await submit_corrections(
|
||||
return submit_corrections(
|
||||
job_id=mock_job.job_id,
|
||||
submission=submission,
|
||||
http_request=mock_request,
|
||||
@@ -1307,7 +1307,7 @@ class TestCompleteReviewSegmentGuard:
|
||||
mock_request.headers = {}
|
||||
|
||||
async def _run():
|
||||
return await complete_review(
|
||||
return complete_review(
|
||||
job_id=job.job_id,
|
||||
body=None,
|
||||
request=mock_request,
|
||||
|
||||
@@ -1401,7 +1401,7 @@ class TestGetPreviewVideoRedirect:
|
||||
from backend.api.routes.review import get_preview_video, _preview_videos
|
||||
_preview_videos.clear() # force the standard-path / file_exists branch
|
||||
with patch("backend.api.routes.review.StorageService", return_value=mock_storage):
|
||||
return asyncio.run(get_preview_video(
|
||||
return (get_preview_video(
|
||||
job_id=job_id,
|
||||
preview_hash=preview_hash,
|
||||
auth_info=("user@test.com", "job_owner"),
|
||||
@@ -1789,7 +1789,7 @@ class TestPreviewVideoStatusEndpoint:
|
||||
import asyncio
|
||||
from backend.api.routes.review import get_preview_video_status
|
||||
with patch("backend.api.routes.review.StorageService", return_value=mock_storage):
|
||||
return asyncio.run(get_preview_video_status(
|
||||
return (get_preview_video_status(
|
||||
job_id=job_id,
|
||||
preview_hash=preview_hash,
|
||||
auth_info=("user@test.com", "job_owner"),
|
||||
|
||||
@@ -0,0 +1,681 @@
|
||||
"""
|
||||
Tests for the storage-retention purge (backend/services/storage_retention.py).
|
||||
|
||||
Covers the per-file policy (keep list, purge list, 720p keep, user
|
||||
instrumentals, finalise-only sources, unknown files), job eligibility
|
||||
(age, job types, in-flight markers, tenants), per-job planning (input must be
|
||||
recoverable, bring-your-own-instrumental keeps stems, never outside
|
||||
jobs/{id}/), file_urls cleanup, and the service: dry-run writes only a report,
|
||||
real runs delete + record markers/manifest, scoping, batching + cursor,
|
||||
idempotency and the eligibility re-check at claim time.
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
from backend.services import storage_retention as sr
|
||||
from backend.services.storage_retention import (
|
||||
KEEP,
|
||||
PURGE,
|
||||
StorageRetentionService,
|
||||
classify_file,
|
||||
completed_at,
|
||||
file_url_deletions,
|
||||
job_skip_reason,
|
||||
plan_job,
|
||||
purge_in_progress,
|
||||
)
|
||||
|
||||
NOW = datetime(2026, 10, 3, 12, 0, tzinfo=timezone.utc)
|
||||
OLD = (NOW - timedelta(days=45)).isoformat()
|
||||
|
||||
|
||||
# --- classify_file ----------------------------------------------------------------
|
||||
|
||||
class TestClassifyFile:
|
||||
@pytest.mark.parametrize("rel", [
|
||||
"input/Artist - Title.flac",
|
||||
"input/edited.flac",
|
||||
"lyrics/corrections.json",
|
||||
"lyrics/karaoke.lrc",
|
||||
"style/style_params.json",
|
||||
"review_sessions/abc.json",
|
||||
"audio_edit/session1/stack.json",
|
||||
"audio_edit_sessions/x.json",
|
||||
"uploads/custom_instrumental_source.wav",
|
||||
"packages/cdg_zip.zip",
|
||||
"packages/txt_zip.zip",
|
||||
"screens/title.png",
|
||||
"screens/end.jpg",
|
||||
"analysis/backing_vocals_waveform.png",
|
||||
"stems/custom_instrumental.flac",
|
||||
"stems/custom_instrumental.mp3",
|
||||
"stems/vocals_derived.flac",
|
||||
"custom_instrumental.mp3",
|
||||
"custom_instrumental.wav",
|
||||
"existing_instrumental.flac",
|
||||
"quick/lyrics.json",
|
||||
"something_new/file.bin",
|
||||
"random_root_file.txt",
|
||||
])
|
||||
def test_kept(self, rel):
|
||||
assert classify_file(rel)[0] == KEEP
|
||||
|
||||
@pytest.mark.parametrize("rel, category", [
|
||||
("finals/lossless_4k_mp4.mp4", "finals"),
|
||||
("finals/lossless_4k_mkv.mkv", "finals"),
|
||||
("finals/lossy_4k_mp4.mp4", "finals"),
|
||||
("finals/with_vocals_mp4.mp4", "finals"),
|
||||
("finals/portrait_1080x1920.mp4", "finals"),
|
||||
("finals/title_mov.mov", "finals"),
|
||||
("finals/Artist - Title (Final Karaoke Lossless 4k).mp4", "finals"),
|
||||
("finals/Artist - Title (Final Karaoke Lossy 4k).mp4", "finals"),
|
||||
("finals/Artist - Title (Karaoke).mp4", "finals"),
|
||||
("finals/Artist - Title (With Vocals).mp4", "finals"),
|
||||
("finals/Artist - Title (Title).mov", "finals"),
|
||||
("videos/with_vocals.mkv", "videos"),
|
||||
("previews/f9d280ecd095.mp4", "previews"),
|
||||
("previews/f9d280ecd095.ass", "previews"),
|
||||
("encoded/out.mp4", "encoded"),
|
||||
("quick/video.mp4", "quick"),
|
||||
("screens/title.mov", "screens_mov"),
|
||||
("screens/end.mov", "screens_mov"),
|
||||
("review-audio/instrumental_clean.ogg", "review_audio"),
|
||||
("review-audio/waveform_review_500.json", "review_audio"),
|
||||
("stems/instrumental_clean.flac", "stems"),
|
||||
("stems/instrumental_with_backing.flac", "stems"),
|
||||
("stems/vocals_clean.flac", "stems"),
|
||||
("stems/lead_vocals.flac", "stems"),
|
||||
("stems/backing_vocals.flac", "stems"),
|
||||
])
|
||||
def test_purged(self, rel, category):
|
||||
assert classify_file(rel) == (PURGE, category)
|
||||
|
||||
@pytest.mark.parametrize("rel", [
|
||||
"finals/lossy_720p_mp4.mp4",
|
||||
"finals/Artist - Title (Final Karaoke Lossy 720p).mp4",
|
||||
# artist/title containing format words must not confuse the 720p keep
|
||||
"finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4",
|
||||
])
|
||||
def test_720p_final_is_kept(self, rel):
|
||||
assert classify_file(rel) == (KEEP, "final_720p")
|
||||
|
||||
def test_720p_lookalike_title_is_still_purged(self):
|
||||
# "720p" in the title but the format tag says 4K
|
||||
assert classify_file("finals/720p Song - X (Final Karaoke Lossy 4k).mp4")[0] == PURGE
|
||||
|
||||
@pytest.mark.parametrize("rel", [
|
||||
"videos/with_vocals.mkv",
|
||||
"videos/with_vocals.mov",
|
||||
"screens/title.mov",
|
||||
"screens/end.mov",
|
||||
"stems/instrumental_clean.flac",
|
||||
"stems/instrumental_with_backing.flac",
|
||||
])
|
||||
def test_finalise_only_sources_are_kept(self, rel):
|
||||
assert classify_file(rel, finalise_only=True)[0] == KEEP
|
||||
|
||||
def test_finalise_only_still_purges_regenerable_finals(self):
|
||||
assert classify_file("finals/lossy_4k_mp4.mp4", finalise_only=True)[0] == PURGE
|
||||
|
||||
def test_unrecoverable_stems_are_kept(self):
|
||||
assert classify_file("stems/instrumental_clean.flac", stems_purgeable=False) == (KEEP, "stems_unrecoverable")
|
||||
|
||||
|
||||
# --- completed_at / eligibility ---------------------------------------------------
|
||||
|
||||
def _job(**overrides):
|
||||
job = {
|
||||
"job_id": "job1",
|
||||
"status": "complete",
|
||||
"timeline": [
|
||||
{"status": "encoding", "timestamp": (NOW - timedelta(days=46)).isoformat()},
|
||||
{"status": "complete", "timestamp": OLD},
|
||||
],
|
||||
"input_media_gcs_path": "jobs/job1/input/song.flac",
|
||||
"state_data": {"instrumental_selection": "clean"},
|
||||
"file_urls": {"lyrics": {"corrections": "jobs/job1/lyrics/corrections.json"}},
|
||||
"theme_id": "nomad",
|
||||
"tenant_id": "",
|
||||
}
|
||||
job.update(overrides)
|
||||
return job
|
||||
|
||||
|
||||
class TestEligibility:
|
||||
def test_completed_at_uses_latest_complete_entry(self):
|
||||
later = (NOW - timedelta(days=3)).isoformat()
|
||||
job = _job(timeline=[{"status": "complete", "timestamp": OLD},
|
||||
{"status": "complete", "timestamp": later}])
|
||||
assert completed_at(job) == datetime.fromisoformat(later)
|
||||
|
||||
def test_completed_at_falls_back_to_updated_at(self):
|
||||
assert completed_at(_job(timeline=[], updated_at=NOW)) == NOW
|
||||
|
||||
def test_naive_timestamps_are_utc(self):
|
||||
assert completed_at(_job(timeline=[{"status": "complete", "timestamp": "2026-08-01T10:00:00"}])).tzinfo
|
||||
|
||||
def test_old_complete_job_is_candidate(self):
|
||||
assert job_skip_reason(_job(), NOW, 30) is None
|
||||
|
||||
@pytest.mark.parametrize("overrides, reason", [
|
||||
({"status": "failed"}, "not_complete"),
|
||||
({"status": "in_review"}, "not_complete"),
|
||||
({"finalise_only": True}, "finalise_only"),
|
||||
({"prep_only": True}, "prep_only"),
|
||||
({"outputs_deleted_at": NOW}, "outputs_deleted"),
|
||||
({"state_data": {"visibility_change_in_progress": True}}, "active_visibility_change_in_progress"),
|
||||
({"state_data": {"admin_rerender": {"brand_code": "X"}}}, "active_admin_rerender"),
|
||||
({"state_data": {"theme_rerender": {"theme_id": "t"}}}, "active_theme_rerender"),
|
||||
({"state_data": {"regenerate": {"source": "customer"}}}, "active_regenerate"),
|
||||
({"state_data": {"youtube_upload_queued": True}}, "youtube_upload_queued"),
|
||||
({"state_data": {"storage_purge_in_progress": NOW.isoformat()}}, "purge_in_progress"),
|
||||
({"timeline": [{"status": "complete", "timestamp": (NOW - timedelta(days=29)).isoformat()}]}, "too_recent"),
|
||||
({"timeline": [], "updated_at": None}, "no_completion_time"),
|
||||
# only purge what a regenerate could rebuild
|
||||
({"state_data": {}}, "not_regenerable_no_instrumental_selection"),
|
||||
({"file_urls": {}}, "not_regenerable_no_reviewed_lyrics"),
|
||||
({"theme_id": None}, "not_regenerable_no_theme"),
|
||||
])
|
||||
def test_skip_reasons(self, overrides, reason):
|
||||
assert job_skip_reason(_job(**overrides), NOW, 30) == reason
|
||||
|
||||
def test_stale_purge_claim_does_not_block(self):
|
||||
stale = (NOW - timedelta(hours=2)).isoformat()
|
||||
job = _job(state_data={"storage_purge_in_progress": stale, "instrumental_selection": "clean"})
|
||||
assert job_skip_reason(job, NOW, 30) is None
|
||||
|
||||
def test_excluded_tenant(self):
|
||||
assert job_skip_reason(_job(tenant_id="vocalstar"), NOW, 30, ["vocalstar"]) == "excluded_tenant"
|
||||
|
||||
def test_tenant_jobs_follow_the_same_policy_by_default(self):
|
||||
assert job_skip_reason(_job(tenant_id="randy-vild"), NOW, 30) is None
|
||||
|
||||
def test_purge_in_progress_helper_accepts_models_and_dicts(self):
|
||||
recent = datetime.now(timezone.utc).isoformat()
|
||||
assert purge_in_progress({"state_data": {"storage_purge_in_progress": recent}})
|
||||
assert purge_in_progress(SimpleNamespace(state_data={"storage_purge_in_progress": recent}))
|
||||
assert not purge_in_progress(SimpleNamespace(state_data={}))
|
||||
assert not purge_in_progress(SimpleNamespace(state_data=None))
|
||||
|
||||
|
||||
# --- plan_job -----------------------------------------------------------------------
|
||||
|
||||
def _listing(job_id="job1", extra=()):
|
||||
files = [
|
||||
("input/song.flac", 30_000_000),
|
||||
("lyrics/corrections.json", 200_000),
|
||||
("finals/lossless_4k_mp4.mp4", 60_000_000),
|
||||
("finals/lossy_4k_mp4.mp4", 30_000_000),
|
||||
("finals/lossy_720p_mp4.mp4", 29_000_000),
|
||||
("finals/Artist - Title (Final Karaoke Lossy 720p).mp4", 29_000_000),
|
||||
("finals/Artist - Title (Karaoke).mp4", 140_000_000),
|
||||
("videos/with_vocals.mkv", 150_000_000),
|
||||
("previews/abc.mp4", 3_000_000),
|
||||
("review-audio/instrumental_clean.ogg", 3_000_000),
|
||||
("screens/title.png", 3_000_000),
|
||||
("screens/title.mov", 300_000),
|
||||
("packages/cdg_zip.zip", 4_000_000),
|
||||
("stems/instrumental_clean.flac", 23_000_000),
|
||||
("stems/vocals_clean.flac", 14_000_000),
|
||||
*extra,
|
||||
]
|
||||
return [(f"jobs/{job_id}/{rel}", size) for rel, size in files]
|
||||
|
||||
|
||||
class TestPlanJob:
|
||||
def test_purges_regenerables_and_keeps_the_rest(self):
|
||||
plan = plan_job(_job(), _listing())
|
||||
purged = {p.split("/", 2)[2] for p, _, _ in plan.purge}
|
||||
assert purged == {
|
||||
"finals/lossless_4k_mp4.mp4", "finals/lossy_4k_mp4.mp4",
|
||||
"finals/Artist - Title (Karaoke).mp4", "videos/with_vocals.mkv",
|
||||
"previews/abc.mp4", "review-audio/instrumental_clean.ogg",
|
||||
"screens/title.mov", "stems/instrumental_clean.flac", "stems/vocals_clean.flac",
|
||||
}
|
||||
assert plan.purges_renders and plan.purges_stems
|
||||
assert plan.bytes_by_category()["stems"] == 37_000_000
|
||||
assert plan.kept_bytes == 30_000_000 + 200_000 + 29_000_000 * 2 + 3_000_000 + 4_000_000
|
||||
|
||||
def test_custom_instrumental_is_never_purged(self):
|
||||
extra = [("stems/custom_instrumental.flac", 40_000_000), ("custom_instrumental.mp3", 9_000_000)]
|
||||
plan = plan_job(_job(state_data={"instrumental_selection": "custom"}), _listing(extra=extra))
|
||||
purged = {p for p, _, _ in plan.purge}
|
||||
assert "jobs/job1/stems/custom_instrumental.flac" not in purged
|
||||
assert "jobs/job1/custom_instrumental.mp3" not in purged
|
||||
# the separated stems still go (re-separated on demand)
|
||||
assert "jobs/job1/stems/instrumental_clean.flac" in purged
|
||||
|
||||
def test_input_unavailable_keeps_everything(self):
|
||||
plan = plan_job(_job(input_media_gcs_path="uploads/job1/audio/song.flac"), _listing())
|
||||
assert plan.skip_reason == "input_unavailable" and not plan.purge
|
||||
|
||||
def test_input_missing_from_listing_keeps_everything(self):
|
||||
listing = [x for x in _listing() if "/input/" not in x[0]]
|
||||
assert plan_job(_job(), listing).skip_reason == "input_unavailable"
|
||||
|
||||
def test_input_only_from_input_media_gcs_path(self):
|
||||
# regenerate/separation/render read input_media_gcs_path only
|
||||
job = _job(input_media_gcs_path=None, file_urls={"input": {"audio": "jobs/job1/input/song.flac"}})
|
||||
assert plan_job(job, _listing()).skip_reason == "input_unavailable"
|
||||
|
||||
def test_existing_instrumental_job_keeps_stems(self):
|
||||
plan = plan_job(_job(existing_instrumental_gcs_path="jobs/job1/custom_instrumental.flac"), _listing())
|
||||
assert not plan.purges_stems and plan.purges_renders
|
||||
assert plan.stems_note == "existing_instrumental"
|
||||
|
||||
def test_finalise_only_sources_kept_by_plan(self):
|
||||
plan = plan_job(_job(finalise_only=True), _listing())
|
||||
purged = {p for p, _, _ in plan.purge}
|
||||
assert "jobs/job1/videos/with_vocals.mkv" not in purged
|
||||
assert "jobs/job1/screens/title.mov" not in purged
|
||||
assert "jobs/job1/stems/instrumental_clean.flac" not in purged
|
||||
|
||||
def test_never_plans_outside_the_job_prefix(self):
|
||||
listing = _listing() + [("jobs/job10/finals/lossy_4k_mp4.mp4", 1), ("uploads/job1/x.mp4", 1)]
|
||||
plan = plan_job(_job(), listing)
|
||||
assert all(p.startswith("jobs/job1/") for p, _, _ in plan.purge)
|
||||
|
||||
def test_tenant_job_planned_like_any_other(self):
|
||||
plan = plan_job(_job(tenant_id="randy-vild"), _listing())
|
||||
assert plan.purges_renders and plan.purges_stems
|
||||
|
||||
|
||||
class TestFileUrlDeletions:
|
||||
def test_only_purged_entries_are_dropped(self):
|
||||
file_urls = {
|
||||
"finals": {"lossy_4k_mp4": "jobs/job1/finals/lossy_4k_mp4.mp4",
|
||||
"lossy_720p_mp4": "jobs/job1/finals/lossy_720p_mp4.mp4"},
|
||||
"stems": {"instrumental_clean": "gs://bucket/jobs/job1/stems/instrumental_clean.flac",
|
||||
"custom_instrumental": "jobs/job1/stems/custom_instrumental.flac"},
|
||||
"videos": {"with_vocals": "jobs/job1/videos/with_vocals.mkv"},
|
||||
"input": "jobs/job1/input/song.flac",
|
||||
}
|
||||
purged = ["jobs/job1/finals/lossy_4k_mp4.mp4", "jobs/job1/stems/instrumental_clean.flac",
|
||||
"jobs/job1/videos/with_vocals.mkv"]
|
||||
assert sorted(file_url_deletions(file_urls, purged)) == [
|
||||
"file_urls.finals.lossy_4k_mp4",
|
||||
"file_urls.stems.instrumental_clean",
|
||||
"file_urls.videos.with_vocals",
|
||||
]
|
||||
|
||||
def test_unsafe_keys_are_never_written(self):
|
||||
file_urls = {"finals": {"weird.key": "jobs/job1/finals/a.mp4"}}
|
||||
assert file_url_deletions(file_urls, ["jobs/job1/finals/a.mp4"]) == []
|
||||
|
||||
|
||||
# --- Service ----------------------------------------------------------------------
|
||||
|
||||
class FakeStorage:
|
||||
def __init__(self, files):
|
||||
self.files = dict(files)
|
||||
self.deleted = []
|
||||
self.reports = {}
|
||||
|
||||
def list_files_with_sizes(self, prefix):
|
||||
return [(k, v) for k, v in sorted(self.files.items()) if k.startswith(prefix)]
|
||||
|
||||
def delete_file(self, path, ignore_missing=False):
|
||||
self.deleted.append(path)
|
||||
self.files.pop(path, None)
|
||||
return True
|
||||
|
||||
def upload_json(self, path, data):
|
||||
self.reports[path] = data
|
||||
return path
|
||||
|
||||
|
||||
class FakeDoc:
|
||||
def __init__(self, db, doc_id):
|
||||
self.db, self.id = db, doc_id
|
||||
|
||||
def get(self, transaction=None):
|
||||
data = self.db.data.get(self.id)
|
||||
return SimpleNamespace(exists=data is not None, id=self.id, to_dict=lambda: _copy(data))
|
||||
|
||||
def update(self, payload):
|
||||
self.db.updates.append((self.id, payload))
|
||||
_apply(self.db.data.setdefault(self.id, {}), payload)
|
||||
|
||||
def set(self, payload, merge=False):
|
||||
self.db.data.setdefault(self.id, {}).update(payload)
|
||||
|
||||
|
||||
def _copy(data):
|
||||
import copy
|
||||
return copy.deepcopy(data) if data is not None else None
|
||||
|
||||
|
||||
def _apply(doc, payload):
|
||||
import sys
|
||||
# The service imports DELETE_FIELD at call time; other suites stub
|
||||
# google.cloud.firestore_v1, so compare against whatever is live now.
|
||||
delete_sentinels = {id(DELETE_FIELD), id(getattr(sys.modules.get("google.cloud.firestore_v1"), "DELETE_FIELD", DELETE_FIELD))}
|
||||
for key, value in payload.items():
|
||||
parts = key.split(".")
|
||||
target = doc
|
||||
for part in parts[:-1]:
|
||||
target = target.setdefault(part, {})
|
||||
if id(value) in delete_sentinels:
|
||||
target.pop(parts[-1], None)
|
||||
else:
|
||||
target[parts[-1]] = value
|
||||
|
||||
|
||||
class FakeQuery:
|
||||
def __init__(self, db, docs):
|
||||
self.db, self.docs = db, docs
|
||||
self._limit, self._after = None, None
|
||||
|
||||
def where(self, filter=None):
|
||||
return FakeQuery(self.db, [d for d in self.docs if self.db.data[d].get("status") == "complete"])
|
||||
|
||||
def order_by(self, *_):
|
||||
q = FakeQuery(self.db, sorted(self.docs)); q._limit, q._after = self._limit, self._after
|
||||
return q
|
||||
|
||||
def select(self, _):
|
||||
return self
|
||||
|
||||
def limit(self, n):
|
||||
self._limit = n
|
||||
return self
|
||||
|
||||
def start_after(self, cursor):
|
||||
self._after = cursor["__name__"].id
|
||||
return self
|
||||
|
||||
def stream(self):
|
||||
docs = [d for d in self.docs if self._after is None or d > self._after]
|
||||
if self._limit:
|
||||
docs = docs[: self._limit]
|
||||
return [SimpleNamespace(id=d, to_dict=(lambda d=d: _copy(self.db.data[d]))) for d in docs]
|
||||
|
||||
|
||||
class FakeCollection:
|
||||
def __init__(self, db, name):
|
||||
self.db, self.name = db, name
|
||||
|
||||
def document(self, doc_id):
|
||||
if self.name == "storage_retention":
|
||||
return self.db.state_doc
|
||||
return FakeDoc(self.db, doc_id)
|
||||
|
||||
def where(self, filter=None):
|
||||
return FakeQuery(self.db, list(self.db.data)).where(filter)
|
||||
|
||||
def select(self, fields):
|
||||
return FakeQuery(self.db, list(self.db.data))
|
||||
|
||||
|
||||
class FakeDb:
|
||||
def __init__(self, jobs):
|
||||
self.data = {j["job_id"]: j for j in jobs}
|
||||
self.updates = []
|
||||
self.state = {}
|
||||
state = self
|
||||
|
||||
class StateDoc:
|
||||
def get(self_inner):
|
||||
return SimpleNamespace(exists=bool(state.state), to_dict=lambda: dict(state.state))
|
||||
|
||||
def set(self_inner, payload, merge=False):
|
||||
state.state.update(payload)
|
||||
|
||||
self.state_doc = StateDoc()
|
||||
|
||||
def collection(self, name):
|
||||
return FakeCollection(self, name)
|
||||
|
||||
def transaction(self):
|
||||
class FakeTransaction:
|
||||
def update(self_inner, ref, payload):
|
||||
ref.update(payload)
|
||||
|
||||
return FakeTransaction()
|
||||
|
||||
|
||||
def _settings(**overrides):
|
||||
values = dict(
|
||||
storage_retention_dry_run=True, storage_retention_min_age_days=30,
|
||||
storage_retention_max_jobs_per_run=50, storage_retention_excluded_tenants="",
|
||||
firestore_collection="jobs", gcs_bucket_name="bucket",
|
||||
)
|
||||
values.update(overrides)
|
||||
return SimpleNamespace(**values)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_transactions():
|
||||
with patch.object(sr, "_run_in_transaction", lambda db, fn: fn(db.transaction())), \
|
||||
patch("backend.services.firestore_service.log_to_job"):
|
||||
yield
|
||||
|
||||
|
||||
def _service(jobs, files=None, **settings):
|
||||
files = files if files is not None else {k: v for j in jobs for k, v in _listing(j["job_id"])}
|
||||
for j in jobs:
|
||||
j.setdefault("input_media_gcs_path", f"jobs/{j['job_id']}/input/song.flac")
|
||||
j["input_media_gcs_path"] = f"jobs/{j['job_id']}/input/song.flac"
|
||||
db, storage = FakeDb(jobs), FakeStorage(files)
|
||||
return StorageRetentionService(db=db, storage=storage, settings=_settings(**settings)), db, storage
|
||||
|
||||
|
||||
class TestServiceDryRun:
|
||||
def test_dry_run_reports_without_touching_anything(self):
|
||||
svc, db, storage = _service([_job(job_id="a"), _job(job_id="b", status="failed")])
|
||||
report = svc.run(now=NOW)
|
||||
assert report["dry_run"] is True
|
||||
assert storage.deleted == [] and db.updates == []
|
||||
assert [j["job_id"] for j in report["jobs"]] == ["a"]
|
||||
assert report["summary"]["jobs_to_purge"] == 1
|
||||
cats = report["summary"]["bytes_by_category"]
|
||||
assert cats["finals"] == 60_000_000 + 30_000_000 + 140_000_000
|
||||
assert cats["stems"] == 37_000_000
|
||||
assert "final_720p" not in cats
|
||||
# only completed jobs are walked at all
|
||||
assert report["skipped"] == {} and report["summary"]["jobs_scanned"] == 1
|
||||
# report written to GCS
|
||||
assert report["report_path"] in storage.reports
|
||||
assert report["report_path"].startswith("storage-retention/reports/") and "dry-run" in report["report_path"]
|
||||
|
||||
def test_default_comes_from_settings(self):
|
||||
svc, db, storage = _service([_job(job_id="a")], storage_retention_dry_run=True)
|
||||
assert svc.run(now=NOW)["dry_run"] is True
|
||||
|
||||
def test_dry_run_scans_everything_without_cursor(self):
|
||||
jobs = [_job(job_id=f"j{i:03d}") for i in range(5)]
|
||||
svc, db, storage = _service(jobs)
|
||||
report = svc.run(now=NOW)
|
||||
assert report["summary"]["jobs_to_purge"] == 5
|
||||
assert db.state == {} # cursor untouched
|
||||
|
||||
|
||||
class TestServiceRealRun:
|
||||
def test_real_run_deletes_and_records(self):
|
||||
job = _job(job_id="a", file_urls={
|
||||
"lyrics": {"corrections": "jobs/a/lyrics/corrections.json"},
|
||||
"finals": {"lossy_4k_mp4": "jobs/a/finals/lossy_4k_mp4.mp4",
|
||||
"lossy_720p_mp4": "jobs/a/finals/lossy_720p_mp4.mp4"},
|
||||
"stems": {"instrumental_clean": "jobs/a/stems/instrumental_clean.flac"},
|
||||
"videos": {"with_vocals": "jobs/a/videos/with_vocals.mkv"},
|
||||
"packages": {"cdg_zip": "jobs/a/packages/cdg_zip.zip"},
|
||||
})
|
||||
svc, db, storage = _service([job])
|
||||
report = svc.run(dry_run=False, now=NOW)
|
||||
|
||||
assert report["summary"]["jobs_purged"] == 1
|
||||
assert "jobs/a/finals/lossy_720p_mp4.mp4" not in storage.deleted
|
||||
assert "jobs/a/input/song.flac" not in storage.deleted
|
||||
assert "jobs/a/packages/cdg_zip.zip" not in storage.deleted
|
||||
assert "jobs/a/stems/instrumental_clean.flac" in storage.deleted
|
||||
doc = db.data["a"]
|
||||
assert doc["renders_purged_at"] == NOW and doc["stems_purged_at"] == NOW
|
||||
assert doc["file_urls"]["finals"] == {"lossy_720p_mp4": "jobs/a/finals/lossy_720p_mp4.mp4"}
|
||||
assert "instrumental_clean" not in doc["file_urls"]["stems"]
|
||||
assert "with_vocals" not in doc["file_urls"]["videos"]
|
||||
assert doc["file_urls"]["packages"] == {"cdg_zip": "jobs/a/packages/cdg_zip.zip"}
|
||||
manifest = doc["storage_purge"]
|
||||
assert manifest["status"] == "complete"
|
||||
assert manifest["bytes"] == sum(f["bytes"] for f in manifest["files"])
|
||||
assert {f["path"] for f in manifest["files"]} == set(storage.deleted)
|
||||
# the claim marker is cleared
|
||||
assert "storage_purge_in_progress" not in doc["state_data"]
|
||||
assert "run" in report["report_path"] and "dry-run" not in report["report_path"]
|
||||
|
||||
def test_second_run_is_idempotent(self):
|
||||
svc, db, storage = _service([_job(job_id="a")])
|
||||
svc.run(dry_run=False, now=NOW)
|
||||
deleted = list(storage.deleted)
|
||||
report = svc.run(dry_run=False, now=NOW + timedelta(days=1))
|
||||
assert storage.deleted == deleted
|
||||
assert report["skipped"] == {"already_purged": 1}
|
||||
|
||||
def test_regenerated_job_becomes_eligible_again_after_its_window(self):
|
||||
svc, db, storage = _service([_job(job_id="a")])
|
||||
svc.run(dry_run=False, now=NOW)
|
||||
# regenerate: files come back, a new completion is recorded
|
||||
regenerated_at = NOW + timedelta(days=1)
|
||||
db.data["a"]["timeline"].append({"status": "complete", "timestamp": regenerated_at.isoformat()})
|
||||
db.data["a"]["renders_purged_at"] = None
|
||||
db.data["a"]["stems_purged_at"] = None
|
||||
storage.files.update({k: v for k, v in _listing("a")})
|
||||
assert svc.run(dry_run=True, now=NOW + timedelta(days=10))["skipped"] == {"too_recent": 1}
|
||||
later = svc.run(dry_run=True, now=regenerated_at + timedelta(days=31))
|
||||
assert later["summary"]["jobs_to_purge"] == 1
|
||||
|
||||
def test_custom_instrumental_job(self):
|
||||
files = {k: v for k, v in _listing("a", extra=[("stems/custom_instrumental.flac", 1),
|
||||
("custom_instrumental.mp3", 1)])}
|
||||
svc, db, storage = _service([_job(job_id="a", state_data={"instrumental_selection": "custom"})], files)
|
||||
svc.run(dry_run=False, now=NOW)
|
||||
assert "jobs/a/stems/custom_instrumental.flac" in storage.files
|
||||
assert "jobs/a/custom_instrumental.mp3" in storage.files
|
||||
assert "jobs/a/finals/lossy_720p_mp4.mp4" in storage.files
|
||||
|
||||
def test_finalise_only_job_untouched(self):
|
||||
svc, db, storage = _service([_job(job_id="a", finalise_only=True)])
|
||||
report = svc.run(dry_run=False, now=NOW)
|
||||
assert storage.deleted == [] and report["skipped"] == {"finalise_only": 1}
|
||||
|
||||
def test_tenant_job_purged_unless_excluded(self):
|
||||
svc, db, storage = _service([_job(job_id="a", tenant_id="vocalstar")])
|
||||
assert svc.run(dry_run=True, now=NOW)["summary"]["jobs_to_purge"] == 1
|
||||
svc, db, storage = _service([_job(job_id="a", tenant_id="vocalstar")],
|
||||
storage_retention_excluded_tenants="vocalstar, singa")
|
||||
assert svc.run(dry_run=False, now=NOW)["skipped"] == {"excluded_tenant": 1}
|
||||
assert storage.deleted == []
|
||||
|
||||
def test_claim_rechecks_live_doc(self):
|
||||
svc, db, storage = _service([_job(job_id="a")])
|
||||
original_plan = sr.plan_job
|
||||
|
||||
def plan_then_race(job, listing):
|
||||
# a regenerate claims the job between planning and deletion
|
||||
db.data["a"]["state_data"]["regenerate"] = {"source": "customer"}
|
||||
return original_plan(job, listing)
|
||||
|
||||
with patch.object(sr, "plan_job", side_effect=plan_then_race):
|
||||
report = svc.run(dry_run=False, now=NOW)
|
||||
assert storage.deleted == []
|
||||
assert report["jobs"][0]["result"] == {"status": "skipped", "reason": "no_longer_eligible"}
|
||||
assert report["summary"]["jobs_purged"] == 0
|
||||
|
||||
def test_delete_failures_are_recorded_not_fatal(self):
|
||||
svc, db, storage = _service([_job(job_id="a")])
|
||||
real_delete = storage.delete_file
|
||||
|
||||
def flaky(path, ignore_missing=False):
|
||||
if path.endswith("lossy_4k_mp4.mp4"):
|
||||
raise RuntimeError("boom")
|
||||
return real_delete(path, ignore_missing)
|
||||
|
||||
storage.delete_file = flaky
|
||||
svc.run(dry_run=False, now=NOW)
|
||||
manifest = db.data["a"]["storage_purge"]
|
||||
assert manifest["failures"][0]["path"].endswith("lossy_4k_mp4.mp4")
|
||||
assert db.data["a"]["renders_purged_at"] == NOW
|
||||
|
||||
def test_batch_limit_and_resumable_cursor(self):
|
||||
jobs = [_job(job_id=f"j{i}") for i in range(5)]
|
||||
svc, db, storage = _service(jobs)
|
||||
first = svc.run(dry_run=False, max_jobs=2, now=NOW)
|
||||
assert first["summary"]["jobs_purged"] == 2
|
||||
assert db.state["cursor_job_id"] == "j1"
|
||||
second = svc.run(dry_run=False, max_jobs=2, now=NOW)
|
||||
assert [j["job_id"] for j in second["jobs"]] == ["j2", "j3"]
|
||||
third = svc.run(dry_run=False, max_jobs=2, now=NOW)
|
||||
assert [j["job_id"] for j in third["jobs"]] == ["j4"]
|
||||
assert db.state["cursor_job_id"] is None # wrapped
|
||||
|
||||
def test_real_run_uses_settings_batch_size(self):
|
||||
jobs = [_job(job_id=f"j{i}") for i in range(3)]
|
||||
svc, db, storage = _service(jobs, storage_retention_max_jobs_per_run=1)
|
||||
assert svc.run(dry_run=False, now=NOW)["summary"]["jobs_purged"] == 1
|
||||
|
||||
def test_scoped_run_only_touches_listed_jobs(self):
|
||||
svc, db, storage = _service([_job(job_id="a"), _job(job_id="b")])
|
||||
report = svc.run(dry_run=False, job_ids=["b"], now=NOW)
|
||||
assert [j["job_id"] for j in report["jobs"]] == ["b"]
|
||||
assert all(p.startswith("jobs/b/") for p in storage.deleted)
|
||||
assert db.state == {}
|
||||
|
||||
def test_scoped_min_age_override(self):
|
||||
recent = _job(job_id="a", timeline=[{"status": "complete", "timestamp": NOW.isoformat()}])
|
||||
svc, db, storage = _service([recent])
|
||||
assert svc.run(dry_run=True, job_ids=["a"], now=NOW)["skipped"] == {"too_recent": 1}
|
||||
assert svc.run(dry_run=True, job_ids=["a"], min_age_days=0, now=NOW)["summary"]["jobs_to_purge"] == 1
|
||||
|
||||
def test_orphans_section(self):
|
||||
files = {k: v for k, v in _listing("a")}
|
||||
files["jobs/ghost/finals/x.mp4"] = 2**30
|
||||
svc, db, storage = _service([_job(job_id="a")], files)
|
||||
report = svc.run(dry_run=True, include_orphans=True, now=NOW)
|
||||
assert report["orphans"]["folders"] == 1
|
||||
assert report["orphans"]["largest"][0]["job_id"] == "ghost"
|
||||
|
||||
|
||||
class TestInterruptedPurge:
|
||||
def test_markers_are_set_before_any_delete(self):
|
||||
svc, db, storage = _service([_job(job_id="a")])
|
||||
seen = {}
|
||||
|
||||
def delete(path, ignore_missing=False):
|
||||
# at the first delete the job must already say what's being purged
|
||||
if not seen:
|
||||
doc = db.data["a"]
|
||||
seen.update(renders=doc.get("renders_purged_at"), stems=doc.get("stems_purged_at"),
|
||||
status=(doc.get("storage_purge") or {}).get("status"))
|
||||
storage.files.pop(path, None)
|
||||
storage.deleted.append(path)
|
||||
return True
|
||||
|
||||
storage.delete_file = delete
|
||||
svc.run(dry_run=False, now=NOW)
|
||||
assert seen == {"renders": NOW, "stems": NOW, "status": "pending"}
|
||||
|
||||
def test_interrupted_purge_is_finished_by_next_pass(self):
|
||||
svc, db, storage = _service([_job(job_id="a")])
|
||||
calls = {"n": 0}
|
||||
real = storage.delete_file
|
||||
|
||||
def dies_after_two(path, ignore_missing=False):
|
||||
calls["n"] += 1
|
||||
if calls["n"] > 2:
|
||||
raise SystemExit("instance killed")
|
||||
return real(path, ignore_missing)
|
||||
|
||||
storage.delete_file = dies_after_two
|
||||
with pytest.raises(SystemExit):
|
||||
svc.run(dry_run=False, now=NOW)
|
||||
doc = db.data["a"]
|
||||
assert doc["storage_purge"]["status"] == "pending"
|
||||
assert doc["stems_purged_at"] == NOW # regenerate will re-separate
|
||||
storage.delete_file = real
|
||||
db.data["a"]["state_data"].pop("storage_purge_in_progress", None) # stale claim
|
||||
report = svc.run(dry_run=False, now=NOW + timedelta(hours=1))
|
||||
assert report["summary"]["jobs_purged"] == 1
|
||||
assert db.data["a"]["storage_purge"]["status"] == "complete"
|
||||
@@ -120,7 +120,7 @@ class TestGetStyleUploadUrls:
|
||||
)
|
||||
])
|
||||
|
||||
result = await get_style_upload_urls("job-abc", body, admin_auth)
|
||||
result = get_style_upload_urls("job-abc", body, admin_auth)
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert len(result["upload_urls"]) == 1
|
||||
@@ -143,7 +143,7 @@ class TestGetStyleUploadUrls:
|
||||
|
||||
from fastapi import HTTPException
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_style_upload_urls("job-abc", body, admin_auth)
|
||||
get_style_upload_urls("job-abc", body, admin_auth)
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "Invalid file_type for style upload" in str(exc_info.value.detail)
|
||||
|
||||
@@ -163,7 +163,7 @@ class TestGetStyleUploadUrls:
|
||||
|
||||
from fastapi import HTTPException
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_style_upload_urls("nonexistent", body, admin_auth)
|
||||
get_style_upload_urls("nonexistent", body, admin_auth)
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -183,7 +183,7 @@ class TestGetStyleUploadUrls:
|
||||
|
||||
from fastapi import HTTPException
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_style_upload_urls("job-abc", body, admin_auth)
|
||||
get_style_upload_urls("job-abc", body, admin_auth)
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "cutoff" in str(exc_info.value.detail).lower()
|
||||
|
||||
@@ -204,7 +204,7 @@ class TestGetStyleUploadUrls:
|
||||
|
||||
from fastapi import HTTPException
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_style_upload_urls("job-abc", body, user_auth)
|
||||
get_style_upload_urls("job-abc", body, user_auth)
|
||||
assert exc_info.value.status_code == 403
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -223,7 +223,7 @@ class TestGetStyleUploadUrls:
|
||||
|
||||
from fastapi import HTTPException
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_style_upload_urls("job-abc", body, admin_auth)
|
||||
get_style_upload_urls("job-abc", body, admin_auth)
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "extension" in str(exc_info.value.detail).lower()
|
||||
|
||||
@@ -239,7 +239,7 @@ class TestGetStyleUploadUrls:
|
||||
FileUploadRequest(filename="introimg.jpg", content_type="image/jpeg", file_type="style_intro_background"),
|
||||
])
|
||||
|
||||
result = await get_style_upload_urls("job-abc", body, admin_auth)
|
||||
result = get_style_upload_urls("job-abc", body, admin_auth)
|
||||
assert len(result["upload_urls"]) == 2
|
||||
|
||||
|
||||
@@ -269,7 +269,7 @@ class TestCompleteStyleUploads:
|
||||
uploaded_files=["style_karaoke_background"],
|
||||
)
|
||||
|
||||
result = await complete_style_uploads("job-abc", body, admin_auth)
|
||||
result = complete_style_uploads("job-abc", body, admin_auth)
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert "karaoke_background" in result["assets_updated"]
|
||||
@@ -310,7 +310,7 @@ class TestCompleteStyleUploads:
|
||||
color_overrides={"artist_color": "#ff0000"},
|
||||
)
|
||||
|
||||
result = await complete_style_uploads("job-abc", body, admin_auth)
|
||||
result = complete_style_uploads("job-abc", body, admin_auth)
|
||||
|
||||
assert result["status"] == "success"
|
||||
mock_ts.apply_color_overrides.assert_called_once()
|
||||
@@ -330,7 +330,7 @@ class TestCompleteStyleUploads:
|
||||
|
||||
from fastapi import HTTPException
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await complete_style_uploads("job-abc", body, admin_auth)
|
||||
complete_style_uploads("job-abc", body, admin_auth)
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "not uploaded" in str(exc_info.value.detail).lower()
|
||||
|
||||
@@ -345,5 +345,5 @@ class TestCompleteStyleUploads:
|
||||
|
||||
from fastapi import HTTPException
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await complete_style_uploads("job-abc", body, admin_auth)
|
||||
complete_style_uploads("job-abc", body, admin_auth)
|
||||
assert exc_info.value.status_code == 400
|
||||
@@ -228,4 +228,4 @@ class TestAudioSeparatorStatus:
|
||||
|
||||
from backend.api.routes.health import check_audio_separator_status
|
||||
|
||||
assert await audio_separator_health() == check_audio_separator_status()
|
||||
assert audio_separator_health() == check_audio_separator_status()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
Resolve a job's user-supplied ("existing") instrumental to a path that exists.
|
||||
|
||||
``existing_instrumental_gcs_path`` was recorded under ``uploads/{job_id}/...``,
|
||||
which the bucket lifecycle deletes after 7 days — so any re-render, regenerate
|
||||
or edit of an older bring-your-own-instrumental job lost its instrumental. The
|
||||
video pipeline stages a copy at the job root (``jobs/{id}/custom_instrumental.<ext>``,
|
||||
see video_worker_orchestrator._run_encoding), which is kept forever.
|
||||
|
||||
New uploads are persisted to that root path at upload time (file_upload); for
|
||||
older jobs this resolver falls back to the staged copy and (best-effort)
|
||||
repoints the job at it, so the fix migrates jobs lazily as they're used.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STAGED_STEMS = ("custom_instrumental", "existing_instrumental")
|
||||
|
||||
|
||||
def persistent_instrumental_path(job_id: str, source_path: str) -> str:
|
||||
"""The job-root path a user instrumental is kept at (same name the encoder globs)."""
|
||||
ext = os.path.splitext(source_path or "")[1].lower() or ".mp3"
|
||||
return f"jobs/{job_id}/custom_instrumental{ext}"
|
||||
|
||||
|
||||
def _staged_copy(job_id: str, storage) -> Optional[str]:
|
||||
try:
|
||||
names = storage.list_files(f"jobs/{job_id}/")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] Couldn't list job files for staged instrumental: {e}")
|
||||
return None
|
||||
prefix = f"jobs/{job_id}/"
|
||||
for stem in STAGED_STEMS:
|
||||
for name in sorted(names):
|
||||
rel = name[len(prefix):]
|
||||
if "/" not in rel and os.path.splitext(rel)[0] == stem:
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def resolve_existing_instrumental(job, storage, job_manager=None, log=None) -> Optional[str]:
|
||||
"""Return a GCS path for the job's existing instrumental that actually exists.
|
||||
|
||||
- the recorded path, if it exists;
|
||||
- else the staged job-root copy (and repoint the job at it, best-effort);
|
||||
- else the recorded path unchanged (the caller fails loudly as before).
|
||||
"""
|
||||
recorded = getattr(job, "existing_instrumental_gcs_path", None)
|
||||
if not recorded:
|
||||
return recorded
|
||||
job_id = job.job_id
|
||||
try:
|
||||
if storage.file_exists(recorded):
|
||||
return recorded
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] Couldn't check existing instrumental {recorded}: {e}")
|
||||
return recorded
|
||||
|
||||
staged = _staged_copy(job_id, storage)
|
||||
if not staged:
|
||||
logger.error(f"[job:{job_id}] Existing instrumental {recorded} is gone and no staged copy exists")
|
||||
return recorded
|
||||
message = f"Existing instrumental {recorded} expired; using staged copy {staged}"
|
||||
logger.warning(f"[job:{job_id}] {message}")
|
||||
if log is not None:
|
||||
log.warning(message)
|
||||
if job_manager is not None:
|
||||
try:
|
||||
job_manager.update_job(job_id, {"existing_instrumental_gcs_path": staged})
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] Couldn't repoint existing_instrumental_gcs_path: {e}")
|
||||
return staged
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Per-key re-entrant locks (in-process).
|
||||
|
||||
Route handlers now run in FastAPI's threadpool (plain ``def``), so two requests
|
||||
for the same job/user on one instance can interleave inside non-transactional
|
||||
check-then-write code (e.g. a double-clicked Cancel refunding twice). When those
|
||||
handlers were never-awaiting ``async def``s they ran start-to-finish on the
|
||||
event loop, which serialized them per instance; these locks restore exactly
|
||||
that per-instance guarantee. They do NOT coordinate across Cloud Run instances
|
||||
(nothing did before either) — that would need Firestore transactions.
|
||||
|
||||
Usage::
|
||||
|
||||
with job_lock(job_id):
|
||||
...check status, then write...
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from typing import Dict, Iterator
|
||||
|
||||
|
||||
class KeyedLocks:
|
||||
def __init__(self) -> None:
|
||||
self._guard = threading.Lock()
|
||||
self._locks: Dict[str, threading.RLock] = {}
|
||||
self._refs: Dict[str, int] = {}
|
||||
|
||||
@contextmanager
|
||||
def hold(self, key: str) -> Iterator[None]:
|
||||
with self._guard:
|
||||
lock = self._locks.get(key)
|
||||
if lock is None:
|
||||
lock = self._locks[key] = threading.RLock()
|
||||
self._refs[key] = self._refs.get(key, 0) + 1
|
||||
try:
|
||||
with lock:
|
||||
yield
|
||||
finally:
|
||||
with self._guard:
|
||||
self._refs[key] -= 1
|
||||
if self._refs[key] == 0:
|
||||
# Nobody holds or waits on it — drop it so the map stays small.
|
||||
del self._refs[key]
|
||||
del self._locks[key]
|
||||
|
||||
|
||||
_job_locks = KeyedLocks()
|
||||
_user_locks = KeyedLocks()
|
||||
|
||||
|
||||
def job_lock(job_id: str):
|
||||
return _job_locks.hold(job_id or "")
|
||||
|
||||
|
||||
def user_lock(email: str):
|
||||
return _user_locks.hold((email or "").lower())
|
||||
@@ -193,6 +193,15 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
|
||||
quick_render = None
|
||||
|
||||
# Restore mode: storage retention purged this completed job's stems and the
|
||||
# screens worker asked for them back (backend/services/stems_restore.py).
|
||||
# Separate + upload as usual, then hand back to the screens worker; skip the
|
||||
# first-run-only steps (quick version, prep-phase advance, auto-approval).
|
||||
from backend.services.stems_restore import complete_stems_restore, is_restore_run, mark_restore_failed
|
||||
restore_mode = is_restore_run(job)
|
||||
if restore_mode:
|
||||
job_log.info("RESTORE MODE: re-separating stems purged by storage retention")
|
||||
|
||||
# Create temporary working directory
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_{job_id}_")
|
||||
job_log.info(f"Created temp directory: {temp_dir}")
|
||||
@@ -240,7 +249,7 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
# kjbox make-it jobs: a quick single-model separation on the warm
|
||||
# GPU, then a background render of a scrolling-lyrics draft video
|
||||
# while the ensemble below runs. Never raises; joined in `finally`.
|
||||
if model_dir:
|
||||
if model_dir and not restore_mode:
|
||||
quick_render = start_quick_version(
|
||||
job, audio_path, temp_dir, model_dir, job_manager, storage, job_log
|
||||
)
|
||||
@@ -364,7 +373,7 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
|
||||
# Store processing metadata for separation provenance
|
||||
duration = time.time() - start_time
|
||||
job_manager.update_processing_metadata(job_id, "separation", {
|
||||
job_manager.update_processing_metadata(job_id, "separation_restore" if restore_mode else "separation", {
|
||||
"provider": "local_gpu" if model_dir else "remote_api",
|
||||
"clean_model": effective_model_names['clean_instrumental_model'],
|
||||
"backing_models": effective_model_names['backing_vocals_models'],
|
||||
@@ -383,6 +392,12 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Backing vocals analysis failed (non-fatal): {e}")
|
||||
|
||||
if restore_mode:
|
||||
await complete_stems_restore(job_id, job_manager)
|
||||
duration = time.time() - start_time
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=audio mode=restore status=success duration={duration:.1f}s")
|
||||
return True
|
||||
|
||||
# Mark audio processing complete
|
||||
job_manager.mark_audio_complete(job_id)
|
||||
|
||||
@@ -413,6 +428,8 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
except DownloadError as e:
|
||||
duration = time.time() - start_time
|
||||
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
|
||||
if restore_mode:
|
||||
mark_restore_failed(job_id, job_manager)
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id,
|
||||
error_message=f"Audio download failed: {str(e)}",
|
||||
@@ -423,6 +440,8 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
except Exception as e:
|
||||
duration = time.time() - start_time
|
||||
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
|
||||
if restore_mode:
|
||||
mark_restore_failed(job_id, job_manager)
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id,
|
||||
error_message=f"Audio separation failed: {str(e)}",
|
||||
|
||||
@@ -117,6 +117,14 @@ async def generate_screens(job_id: str) -> bool:
|
||||
logger.error(f"[job:{job_id}] Prerequisites not met for screen generation")
|
||||
return False
|
||||
|
||||
# Storage retention purged this job's separated stems: re-run audio
|
||||
# separation first (the audio worker re-triggers this worker when done), so
|
||||
# review / render / encode find the stems where they always were.
|
||||
from backend.services.stems_restore import NOT_NEEDED, FAILED as RESTORE_FAILED, maybe_start_stems_restore
|
||||
restore = await maybe_start_stems_restore(job, job_manager, job_log)
|
||||
if restore != NOT_NEEDED:
|
||||
return restore != RESTORE_FAILED
|
||||
|
||||
# Set up log capture for VideoGenerator and style_helper (after the guards above
|
||||
# so their early returns don't leak handlers).
|
||||
log_handler = setup_job_logging(job_id, "screens", *SCREENS_WORKER_LOGGERS)
|
||||
@@ -462,7 +470,10 @@ async def _generate_title_screen(
|
||||
# Generate title screen images only (MOV video is generated on GCE encoding worker)
|
||||
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
|
||||
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
|
||||
video_generator.create_title_video(
|
||||
# 4K PIL render + PNG/JPG encode is seconds of CPU — keep it off the
|
||||
# event loop (it froze every request on the instance; 2026-10-03).
|
||||
await asyncio.to_thread(
|
||||
video_generator.create_title_video,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
format=title_format,
|
||||
@@ -537,7 +548,10 @@ async def _generate_end_screen(
|
||||
# Generate end screen images only (MOV video is generated on GCE encoding worker)
|
||||
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
|
||||
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
|
||||
video_generator.create_end_video(
|
||||
# 4K PIL render + PNG/JPG encode is seconds of CPU — keep it off the
|
||||
# event loop (it froze every request on the instance; 2026-10-03).
|
||||
await asyncio.to_thread(
|
||||
video_generator.create_end_video,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
format=end_format,
|
||||
@@ -583,6 +597,19 @@ async def _upload_screens(
|
||||
title_screen_path: Path to title screen image (.png)
|
||||
end_screen_path: Path to end screen image (.png)
|
||||
"""
|
||||
# Sync GCS uploads (multi-MB 4K PNGs) + Firestore writes — off the loop.
|
||||
await asyncio.to_thread(
|
||||
_upload_screens_sync, job_id, job_manager, storage, title_screen_path, end_screen_path
|
||||
)
|
||||
|
||||
|
||||
def _upload_screens_sync(
|
||||
job_id: str,
|
||||
job_manager: JobManager,
|
||||
storage: StorageService,
|
||||
title_screen_path: str,
|
||||
end_screen_path: str
|
||||
) -> None:
|
||||
# Upload title screen images (.png and .jpg)
|
||||
title_base = title_screen_path.replace('.png', '')
|
||||
for ext, key in [('.png', 'title_png'), ('.jpg', 'title_jpg')]:
|
||||
@@ -757,13 +784,16 @@ async def _transcode_review_audio(
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
try:
|
||||
job = job_manager.get_job(job_id)
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
job_log.warning(f"Could not get job {job_id} for review audio transcoding")
|
||||
return
|
||||
|
||||
# GCS download of up to 4 ~35MB FLACs + an ffmpeg transcode each (7-15s
|
||||
# apiece) — this ran ON the event loop and froze the whole instance for
|
||||
# 10-45s per job (2026-10-03 analysis). Run it in a worker thread.
|
||||
transcoding = AudioTranscodingService()
|
||||
transcoded = transcoding.prepare_review_audio_for_job(job)
|
||||
transcoded = await asyncio.to_thread(transcoding.prepare_review_audio_for_job, job)
|
||||
|
||||
job_log.info(f"Review audio transcoding complete: {len(transcoded)} files")
|
||||
|
||||
@@ -771,7 +801,13 @@ async def _transcode_review_audio(
|
||||
# /waveform-data endpoint is a pure GCS-cache read when the user opens
|
||||
# review (a miss there decodes a whole stem — seconds of CPU on the
|
||||
# API instance, which is what wedged it under concurrent load).
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
# The first import pulls in numpy/pydub/matplotlib (seconds of CPU on a
|
||||
# fresh instance) — import it in a worker thread, not on the loop.
|
||||
def _import_audio_analysis():
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
return AudioAnalysisService
|
||||
|
||||
AudioAnalysisService = await asyncio.to_thread(_import_audio_analysis)
|
||||
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
waveform_source = stems.get("backing_vocals") or job.input_media_gcs_path
|
||||
|
||||
@@ -8,6 +8,7 @@ confirmation (awaiting_duration_confirm) and takes action:
|
||||
|
||||
Called by Cloud Scheduler via an internal endpoint (hourly).
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
@@ -33,6 +34,17 @@ _DURATION_CONFIRM_STATUSES = {JobStatus.AWAITING_DURATION_CONFIRM}
|
||||
|
||||
|
||||
async def process_stale_reviews() -> Dict[str, Any]:
|
||||
"""Async entry point: run the (entirely synchronous) processor in a worker thread.
|
||||
|
||||
The body does up to ~1500 Firestore job reads, credit refunds and email
|
||||
sends (Postmark API → SMTP fallback, up to ~15s each). It used to be an
|
||||
``async def`` with no awaits, so the hourly cron froze every request on the
|
||||
API instance for its whole duration (2026-10-03 analysis).
|
||||
"""
|
||||
return await asyncio.to_thread(process_stale_reviews_sync)
|
||||
|
||||
|
||||
def process_stale_reviews_sync() -> Dict[str, Any]:
|
||||
"""
|
||||
Query for stale review / duration-confirm jobs and take action.
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
Storage-retention pass as a Cloud Run Job (``storage-retention-job``).
|
||||
|
||||
The API endpoint ``POST /api/internal/storage-retention/run`` (Cloud Scheduler,
|
||||
daily) starts this job instead of doing the work itself: the backend service
|
||||
throttles CPU outside requests and requests through Cloudflare time out after
|
||||
100s, while a full pass takes minutes. See backend/services/storage_retention.py.
|
||||
|
||||
Usage:
|
||||
python -m backend.workers.storage_retention_worker --dry-run true \\
|
||||
[--max-jobs N] [--include-orphans] [--report-path storage-retention/reports/x.json]
|
||||
"""
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
|
||||
|
||||
def _bool(value: str) -> bool:
|
||||
return str(value).strip().lower() not in ("false", "0", "no")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Storage-retention pass")
|
||||
parser.add_argument("--dry-run", type=_bool, default=True)
|
||||
parser.add_argument("--max-jobs", type=int, default=None)
|
||||
parser.add_argument("--include-orphans", action="store_true")
|
||||
parser.add_argument("--report-path", default=None)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
||||
from backend.services.storage_retention import StorageRetentionService
|
||||
|
||||
try:
|
||||
report = StorageRetentionService().run(
|
||||
dry_run=args.dry_run, max_jobs=args.max_jobs,
|
||||
include_orphans=args.include_orphans, report_path=args.report_path,
|
||||
)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("STORAGE_RETENTION job crashed")
|
||||
return 1
|
||||
# Non-zero exit marks the Cloud Run execution failed (visible in the
|
||||
# console/alerts) when the report couldn't be written or any job errored.
|
||||
return 1 if (report.get("report_write_error") or report.get("errors")) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -8,6 +8,7 @@ This module uses the unified style_loader from karaoke_gen for
|
||||
consistent style handling across local CLI and cloud backend.
|
||||
"""
|
||||
import json
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -101,7 +102,10 @@ class StyleConfig:
|
||||
self._has_custom_styles = bool(style_params_gcs_path)
|
||||
|
||||
# Use the unified style loader
|
||||
self._styles_path, self._style_params = load_styles_from_gcs(
|
||||
# Sync GCS downloads (theme JSON, 4K backgrounds, fonts) — run off the
|
||||
# event loop so they can't freeze the API instance (2026-10-03).
|
||||
self._styles_path, self._style_params = await asyncio.to_thread(
|
||||
load_styles_from_gcs,
|
||||
style_params_gcs_path=style_params_gcs_path,
|
||||
style_assets=style_assets,
|
||||
temp_dir=self.temp_dir,
|
||||
|
||||
@@ -42,6 +42,8 @@ from backend.services.admin_rerender_service import (
|
||||
admin_rerender_kept_outputs,
|
||||
suppress_customer_notifications,
|
||||
)
|
||||
from backend.services.regenerate_service import active_regenerate
|
||||
from backend.utils.existing_instrumental import resolve_existing_instrumental
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
from backend.services.rclone_service import get_rclone_service
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
@@ -269,6 +271,17 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
job_log.warning(status_error)
|
||||
return False
|
||||
|
||||
# A user-supplied instrumental recorded under uploads/ expires after 7 days;
|
||||
# fall back to (and repoint the job at) its staged copy under jobs/{id}/.
|
||||
if getattr(job, 'existing_instrumental_gcs_path', None):
|
||||
job.existing_instrumental_gcs_path = resolve_existing_instrumental(
|
||||
job, storage, job_manager=job_manager, log=job_log,
|
||||
)
|
||||
|
||||
# Storage-retention regenerate: GCS outputs only (snapshot taken at worker
|
||||
# start — the marker is cleared with the COMPLETE transition below).
|
||||
regenerate = active_regenerate(job)
|
||||
|
||||
# Create temporary working directory
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_video_{job_id}_")
|
||||
original_cwd = os.getcwd()
|
||||
@@ -346,26 +359,30 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
if not result.success:
|
||||
raise Exception(result.error_message or "Orchestrator failed")
|
||||
|
||||
# Prepare distribution directory for native uploads
|
||||
with job_span("distribution", job_id):
|
||||
await _handle_native_distribution(
|
||||
job_id=job_id,
|
||||
job=job,
|
||||
job_log=job_log,
|
||||
job_manager=job_manager,
|
||||
temp_dir=temp_dir,
|
||||
result={
|
||||
'brand_code': result.brand_code,
|
||||
'youtube_url': result.youtube_url,
|
||||
'final_video': result.final_video,
|
||||
'final_video_lossy': result.final_video_lossy,
|
||||
'final_video_720p': result.final_video_720p,
|
||||
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
|
||||
'dropbox_link': result.dropbox_link,
|
||||
'gdrive_files': result.gdrive_files,
|
||||
},
|
||||
storage=storage,
|
||||
)
|
||||
# Prepare distribution directory for native uploads. A GCS-only
|
||||
# regenerate publishes nothing.
|
||||
if regenerate:
|
||||
job_log.info("GCS-only regenerate: skipping native distribution")
|
||||
else:
|
||||
with job_span("distribution", job_id):
|
||||
await _handle_native_distribution(
|
||||
job_id=job_id,
|
||||
job=job,
|
||||
job_log=job_log,
|
||||
job_manager=job_manager,
|
||||
temp_dir=temp_dir,
|
||||
result={
|
||||
'brand_code': result.brand_code,
|
||||
'youtube_url': result.youtube_url,
|
||||
'final_video': result.final_video,
|
||||
'final_video_lossy': result.final_video_lossy,
|
||||
'final_video_720p': result.final_video_720p,
|
||||
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
|
||||
'dropbox_link': result.dropbox_link,
|
||||
'gdrive_files': result.gdrive_files,
|
||||
},
|
||||
storage=storage,
|
||||
)
|
||||
|
||||
# Upload generated files to GCS
|
||||
# Note: State transition to PACKAGING is handled by the orchestrator in _run_distribution()
|
||||
@@ -394,12 +411,22 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
# An admin re-render leaves outputs it doesn't re-publish in place
|
||||
# (e.g. YouTube now disabled) — keep their links.
|
||||
kept_outputs = admin_rerender_kept_outputs(job)
|
||||
state_updates: Dict[str, Any] = {
|
||||
'state_data.brand_code': result.brand_code,
|
||||
'state_data.youtube_url': result.youtube_url or kept_outputs.get('youtube_url'),
|
||||
'state_data.youtube_upload_queued': result.youtube_upload_queued,
|
||||
'state_data.dropbox_link': result.dropbox_link or kept_outputs.get('dropbox_link'),
|
||||
'state_data.gdrive_files': result.gdrive_files or kept_outputs.get('gdrive_files'),
|
||||
if regenerate:
|
||||
# GCS-only regenerate: nothing was published, so the job's
|
||||
# existing brand code / YouTube / Dropbox / Drive links stand.
|
||||
state_updates: Dict[str, Any] = {}
|
||||
else:
|
||||
state_updates = {
|
||||
'state_data.brand_code': result.brand_code,
|
||||
'state_data.youtube_url': result.youtube_url or kept_outputs.get('youtube_url'),
|
||||
'state_data.youtube_upload_queued': result.youtube_upload_queued,
|
||||
'state_data.dropbox_link': result.dropbox_link or kept_outputs.get('dropbox_link'),
|
||||
'state_data.gdrive_files': result.gdrive_files or kept_outputs.get('gdrive_files'),
|
||||
}
|
||||
state_updates.update({
|
||||
# Fresh renders were just uploaded, so a storage-retention purge
|
||||
# marker is stale (the stems marker is cleared by the restore).
|
||||
'renders_purged_at': None,
|
||||
# Clear the visibility-change guard flag (previously popped from the map).
|
||||
'state_data.visibility_change_in_progress': DELETE_FIELD,
|
||||
# Fresh finals were just uploaded, so any earlier "outputs deleted"
|
||||
@@ -410,9 +437,12 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
# A theme/admin re-render (if any) finished; only a FAILED
|
||||
# re-render keeps its marker (it lets the retry re-run it).
|
||||
'state_data.theme_rerender': DELETE_FIELD,
|
||||
# The admin re-render marker is cleared atomically WITH the
|
||||
# COMPLETE transition below, so a failed transition keeps it.
|
||||
}
|
||||
# The admin re-render / regenerate markers are cleared atomically
|
||||
# WITH the COMPLETE transition below, so a failed transition keeps them.
|
||||
})
|
||||
if regenerate and regenerate.get('after') == 'change_to_private':
|
||||
# The chained visibility change sets its own guard right away.
|
||||
state_updates.pop('state_data.visibility_change_in_progress', None)
|
||||
if result.distribution_warnings:
|
||||
state_updates['state_data.distribution_warnings'] = result.distribution_warnings
|
||||
job_manager.update_job(job_id, state_updates)
|
||||
@@ -451,20 +481,34 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
if is_admin_rerender:
|
||||
completion_metadata["admin_rerender"] = True
|
||||
completion_metadata["customer_notified"] = notify_customer
|
||||
if regenerate:
|
||||
completion_metadata["regenerate"] = True
|
||||
completion_metadata["customer_notified"] = notify_customer
|
||||
completion_metadata["regenerate_source"] = regenerate.get("source")
|
||||
if not notify_customer:
|
||||
job_log.info("Admin re-render: completion email/push suppressed (notify_customer=False)")
|
||||
job_log.info("Re-render/regenerate: completion email/push suppressed (notify_customer=False)")
|
||||
extra_updates = {'state_data.admin_rerender': DELETE_FIELD}
|
||||
if regenerate:
|
||||
from datetime import datetime as _dt, timezone as _tz
|
||||
extra_updates['state_data.regenerate'] = DELETE_FIELD
|
||||
extra_updates['renders_regenerated_at'] = _dt.now(_tz.utc)
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.COMPLETE,
|
||||
progress=100,
|
||||
message="Karaoke generation complete!",
|
||||
message="Karaoke generation complete!" if not regenerate else "Video regenerated",
|
||||
timeline_metadata=completion_metadata,
|
||||
notify=notify_customer,
|
||||
extra_updates={'state_data.admin_rerender': DELETE_FIELD},
|
||||
# An admin re-render isn't a newly completed job for the user.
|
||||
count_completion=not is_admin_rerender,
|
||||
extra_updates=extra_updates,
|
||||
# An admin re-render / regenerate isn't a newly completed job for the user.
|
||||
count_completion=not (is_admin_rerender or regenerate),
|
||||
)
|
||||
|
||||
# A regenerate started by a public->private visibility change (the
|
||||
# redistribution needs the full finals set): run that change now.
|
||||
if regenerate and regenerate.get('after') == 'change_to_private':
|
||||
await _run_chained_change_to_private(job_id, job_manager, regenerate, job_log)
|
||||
|
||||
# If this was a requests-board community pick published directly here
|
||||
# (i.e. not deferred to the youtube_upload_queue), advance its request
|
||||
# to `published` and fan out "your track is live" voter emails. The
|
||||
@@ -532,6 +576,25 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
logger.debug(f"Cleaned up temp directory: {temp_dir}")
|
||||
|
||||
|
||||
async def _run_chained_change_to_private(job_id: str, job_manager: JobManager, regenerate: Dict[str, Any], job_log) -> None:
|
||||
"""Finish a public->private visibility change that waited for a regenerate."""
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
requested_by = regenerate.get('requested_by') or 'unknown'
|
||||
try:
|
||||
fresh = job_manager.get_job(job_id)
|
||||
await VisibilityChangeService(job_manager).change_to_private(
|
||||
job_id, fresh, requested_by, regenerate_if_missing=False,
|
||||
)
|
||||
job_log.info("Regenerated finals redistributed: visibility changed to private")
|
||||
except Exception as e: # noqa: BLE001 - the regenerate itself succeeded
|
||||
job_log.error(f"Visibility change to private after regenerate failed: {e}")
|
||||
logger.exception(f"[job:{job_id}] Chained change_to_private failed")
|
||||
try:
|
||||
job_manager.update_job(job_id, {'state_data.visibility_change_in_progress': DELETE_FIELD})
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
async def redistribute_video(job_id: str) -> bool:
|
||||
"""
|
||||
Redistribute existing finals for a completed job (no re-encoding).
|
||||
|
||||
@@ -32,6 +32,7 @@ from backend.services.tracing import job_span, add_span_event
|
||||
from backend.workers.supersede import capture_generation, encoding_worker_job_id
|
||||
from backend.services.theme_rerender_service import rerender_brand_code
|
||||
from backend.services.admin_rerender_service import suppress_customer_notifications
|
||||
from backend.services.regenerate_service import is_gcs_only_run
|
||||
from backend.services.original_audio import (
|
||||
original_audio_gcs_path,
|
||||
original_audio_output_filename,
|
||||
@@ -133,6 +134,12 @@ class OrchestratorConfig:
|
||||
# transitions that would otherwise abort the redistribution.
|
||||
redistribute_mode: bool = False
|
||||
|
||||
# GCS-only regenerate (storage retention, backend/services/regenerate_service.py):
|
||||
# rebuild the finals/packages in GCS but skip brand-code allocation, every
|
||||
# distribution upload (YouTube/Dropbox/GDrive), the Discord post and the
|
||||
# GDrive validation — the published outputs are left exactly as they are.
|
||||
gcs_only: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class OrchestratorResult:
|
||||
@@ -333,19 +340,27 @@ class VideoWorkerOrchestrator:
|
||||
# Stage 2: Encoding
|
||||
await self._run_encoding()
|
||||
|
||||
# Stage 3: Organization (brand code)
|
||||
await self._run_organization()
|
||||
if self.config.gcs_only:
|
||||
# Regenerate: GCS outputs only. Keep the existing brand code
|
||||
# (never allocate one) and publish nowhere.
|
||||
self.result.brand_code = self.config.keep_brand_code
|
||||
self.job_log.info(
|
||||
"GCS-only regenerate: skipping organization, distribution and notifications"
|
||||
)
|
||||
else:
|
||||
# Stage 3: Organization (brand code)
|
||||
await self._run_organization()
|
||||
|
||||
# Stage 4: Distribution (YouTube, Dropbox, GDrive)
|
||||
await self._run_distribution()
|
||||
# Stage 4: Distribution (YouTube, Dropbox, GDrive)
|
||||
await self._run_distribution()
|
||||
|
||||
# Stage 5: Notifications (Discord)
|
||||
await self._run_notifications()
|
||||
# Stage 5: Notifications (Discord)
|
||||
await self._run_notifications()
|
||||
|
||||
# Stage 6: Post-distribution GDrive validation
|
||||
# Only for jobs that uploaded to the public share (non-private)
|
||||
if self.config.gdrive_folder_id:
|
||||
await self._trigger_gdrive_validation()
|
||||
# Stage 6: Post-distribution GDrive validation
|
||||
# Only for jobs that uploaded to the public share (non-private)
|
||||
if self.config.gdrive_folder_id:
|
||||
await self._trigger_gdrive_validation()
|
||||
|
||||
self.result.success = True
|
||||
self.result.total_time_seconds = time.time() - start_time
|
||||
@@ -533,8 +548,16 @@ class VideoWorkerOrchestrator:
|
||||
if src:
|
||||
ext = os.path.splitext(src)[1].lower() or ".mp3"
|
||||
dest = f"jobs/{self.config.job_id}/custom_instrumental{ext}"
|
||||
self.storage.copy_blob(src, dest)
|
||||
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
|
||||
if src != dest:
|
||||
self.storage.copy_blob(src, dest)
|
||||
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
|
||||
# uploads/ expires after 7 days: point the job at the
|
||||
# kept job-root copy for future re-renders/regenerates.
|
||||
if src.startswith("uploads/") and self.job_manager:
|
||||
self.job_manager.update_job(
|
||||
self.config.job_id, {"existing_instrumental_gcs_path": dest}
|
||||
)
|
||||
self.config.existing_instrumental_gcs_path = dest
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Failed to stage custom instrumental for GCE encoder: {e}")
|
||||
|
||||
@@ -1280,6 +1303,9 @@ def create_orchestrator_config_from_job(
|
||||
is_duet=is_duet,
|
||||
duet_corrections_json_path=duet_corrections_json_path,
|
||||
|
||||
# GCS-only regenerate (storage retention): no distribution at all
|
||||
gcs_only=is_gcs_only_run(job),
|
||||
|
||||
# Encoding backend - auto selects GCE if available
|
||||
encoding_backend="auto",
|
||||
|
||||
|
||||
+36
-3
@@ -358,6 +358,28 @@ Re-snapshots the tenant theme onto the job (`style_params_gcs_path`, `style_asse
|
||||
|
||||
**Validation (400):** tenant job; `complete` (or `failed` mid re-render); outputs not deleted; has a theme, reviewed lyrics and an instrumental selection; never published to YouTube/GDrive. A tenant Dropbox archive (e.g. `RVILD-0001 - Artist - Title`) is refreshed in place: the re-render reuses the job's brand code (`state_data.theme_rerender.brand_code` → orchestrator `keep_brand_code`), and Dropbox uploads overwrite. **409** if the job left `complete` in the meantime (e.g. a double-click already started a re-render).
|
||||
|
||||
### Regenerate Video (storage retention)
|
||||
|
||||
Rebuild a finished track's archived video files. Storage retention (see
|
||||
docs/ARCHITECTURE.md § Storage Retention) keeps the 720p final and the CDG/TXT
|
||||
packages of tracks completed >30 days ago and archives the rest.
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/regenerate
|
||||
```
|
||||
|
||||
Response: `{"status": "processing", "job_id": "abc123", "needs_stems": true, "message": "..."}`
|
||||
|
||||
Claims the job (`complete` → `lyrics_complete` with `state_data.regen_restore_status = "review_complete"` and the `state_data.regenerate` marker) and triggers the screens worker. If `stems_purged_at` is set the screens worker first re-runs audio separation from `input_media_gcs_path` (`state_data.stems_restore`), then screens → render → encode, using the existing reviewed lyrics, `instrumental_selection` and style. **GCS only**: no brand-code allocation, no YouTube/Dropbox/Google Drive upload, no Discord post; published links are kept. The owner is emailed/pushed on completion; regenerate completions don't count as new jobs. On success `renders_purged_at` is cleared and `renders_regenerated_at` set.
|
||||
|
||||
**Access:** the job owner or an admin (admin token, e.g. kjbox with `X-Client-Id: kjbox`). **Limits** (customers only, rolling 24h): `REGENERATE_MAX_PER_JOB_PER_DAY` (3) and `REGENERATE_MAX_PER_USER_PER_DAY` (10) → **429**. **400** when not regenerable (not `complete`, outputs deleted, prep/finalise-only, no reviewed lyrics/instrumental selection, input audio gone); **409** while a re-render / visibility change / purge is in progress. A failed regenerate is resumed by `POST /api/jobs/{id}/retry` (`retry_stage: "regenerate"`).
|
||||
|
||||
Downloads of archived files (`GET /api/jobs/{id}/download/{category}/{key}`) return **410** with `detail = {"code": "output_archived", "message": ..., "regenerate_url": "/api/jobs/{id}/regenerate"}`.
|
||||
|
||||
Admin variant (optional quiet run, no rate limit): `POST /api/admin/jobs/{job_id}/regenerate` with `{"notify_customer": false}`.
|
||||
|
||||
A public → private visibility change on a track whose finals were archived regenerates them first (`after: "change_to_private"`), then runs the redistribution automatically.
|
||||
|
||||
### Review
|
||||
|
||||
The combined review flow allows users to review lyrics AND select instrumental track in a single session.
|
||||
@@ -2934,9 +2956,20 @@ user-visible degraded-service surface: `banner_reconnecting`, `banner_unavailabl
|
||||
`banner_waking` (the connectivity banner — reported by `BackendStatusBanner`; `banner_waking`
|
||||
is the calm "starting up our karaoke servers" cold-start state), `lyrics_load_failed`
|
||||
(review page "temporarily unavailable"), `waveform_slow` / `waveform_failed`
|
||||
(Waveforms-mode strips late or missing). Body: `{type, url, job_id?, user_email?,
|
||||
locale, release, detail?}` — `detail` is size-capped server-side (≤12 keys, ≤200
|
||||
chars per value); URLs are stored query-stripped.
|
||||
(Waveforms-mode strips late or missing), and `banner_recovered` (sent once when the
|
||||
banner clears; `detail.duration_ms` / `peak_status` / `dismissed`). Body: `{type, url,
|
||||
job_id?, locale, release, detail?, device_fingerprint?, tab_id?, episode_id?}` — `detail`
|
||||
is size-capped server-side (≤12 keys, ≤200 chars per value); URLs are stored query-stripped.
|
||||
|
||||
**Identity (v0.264.0):** the frontend sends its session token as `Authorization: Bearer …`
|
||||
when signed in; the server resolves and stores `user_email`, `is_admin`, `is_internal`
|
||||
(team domains) and `is_test` (automated-test accounts). A client-sent `user_email` is
|
||||
ignored. `device_fingerprint` is the FingerprintJS `visitorId` (same one the magic-link
|
||||
abuse checks store), `tab_id` is per browser tab, `episode_id` groups one degradation
|
||||
episode (first banner → `banner_recovered`), and `tenant` is derived from the page URL.
|
||||
`server_loop_stall` docs (written by the backend's event-loop watchdog, `source: "server"`)
|
||||
share the collection; clients can't submit that type (422).
|
||||
Summary: `python scripts/client_events_report.py [--days N] [--all]`.
|
||||
|
||||
Each event emits a structured `client_event type=…` INFO log line and is
|
||||
best-effort persisted to the Firestore `client_events` collection (a Firestore
|
||||
|
||||
@@ -224,6 +224,38 @@ jobs/{job_id}/
|
||||
└── lossy_720p.mp4
|
||||
```
|
||||
|
||||
## Storage Retention
|
||||
|
||||
Approved plan: `docs/archive/2026-10-03-gen-storage-retention-plan.md` (workspace repo). Generated files
|
||||
are regenerable, so a daily Cloud Scheduler job (`storage-retention-daily`, 10:30 UTC) →
|
||||
`POST /api/internal/storage-retention/run` → Cloud Run Job `storage-retention-job` (us-east4,
|
||||
`backend/workers/storage_retention_worker.py`; the API throttles CPU outside requests and Cloudflare
|
||||
cuts requests at 100s) → `backend/services/storage_retention.py` purges them from
|
||||
jobs completed (newest `complete` timeline entry) more than `STORAGE_RETENTION_MIN_AGE_DAYS` (30) ago.
|
||||
|
||||
- **Kept forever:** `input/*` (incl. `edited.flac`), `lyrics/`, `style/`, `review_sessions/`,
|
||||
`audio_edit*/`, `uploads/`, `packages/`, `analysis/`, `screens/*.png|jpg`, the 720p final (both the
|
||||
descriptive and `lossy_720p_mp4.mp4` copies), `stems/custom_instrumental.*`, `stems/vocals_derived.*`
|
||||
and the job-root `custom_instrumental.*` / `existing_instrumental.*`. Unknown files are kept.
|
||||
- **Purged:** other `finals/*`, `videos/*`, `previews/*`, `encoded/*`, `quick/*.mp4`, `screens/*.mov`,
|
||||
`review-audio/*`, and separated `stems/*` (only when the input audio is in `jobs/{id}/input/`).
|
||||
- **Never touched:** finalise-only jobs, jobs whose input audio is gone, jobs mid edit/re-render/
|
||||
visibility change/regenerate, pending deferred YouTube uploads, `STORAGE_RETENTION_EXCLUDED_TENANTS`.
|
||||
- **DRY-RUN by default** (`STORAGE_RETENTION_DRY_RUN`, default true): writes a report to
|
||||
`gs://<bucket>/storage-retention/reports/<ts>-dry-run.json`. Real runs purge
|
||||
`STORAGE_RETENTION_MAX_JOBS_PER_RUN` jobs per pass (cursor in `storage_retention/state`), atomically
|
||||
re-check eligibility (`state_data.storage_purge_in_progress` claim), drop the purged `file_urls`
|
||||
entries and record `renders_purged_at`, `stems_purged_at` and a `storage_purge` manifest.
|
||||
`?job_ids=a,b&dry_run=false&min_age_days=0` runs a scoped real pass (testing); a global real purge
|
||||
only happens via the setting.
|
||||
- **Regenerate** (`backend/services/regenerate_service.py`): customer button / admin / kjbox →
|
||||
GCS-only re-run (see docs/API.md § Regenerate Video). Every flow that rebuilds a completed job
|
||||
(regenerate, admin/theme re-render, private→public, Edit, retry) passes the screens worker, whose
|
||||
**stems gate** (`backend/services/stems_restore.py`) re-runs the audio-separation job in restore mode
|
||||
when `stems_purged_at` is set; the audio worker re-triggers screens when the stems are back.
|
||||
- Bucket: versioning on, overwritten versions kept 7 days, soft delete 7 days — purged bytes remain
|
||||
recoverable for about a week.
|
||||
|
||||
## LyricsTranscriber Integration
|
||||
|
||||
**Key Design Decision**: We use LyricsTranscriber as a **library**, not a server.
|
||||
|
||||
@@ -6,6 +6,21 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
---
|
||||
|
||||
## One event loop per instance: `async def` without `await` is a whole-instance freeze (Oct 2026, v0.264.0)
|
||||
|
||||
The "servers unavailable" banner (49 episodes in 2 weeks) was mostly the API's own event loop freezing for 20-45s. Each episode hit 2-3 browsers in the same second, and only ~7 of 28 were near a deploy. Signature in the request logs: every request on the instance, `/api/health` included, completes at the same moment.
|
||||
|
||||
- **The timestamp of a long-latency Cloud Run request log is its START time.** Requests that started at different times but all *end* together (start + latency is constant) mean the loop was blocked.
|
||||
- **A BackgroundTask that is an `async def` runs ON the loop.** The screens worker did 4K PIL renders, GCS transfers and ffmpeg transcodes there. Under `--cpu-throttling` it also ran CPU-starved after the response. Fix: await it inline in the Cloud Tasks request, with heavy steps in `asyncio.to_thread`.
|
||||
- **First `import matplotlib.pyplot` on a fresh instance builds the font cache.** With the Noto font set that was 20-40s of GIL-holding CPU (17 of 28 episodes). Pre-build it in the image (`MPLCONFIGDIR`) and import pyplot lazily. Moving the import to a thread alone wouldn't help, because the build holds the GIL.
|
||||
- **`async def` route + zero awaits = sync I/O on the loop.** 161 such routes existed. A plain `def` route runs in FastAPI's threadpool. The AST guard `backend/tests/test_no_blocking_async_routes.py` fails CI on new ones.
|
||||
- The inverse also fails: a `def` route that calls `asyncio.create_task`/`get_running_loop`. In the threadpool, that raises, or silently does nothing if the `RuntimeError` is swallowed (`rate_limits.trigger_youtube_queue_processing` did exactly that).
|
||||
- **Moving a handler into the threadpool removes the implicit per-instance serialization.** A never-awaiting `async def` used to run start-to-finish uninterrupted, so non-transactional check-then-write code (a double-clicked Cancel refunding twice, a double Complete) was safe on one instance. `backend/utils/keyed_lock.py` restores that: `JobManager.transition_to_state`/`cancel_job` lock per job, `UserService.add_credits` per user. Also grep for `await <converted handler>(`; the guard test checks this now (it found `admin.update_job` awaiting `delete_job_outputs`).
|
||||
- **Watchdog vs `--cpu-throttling`:** an idle instance gets no CPU between requests, so a gap with the loop parked in `select()` is not a stall. The watchdog drops all-idle samples.
|
||||
- **Detection:** `backend/services/loop_watchdog.py` logs `EVENT_LOOP_STALL` with the loop thread's stack and a `culprit=file:line`. Grep for it before guessing.
|
||||
|
||||
---
|
||||
|
||||
## Re-running the render pipeline: three ways the OLD output sneaks back in (Sep 2026, v0.253.0)
|
||||
|
||||
Building "re-render with the current theme" turned up three traps. Any path that re-runs screens/render/encode on a finished job (edit, visibility change, admin reset, theme re-render) has to handle all three.
|
||||
@@ -2221,3 +2236,26 @@ got it right. What we learned (verified on prod's static ffmpeg 7.0.2 and libass
|
||||
fallback. Verify rendering in Linux (`scripts/run-render-tests-linux.sh`).
|
||||
- **Dropped sub-0.1s word gaps made the highlight run early** (up to 0.22s by line end on
|
||||
this job). Karaoke tags now come from one absolute centisecond timeline.
|
||||
|
||||
## Stripe Checkout E2E: self-heal instead of chasing selectors (2026-10-03)
|
||||
|
||||
Stripe's hosted checkout broke the daily E2E five times in six months (radio→button chooser,
|
||||
card-only layout, nested iframe, relabelled name/ZIP, hidden "Pay with card" overlay). Each fix
|
||||
added another selector variant — and each next change still needed a human. Lessons:
|
||||
|
||||
- **Verify sub-goals, don't trust actions.** Run #192 "selected Card" (it found nothing to
|
||||
click), carried on, and failed later on a symptom. Every step now has a `verify`
|
||||
postcondition; a variant only counts if the postcondition holds.
|
||||
- **Self-heal into data, not code.** The LLM fallback's output is a serializable recipe
|
||||
(semantic role/name/text targets, never snapshot refs), promoted to `learned-variants.json`
|
||||
by an auto-merging, data-only PR — safe to merge unattended and replayed without the LLM.
|
||||
- **Bot PRs hit three invisible merge gates** (found live on #1117): (1) their
|
||||
`pull_request` CI run is created "action_required" and, unrun, supersedes a passing
|
||||
dispatched CI Gate — approve it via `POST /actions/runs/{id}/approve`; (2) GitHub's new
|
||||
ruleset default `require_extra_approval_for_unattributed_changes: true` demands a human
|
||||
approval for bot-authored changes even with 0 required reviews — set false explicitly;
|
||||
(3) review threads must be resolved → `@coderabbitai ignore` in bot PR bodies.
|
||||
- **Never send card data to an LLM.** Placeholders substituted locally + redacted snapshots +
|
||||
masked screenshots; tests assert the prompt contains no secrets.
|
||||
|
||||
See `docs/TESTING.md` § Self-Healing Stripe Checkout.
|
||||
@@ -57,6 +57,16 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Encoding-service construction moved off the event loop** (2026-10-03, v0.264.1). The new loop watchdog's first prod catch was a 9.9s stall in `/api/health/detailed`. A cold `get_encoding_service()` imports `google.cloud.compute_v1` (~10s). It's now built in the startup warmup thread, is thread-safe, and async callers use `asyncio.to_thread`. (v0.264.0 was shipped by both #1120 and #1122.)
|
||||
|
||||
- **API event-loop freezes fixed + degradation telemetry identifies users** (2026-10-03, v0.264.0). The "Reconnecting" pill and "servers unavailable" banner were mostly caused by the single API instance freezing for 20-45s. Plan + evidence: `docs/archive/2026-10-03-backend-loop-freezes-telemetry-plan.md`.
|
||||
- **Screens worker:** now runs inline in its Cloud Tasks request (so CPU stays allocated under `--cpu-throttling`), with the heavy steps in worker threads: 4K PIL renders, GCS uploads, review-audio transcode, timing signals and pre-apply.
|
||||
- **Hourly stale-review cron:** runs in a thread.
|
||||
- **Matplotlib font cache:** pre-built in the base image (`MPLCONFIGDIR=/opt/mplconfig`), and pyplot is imported lazily.
|
||||
- **Route handlers:** 161 `async def` routes that never awaited (sync Firestore/GCS/email/Gemini on the loop) are now plain `def`, so they run in FastAPI's threadpool. `backend/tests/test_no_blocking_async_routes.py` keeps it that way, and also blocks sync routes that call `asyncio.create_task`.
|
||||
- **Loop watchdog:** new `backend/services/loop_watchdog.py` logs `EVENT_LOOP_STALL` with the blocking stack. Stalls ≥5s are recorded to `client_events` (`server_loop_stall`). A Cloud Monitoring alert fires on ≥2 stalls of ≥10s in 30 min.
|
||||
- **Telemetry identity:** `client_events` now records the server-resolved user (plus admin/internal/test flags), device fingerprint, tab id, tenant, and a `banner_recovered` event with episode duration. Use `scripts/client_events_report.py` for summaries.
|
||||
|
||||
- **Gemini moved off Vertex AI** (2026-10-01, v0.262.0): every Gemini call (auto-correct compare leg, match-judge, parse-titles, credit eval, tenant bulk analyze, custom lyrics, lyrics translation, error-monitor LLM, agentic correction, translate.py) now uses the Gemini Developer API with the `gemini-api-key` secret via `backend/services/gemini_client.py`, so no AI spend lands on the nomadkaraoke project (Vertex APIs disabled there). Quota/billing/key failures degrade per caller and send one Discord ops alert per 6h. See LESSONS-LEARNED "Gemini: Developer API key, never Vertex".
|
||||
|
||||
- **Translated lyrics follow-ups + review waveform spinner** (2026-10-01, v0.261.0):
|
||||
|
||||
@@ -480,6 +480,56 @@ The production tests cover:
|
||||
- Final encoding and download
|
||||
- Admin dashboard functionality
|
||||
|
||||
## Self-Healing Stripe Checkout (daily E2E Stage 1)
|
||||
|
||||
Stripe changes its hosted checkout page without notice (5 breaking changes Apr–Oct 2026),
|
||||
so `frontend/e2e/helpers/stripe-checkout.ts` runs the checkout as **verified sub-goals**
|
||||
(`selectCard`, `fillCardNumber`, `fillCardExpiry`, `fillCardCvc`, `fillCardholderName`,
|
||||
`fillPostalCode`, `uncheckSaveInfo`, `submitPayment`) via `e2e/helpers/self-healing/`:
|
||||
|
||||
1. **Learned variants** (`self-healing/learned-variants.json`, newest first) — recipes the
|
||||
LLM discovered on earlier live runs.
|
||||
2. **Builtin variants** — the hand-written selectors in `stripe-checkout.ts`.
|
||||
3. **LLM fallback** — Gemini (`E2E_SELF_HEAL_MODELS`, default
|
||||
`gemini-3.5-flash-lite,gemini-3.1-flash-lite,gemini-3.8-flash`; unavailable ids are skipped,
|
||||
failures escalate down the list) is shown a redacted ARIA snapshot + input-masked screenshot
|
||||
and drives the page one action at a time until the step's `verify` postcondition passes.
|
||||
|
||||
Each attempt is judged only by the step's `verify` (e.g. "card-number input visible",
|
||||
"filled field holds the expected value and looks like a card-number field", "redirected to
|
||||
our success page or credit granted server-side") — never by "the click didn't throw".
|
||||
|
||||
**Card data never reaches the LLM:** it may only use `{{CARD_NUMBER}}`-style placeholders
|
||||
(per-step allowlist) that are substituted locally; textbox values and PAN-like digit runs are
|
||||
redacted from observations; inputs are masked in screenshots. Guardrails refuse clicks on
|
||||
Link/Klarna/Cash App/Bank/"Back to…" and on the final Pay button outside `submitPayment`.
|
||||
|
||||
**Fully automatic loop.** When the LLM heals a step and the purchase is verified server-side,
|
||||
the spec writes `test-results/self-heal/learned-variants.json`; the workflow's
|
||||
`self-heal-pr` job opens a data-only PR (label `e2e-self-heal`, `@coderabbitai ignore`),
|
||||
enables auto-merge, and approves the PR's `pull_request` CI run (bot PRs' runs start as
|
||||
"action_required" and block the CI Gate until run; falls back to dispatching `ci.yml`).
|
||||
Next run replays the recipe without the LLM.
|
||||
|
||||
**Repo setting this depends on (changed 2026-10-03, not in code):** the `protect main`
|
||||
ruleset (id 11423976) has `require_extra_approval_for_unattributed_changes: false`. GitHub
|
||||
defaults it to `true` (server-side, ~Aug 2026), which silently blocks bot-authored PRs
|
||||
(`mergeStateStatus: BLOCKED` with all checks green) until a human approves. If a ruleset
|
||||
update ever omits the key, GitHub resets it to `true` — set it explicitly. Discord + the daily email
|
||||
report 🩹 when this happens. Only one open self-heal PR at a time.
|
||||
|
||||
The Gemini key is the AI Studio `gemini-api-key` (billed outside the nomadkaraoke project):
|
||||
a `GEMINI_API_KEY` repo secret if set, else read from Secret Manager via keyless auth (the
|
||||
credential file is deleted before tests run). No key → deterministic-only, as before.
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
# Offline tests (fixture checkout pages + stub LLM) — also run in CI's smoke job
|
||||
npx playwright test --config=playwright.selfheal.config.ts
|
||||
# Exercise the live LLM path end-to-end: Actions → E2E Daily → Run workflow →
|
||||
# self_heal_force_llm = selectCard (forces that step through Gemini; opens a PR)
|
||||
```
|
||||
|
||||
## Concurrent-Load Regression Test (review pages)
|
||||
|
||||
`scripts/load-test-review.py` replays the 2026-09-18 "10 tabs melt the backend"
|
||||
|
||||
+27
-3
@@ -60,6 +60,23 @@ defense-in-depth beneath the signing-free review path.
|
||||
|
||||
---
|
||||
|
||||
## Users see "Reconnecting" / "servers unavailable" banner (API event loop frozen)
|
||||
|
||||
**Symptom:** Users report the orange banner, or `client_events` shows `banner_unavailable` bursts. In the request logs, every request on one instance (including `/api/health`) finishes at the same moment after 10-45s.
|
||||
|
||||
1. **Find the blocking line:**
|
||||
|
||||
```bash
|
||||
gcloud logging read 'resource.labels.service_name="karaoke-backend" AND jsonPayload.message:"EVENT_LOOP_STALL"' --project nomadkaraoke --limit 20 --format='value(timestamp,severity,jsonPayload.message)'
|
||||
```
|
||||
|
||||
The `in progress` lines include the loop thread's stack; `culprit=` is the innermost `backend/` or `karaoke_gen/` frame.
|
||||
2. **Fix:** move that sync work off the loop with `await asyncio.to_thread(...)`, or make the route a plain `def`. `test_no_blocking_async_routes.py` already blocks async routes that never await.
|
||||
3. **Measure user impact:** `python scripts/client_events_report.py --days 7`. It excludes admin/internal/test accounts unless you pass `--all`, and lists `server_loop_stall` culprits.
|
||||
4. **If there are no `EVENT_LOOP_STALL` lines:** the cause is elsewhere (cold start, deploy swap, Cloudflare). Check `banner_waking` events and revision times.
|
||||
|
||||
Background: `docs/archive/2026-10-03-backend-loop-freezes-telemetry-plan.md`.
|
||||
|
||||
## Emails not arriving / E2E "Timed out waiting for email" (Postmark HTML 403)
|
||||
|
||||
**Symptom:** magic links or job emails never arrive; E2E Daily Stage 1 fails at
|
||||
@@ -72,7 +89,8 @@ block at `api.postmarkapp.com`, not a token or payload problem. Seen from
|
||||
`karaoke-backend` and karaoke-decide (us-central1, shared Cloud Run egress IPs) since
|
||||
2026-09-30, in blocks lasting hours (all sends failed 2026-10-02 11:25 UTC onward);
|
||||
us-east4 Cloud Run Jobs were unaffected. IP Allowlisting is OFF in Postmark (checked
|
||||
2026-10-02), so this is Postmark's network firewall — ticket #11562402. A JSON 403
|
||||
2026-10-02), so this is Postmark's network firewall — ticket #11562402, where Postmark
|
||||
confirmed an IP-reputation block on the shared Google IP that they won't lift. A JSON 403
|
||||
(`ErrorCode=10`) is a real bad-token error instead.
|
||||
|
||||
**Mitigation in code:** on an HTML 403, `PostmarkEmailProvider` immediately re-sends via
|
||||
@@ -93,8 +111,14 @@ The E2E `waitForEmail` helper now checks `GET /api/admin/users/{email}/emails` o
|
||||
timeout and reports whether the backend sent anything ("backend has NO record…" =
|
||||
server-side send failure; "backend sent N email(s)…" = delivery/testmail problem).
|
||||
|
||||
**If SMTP fallback also fails:** follow up on the Postmark ticket, or give the backend a
|
||||
static egress IP (Direct VPC egress + Cloud NAT).
|
||||
**Alert:** "Email - Postmark SMTP fallback failing (emails being lost)" (log-based metric
|
||||
`email/postmark_smtp_fallback_failures`, `infrastructure/modules/monitoring.py`) fires if a
|
||||
fallback send fails in karaoke-backend or karaoke-decide.
|
||||
|
||||
**If SMTP fallback also fails / the alert fires:** Postmark is likely blocking SMTP from our
|
||||
IPs too → give the services a static egress IP. Options, measured costs (~$4–7/mo for the
|
||||
recommended reuse-the-existing-NAT route) and Pulumi steps:
|
||||
[`docs/archive/2026-10-02-postmark-ip-block-options.md`](archive/2026-10-02-postmark-ip-block-options.md).
|
||||
|
||||
## Fast rollback (bad backend deploy)
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# Postmark IP block: current mitigation, and options if we need more
|
||||
|
||||
**Date:** 2026-10-02 · **Status:** mitigated (SMTP fallback, $0). Static egress IP **deferred** to save money; revisit only if the alert below fires.
|
||||
**Applies to:** `karaoke-backend` (this repo) and `karaoke-decide` (both Cloud Run, us-central1).
|
||||
|
||||
## TL;DR
|
||||
|
||||
- Postmark's network firewall blocks some of Google Cloud's **shared us-central1 egress IPs** for API sends. They return a bare **nginx HTML 403**, not Postmark JSON. Postmark support confirmed the cause on ticket #11562402: the IP "has previously been associated with malicious activity, and has been blocked. We do not lift these blocks ourselves."
|
||||
- **Current mitigation (free):** on that HTML 403, both services resend the email through **Postmark SMTP** (`smtp.postmarkapp.com:587`). This is proven in prod: on 2026-10-02 between 19:10 and 20:17 UTC, 12 of 12 blocked sends were delivered via SMTP, each ~0.5s slower, with 0 failures.
|
||||
- **Tripwire (free until 2027-09-01, then $0.35/mo):** a Cloud Monitoring alert, **"Email - Postmark SMTP fallback failing (emails being lost)"**, emails andrew@beveridge.uk if an SMTP-fallback send ever fails.
|
||||
- **If that alert fires**, Postmark is probably blocking SMTP from our IPs too. Implement **Option A** below (reuse the existing Cloud NAT with a reserved static IP). Estimated cost: **~$4–7/month**.
|
||||
|
||||
## Background & evidence
|
||||
|
||||
- Onset: 2026-09-30 05:26 UTC. Every gen backend send failed from 2026-10-02 11:25 UTC until the fallback shipped. Lost emails included magic-link logins, made-for-you order confirmations, and admin alerts. Impacted users got an apology plus 1 credit (see the workspace session record `docs/sessions/2026-Q4/2026-10-02-postmark-403-smtp-fallback.md`).
|
||||
- The block is per egress IP. On 2026-10-02 at 03:33 UTC decide was blocked while gen succeeded in the same minute. us-east4 Cloud Run Jobs were never blocked. From a residential IP, all 3 `api.postmarkapp.com` IPs answer normally.
|
||||
- Postmark **IP Allowlisting** (UI-only, released 2026-08-27) is **OFF** at both account and server level (checked 2026-10-02). It also returns JSON `ErrorCode 1480` when it blocks, which is a different signature from this.
|
||||
- Retrying the API is useless: each Cloud Run instance keeps the same egress IP, so the block lasts hours. v0.261.1's retries never got through. Postmark's own advice: retry only helps if the IP changes; otherwise use a dedicated static egress.
|
||||
|
||||
## How the current mitigation works
|
||||
|
||||
| | karaoke-backend | karaoke-decide |
|
||||
|---|---|---|
|
||||
| Code | `backend/services/email_service.py` → `PostmarkEmailProvider._send_via_smtp` | `backend/services/email_service.py` → `EmailService._send_via_smtp` |
|
||||
| Version / PR | v0.263.1 (#1112), v0.263.2 (#1113) | v0.9.3 (decide #147) |
|
||||
| Log field | `jsonPayload.message` (structured) | `textPayload` (plain) |
|
||||
|
||||
- **Falls back to SMTP on:** an HTML (non-JSON) 403, or the API being unreachable (connect errors).
|
||||
- **Never falls back on:** Postmark JSON errors (bad token, invalid payload, suppressed recipient) or read timeouts (Postmark may already have accepted the message, so a resend could duplicate).
|
||||
- **SMTP auth:** the server token is both username and password. The header `X-PM-Message-Stream: outbound` selects the stream.
|
||||
- **Trade-offs while on SMTP:** no Postmark `MessageID` is returned (the email_log entry is not linked to Postmark), and suppressed or invalid recipients only show up later as bounces in Postmark, not as an immediate error.
|
||||
- **Requirement:** SMTP must stay **enabled** on the Postmark server "Nomad Karaoke Gen" (ID 19037711) under Server → Settings.
|
||||
- **Log lines to grep:** `falling back to SMTP` (block hit), `via Postmark SMTP fallback` (sent), `Failed to send email to … via Postmark SMTP fallback` (lost; this is what the alert counts).
|
||||
|
||||
## The alert (tripwire)
|
||||
|
||||
- Code: `infrastructure/modules/monitoring.py` → `create_email_delivery_observability()`.
|
||||
- **Log-based metric:** `logging.googleapis.com/user/email/postmark_smtp_fallback_failures`.
|
||||
- **Filter:** `SMTP_FALLBACK_FAILURE_LOG_FILTER`. It must match **both** `jsonPayload.message` (gen) and `textPayload` (decide).
|
||||
- Validated 2026-10-02: 0 matches, which is correct. A positive control on the gen JSON branch matched 12/12 real fallback sends; one on the decide text branch matched 5/5 real decide 403 lines.
|
||||
- **Fires on:** any failure within a 10-minute window. Notifies the `alerts-email` channel.
|
||||
- **Cost:** counter metric points are within the free allotment. Alert policies are free until **2027-09-01**, then **$0.35/month** per metric reference (Google Cloud Observability pricing, checked 2026-10-02).
|
||||
|
||||
## Options if we need more
|
||||
|
||||
Prices are from Google's Cloud NAT pricing page, checked 2026-10-02:
|
||||
- **Gateway:** $0.0014/hr per instance using it, capped at $0.044/hr above 32 instances.
|
||||
- **Static IP:** $0.005/hr each.
|
||||
- **Data processing:** $0.045/GiB, counting both directions of connections *initiated* by the workload. Responses to inbound user requests do **not** go through the NAT.
|
||||
|
||||
Measured usage (2026-10-02):
|
||||
- Average instances (7-day, hourly max): karaoke-backend ~2.2, karaoke-decide ~0.9 (it scales to zero ~half the time).
|
||||
- The existing `github-runners-nat` cost **~$4.53/30 days** (IP $2.90 + gateway uptime $1.63).
|
||||
|
||||
### Option A (recommended if needed): reuse the existing Cloud NAT with a reserved static IP. ~$4–7/month extra
|
||||
|
||||
`infrastructure/compute/github_runners.py` already creates `github-runners-router` and `github-runners-nat` on the `default` network in us-central1, with `AUTO_ONLY` IPs and `ALL_SUBNETWORKS_ALL_IP_RANGES`.
|
||||
|
||||
Steps:
|
||||
1. Reserve a static external IP: `compute.Address("email-egress-ip", region="us-central1")`.
|
||||
2. Switch `github-runners-nat` to `nat_ip_allocate_option="MANUAL_ONLY"` with `nat_ips=[address.self_link]`. Its traffic is all ours (CI runners plus our services), so the IP's reputation is our own. You could also keep the runners on AUTO by giving the NAT subnetwork-specific config and putting Cloud Run on its own subnet; that's more config for no saving.
|
||||
3. Put **karaoke-backend** and **karaoke-decide** on **Direct VPC egress**: `--network=default --subnet=default --vpc-egress=all-traffic`, set in each service's deploy config (gen: the CI deploy step or `modules/cloud_run.py`; decide: its own `infrastructure/`). `all-traffic` is required, because `private-ranges-only` keeps internet traffic on Google's shared IPs.
|
||||
4. Make sure **Private Google Access** is on for that subnet, so Firestore/GCS/Secret Manager/Gemini traffic goes direct and isn't billed as NAT data processing.
|
||||
5. **Size the NAT for Cloud Run.** Port exhaustion makes outbound connections time out, which would break email again and every other outbound call too. Settings on the `RouterNat`:
|
||||
- `endpoint_types=["ENDPOINT_TYPE_VM"]`. This is the default, and Direct VPC egress instances count as VM endpoints.
|
||||
- `enable_dynamic_port_allocation=True` with `min_ports_per_vm=128` and `max_ports_per_vm=4096`. Google's guidance is a minimum of at least ~2× the ports each Cloud Run instance needs. A backend instance makes many concurrent outbound calls (Stripe, Postmark, flacfetch, AudioShake), so 64 static ports could run out.
|
||||
- Capacity check: 1 NAT IP = 64,512 ports, about 504 endpoints at 128 min ports each. Peak demand is 20 backend + 10 decide max instances, plus CI runners, which is well under that. If NAT logs ever show `OUT_OF_RESOURCES` / dropped packets, add a second reserved IP to `nat_ips`.
|
||||
- Turn on NAT logging (`log_config.filter="ALL"` temporarily, then back to `ERRORS_ONLY`) for the first week, to watch for drops and to measure the data-processing volume.
|
||||
6. Apply locally with `pulumi up` **before** merging (repo rule).
|
||||
7. **Verify the reserved IP is actually used.** A successful Postmark send alone doesn't prove it, since the old dynamic IP might just not be blocked at that moment.
|
||||
- From inside the deployed service's network path, call an IP-echo endpoint, e.g. `curl -s https://checkip.amazonaws.com`. Do this from a one-off Cloud Run job using the same `--network/--subnet/--vpc-egress=all-traffic` settings, or a temporary admin-only debug endpoint. The result must equal the reserved `email-egress-ip` address.
|
||||
- With NAT logging on `ALL`, confirm that translations from the Cloud Run subnet show the reserved IP.
|
||||
- Then trigger a magic link and confirm `Email sent to … via Postmark` (the API path, not the SMTP fallback) in the logs.
|
||||
- Optionally tell Postmark the new IP on ticket #11562402.
|
||||
|
||||
Cost estimate:
|
||||
- **IP:** switching AUTO → 1 reserved IP: $3.65/mo vs the ~$2.90 auto-IP spend today, so **+~$0.75**.
|
||||
- **Gateway:** +(2.2 + 0.9) × $0.0014 × 730h = **+~$3.20**.
|
||||
- **Data processing:** **+~$0.50–3**, unmeasured. It covers the outbound calls we make (Stripe, Postmark, flacfetch, AudioShake, Dropbox, YouTube, etc.). It could be more if the backend downloads large media from non-Google hosts, so measure it for a week via NAT logs after enabling.
|
||||
- **Total: ~$4–7/month.**
|
||||
|
||||
### Option B: dedicated new NAT just for the Cloud Run services. ~$7–10/month extra
|
||||
|
||||
Same as A but with a new router + NAT + reserved IP scoped to one subnet. Cleaner separation from the CI runners, but you pay a second IP and gateway. Only worth it if CI-runner traffic ever risks our email IP's reputation.
|
||||
|
||||
### Option C: route only email through a fixed IP. ~$0 extra, more moving parts
|
||||
|
||||
Send Postmark traffic through something that already has a static IP, e.g. a tiny relay or proxy. The candidates are poor:
|
||||
- The **encoding-worker VMs** have reserved IPs (34.57.78.246, 34.10.189.118, 34.16.73.140), but they're Spot and stop when idle, so they're unsuitable as an always-on relay.
|
||||
- `divebar-sync` is TERMINATED.
|
||||
- Home servers are out (reliability, and residential IPs have their own deliverability problems).
|
||||
|
||||
Not recommended unless we get an always-on box with a static IP for another reason.
|
||||
|
||||
### Option D: switch or add an email provider
|
||||
|
||||
As a last resort, send via a second provider (e.g. SES/Resend) when both Postmark paths fail. That means another account and another set of DNS/DKIM. Only consider it if Postmark keeps blocking us even from a static IP.
|
||||
|
||||
## Decision log
|
||||
|
||||
- **2026-10-02:** shipped the SMTP fallback (gen + decide) and the tripwire alert. **Deferred Option A to save money** (Andrew: "we're trying to save money everywhere right now"). Revisit if the alert fires, if SMTP-path bounces show something odd, or if we need Postmark `MessageID`s during blocks.
|
||||
@@ -0,0 +1,82 @@
|
||||
# Backend event-loop freezes + degradation telemetry gaps — plan (2026-10-03)
|
||||
|
||||
## Evidence (client_events 2026-09-19 → 10-02)
|
||||
- 164 `banner_reconnecting`, 49 `banner_unavailable`, 1 `banner_waking`, 27 `waveform_slow`, 19 `waveform_failed`. Peak on 09-29/30.
|
||||
- 34 of 92 episodes hit 2–3 browsers in the same second. Only ~7 of the 28 "unavailable" episodes are near a deploy.
|
||||
- Signature in the Cloud Run logs: the single `karaoke-backend` instance stops serving for 20–45 s. Every request on it, `/api/health` included, then completes at the same moment.
|
||||
- What starts a freeze:
|
||||
- `/api/internal/workers/screens` + `auto-correct`. 17 of 28 episodes also log "Matplotlib is building the font cache".
|
||||
- The 09:00 crons (`process-stale-reviews` + `youtube-backfill`).
|
||||
- Once, `/api/users/auth/verify`.
|
||||
- **`user_email` is always null.** `degradation-events.ts` hard-codes it, so customers can't be told apart from Andrew's tabs or E2E runs.
|
||||
|
||||
## Root causes (audit)
|
||||
1. **Screens worker.** `generate_screens` is an `async def` BackgroundTask on the event loop, and its work is synchronous: GCS style downloads, 4K PIL title/end renders, GCS uploads, `prepare_review_audio_for_job` (FLAC download + ffmpeg ×≤4), the lazy `audio_analysis_service` import (matplotlib), `executor._compute_timing_signals`, and `pre_apply`. It also runs after the response, so under `--cpu-throttling` it is CPU-starved.
|
||||
2. **Matplotlib font cache.** It is never pre-built in the image, so it is rebuilt (20–40 s of CPU while holding the GIL) on every new instance. `karaoke_gen/instrumental_review/__init__.py` → `waveform.py` imports pyplot at module import time.
|
||||
3. **`process_stale_reviews`.** An `async def` with zero awaits: ≤1500 job reads, credit refunds, and email sends (SMTP fallback up to 15 s each).
|
||||
4. **163 route handlers** are `async def` with no `await`, so sync Firestore/GCS/email/Gemini calls run on the loop. Examples: magic-link verify (sync Gemini credit eval ≤60 s plus the welcome email) and magic-link send.
|
||||
5. **Nothing detects a blocked loop.**
|
||||
|
||||
## Decisions (Andrew, 2026-10-03)
|
||||
- **Screens:** run inline in the Cloud Tasks request and await it, with the heavy synchronous parts in `asyncio.to_thread`. CPU stays allocated, Cloud Tasks still owns retries, and there is no new infra.
|
||||
- **Safety net:** a loop-lag watchdog (stack dump), a log metric, and an alert.
|
||||
- **Telemetry:** all four improvements:
|
||||
- server-resolved user (email, tenant, admin/internal/test flags);
|
||||
- the existing FingerprintJS `visitorId` (`lib/fingerprint.ts`) plus a per-tab id;
|
||||
- a `banner_recovered` event with episode duration;
|
||||
- `server_loop_stall` events written by the watchdog into `client_events`.
|
||||
- **Handler sweep:** convert all no-await `async def` routes to `def` (FastAPI threadpool), with an AST guard test in CI.
|
||||
- **One PR.**
|
||||
|
||||
## Changes
|
||||
### Backend
|
||||
- `backend/services/loop_watchdog.py` (new):
|
||||
- An asyncio heartbeat task ticks every 250 ms; a daemon thread checks it.
|
||||
- At 1 s without a tick → log `EVENT_LOOP_STALL started` with the loop thread's stack (`sys._current_frames`). It resamples at 5 s and 15 s, deduping identical stacks.
|
||||
- On resume → `EVENT_LOOP_STALL ended duration_ms=…`: WARNING, or ERROR when ≥10 s.
|
||||
- Stalls ≥5 s → Firestore `client_events` doc `type=server_loop_stall` with `duration_ms`, top frames, revision and instance id (written from the thread).
|
||||
- Started and stopped in the `main.py` lifespan; can be disabled via a setting.
|
||||
- `internal.py` `/workers/screens` awaits `generate_screens` instead of using a BackgroundTask. It still returns 200 on handled failures, so Cloud Tasks doesn't double-run.
|
||||
- `screens_worker.py`: offload `load_style_config`'s sync body, `_generate_title_screen`/`_generate_end_screen` renders, `_upload_screens`, `prepare_review_audio_for_job` + the import, and `_apply_countdown_padding_if_needed`'s heavy work.
|
||||
- `auto_approval/executor.py`: offload `_compute_timing_signals` (its comment already calls it heavy). `pre_apply.ensure_and_pre_apply`: offload the sync GCS/build section.
|
||||
- `stale_review_processor.py`: rename the body to sync `process_stale_reviews_sync`, keep an `async` wrapper that does `asyncio.to_thread`, and update the cron.
|
||||
- Matplotlib:
|
||||
- `Dockerfile.base`: `ENV MPLCONFIGDIR=/opt/mplconfig` and `RUN python -c "import matplotlib; matplotlib.use('Agg'); import matplotlib.font_manager"` after fonts + pip.
|
||||
- `waveform.py`: import pyplot lazily.
|
||||
- Route sweep: `async def` → `def` for every route handler with no await/async-for/async-with. Fix tests that await them.
|
||||
- `tests/unit/test_no_blocking_async_routes.py`: an AST guard that fails if a route decorated with `@router.<verb>` is `async def` without an await.
|
||||
- `client_events.py`:
|
||||
- Resolve the caller from the bearer token (`get_token_from_request` + `validate_token_full`, the same pattern as `requests_board.optional_user_email`) → `user_email`, `is_admin`. Ignore the client-sent email.
|
||||
- `is_internal` (`INTERNAL_EMAIL_DOMAINS`), `is_test` (`is_test_email`), `tenant` (parsed from the page URL host).
|
||||
- New fields: `device_fingerprint`, `tab_id`, `episode_id`.
|
||||
- New type `banner_recovered`. `server_loop_stall` is server-only (rejected from clients).
|
||||
- `scripts/client_events_report.py`: summary by type/day/user/browser that excludes admin/internal/test, plus stall correlation.
|
||||
|
||||
### Frontend
|
||||
- `lib/degradation-events.ts`:
|
||||
- Send `Authorization: Bearer <karaoke_access_token>` when present.
|
||||
- Send the `device_fingerprint` (lazy `getDeviceFingerprint()`, ≤1.5 s wait, then cached), a per-tab `tab_id` (sessionStorage) and an `episode_id`.
|
||||
- `user_email` is removed from the body.
|
||||
- `components/backend-status-banner.tsx`: track the episode (first non-online → back online) and report `banner_recovered` (unthrottled, one per episode) with `duration_ms` and the peak status.
|
||||
|
||||
### Infra
|
||||
- `infrastructure/modules/monitoring.py`:
|
||||
- Log metric `backend/event_loop_stalls` on `EVENT_LOOP_STALL ended` at ERROR severity (≥10 s).
|
||||
- Alert "Backend event loop frozen ≥10s" when there are ≥2 in 30 min (free tier).
|
||||
|
||||
## Testing
|
||||
- Unit (pytest):
|
||||
- Watchdog: a coroutine doing `time.sleep(1.5)` produces a stall with a stack containing that function, and the Firestore writer is called only for ≥5 s stalls.
|
||||
- client_events: token resolution, flags, new fields, `banner_recovered` accepted, `server_loop_stall` rejected from clients.
|
||||
- Screens endpoint awaits the worker.
|
||||
- Loop responsiveness: with heavy helpers patched to `time.sleep(0.5)`, a concurrent ticker keeps ticking during `generate_screens` and `process_stale_reviews`.
|
||||
- The AST guard.
|
||||
- The existing suites pass after the sweep.
|
||||
- Jest: degradation-events (auth header, fingerprint, tab id, no email) and banner recovery (one event with a duration).
|
||||
- Build: `Dockerfile.base` builds and the font cache exists (CI base build).
|
||||
- Prod verification after deploy:
|
||||
- No "Matplotlib is building the font cache" on new instances.
|
||||
- Watchdog logs present and quiet.
|
||||
- A new client_events doc has `user_email`/fingerprint populated.
|
||||
- The report script runs.
|
||||
- Run a real job through screens and confirm `/api/health` latency stays low during it.
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react'
|
||||
import type { BackendStatus } from '@/lib/backend-status'
|
||||
|
||||
let mockStatus: BackendStatus = 'online'
|
||||
|
||||
jest.mock('@/lib/backend-status', () => ({
|
||||
useBackendStatus: () => mockStatus,
|
||||
getBackendStatusDebug: () => ({
|
||||
oldestStallMs: 0,
|
||||
inFlightCount: 0,
|
||||
lastProbeOk: null,
|
||||
consecutiveProbeFailures: 0,
|
||||
sinceReachableMs: 0,
|
||||
}),
|
||||
installBackendPrewarm: jest.fn(),
|
||||
__installBackendStatusDevHook: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/api', () => ({ __backendPrewarm: jest.fn() }))
|
||||
|
||||
jest.mock('@/lib/degradation-events', () => ({
|
||||
reportDegradationEvent: jest.fn(),
|
||||
startDegradationEpisode: jest.fn(() => 'ep-1'),
|
||||
endDegradationEpisode: jest.fn(),
|
||||
}))
|
||||
|
||||
import { BackendStatusBanner } from '@/components/backend-status-banner'
|
||||
import {
|
||||
reportDegradationEvent,
|
||||
startDegradationEpisode,
|
||||
endDegradationEpisode,
|
||||
} from '@/lib/degradation-events'
|
||||
|
||||
const reportMock = reportDegradationEvent as jest.Mock
|
||||
const startMock = startDegradationEpisode as jest.Mock
|
||||
const endMock = endDegradationEpisode as jest.Mock
|
||||
|
||||
function recoveredCalls() {
|
||||
return reportMock.mock.calls.filter((c) => c[0] === 'banner_recovered')
|
||||
}
|
||||
|
||||
describe('BackendStatusBanner episode telemetry', () => {
|
||||
let now: number
|
||||
let nowSpy: jest.SpyInstance
|
||||
|
||||
beforeEach(() => {
|
||||
mockStatus = 'online'
|
||||
reportMock.mockClear()
|
||||
startMock.mockClear()
|
||||
endMock.mockClear()
|
||||
now = 1_000_000
|
||||
nowSpy = jest.spyOn(Date, 'now').mockImplementation(() => now)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
nowSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('reports nothing when status never leaves online', () => {
|
||||
const { rerender } = render(<BackendStatusBanner />)
|
||||
rerender(<BackendStatusBanner />)
|
||||
expect(reportMock).not.toHaveBeenCalled()
|
||||
expect(startMock).not.toHaveBeenCalled()
|
||||
expect(endMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports exactly one banner_recovered with duration and peak after offline → online', () => {
|
||||
const { rerender } = render(<BackendStatusBanner />)
|
||||
|
||||
mockStatus = 'reconnecting'
|
||||
rerender(<BackendStatusBanner />)
|
||||
expect(startMock).toHaveBeenCalledTimes(1)
|
||||
// Episode starts before the banner event is reported, so it carries the id.
|
||||
expect(startMock.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
reportMock.mock.invocationCallOrder[0],
|
||||
)
|
||||
expect(reportMock).toHaveBeenCalledWith('banner_reconnecting', expect.any(Object))
|
||||
|
||||
now += 5_000
|
||||
mockStatus = 'unavailable'
|
||||
rerender(<BackendStatusBanner />)
|
||||
now += 2_000
|
||||
mockStatus = 'reconnecting'
|
||||
rerender(<BackendStatusBanner />)
|
||||
expect(startMock).toHaveBeenCalledTimes(1) // same episode
|
||||
|
||||
now += 3_000
|
||||
mockStatus = 'online'
|
||||
rerender(<BackendStatusBanner />)
|
||||
rerender(<BackendStatusBanner />) // extra re-renders must not double-report
|
||||
|
||||
expect(recoveredCalls()).toHaveLength(1)
|
||||
expect(recoveredCalls()[0][1]).toEqual({
|
||||
duration_ms: 10_000,
|
||||
peak_status: 'unavailable',
|
||||
dismissed: false,
|
||||
})
|
||||
expect(endMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('starts a fresh episode for a later outage', () => {
|
||||
const { rerender } = render(<BackendStatusBanner />)
|
||||
mockStatus = 'waking'
|
||||
rerender(<BackendStatusBanner />)
|
||||
now += 1_000
|
||||
mockStatus = 'online'
|
||||
rerender(<BackendStatusBanner />)
|
||||
|
||||
mockStatus = 'reconnecting'
|
||||
rerender(<BackendStatusBanner />)
|
||||
now += 4_000
|
||||
mockStatus = 'online'
|
||||
rerender(<BackendStatusBanner />)
|
||||
|
||||
expect(startMock).toHaveBeenCalledTimes(2)
|
||||
expect(recoveredCalls().map((c) => c[1])).toEqual([
|
||||
{ duration_ms: 1_000, peak_status: 'waking', dismissed: false },
|
||||
{ duration_ms: 4_000, peak_status: 'reconnecting', dismissed: false },
|
||||
])
|
||||
})
|
||||
|
||||
it('records a dismissed unavailable card and does not report it again', () => {
|
||||
const { rerender } = render(<BackendStatusBanner />)
|
||||
mockStatus = 'unavailable'
|
||||
rerender(<BackendStatusBanner />)
|
||||
expect(reportMock).toHaveBeenCalledWith('banner_unavailable', expect.any(Object))
|
||||
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
})
|
||||
const unavailableCount = reportMock.mock.calls.filter((c) => c[0] === 'banner_unavailable').length
|
||||
expect(unavailableCount).toBe(1)
|
||||
|
||||
now += 8_000
|
||||
mockStatus = 'online'
|
||||
rerender(<BackendStatusBanner />)
|
||||
expect(recoveredCalls()).toHaveLength(1)
|
||||
expect(recoveredCalls()[0][1]).toEqual({
|
||||
duration_ms: 8_000,
|
||||
peak_status: 'unavailable',
|
||||
dismissed: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -33,6 +33,7 @@ jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
getDownloadUrl: jest.fn((jobId, category, key) => `https://example.com/${jobId}/${category}/${key}`),
|
||||
rerenderWithCurrentTheme: jest.fn(() => Promise.resolve({ status: 'processing' })),
|
||||
regenerateJob: jest.fn(() => Promise.resolve({ status: 'processing', needs_stems: true })),
|
||||
},
|
||||
adminApi: {
|
||||
getCompletionMessage: jest.fn(),
|
||||
@@ -582,4 +583,44 @@ describe('OutputLinks', () => {
|
||||
expect(screen.getByTestId('admin-rerender-warnings')).toHaveTextContent('YouTube upload is disabled for this job')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Regenerate video (storage retention)', () => {
|
||||
const archivedJob: Job = {
|
||||
...baseJob,
|
||||
renders_purged_at: '2026-09-01T00:00:00Z',
|
||||
file_urls: {
|
||||
finals: { lossy_720p_mp4: 'gs://bucket/finals/720p.mp4' },
|
||||
packages: { cdg_zip: 'gs://bucket/packages/cdg.zip' },
|
||||
},
|
||||
}
|
||||
|
||||
it('shows the button and the kept downloads for an archived track', () => {
|
||||
render(<OutputLinks job={archivedJob} />)
|
||||
expect(screen.getByTestId('regenerate-button')).toHaveTextContent('Regenerate video')
|
||||
expect(screen.getByText('720p Video')).toBeInTheDocument()
|
||||
expect(screen.queryByText('4K Video')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the button when all finals are present', () => {
|
||||
render(<OutputLinks job={baseJob} />)
|
||||
expect(screen.queryByTestId('regenerate-button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the button while the track is not complete', () => {
|
||||
render(<OutputLinks job={{ ...archivedJob, status: 'rendering_video' }} />)
|
||||
expect(screen.queryByTestId('regenerate-button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('confirms then calls the regenerate API', async () => {
|
||||
const { api } = require('@/lib/api')
|
||||
const onJobUpdated = jest.fn()
|
||||
render(<OutputLinks job={archivedJob} onJobUpdated={onJobUpdated} />)
|
||||
fireEvent.click(screen.getByTestId('regenerate-button'))
|
||||
expect(screen.getByTestId('regenerate-dialog')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByTestId('regenerate-confirm'))
|
||||
await waitFor(() => expect(api.regenerateJob).toHaveBeenCalledWith('test-123'))
|
||||
await waitFor(() => expect(onJobUpdated).toHaveBeenCalled())
|
||||
expect(mockToast).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Loader2, CloudOff, X } from "lucide-react"
|
||||
import {
|
||||
@@ -8,8 +8,13 @@ import {
|
||||
getBackendStatusDebug,
|
||||
installBackendPrewarm,
|
||||
__installBackendStatusDevHook,
|
||||
type BackendStatus,
|
||||
} from "@/lib/backend-status"
|
||||
import { reportDegradationEvent } from "@/lib/degradation-events"
|
||||
import {
|
||||
reportDegradationEvent,
|
||||
startDegradationEpisode,
|
||||
endDegradationEpisode,
|
||||
} from "@/lib/degradation-events"
|
||||
import { __backendPrewarm } from "@/lib/api"
|
||||
|
||||
/**
|
||||
@@ -28,10 +33,26 @@ import { __backendPrewarm } from "@/lib/api"
|
||||
* It floats over content (no layout shift) and disappears the instant connectivity
|
||||
* is restored.
|
||||
*/
|
||||
/** Severity order for an episode's peak status (higher = worse). */
|
||||
const SEVERITY: Record<Exclude<BackendStatus, "online">, number> = {
|
||||
waking: 1,
|
||||
reconnecting: 2,
|
||||
unavailable: 3,
|
||||
}
|
||||
|
||||
type Episode = {
|
||||
startedAt: number
|
||||
peak: Exclude<BackendStatus, "online">
|
||||
dismissed: boolean
|
||||
}
|
||||
|
||||
export function BackendStatusBanner() {
|
||||
const status = useBackendStatus()
|
||||
const t = useTranslations("backendStatus")
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
// The current degradation episode (first non-online status → back online).
|
||||
// A ref so re-renders never double-start or double-report.
|
||||
const episodeRef = useRef<Episode | null>(null)
|
||||
|
||||
// Expose the dev/preview trigger (window.__nkBackendStatus) for manual UX review,
|
||||
// and pre-warm a possibly scaled-to-zero backend as early as possible (this
|
||||
@@ -46,6 +67,45 @@ export function BackendStatusBanner() {
|
||||
if (status === "online") setDismissed(false)
|
||||
}, [status])
|
||||
|
||||
// Episode tracking. Declared BEFORE the per-status reporting effect so the
|
||||
// first banner event of an episode already carries its episode_id.
|
||||
useEffect(() => {
|
||||
const episode = episodeRef.current
|
||||
if (status !== "online") {
|
||||
if (!episode) {
|
||||
startDegradationEpisode()
|
||||
episodeRef.current = { startedAt: Date.now(), peak: status, dismissed: false }
|
||||
} else if (SEVERITY[status] > SEVERITY[episode.peak]) {
|
||||
episode.peak = status
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!episode) return
|
||||
// Back online: exactly one recovery event per episode, then close it.
|
||||
episodeRef.current = null
|
||||
reportDegradationEvent("banner_recovered", {
|
||||
duration_ms: Date.now() - episode.startedAt,
|
||||
peak_status: episode.peak,
|
||||
dismissed: episode.dismissed,
|
||||
})
|
||||
endDegradationEpisode()
|
||||
}, [status])
|
||||
|
||||
useEffect(() => {
|
||||
if (dismissed && episodeRef.current) episodeRef.current.dismissed = true
|
||||
}, [dismissed])
|
||||
|
||||
// Don't leak an open episode id into later reports if the banner unmounts.
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (episodeRef.current) {
|
||||
episodeRef.current = null
|
||||
endDegradationEpisode()
|
||||
}
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
// Persist every banner display server-side (Andrew's telemetry ask): this is
|
||||
// the single global banner instance, so reporting here == "shown to a user".
|
||||
// The reporter throttles per type, so a flapping status can't spam.
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState } from "react"
|
||||
import { useTranslations, useLocale } from 'next-intl'
|
||||
import { Job } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Zap, Globe } from "lucide-react"
|
||||
import { Zap, Globe, Sparkles } from "lucide-react"
|
||||
import { JobActions } from "./JobActions"
|
||||
import { AdminJobActions } from "./AdminJobActions"
|
||||
import { OutputLinks } from "./OutputLinks"
|
||||
@@ -12,7 +12,7 @@ import { StalledDownloadNotice, isStalledDownload } from "./StalledDownloadNotic
|
||||
import { AudioSearchDialog } from "../audio-search/AudioSearchDialog"
|
||||
import { DurationCostConfirm } from "./DurationCostConfirm"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
import { getJobStep, formatStepIndicator, getJobProgressPercent, isWaitingForEncodingCapacity, isVisibilityChangeInProgress } from "@/lib/job-status"
|
||||
import { getJobStep, formatStepIndicator, getJobProgressPercent, isWaitingForEncodingCapacity, isVisibilityChangeInProgress, isRegenerating } from "@/lib/job-status"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { LocaleBadge } from "@/components/admin/locale-badge"
|
||||
import { useDurationConfirm } from "@/hooks/use-duration-confirm"
|
||||
@@ -254,6 +254,16 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Regenerate (storage retention) in progress: the archived video files
|
||||
are being rebuilt; set expectations rather than showing a bare
|
||||
processing state on a track the customer finished long ago. */}
|
||||
{isRegenerating(job) && job.status !== "failed" && (
|
||||
<div className="mt-2 text-xs bg-pink-500/10 text-pink-300 rounded p-2 flex items-start gap-2" data-testid="regenerating-notice">
|
||||
<Sparkles className="w-3.5 h-3.5 mt-0.5 shrink-0" />
|
||||
<span>{t('regeneratingInProgress')}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error message — only shown when the job is actually in a failed
|
||||
state. Completed jobs may carry a stale error_message from a transient
|
||||
failure that was auto-retried; we don't want to alarm users about
|
||||
|
||||
@@ -5,7 +5,8 @@ import { useTranslations } from 'next-intl'
|
||||
import { api, adminApi, Job } from "@/lib/api"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings, Lock, Globe, Pencil, RefreshCw, RotateCcw } from "lucide-react"
|
||||
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings, Lock, Globe, Pencil, RefreshCw, RotateCcw, Sparkles } from "lucide-react"
|
||||
import { canRegenerate as canRegenerateJob } from "@/lib/job-status"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import {
|
||||
@@ -61,6 +62,8 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
const [showAdminRerenderDialog, setShowAdminRerenderDialog] = useState(false)
|
||||
const [isStartingAdminRerender, setIsStartingAdminRerender] = useState(false)
|
||||
const [adminRerenderNotify, setAdminRerenderNotify] = useState(false)
|
||||
const [showRegenerateDialog, setShowRegenerateDialog] = useState(false)
|
||||
const [isStartingRegenerate, setIsStartingRegenerate] = useState(false)
|
||||
const copyTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const messageTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const emailTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
@@ -238,6 +241,25 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
}
|
||||
}, [job.job_id, adminRerenderNotify, onJobUpdated, t, toast])
|
||||
|
||||
const handleRegenerate = useCallback(async () => {
|
||||
setIsStartingRegenerate(true)
|
||||
setShowRegenerateDialog(false)
|
||||
try {
|
||||
await api.regenerateJob(job.job_id)
|
||||
toast({ title: t('regenerateStarted') })
|
||||
onJobUpdated?.()
|
||||
} catch (err) {
|
||||
console.error("Failed to start regenerate:", err)
|
||||
alert(t('regenerateFailed', { error: err instanceof Error ? err.message : String(err) }))
|
||||
} finally {
|
||||
setIsStartingRegenerate(false)
|
||||
}
|
||||
}, [job.job_id, onJobUpdated, t, toast])
|
||||
|
||||
// Storage retention: older tracks keep the 720p + packages; the rest can be
|
||||
// rebuilt on demand (GCS only — nothing is re-published).
|
||||
const canRegenerate = canRegenerateJob(job)
|
||||
|
||||
const hasOutputs = showYoutubeLink || showDropboxLink || (!outputsUnavailable && downloadUrls && Object.keys(downloadUrls).length > 0)
|
||||
|
||||
// Check if we have any downloads (and outputs are currently available)
|
||||
@@ -268,7 +290,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* Links, Downloads, and Admin Tools - all in one row */}
|
||||
{(hasDownloads || hasExternalLinks || isAdmin || canChangeVisibility || canRerender || canAdminRerender) && (
|
||||
{(hasDownloads || hasExternalLinks || isAdmin || canChangeVisibility || canRerender || canAdminRerender || canRegenerate) && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{/* Links first */}
|
||||
{hasExternalLinks && (
|
||||
@@ -391,6 +413,21 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Regenerate archived video files (storage retention) */}
|
||||
{canRegenerate && (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="regenerate-button"
|
||||
onClick={(e) => { e.stopPropagation(); setShowRegenerateDialog(true) }}
|
||||
disabled={isStartingRegenerate}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white transition-colors disabled:opacity-50"
|
||||
title={t('regenerateTooltip')}
|
||||
>
|
||||
{isStartingRegenerate ? <Loader2 className="w-3 h-3 animate-spin" /> : <Sparkles className="w-3 h-3" />}
|
||||
{t('regenerate')}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Change Visibility Button */}
|
||||
{canChangeVisibility && (
|
||||
<button
|
||||
@@ -669,6 +706,28 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Regenerate Confirmation Dialog */}
|
||||
<AlertDialog open={showRegenerateDialog} onOpenChange={setShowRegenerateDialog}>
|
||||
<AlertDialogContent onClick={(e) => e.stopPropagation()} data-testid="regenerate-dialog">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('regenerateTitle')}</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-3">
|
||||
<p>{t('regenerateDesc')}</p>
|
||||
<p>{t('regenerateNoRepublish')}</p>
|
||||
<p>{t('regenerateTime')}</p>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{tc('cancel')}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleRegenerate} data-testid="regenerate-confirm">
|
||||
{t('regenerate')}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Edit Track Modal */}
|
||||
<EditTrackModal
|
||||
job={job}
|
||||
|
||||
@@ -258,7 +258,7 @@ export function AudioSourceStep({
|
||||
preloadKaraokeBg()
|
||||
}, [])
|
||||
|
||||
const confidence = useMemo(() => getSearchConfidence(results, title), [results, title])
|
||||
const confidence = useMemo(() => getSearchConfidence(results, title, artist), [results, title, artist])
|
||||
const groupedResults = useMemo(() => groupResults(results), [results])
|
||||
const otherResultsCount = results.length > 0 && confidence.bestResult ? results.length - 1 : 0
|
||||
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// frontend/e2e/helpers/self-healing/actions.ts
|
||||
import type { Frame, Locator, Page } from '@playwright/test';
|
||||
import type { Action, Secrets, TargetSpec } from './types';
|
||||
|
||||
const PLACEHOLDER_RE = /\{\{([A-Z_]+)\}\}/g;
|
||||
|
||||
/** Substitute `{{NAME}}` placeholders. Throws on unknown placeholders so a typo can't type literal braces into a payment form. */
|
||||
export function substitutePlaceholders(value: string, secrets: Secrets): string {
|
||||
return value.replace(PLACEHOLDER_RE, (_, key: string) => {
|
||||
if (!(key in secrets)) throw new Error(`Unknown placeholder {{${key}}}`);
|
||||
return secrets[key];
|
||||
});
|
||||
}
|
||||
|
||||
/** Path segments that identify a session/object rather than a page (e.g. `cs_live_a1j04…`). */
|
||||
function isDynamicSegment(seg: string): boolean {
|
||||
// Stripe object ids, or long opaque tokens (no '.'/'-' like real page names).
|
||||
return (
|
||||
/^[a-z]{2,5}_(live|test)_/i.test(seg) ||
|
||||
(seg.length >= 16 && /^[A-Za-z0-9_]+$/.test(seg) && /\d/.test(seg) && /[a-z]/i.test(seg))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable frame key: host + path up to the first session-specific segment, no
|
||||
* query/hash. Stripe puts the checkout session id in the PATH
|
||||
* (`checkout.stripe.com/c/pay/cs_live_…`), so stripping the query isn't enough —
|
||||
* a learned recipe must never pin (or leak) one run's session id.
|
||||
*/
|
||||
export function frameUrlKey(url: string): string {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
const kept: string[] = [];
|
||||
for (const seg of u.pathname.split('/').filter(Boolean)) {
|
||||
if (isDynamicSegment(seg)) break;
|
||||
kept.push(seg);
|
||||
}
|
||||
return kept.length ? `${u.host}/${kept.join('/')}` : u.host;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function escapeRegex(s: string): string {
|
||||
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
function nameMatcher(name: string, exact?: boolean): string | RegExp {
|
||||
return exact ? name : new RegExp(escapeRegex(name), 'i');
|
||||
}
|
||||
|
||||
/** Build a frame-scoped locator for a TargetSpec. */
|
||||
export function targetLocator(frame: Frame, t: TargetSpec): Locator {
|
||||
switch (t.by) {
|
||||
case 'role':
|
||||
if (!t.role) throw new Error('TargetSpec by=role requires role');
|
||||
return frame.getByRole(t.role as Parameters<Frame['getByRole']>[0], {
|
||||
...(t.name ? { name: nameMatcher(t.name, t.exact), exact: t.exact } : {}),
|
||||
includeHidden: t.includeHidden,
|
||||
});
|
||||
case 'text':
|
||||
if (!t.text) throw new Error('TargetSpec by=text requires text');
|
||||
return frame.getByText(nameMatcher(t.text, t.exact));
|
||||
case 'placeholder':
|
||||
if (!t.text) throw new Error('TargetSpec by=placeholder requires text');
|
||||
return frame.getByPlaceholder(nameMatcher(t.text, t.exact));
|
||||
case 'label':
|
||||
if (!t.text) throw new Error('TargetSpec by=label requires text');
|
||||
return frame.getByLabel(nameMatcher(t.text, t.exact));
|
||||
case 'css':
|
||||
if (!t.css) throw new Error('TargetSpec by=css requires css');
|
||||
return frame.locator(t.css);
|
||||
default:
|
||||
throw new Error(`Unknown TargetSpec.by: ${(t as TargetSpec).by}`);
|
||||
}
|
||||
}
|
||||
|
||||
function orderedFrames(page: Page, t: TargetSpec): Frame[] {
|
||||
const frames = page.frames().filter((f) => !f.isDetached());
|
||||
if (!t.frameUrlIncludes) return frames;
|
||||
const preferred = frames.filter((f) => frameUrlKey(f.url()).includes(t.frameUrlIncludes!));
|
||||
return [...preferred, ...frames.filter((f) => !preferred.includes(f))];
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the element for a TargetSpec in any frame (preferred frame first),
|
||||
* polling until `timeoutMs`. Visible matches win; with `includeHidden`, an
|
||||
* attached-but-hidden match is accepted as a last resort.
|
||||
*/
|
||||
export async function resolveTarget(
|
||||
page: Page,
|
||||
t: TargetSpec,
|
||||
timeoutMs = 5_000
|
||||
): Promise<{ locator: Locator; visible: boolean } | null> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
do {
|
||||
let hidden: Locator | null = null;
|
||||
for (const frame of orderedFrames(page, t)) {
|
||||
let loc: Locator;
|
||||
try {
|
||||
loc = targetLocator(frame, t).first();
|
||||
} catch {
|
||||
return null; // malformed spec — retrying won't help
|
||||
}
|
||||
if (await loc.isVisible().catch(() => false)) return { locator: loc, visible: true };
|
||||
if (t.includeHidden && !hidden && (await loc.count().catch(() => 0)) > 0) hidden = loc;
|
||||
}
|
||||
if (hidden) return { locator: hidden, visible: false };
|
||||
await page.waitForTimeout(250);
|
||||
} while (Date.now() < deadline);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Execute one Action. Throws if the target can't be found or the action fails. */
|
||||
export async function executeAction(
|
||||
page: Page,
|
||||
action: Action,
|
||||
secrets: Secrets,
|
||||
timeoutMs = 5_000
|
||||
): Promise<Locator> {
|
||||
const found = await resolveTarget(page, action.target, timeoutMs);
|
||||
if (!found) throw new Error(`Target not found: ${JSON.stringify(action.target)}`);
|
||||
const { locator, visible } = found;
|
||||
const value = action.value !== undefined ? substitutePlaceholders(action.value, secrets) : undefined;
|
||||
|
||||
switch (action.type) {
|
||||
case 'click':
|
||||
if (visible) await locator.click({ force: true, timeout: timeoutMs });
|
||||
else await locator.dispatchEvent('click');
|
||||
break;
|
||||
case 'fill':
|
||||
if (value === undefined) throw new Error('fill requires value');
|
||||
await locator.click({ timeout: timeoutMs });
|
||||
await locator.fill('', { timeout: timeoutMs }).catch(() => {});
|
||||
// Stripe's card inputs reformat as you type; typing (not fill) keeps their
|
||||
// input handlers and validation in sync.
|
||||
await locator.pressSequentially(value, { delay: 40, timeout: timeoutMs * 4 });
|
||||
break;
|
||||
case 'select':
|
||||
if (value === undefined) throw new Error('select requires value');
|
||||
await locator.selectOption({ label: value }, { timeout: timeoutMs }).catch(() =>
|
||||
locator.selectOption(value, { timeout: timeoutMs })
|
||||
);
|
||||
break;
|
||||
case 'check':
|
||||
await locator.check({ force: true, timeout: timeoutMs });
|
||||
break;
|
||||
case 'uncheck':
|
||||
await locator.uncheck({ force: true, timeout: timeoutMs });
|
||||
break;
|
||||
case 'press':
|
||||
await locator.press(value || 'Enter', { timeout: timeoutMs });
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown action type: ${(action as Action).type}`);
|
||||
}
|
||||
return locator;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// frontend/e2e/helpers/self-healing/learned-store.ts
|
||||
import * as crypto from 'crypto';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import type { Action, LearnedVariant, LearnedVariantsFile } from './types';
|
||||
|
||||
/**
|
||||
* learned-variants.json holds step recipes the LLM fallback discovered on live
|
||||
* runs. The daily E2E workflow opens an auto-merging PR whenever a run adds one,
|
||||
* so the next run replays it deterministically (no LLM) — "1 Stripe change =
|
||||
* 1 auto-merged data PR".
|
||||
*/
|
||||
export const LEARNED_VARIANTS_PATH = path.join(__dirname, 'learned-variants.json');
|
||||
|
||||
/** Keep only the newest N per step: Stripe A/B-tests layouts, so a few recent ones are useful; ancient ones are noise. */
|
||||
export const MAX_LEARNED_PER_STEP = 5;
|
||||
|
||||
export function emptyFile(): LearnedVariantsFile {
|
||||
return { version: 1, steps: {} };
|
||||
}
|
||||
|
||||
export function loadLearned(file = LEARNED_VARIANTS_PATH): LearnedVariantsFile {
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as LearnedVariantsFile;
|
||||
if (parsed?.version === 1 && parsed.steps && typeof parsed.steps === 'object') return parsed;
|
||||
console.warn(` ⚠️ ${file} has unexpected shape — ignoring learned variants`);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
console.warn(` ⚠️ Could not read ${file}: ${(e as Error).message} — ignoring learned variants`);
|
||||
}
|
||||
}
|
||||
return emptyFile();
|
||||
}
|
||||
|
||||
/** Stable id from the actions only (not timestamps), so re-learning the same recipe dedupes. */
|
||||
export function variantId(actions: Action[]): string {
|
||||
return crypto.createHash('sha256').update(JSON.stringify(actions)).digest('hex').slice(0, 12);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge newly-healed recipes into the file (pure — returns a new object).
|
||||
* Returns `changed: false` when every recipe was already known.
|
||||
*/
|
||||
export function mergeLearned(
|
||||
current: LearnedVariantsFile,
|
||||
healed: Array<{ stepId: string; actions: Action[]; model?: string }>,
|
||||
meta: { runUrl?: string; now?: string } = {}
|
||||
): { file: LearnedVariantsFile; changed: boolean; added: Array<{ stepId: string; variant: LearnedVariant }> } {
|
||||
const file: LearnedVariantsFile = JSON.parse(JSON.stringify(current));
|
||||
const added: Array<{ stepId: string; variant: LearnedVariant }> = [];
|
||||
for (const h of healed) {
|
||||
if (!h.actions.length) continue;
|
||||
const id = variantId(h.actions);
|
||||
const list = file.steps[h.stepId] || [];
|
||||
if (list.some((v) => v.id === id)) continue;
|
||||
const variant: LearnedVariant = {
|
||||
id,
|
||||
learnedAt: meta.now || new Date().toISOString(),
|
||||
...(meta.runUrl ? { runUrl: meta.runUrl } : {}),
|
||||
...(h.model ? { model: h.model } : {}),
|
||||
actions: h.actions,
|
||||
};
|
||||
// Newest first — the most recent layout is the likeliest to be live.
|
||||
file.steps[h.stepId] = [variant, ...list].slice(0, MAX_LEARNED_PER_STEP);
|
||||
added.push({ stepId: h.stepId, variant });
|
||||
}
|
||||
return { file, changed: added.length > 0, added };
|
||||
}
|
||||
|
||||
export function serialize(file: LearnedVariantsFile): string {
|
||||
return JSON.stringify(file, null, 2) + '\n';
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"version": 1,
|
||||
"steps": {
|
||||
"selectCard": [
|
||||
{
|
||||
"id": "19fdebfcbbb1",
|
||||
"learnedAt": "2026-10-03T17:05:03.246Z",
|
||||
"runUrl": "https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37139075045",
|
||||
"model": "gemini-3.1-flash-lite",
|
||||
"actions": [
|
||||
{
|
||||
"type": "click",
|
||||
"target": {
|
||||
"by": "css",
|
||||
"css": "[data-testid='card-accordion-item']",
|
||||
"frameUrlIncludes": "checkout.stripe.com/c/pay"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"fillPostalCode": [
|
||||
{
|
||||
"id": "92cb503db41b",
|
||||
"learnedAt": "2026-10-03T17:35:16.436Z",
|
||||
"runUrl": "https://github.com/nomadkaraoke/karaoke-gen/actions/runs/37140934446",
|
||||
"model": "gemini-3.5-flash-lite",
|
||||
"actions": [
|
||||
{
|
||||
"type": "fill",
|
||||
"target": {
|
||||
"by": "css",
|
||||
"css": "#billingPostalCode",
|
||||
"frameUrlIncludes": "checkout.stripe.com/c/pay"
|
||||
},
|
||||
"value": "{{POSTAL_CODE}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// frontend/e2e/helpers/self-healing/llm-agent.ts
|
||||
import { executeAction, resolveTarget } from './actions';
|
||||
import { observe, type Observation } from './observe';
|
||||
import type { Action, ActionType, CheckoutStep, StepContext, TargetSpec } from './types';
|
||||
|
||||
/**
|
||||
* LLM fallback for one checkout step: observe → ask the model for ONE action →
|
||||
* execute → verify, up to MAX_ITERATIONS. The model only ever picks elements by
|
||||
* semantic description and uses `{{PLACEHOLDER}}` tokens for secrets; we
|
||||
* substitute real values locally.
|
||||
*/
|
||||
|
||||
export interface LlmTarget extends Omit<TargetSpec, 'frameUrlIncludes'> {
|
||||
frameIndex?: number;
|
||||
}
|
||||
|
||||
export interface LlmDecision {
|
||||
thought: string;
|
||||
status: 'act' | 'done' | 'give_up';
|
||||
action?: { type: ActionType; target: LlmTarget; value?: string };
|
||||
}
|
||||
|
||||
export interface PlannerInput {
|
||||
stepId: string;
|
||||
goal: string;
|
||||
allowSubmit: boolean;
|
||||
placeholders: string[];
|
||||
history: string[];
|
||||
observation: Observation;
|
||||
/** 0 = cheapest model; incremented after failures to escalate. */
|
||||
escalation: number;
|
||||
}
|
||||
|
||||
export interface Planner {
|
||||
decide(input: PlannerInput): Promise<{ decision: LlmDecision; model: string }>;
|
||||
}
|
||||
|
||||
export interface HealResult {
|
||||
success: boolean;
|
||||
actions: Action[];
|
||||
model: string;
|
||||
llmCalls: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
const MAX_ITERATIONS = 6;
|
||||
const MAX_ESCALATIONS = 2;
|
||||
|
||||
/** Express/alternative payment methods and the cancel/back link — the agent must never pick these. */
|
||||
const FORBIDDEN_CLICK_RE = /\b(back to|cancel|link|klarna|cash ?app|bank|affirm|afterpay|google pay|apple pay|amazon pay|paypal)\b/i;
|
||||
/** The final submit button ("Pay", "Pay $0.50", "Subscribe"…) — only allowed in the submit step. */
|
||||
const SUBMIT_RE = /^\s*(pay|subscribe|buy|purchase|place order|complete (order|purchase)|confirm( payment)?)\s*(\$?[\d.,]+)?\s*$/i;
|
||||
|
||||
/** Returns a rejection reason, or null if the action is acceptable. */
|
||||
export function checkGuards(
|
||||
action: NonNullable<LlmDecision['action']>,
|
||||
step: Pick<CheckoutStep, 'allowSubmit' | 'placeholders'>
|
||||
): string | null {
|
||||
const label = action.target.name || action.target.text || '';
|
||||
if (action.type === 'click' && FORBIDDEN_CLICK_RE.test(label)) {
|
||||
return `Refused: "${label}" looks like an alternative/express payment method. Use the card form only.`;
|
||||
}
|
||||
if (action.type === 'click' && !step.allowSubmit && SUBMIT_RE.test(label)) {
|
||||
return `Refused: clicking the final "${label}" button is not allowed in this step.`;
|
||||
}
|
||||
if (action.value !== undefined) {
|
||||
const allowed = new Set(step.placeholders || []);
|
||||
for (const m of action.value.matchAll(/\{\{([A-Z_]+)\}\}/g)) {
|
||||
if (!allowed.has(m[1])) return `Refused: placeholder {{${m[1]}}} is not available in this step.`;
|
||||
}
|
||||
// A model must never invent card-like numbers — secrets come only via placeholders.
|
||||
if (/\d{4,}/.test(action.value.replace(/\{\{[A-Z_]+\}\}/g, '').replace(/\s/g, ''))) {
|
||||
return 'Refused: literal digits in value. Use a {{PLACEHOLDER}} for secret values.';
|
||||
}
|
||||
}
|
||||
if (action.target.by === 'css' && !action.target.css) return 'Refused: by=css requires css.';
|
||||
if (action.target.by === 'role' && !action.target.role) return 'Refused: by=role requires role.';
|
||||
if (['text', 'placeholder', 'label'].includes(action.target.by) && !action.target.text) {
|
||||
return `Refused: by=${action.target.by} requires text.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What a click target actually is on the page (not what the model called it). */
|
||||
export interface ResolvedElementInfo {
|
||||
text?: string;
|
||||
ariaLabel?: string;
|
||||
value?: string;
|
||||
title?: string;
|
||||
testid?: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guard the RESOLVED element of a click, so css/unnamed targets can't bypass
|
||||
* the label-based checks (e.g. `[data-testid="hosted-payment-submit-button"]`).
|
||||
*/
|
||||
export function checkResolvedClick(
|
||||
info: ResolvedElementInfo,
|
||||
step: Pick<CheckoutStep, 'allowSubmit'>
|
||||
): string | null {
|
||||
const labels = [info.text, info.ariaLabel, info.value, info.title].filter(Boolean) as string[];
|
||||
for (const label of labels) {
|
||||
if (FORBIDDEN_CLICK_RE.test(label)) {
|
||||
return `Refused: the target element ("${label.slice(0, 60)}") is an alternative/express payment method or cancel link.`;
|
||||
}
|
||||
}
|
||||
if (info.testid && /\b(link|klarna|cashapp|cash-app|bank|express|back|cancel)\b/i.test(info.testid.replace(/[-_]/g, ' '))) {
|
||||
return `Refused: the target element (data-testid="${info.testid}") is an alternative/express payment method or cancel link.`;
|
||||
}
|
||||
if (!step.allowSubmit) {
|
||||
const isSubmit =
|
||||
info.type === 'submit' ||
|
||||
(info.testid !== undefined && /submit/i.test(info.testid)) ||
|
||||
labels.some((l) => SUBMIT_RE.test(l));
|
||||
if (isSubmit) return 'Refused: the target element is the final Pay/submit button, which is not allowed in this step.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function describeResolved(ctx: StepContext, action: Action): Promise<ResolvedElementInfo | null> {
|
||||
const found = await resolveTarget(ctx.page, action.target, 3_000);
|
||||
if (!found) return null;
|
||||
return found.locator
|
||||
.evaluate((n) => {
|
||||
const el = n as HTMLInputElement;
|
||||
const clean = (v: string | null | undefined) => (v || '').replace(/\s+/g, ' ').trim() || undefined;
|
||||
return {
|
||||
text: clean(el.innerText || el.textContent),
|
||||
ariaLabel: clean(el.getAttribute('aria-label')),
|
||||
value: el.tagName === 'INPUT' || el.tagName === 'BUTTON' ? clean(el.getAttribute('value')) : undefined,
|
||||
title: clean(el.getAttribute('title')),
|
||||
testid: clean(el.getAttribute('data-testid')),
|
||||
type: clean(el.getAttribute('type')),
|
||||
};
|
||||
})
|
||||
.catch(() => null);
|
||||
}
|
||||
|
||||
export function toTargetSpec(t: LlmTarget, frameKeys: string[]): TargetSpec {
|
||||
const { frameIndex, ...rest } = t;
|
||||
const spec: TargetSpec = { ...rest };
|
||||
if (frameIndex !== undefined && frameKeys[frameIndex]) spec.frameUrlIncludes = frameKeys[frameIndex];
|
||||
// Drop empty optional fields the model sometimes emits.
|
||||
for (const k of Object.keys(spec) as (keyof TargetSpec)[]) {
|
||||
if (spec[k] === '' || spec[k] === null) delete spec[k];
|
||||
}
|
||||
return spec;
|
||||
}
|
||||
|
||||
export async function pollVerify(step: CheckoutStep, ctx: StepContext, timeoutMs: number): Promise<boolean> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
do {
|
||||
if (await step.verify(ctx).catch(() => false)) return true;
|
||||
await ctx.page.waitForTimeout(500);
|
||||
} while (Date.now() < deadline);
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function healStep(step: CheckoutStep, ctx: StepContext, planner: Planner): Promise<HealResult> {
|
||||
const history: string[] = [];
|
||||
const executed: Action[] = [];
|
||||
let escalation = 0;
|
||||
let llmCalls = 0;
|
||||
let model = '';
|
||||
|
||||
for (let i = 0; i < MAX_ITERATIONS; i++) {
|
||||
const observation = await observe(ctx.page, ctx.secrets);
|
||||
let decision: LlmDecision;
|
||||
try {
|
||||
const res = await planner.decide({
|
||||
stepId: step.id,
|
||||
goal: step.goal,
|
||||
allowSubmit: !!step.allowSubmit,
|
||||
placeholders: step.placeholders || [],
|
||||
history,
|
||||
observation,
|
||||
escalation,
|
||||
});
|
||||
llmCalls++;
|
||||
decision = res.decision;
|
||||
model = res.model;
|
||||
} catch (e) {
|
||||
return { success: false, actions: executed, model, llmCalls, reason: `planner error: ${(e as Error).message}` };
|
||||
}
|
||||
console.log(` 🤖 [${model}] ${decision.status}: ${decision.thought}`);
|
||||
|
||||
if (decision.status === 'give_up') {
|
||||
history.push(`You gave up: ${decision.thought}`);
|
||||
if (++escalation > MAX_ESCALATIONS) break;
|
||||
continue;
|
||||
}
|
||||
if (decision.status === 'done' || !decision.action) {
|
||||
if (await pollVerify(step, ctx, 3_000)) return { success: true, actions: executed, model, llmCalls };
|
||||
history.push('You said the goal is done, but the automated check says it is NOT. Look again.');
|
||||
escalation = Math.min(escalation + 1, MAX_ESCALATIONS);
|
||||
continue;
|
||||
}
|
||||
|
||||
const refusal = checkGuards(decision.action, step);
|
||||
if (refusal) {
|
||||
history.push(refusal);
|
||||
continue;
|
||||
}
|
||||
const action: Action = {
|
||||
type: decision.action.type,
|
||||
target: toTargetSpec(decision.action.target, observation.frameKeys),
|
||||
...(decision.action.value !== undefined ? { value: decision.action.value } : {}),
|
||||
};
|
||||
if (action.type === 'click') {
|
||||
const info = await describeResolved(ctx, action);
|
||||
const resolvedRefusal = info && checkResolvedClick(info, step);
|
||||
if (resolvedRefusal) {
|
||||
history.push(resolvedRefusal);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const loc = await executeAction(ctx.page, action, ctx.secrets);
|
||||
if (action.type === 'fill') ctx.lastFilled = loc;
|
||||
executed.push(action);
|
||||
history.push(`OK: ${JSON.stringify(action)}`);
|
||||
} catch (e) {
|
||||
history.push(`FAILED: ${JSON.stringify(action)} — ${(e as Error).message.split('\n')[0]}`);
|
||||
escalation = Math.min(escalation + 1, MAX_ESCALATIONS);
|
||||
continue;
|
||||
}
|
||||
// Clicks can trigger slow transitions (accordion, redirect); after a fill,
|
||||
// a short check suffices — the model will usually need more actions.
|
||||
const verifyMs = action.type === 'click' ? step.verifyTimeoutMs ?? 5_000 : 2_000;
|
||||
if (await pollVerify(step, ctx, verifyMs)) {
|
||||
return { success: true, actions: executed, model, llmCalls };
|
||||
}
|
||||
}
|
||||
return { success: false, actions: executed, model, llmCalls, reason: 'goal not verified after LLM attempts' };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Gemini planner
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Cheapest first; escalation walks down the list. Unavailable model ids are skipped. */
|
||||
export const DEFAULT_MODELS = ['gemini-3.5-flash-lite', 'gemini-3.1-flash-lite', 'gemini-3.8-flash'];
|
||||
|
||||
const SYSTEM_PROMPT = `You are a careful browser-automation assistant completing ONE sub-goal on a Stripe hosted checkout page during an automated end-to-end test of our own product.
|
||||
You receive: the sub-goal, a history of your previous actions and their results, and an observation of every frame (ARIA snapshot + interactive element attributes + a screenshot where input contents are masked).
|
||||
Respond with exactly ONE next action (status "act"), or status "done" if the sub-goal is already achieved, or "give_up" if it is impossible.
|
||||
|
||||
Rules:
|
||||
- Pay ONLY with the card form. Never click Link, Klarna, Cash App, Bank, Affirm, Google/Apple Pay or any other alternative/express method.
|
||||
- Never type real data. Use ONLY the {{PLACEHOLDER}} tokens listed for this step as values (e.g. "{{CARD_NUMBER}}"). Non-secret literals (e.g. a country name for a select) are allowed.
|
||||
- Do not click the final Pay/submit button unless the step explicitly allows it.
|
||||
- Identify targets by STABLE semantics so the same description works on future runs:
|
||||
prefer by="role" with role + accessible name; else by="label"/"placeholder"/"text"; use by="css" only with stable attributes (id, name, autocomplete, data-testid), never generated class names or nth-child.
|
||||
- Set frameIndex to the frame[N] that contains the element.
|
||||
- If the right element exists but is hidden behind an overlay or visually hidden, set includeHidden=true.
|
||||
- Do not repeat an action that already FAILED with the same target; try a different description.`;
|
||||
|
||||
const RESPONSE_SCHEMA = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
thought: { type: 'string', description: 'One short sentence of reasoning.' },
|
||||
status: { type: 'string', enum: ['act', 'done', 'give_up'] },
|
||||
action: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: { type: 'string', enum: ['click', 'fill', 'select', 'check', 'uncheck', 'press'] },
|
||||
target: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
frameIndex: { type: 'integer' },
|
||||
by: { type: 'string', enum: ['role', 'text', 'css', 'placeholder', 'label'] },
|
||||
role: { type: 'string' },
|
||||
name: { type: 'string' },
|
||||
exact: { type: 'boolean' },
|
||||
text: { type: 'string' },
|
||||
css: { type: 'string' },
|
||||
includeHidden: { type: 'boolean' },
|
||||
},
|
||||
required: ['by'],
|
||||
},
|
||||
value: { type: 'string' },
|
||||
},
|
||||
required: ['type', 'target'],
|
||||
},
|
||||
},
|
||||
required: ['thought', 'status'],
|
||||
};
|
||||
|
||||
function isModelUnavailable(e: unknown): boolean {
|
||||
const msg = String((e as Error)?.message || e);
|
||||
return /\b404\b|not found|NOT_FOUND|is not supported|unsupported model|invalid model/i.test(msg);
|
||||
}
|
||||
|
||||
export function buildPrompt(input: PlannerInput): string {
|
||||
return [
|
||||
`## Sub-goal (step "${input.stepId}")\n${input.goal}`,
|
||||
`## Allowed placeholders\n${input.placeholders.length ? input.placeholders.map((p) => `{{${p}}}`).join(', ') : '(none)'}`,
|
||||
`## Final Pay/submit button allowed in this step: ${input.allowSubmit ? 'YES' : 'NO'}`,
|
||||
`## History\n${input.history.length ? input.history.map((h, i) => `${i + 1}. ${h}`).join('\n') : '(no actions yet)'}`,
|
||||
`## Observation (page ${input.observation.url})\n${input.observation.text}`,
|
||||
].join('\n\n');
|
||||
}
|
||||
|
||||
export class GeminiPlanner implements Planner {
|
||||
private readonly unavailable = new Set<string>();
|
||||
|
||||
constructor(
|
||||
private readonly apiKey: string,
|
||||
private readonly models: string[] = DEFAULT_MODELS
|
||||
) {}
|
||||
|
||||
static fromEnv(): GeminiPlanner | null {
|
||||
const key = process.env.GEMINI_API_KEY;
|
||||
if (!key) return null;
|
||||
const models = (process.env.E2E_SELF_HEAL_MODELS || '').split(',').map((m) => m.trim()).filter(Boolean);
|
||||
return new GeminiPlanner(key, models.length ? models : DEFAULT_MODELS);
|
||||
}
|
||||
|
||||
async decide(input: PlannerInput): Promise<{ decision: LlmDecision; model: string }> {
|
||||
// Lazy import: the SDK is only needed when a fallback actually fires.
|
||||
const { GoogleGenAI } = await import('@google/genai');
|
||||
// vertexai:false — Vertex AI is disabled in the nomadkaraoke GCP project; this
|
||||
// key bills to the AI Studio project (see project_no_ai_spend_in_gcp_project).
|
||||
const ai = new GoogleGenAI({ apiKey: this.apiKey, vertexai: false });
|
||||
const candidates = this.models.filter((m) => !this.unavailable.has(m));
|
||||
const ordered = candidates.slice(Math.min(input.escalation, Math.max(candidates.length - 1, 0)));
|
||||
let lastErr: unknown;
|
||||
for (const model of ordered) {
|
||||
try {
|
||||
const parts: Array<{ text: string } | { inlineData: { mimeType: string; data: string } }> = [
|
||||
{ text: buildPrompt(input) },
|
||||
];
|
||||
if (input.observation.screenshotJpegBase64) {
|
||||
parts.push({ inlineData: { mimeType: 'image/jpeg', data: input.observation.screenshotJpegBase64 } });
|
||||
}
|
||||
const res = await ai.models.generateContent({
|
||||
model,
|
||||
contents: [{ role: 'user', parts }],
|
||||
config: {
|
||||
systemInstruction: SYSTEM_PROMPT,
|
||||
responseMimeType: 'application/json',
|
||||
responseJsonSchema: RESPONSE_SCHEMA,
|
||||
temperature: 0,
|
||||
httpOptions: { timeout: 45_000 },
|
||||
},
|
||||
});
|
||||
const decision = JSON.parse(res.text || '{}') as LlmDecision;
|
||||
if (!decision.status) throw new Error(`malformed response: ${res.text?.slice(0, 200)}`);
|
||||
return { decision, model };
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
if (isModelUnavailable(e)) {
|
||||
console.log(` 🤖 model ${model} unavailable — skipping (${String((e as Error).message).slice(0, 120)})`);
|
||||
this.unavailable.add(model);
|
||||
} else {
|
||||
console.log(` 🤖 model ${model} error — trying next (${String((e as Error).message).slice(0, 120)})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// frontend/e2e/helpers/self-healing/observe.ts
|
||||
import type { Page } from '@playwright/test';
|
||||
import { frameUrlKey } from './actions';
|
||||
import type { Secrets } from './types';
|
||||
|
||||
/**
|
||||
* Builds the page observation the LLM fallback sees: per-frame ARIA snapshot +
|
||||
* a compact list of interactive elements (attributes only, NEVER input values),
|
||||
* plus a screenshot with every <input> masked.
|
||||
*
|
||||
* ⚠️ PCI: the real card number/expiry/CVC must never reach the LLM. Defence in
|
||||
* depth: values aren't collected, textbox values in ARIA snapshots are blanked,
|
||||
* PAN-like digit runs are scrubbed, every known secret is scrubbed verbatim,
|
||||
* and inputs are masked in the screenshot.
|
||||
*/
|
||||
|
||||
const MAX_SNAPSHOT_CHARS_PER_FRAME = 8_000;
|
||||
const MAX_ELEMENTS_PER_FRAME = 80;
|
||||
const MAX_TOTAL_CHARS = 40_000;
|
||||
|
||||
export function redact(text: string, secrets: Secrets): string {
|
||||
let out = text
|
||||
// ARIA snapshot textbox/combobox/spinbutton lines carry the current value after ':'
|
||||
.replace(/^(\s*- (?:textbox|combobox|spinbutton|searchbox)\b[^\n:]*?(?:"[^"\n]*")?[^\n:]*):\s.*$/gm, '$1: [value redacted]')
|
||||
// Anything shaped like a card number (13-19 digits, optional space/dash separators)
|
||||
.replace(/\b(?:\d[ -]?){12,18}\d\b/g, '[redacted-digits]');
|
||||
for (const secret of Object.values(secrets)) {
|
||||
// Short secrets (CVC "123", ZIP) would scrub unrelated text everywhere; the
|
||||
// value-blanking above already covers them inside fields.
|
||||
if (secret && secret.replace(/\s/g, '').length >= 5) {
|
||||
out = out.split(secret).join('[redacted]');
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
interface ElementInfo {
|
||||
tag: string;
|
||||
type?: string;
|
||||
role?: string;
|
||||
id?: string;
|
||||
name?: string;
|
||||
ariaLabel?: string;
|
||||
placeholder?: string;
|
||||
autocomplete?: string;
|
||||
testid?: string;
|
||||
text?: string;
|
||||
visible: boolean;
|
||||
checked?: boolean;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface Observation {
|
||||
url: string;
|
||||
text: string;
|
||||
/** frame index (as referenced in `text`) → stable frame URL key. */
|
||||
frameKeys: string[];
|
||||
screenshotJpegBase64?: string;
|
||||
}
|
||||
|
||||
export async function observe(page: Page, secrets: Secrets, withScreenshot = true): Promise<Observation> {
|
||||
const sections: string[] = [];
|
||||
const frames = page.frames().filter((f) => !f.isDetached());
|
||||
for (let i = 0; i < frames.length; i++) {
|
||||
const frame = frames[i];
|
||||
const key = frameUrlKey(frame.url());
|
||||
if (!key || key === 'about:blank') continue;
|
||||
|
||||
const snapshot = await frame
|
||||
.locator('body')
|
||||
.ariaSnapshot({ timeout: 3_000 })
|
||||
.catch(() => '');
|
||||
const elements: ElementInfo[] = await frame
|
||||
.evaluate((max: number) => {
|
||||
const sel = 'input, button, select, textarea, a[href], label, [role], [data-testid]';
|
||||
const out: ElementInfo[] = [];
|
||||
for (const el of Array.from(document.querySelectorAll<HTMLElement>(sel))) {
|
||||
if (out.length >= max) break;
|
||||
const r = el.getBoundingClientRect();
|
||||
const cs = getComputedStyle(el);
|
||||
const visible = r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none' && cs.opacity !== '0';
|
||||
const input = el as HTMLInputElement;
|
||||
const info: ElementInfo = { tag: el.tagName.toLowerCase(), visible };
|
||||
const attr = (n: string) => el.getAttribute(n) || undefined;
|
||||
info.type = attr('type');
|
||||
info.role = attr('role');
|
||||
info.id = el.id || undefined;
|
||||
info.name = attr('name');
|
||||
info.ariaLabel = attr('aria-label');
|
||||
info.placeholder = attr('placeholder');
|
||||
info.autocomplete = attr('autocomplete');
|
||||
info.testid = attr('data-testid');
|
||||
// Text content only for non-form elements — never read input values.
|
||||
if (!['input', 'select', 'textarea'].includes(info.tag)) {
|
||||
const t = (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim();
|
||||
if (t) info.text = t.slice(0, 60);
|
||||
}
|
||||
if (info.type === 'checkbox' || info.type === 'radio') info.checked = input.checked;
|
||||
if ((el as HTMLButtonElement).disabled) info.disabled = true;
|
||||
out.push(info);
|
||||
}
|
||||
return out;
|
||||
}, MAX_ELEMENTS_PER_FRAME)
|
||||
.catch(() => []);
|
||||
|
||||
if (!snapshot && elements.length === 0) continue;
|
||||
const elementLines = elements
|
||||
.map((e) => JSON.stringify(Object.fromEntries(Object.entries(e).filter(([, v]) => v !== undefined))))
|
||||
.join('\n');
|
||||
sections.push(
|
||||
`### frame[${i}] url=${key}\n` +
|
||||
`#### ARIA snapshot\n${snapshot.slice(0, MAX_SNAPSHOT_CHARS_PER_FRAME)}\n` +
|
||||
`#### Interactive elements (attributes only)\n${elementLines}`
|
||||
);
|
||||
}
|
||||
|
||||
let text = redact(sections.join('\n\n'), secrets);
|
||||
if (text.length > MAX_TOTAL_CHARS) text = text.slice(0, MAX_TOTAL_CHARS) + '\n…[truncated]';
|
||||
|
||||
let screenshotJpegBase64: string | undefined;
|
||||
if (withScreenshot) {
|
||||
const buf = await page
|
||||
.screenshot({
|
||||
type: 'jpeg',
|
||||
quality: 50,
|
||||
mask: frames.map((f) => f.locator('input, textarea')),
|
||||
maskColor: '#888888',
|
||||
})
|
||||
.catch(() => undefined);
|
||||
screenshotJpegBase64 = buf?.toString('base64');
|
||||
}
|
||||
|
||||
return { url: frameUrlKey(page.url()), text, frameKeys: frames.map((f) => frameUrlKey(f.url())), screenshotJpegBase64 };
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// frontend/e2e/helpers/self-healing/step-runner.ts
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { executeAction } from './actions';
|
||||
import { healStep, pollVerify, type Planner } from './llm-agent';
|
||||
import { loadLearned, mergeLearned, serialize } from './learned-store';
|
||||
import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext, StepOutcome } from './types';
|
||||
|
||||
/**
|
||||
* Runs a flow as a sequence of verified sub-goals:
|
||||
* learned variants (newest first) → hand-written builtins → LLM fallback.
|
||||
* Each attempt is judged ONLY by the step's `verify` postcondition — never by
|
||||
* "the click didn't throw" — so a silently-wrong variant can't pass.
|
||||
*/
|
||||
export class SelfHealingRunner {
|
||||
readonly outcomes: StepOutcome[] = [];
|
||||
private readonly forceLlm: Set<string>;
|
||||
private readonly ctx: StepContext;
|
||||
|
||||
constructor(
|
||||
page: Page,
|
||||
secrets: Secrets,
|
||||
private readonly planner: Planner | null,
|
||||
private readonly learned: LearnedVariantsFile = loadLearned(),
|
||||
opts: { forceLlmSteps?: string[] } = {}
|
||||
) {
|
||||
this.ctx = { page, secrets };
|
||||
this.forceLlm = new Set(
|
||||
opts.forceLlmSteps ??
|
||||
(process.env.E2E_SELF_HEAL_FORCE_LLM || '').split(',').map((s) => s.trim()).filter(Boolean)
|
||||
);
|
||||
}
|
||||
|
||||
async run(step: CheckoutStep): Promise<StepOutcome> {
|
||||
const outcome = await this.attempt(step);
|
||||
this.outcomes.push(outcome);
|
||||
const icon = { ok: '✓', healed: '🩹', skipped: '–', failed: '✘' }[outcome.status];
|
||||
console.log(` ${icon} step ${step.id}: ${outcome.status}${'variant' in outcome ? ` (${outcome.via}: ${outcome.variant})` : ''}`);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
private async attempt(step: CheckoutStep): Promise<StepOutcome> {
|
||||
const ctx = this.ctx;
|
||||
ctx.lastFilled = undefined;
|
||||
const verifyMs = step.verifyTimeoutMs ?? 5_000;
|
||||
|
||||
// Already satisfied (e.g. card fields visible without choosing "Card")?
|
||||
if (await step.verify(ctx).catch(() => false)) {
|
||||
return { stepId: step.id, status: 'ok', via: 'builtin', variant: 'already-satisfied' };
|
||||
}
|
||||
|
||||
const forced = this.forceLlm.has(step.id);
|
||||
if (forced) console.log(` ⚙️ step ${step.id}: E2E_SELF_HEAL_FORCE_LLM — skipping deterministic variants`);
|
||||
|
||||
if (!forced) {
|
||||
for (const v of this.learned.steps[step.id] || []) {
|
||||
try {
|
||||
for (const a of v.actions) {
|
||||
const loc = await executeAction(ctx.page, a, ctx.secrets);
|
||||
if (a.type === 'fill') ctx.lastFilled = loc;
|
||||
}
|
||||
if (await pollVerify(step, ctx, verifyMs)) {
|
||||
return { stepId: step.id, status: 'ok', via: 'learned', variant: v.id };
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(` learned variant ${v.id} failed: ${(e as Error).message.split('\n')[0]}`);
|
||||
}
|
||||
}
|
||||
for (const b of step.builtins) {
|
||||
try {
|
||||
await b.run(ctx);
|
||||
if (await pollVerify(step, ctx, verifyMs)) {
|
||||
return { stepId: step.id, status: 'ok', via: 'builtin', variant: b.name };
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(` builtin "${b.name}" failed: ${(e as Error).message.split('\n')[0]}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (step.optional && !forced) {
|
||||
return { stepId: step.id, status: 'skipped', reason: 'optional step: no variant applied (field may not exist in this layout)' };
|
||||
}
|
||||
if (!this.planner) {
|
||||
return { stepId: step.id, status: 'failed', reason: 'all deterministic variants failed and no LLM planner is configured (GEMINI_API_KEY unset)', llmCalls: 0 };
|
||||
}
|
||||
|
||||
console.log(` 🤖 step ${step.id}: deterministic variants exhausted — LLM fallback`);
|
||||
const heal = await healStep(step, ctx, this.planner);
|
||||
if (heal.success && heal.actions.length) {
|
||||
return { stepId: step.id, status: 'healed', model: heal.model, actions: heal.actions, llmCalls: heal.llmCalls };
|
||||
}
|
||||
if (heal.success) {
|
||||
// Verified with zero actions (e.g. it only needed time) — nothing to learn.
|
||||
return { stepId: step.id, status: 'ok', via: 'builtin', variant: 'verified-after-wait' };
|
||||
}
|
||||
return { stepId: step.id, status: 'failed', reason: heal.reason || 'LLM fallback failed', llmCalls: heal.llmCalls };
|
||||
}
|
||||
|
||||
get healed() {
|
||||
return this.outcomes.filter((o): o is Extract<StepOutcome, { status: 'healed' }> => o.status === 'healed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Write `<dir>/self-heal-report.json` always, and — only when the caller has
|
||||
* independently confirmed the whole flow succeeded — `<dir>/learned-variants.json`
|
||||
* containing the merged recipes, for the workflow to commit.
|
||||
*/
|
||||
writeArtifacts(dir: string, opts: { flowVerified: boolean; runUrl?: string }): { learnedWritten: boolean } {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const healed = this.healed;
|
||||
const llmCalls = this.outcomes.reduce((n, o) => n + ('llmCalls' in o ? o.llmCalls : 0), 0);
|
||||
let learnedWritten = false;
|
||||
let added: string[] = [];
|
||||
if (opts.flowVerified && healed.length) {
|
||||
const merged = mergeLearned(this.learned, healed, { runUrl: opts.runUrl });
|
||||
if (merged.changed) {
|
||||
fs.writeFileSync(path.join(dir, 'learned-variants.json'), serialize(merged.file));
|
||||
learnedWritten = true;
|
||||
added = merged.added.map((a) => `${a.stepId}:${a.variant.id}`);
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'self-heal-report.json'),
|
||||
JSON.stringify({ flowVerified: opts.flowVerified, llmCalls, learnedWritten, added, outcomes: this.outcomes }, null, 2)
|
||||
);
|
||||
return { learnedWritten };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// frontend/e2e/helpers/self-healing/types.ts
|
||||
import type { Locator, Page } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Serializable description of an element. Produced by the LLM fallback and
|
||||
* persisted in learned-variants.json, so it must stay plain JSON and must
|
||||
* describe the element by *stable semantics* (role/name/text/attributes), never
|
||||
* by snapshot refs or indexes that change per run.
|
||||
*/
|
||||
export interface TargetSpec {
|
||||
/** Substring of the frame URL (host + path, no query) to search first. */
|
||||
frameUrlIncludes?: string;
|
||||
by: 'role' | 'text' | 'css' | 'placeholder' | 'label';
|
||||
role?: string;
|
||||
name?: string;
|
||||
/** Exact (case-sensitive, whole-string) name/text match. Default false = case-insensitive substring. */
|
||||
exact?: boolean;
|
||||
text?: string;
|
||||
css?: string;
|
||||
/** Match elements hidden from the accessibility tree / not visible (clicks become dispatchEvent). */
|
||||
includeHidden?: boolean;
|
||||
}
|
||||
|
||||
export type ActionType = 'click' | 'fill' | 'select' | 'check' | 'uncheck' | 'press';
|
||||
|
||||
/**
|
||||
* One UI action. `value` may contain secret placeholders like `{{CARD_NUMBER}}`
|
||||
* which are substituted at execution time — real secrets never appear in an
|
||||
* Action that is sent to or produced by the LLM, or persisted to disk.
|
||||
*/
|
||||
export interface Action {
|
||||
type: ActionType;
|
||||
target: TargetSpec;
|
||||
value?: string;
|
||||
}
|
||||
|
||||
/** Values the runner may substitute into `{{PLACEHOLDER}}` tokens. */
|
||||
export type Secrets = Record<string, string>;
|
||||
|
||||
export interface StepContext {
|
||||
page: Page;
|
||||
secrets: Secrets;
|
||||
/** The element most recently filled during the current step (reset per step) — lets fill-step verifies check the value landed in a plausible field. */
|
||||
lastFilled?: Locator;
|
||||
}
|
||||
|
||||
/** A deterministic, hand-written way to accomplish a step. */
|
||||
export interface BuiltinVariant {
|
||||
name: string;
|
||||
run: (ctx: StepContext) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface CheckoutStep {
|
||||
id: string;
|
||||
/** Natural-language goal handed to the LLM fallback. */
|
||||
goal: string;
|
||||
builtins: BuiltinVariant[];
|
||||
/** Postcondition: did the step actually achieve its goal? Must be side-effect free. */
|
||||
verify: (ctx: StepContext) => Promise<boolean>;
|
||||
/** How long verify may poll after each variant before declaring it failed. */
|
||||
verifyTimeoutMs?: number;
|
||||
/**
|
||||
* Optional steps (e.g. a ZIP field that only some layouts have) never call
|
||||
* the LLM and never fail the run — a missing field is caught by the submit
|
||||
* step's verify instead, whose LLM fallback can fill whatever is required.
|
||||
*/
|
||||
optional?: boolean;
|
||||
/** Whether the LLM may click the final Pay/submit button in this step. */
|
||||
allowSubmit?: boolean;
|
||||
/** Placeholders the LLM may use in this step, e.g. ['CARD_NUMBER']. */
|
||||
placeholders?: string[];
|
||||
}
|
||||
|
||||
export interface LearnedVariant {
|
||||
id: string;
|
||||
learnedAt: string;
|
||||
runUrl?: string;
|
||||
model?: string;
|
||||
actions: Action[];
|
||||
}
|
||||
|
||||
export interface LearnedVariantsFile {
|
||||
version: 1;
|
||||
steps: Record<string, LearnedVariant[]>;
|
||||
}
|
||||
|
||||
export type StepOutcome =
|
||||
| { stepId: string; status: 'ok'; via: 'builtin' | 'learned'; variant: string }
|
||||
| { stepId: string; status: 'healed'; model: string; actions: Action[]; llmCalls: number }
|
||||
| { stepId: string; status: 'skipped'; reason: string }
|
||||
| { stepId: string; status: 'failed'; reason: string; llmCalls: number };
|
||||
@@ -1,46 +1,57 @@
|
||||
// frontend/e2e/helpers/stripe-checkout.ts
|
||||
import { Page, Frame, Locator } from '@playwright/test';
|
||||
import * as fs from 'fs';
|
||||
import { GeminiPlanner, type Planner } from './self-healing/llm-agent';
|
||||
import { SelfHealingRunner } from './self-healing/step-runner';
|
||||
import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext } from './self-healing/types';
|
||||
|
||||
/**
|
||||
* Automate Stripe's hosted checkout page (checkout.stripe.com).
|
||||
*
|
||||
* ⚠️ Stripe changes this page's structure without notice — likely A/B testing
|
||||
* or staged rollouts, so BOTH the old and new layouts can appear on any given
|
||||
* day (and can flip back). We have observed at least three variants:
|
||||
* 1. Multi-method accordion of *radios* (Card / Cash App / Klarna / Bank),
|
||||
* card fields inside iframes, Pay button in the top frame. (Apr 2026)
|
||||
* 2. Single method (Card only): card fields render as *direct* textboxes in
|
||||
* the top document, no chooser at all. (#916, Aug 17)
|
||||
* 3. Multi-method Payment Element where the chooser is *buttons* (not radios)
|
||||
* and the whole element — chooser, card fields AND the "Pay" button — is
|
||||
* rendered inside a nested same-origin iframe. (Aug 19-20)
|
||||
* or staged rollouts, so BOTH old and new layouts can appear on any given day
|
||||
* (and can flip back). Observed variants (see git history for details):
|
||||
* 1. Accordion of *radios* (Card / Cash App / Klarna / Bank). (Apr 2026)
|
||||
* 2. Card-only: card fields as direct textboxes, no chooser. (#916, Aug 17)
|
||||
* 3. Chooser as *buttons*, whole Payment Element in a nested iframe. (#919, Aug 20)
|
||||
* 4. Required "Name on card" + "ZIP code" with new labels. (#945, Aug 26)
|
||||
* 5. Plain "Card" label + visually-hidden "Pay with card" button. (#1115, Oct 3)
|
||||
*
|
||||
* DO NOT narrow this helper to a single layout — it must tolerate all of the
|
||||
* above. It does so by being layout-agnostic:
|
||||
* - `page.getByRole(...)` only sees the top frame, so we search EVERY frame
|
||||
* (top + nested iframes) for each element via `locateVisibleInFrames`.
|
||||
* - The "Card" chooser is matched as a radio OR a button.
|
||||
* - Card fields are matched whether direct inputs or iframe-nested.
|
||||
* If Stripe introduces yet another layout, extend the locators here rather than
|
||||
* assuming a single shape.
|
||||
* So the flow is a sequence of SELF-HEALING STEPS (see ./self-healing/). Each
|
||||
* step has a `verify` postcondition and is attempted with:
|
||||
* 1. learned variants — recipes an LLM discovered on earlier runs, auto-
|
||||
* committed to self-healing/learned-variants.json by the daily workflow;
|
||||
* 2. the hand-written builtin variants below;
|
||||
* 3. an LLM fallback (Gemini) that drives the page one action at a time
|
||||
* until `verify` passes. Card data never reaches the LLM: it uses
|
||||
* `{{CARD_NUMBER}}`-style placeholders that we substitute locally, and
|
||||
* observations are redacted + input-masked.
|
||||
* When the LLM heals a step and the purchase is confirmed server-side, the
|
||||
* daily workflow opens an auto-merging PR adding the recipe to
|
||||
* learned-variants.json — the next run replays it without the LLM.
|
||||
*
|
||||
* You can still add builtin variants by hand, but you shouldn't need to.
|
||||
*
|
||||
* Environment variables:
|
||||
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY,
|
||||
* E2E_STRIPE_CARD_CVC, E2E_STRIPE_CARDHOLDER_NAME (optional)
|
||||
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC,
|
||||
* E2E_STRIPE_CARDHOLDER_NAME (optional), E2E_STRIPE_ZIP (optional)
|
||||
* GEMINI_API_KEY — enables the LLM fallback (absent → deterministic only)
|
||||
* E2E_SELF_HEAL_MODELS — comma-separated Gemini model ids, cheapest first
|
||||
* E2E_SELF_HEAL_FORCE_LLM — comma-separated step ids to force through the LLM (testing)
|
||||
*/
|
||||
|
||||
interface CardDetails {
|
||||
number: string;
|
||||
expiry: string;
|
||||
cvc: string;
|
||||
name?: string;
|
||||
name: string;
|
||||
zip: string;
|
||||
}
|
||||
|
||||
function getCardDetailsFromEnv(): CardDetails {
|
||||
const number = process.env.E2E_STRIPE_CARD_NUMBER;
|
||||
const expiry = process.env.E2E_STRIPE_CARD_EXPIRY;
|
||||
const cvc = process.env.E2E_STRIPE_CARD_CVC;
|
||||
const name = process.env.E2E_STRIPE_CARDHOLDER_NAME;
|
||||
|
||||
if (!number || !expiry || !cvc) {
|
||||
throw new Error(
|
||||
@@ -50,7 +61,13 @@ function getCardDetailsFromEnv(): CardDetails {
|
||||
|
||||
// Default the name so a missing/empty secret can't leave the (now required)
|
||||
// "Name on card" field blank and get the Pay click rejected.
|
||||
return { number, expiry, cvc, name: name || 'E2E Test' };
|
||||
return {
|
||||
number,
|
||||
expiry,
|
||||
cvc,
|
||||
name: process.env.E2E_STRIPE_CARDHOLDER_NAME || 'E2E Test',
|
||||
zip: process.env.E2E_STRIPE_ZIP || '10001',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,201 +97,20 @@ async function locateVisibleInFrames(
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete the Stripe Checkout page with card details from environment.
|
||||
*
|
||||
* @param page - Playwright page that will be redirected to checkout.stripe.com
|
||||
* @returns `{ redirected }` — whether the browser was observed navigating back
|
||||
* to our success/app URL after payment. The redirect can be slow or dropped
|
||||
* even when the charge succeeds (Stripe→site hop, 3DS interstitial), so this
|
||||
* is reported rather than thrown: callers should treat the *server-side*
|
||||
* credit grant (Stripe webhook) as the source of truth and use `redirected`
|
||||
* only as a best-effort UX signal. Genuine failures (no Pay button, card
|
||||
* declined) still throw.
|
||||
* Accessible-name, placeholder and autocomplete metadata for each Stripe card
|
||||
* field, used to build robust locators that work whether Stripe renders the
|
||||
* field as a direct input or inside an iframe.
|
||||
*/
|
||||
export async function completeStripeCheckout(page: Page): Promise<{ redirected: boolean }> {
|
||||
const card = getCardDetailsFromEnv();
|
||||
|
||||
// Step 1: Wait for Stripe Checkout page to fully load
|
||||
console.log(' Waiting for Stripe Checkout page...');
|
||||
await page.waitForURL(/checkout\.stripe\.com/, { timeout: 30_000 });
|
||||
|
||||
// The "Pay" button is one of the last elements to render and confirms the
|
||||
// Payment Element is interactive. It may be in the top frame (single-method
|
||||
// layout) or a nested iframe (multi-method layout). Match it exactly so the
|
||||
// "Pay with Link" / "Pay with Klarna" express buttons don't shadow it.
|
||||
const payButton = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) => f.getByRole('button', { name: /^Pay$/i }),
|
||||
30_000
|
||||
);
|
||||
if (!payButton) {
|
||||
await page.screenshot({ path: 'test-results/stripe-no-pay-button.png' });
|
||||
throw new Error('Stripe "Pay" button not visible in any frame after 30s');
|
||||
}
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
|
||||
console.log(' Stripe Checkout loaded');
|
||||
|
||||
// Step 2: Ensure the card fields are shown. In the single-method layout they
|
||||
// are already visible; in the multi-method accordion we must expand "Card"
|
||||
// (rendered as a button or radio depending on Stripe's variant).
|
||||
console.log(' Selecting Card payment method...');
|
||||
let cardNumberField = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) => cardFieldLocator(f, 'cardNumber'),
|
||||
5_000
|
||||
);
|
||||
|
||||
if (cardNumberField) {
|
||||
console.log(' Card fields already visible — no chooser to expand');
|
||||
} else {
|
||||
const cardChoice = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) =>
|
||||
f
|
||||
.getByRole('radio', { name: /^Card$/i })
|
||||
.or(f.getByRole('button', { name: /^Card$/i })),
|
||||
5_000
|
||||
);
|
||||
if (cardChoice) {
|
||||
// force:true bypasses any overlay/accordion animation intercepting clicks.
|
||||
await cardChoice.click({ force: true }).catch(() => {});
|
||||
console.log(' Card payment method selected');
|
||||
} else {
|
||||
console.log(' No Card chooser found — waiting for card fields to render...');
|
||||
}
|
||||
cardNumberField = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) => cardFieldLocator(f, 'cardNumber'),
|
||||
15_000
|
||||
);
|
||||
if (!cardNumberField) {
|
||||
console.log(' WARNING: card number field not visible after selecting Card');
|
||||
}
|
||||
}
|
||||
|
||||
await page.waitForTimeout(1000);
|
||||
await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
|
||||
|
||||
// Step 3-5: Fill card number, expiry, CVC
|
||||
console.log(' Filling card number...');
|
||||
await fillCardField(page, 'cardNumber', card.number);
|
||||
console.log(' Filling card expiry...');
|
||||
await fillCardField(page, 'cardExpiry', card.expiry);
|
||||
console.log(' Filling CVC...');
|
||||
await fillCardField(page, 'cardCvc', card.cvc);
|
||||
|
||||
// Step 6: Fill cardholder name if the field exists (any frame).
|
||||
// Stripe renames/relabels this field across layouts — we've seen the
|
||||
// accessible name be "Cardholder name", "Name on card", or "Full name on
|
||||
// card", and the placeholder be "Full name on card" or "First and last
|
||||
// name". Match all known variants so an empty name field can't silently
|
||||
// block the Pay button (which produced a false "payment broken" alarm — the
|
||||
// Pay click was rejected with "Please provide the name on your card").
|
||||
if (card.name) {
|
||||
const nameInput = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) =>
|
||||
f
|
||||
.locator(
|
||||
'[data-elements-stable-field-name="billingName"], #billingName, input[name="billingName"], input[placeholder="Full name on card"], input[placeholder="First and last name"]'
|
||||
)
|
||||
.or(f.getByRole('textbox', { name: /name on card|cardholder name/i })),
|
||||
8_000
|
||||
);
|
||||
if (nameInput) {
|
||||
console.log(' Filling cardholder name...');
|
||||
await nameInput.fill(card.name);
|
||||
} else {
|
||||
console.log(' WARNING: cardholder name field not found — Pay may be rejected');
|
||||
}
|
||||
}
|
||||
|
||||
// Step 6b: Fill ZIP code (required for US cards) — search any frame.
|
||||
// The accessible name is "ZIP code" (not exactly "ZIP"), so the regex must
|
||||
// not anchor to ^zip$. Placeholder is often absent, so rely on the stable
|
||||
// field name / accessible name too.
|
||||
const zipInput = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) =>
|
||||
f
|
||||
.locator(
|
||||
'[data-elements-stable-field-name="billingPostalCode"], #billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]'
|
||||
)
|
||||
.or(f.getByRole('textbox', { name: /zip|postal code/i })),
|
||||
8_000
|
||||
);
|
||||
if (zipInput) {
|
||||
console.log(' Filling ZIP code...');
|
||||
await zipInput.fill(process.env.E2E_STRIPE_ZIP || '10001');
|
||||
} else {
|
||||
console.log(' WARNING: ZIP code field not found — Pay may be rejected');
|
||||
}
|
||||
|
||||
// Step 6c: Uncheck "Save my information" to avoid a phone-number requirement
|
||||
const saveCheckbox = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) => f.getByRole('checkbox', { name: /save my information/i }),
|
||||
2_000
|
||||
);
|
||||
if (saveCheckbox && (await saveCheckbox.isChecked().catch(() => false))) {
|
||||
console.log(' Unchecking "Save my information"...');
|
||||
await saveCheckbox.uncheck({ force: true }).catch(() => {});
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
|
||||
console.log(' Card details filled');
|
||||
|
||||
// Step 7: Click "Pay" button (re-locate in case the frame re-rendered)
|
||||
console.log(' Clicking Pay button...');
|
||||
const finalPay = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) => f.getByRole('button', { name: /^Pay$/i }),
|
||||
10_000
|
||||
);
|
||||
if (!finalPay) {
|
||||
await page.screenshot({ path: 'test-results/stripe-no-pay-button-final.png' });
|
||||
throw new Error('Stripe "Pay" button not visible when ready to submit');
|
||||
}
|
||||
await finalPay.click();
|
||||
|
||||
console.log(' Payment submitted, waiting for redirect...');
|
||||
// Wait for redirect back to our site. The charge itself completes on Stripe's
|
||||
// side and is confirmed to us via webhook; the browser redirect back is a
|
||||
// separate, sometimes-slow hop (and can stall on a 3DS interstitial). So a
|
||||
// redirect timeout is NOT a payment failure — report it and let the caller
|
||||
// verify the credit grant server-side instead of failing the whole test.
|
||||
try {
|
||||
await page.waitForURL(/nomadkaraoke\.com.*payment\/success|nomadkaraoke\.com.*\/app/, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-complete.png' });
|
||||
console.log(' Stripe Checkout complete — redirected to success page');
|
||||
return { redirected: true };
|
||||
} catch {
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-no-redirect.png' });
|
||||
console.warn(
|
||||
' ⚠️ Payment submitted but no redirect within 60s — will verify the credit ' +
|
||||
'grant server-side (charge may have succeeded with a slow/dropped redirect)'
|
||||
);
|
||||
return { redirected: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessible-name and placeholder metadata for each Stripe card field, used to
|
||||
* build robust locators that work whether Stripe renders the field as a direct
|
||||
* input (single-payment-method layout) or inside an iframe.
|
||||
*/
|
||||
const CARD_FIELD_META: Record<string, { name: RegExp; placeholder?: string }> = {
|
||||
cardNumber: { name: /card number/i, placeholder: '1234 1234 1234 1234' },
|
||||
cardExpiry: { name: /expiration|expiry/i, placeholder: 'MM / YY' },
|
||||
cardCvc: { name: /^cvc$|security code/i },
|
||||
const CARD_FIELD_META: Record<string, { name: RegExp; placeholder?: string; autocomplete: string }> = {
|
||||
cardNumber: { name: /card number/i, placeholder: '1234 1234 1234 1234', autocomplete: 'cc-number' },
|
||||
cardExpiry: { name: /expiration|expiry/i, placeholder: 'MM / YY', autocomplete: 'cc-exp' },
|
||||
cardCvc: { name: /^cvc$|security code/i, autocomplete: 'cc-csc' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Locator for a Stripe card field within a given frame. Matches by Stripe's
|
||||
* stable field-name attribute, element id, input name, placeholder, or
|
||||
* accessible name — whichever the current Checkout layout uses.
|
||||
* stable field-name attribute, element id, input name, autocomplete token,
|
||||
* placeholder, or accessible name — whichever the current layout uses.
|
||||
*/
|
||||
function cardFieldLocator(frame: Frame, fieldName: string): Locator {
|
||||
const meta = CARD_FIELD_META[fieldName];
|
||||
@@ -283,22 +119,317 @@ function cardFieldLocator(frame: Frame, fieldName: string): Locator {
|
||||
`#${fieldName}`,
|
||||
`input[name="${fieldName}"]`,
|
||||
];
|
||||
if (meta?.autocomplete) selectors.push(`input[autocomplete="${meta.autocomplete}"]`);
|
||||
if (meta?.placeholder) selectors.push(`input[placeholder="${meta.placeholder}"]`);
|
||||
let loc = frame.locator(selectors.join(', '));
|
||||
if (meta) loc = loc.or(frame.getByRole('textbox', { name: meta.name }));
|
||||
return loc.first();
|
||||
}
|
||||
|
||||
function nameFieldLocator(f: Frame): Locator {
|
||||
// Stripe has labelled this "Cardholder name", "Name on card", "Full name on
|
||||
// card"; placeholder "Full name on card" or "First and last name".
|
||||
return f
|
||||
.locator(
|
||||
'[data-elements-stable-field-name="billingName"], #billingName, input[name="billingName"], input[autocomplete="cc-name"], input[placeholder="Full name on card"], input[placeholder="First and last name"]'
|
||||
)
|
||||
.or(f.getByRole('textbox', { name: /name on card|cardholder name/i }));
|
||||
}
|
||||
|
||||
function zipFieldLocator(f: Frame): Locator {
|
||||
// Accessible name is "ZIP code" (not exactly "ZIP") — don't anchor the regex.
|
||||
return f
|
||||
.locator(
|
||||
'[data-elements-stable-field-name="billingPostalCode"], #billingPostalCode, input[name="billingPostalCode"], input[autocomplete="postal-code"], input[placeholder="ZIP"]'
|
||||
)
|
||||
.or(f.getByRole('textbox', { name: /zip|postal code/i }));
|
||||
}
|
||||
|
||||
async function anyVisible(page: Page, make: (f: Frame) => Locator, timeout = 1_500): Promise<boolean> {
|
||||
return (await locateVisibleInFrames(page, make, timeout)) !== null;
|
||||
}
|
||||
|
||||
/** Builtin "fill" variant: locate with `make`, type `value`, record as lastFilled. */
|
||||
function fillVariant(name: string, make: (f: Frame) => Locator, value: string, typed: boolean) {
|
||||
return {
|
||||
name,
|
||||
run: async (ctx: StepContext) => {
|
||||
const input = await locateVisibleInFrames(ctx.page, make, 8_000);
|
||||
if (!input) throw new Error(`${name}: field not found`);
|
||||
await input.click();
|
||||
if (typed) await input.pressSequentially(value, { delay: 50 });
|
||||
else await input.fill(value);
|
||||
ctx.lastFilled = input;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const digits = (s: string) => s.replace(/\D/g, '');
|
||||
|
||||
/**
|
||||
* Fill a card field by name, searching every frame (top document + nested
|
||||
* iframes). Stripe renders card fields either as direct inputs (single-payment-
|
||||
* method layout) or inside the Payment Element iframe (multi-method layout).
|
||||
* Fill-step postcondition: the element filled during this step holds the
|
||||
* expected value AND looks like the intended field (so a fallback that typed
|
||||
* the card number into, say, a phone field can't pass).
|
||||
*/
|
||||
async function fillCardField(page: Page, fieldName: string, value: string): Promise<void> {
|
||||
const input = await locateVisibleInFrames(page, (f) => cardFieldLocator(f, fieldName), 15_000);
|
||||
if (!input) {
|
||||
throw new Error(`Could not find card field: ${fieldName} in any frame`);
|
||||
function filledVerify(expected: string, fieldHint: RegExp, compare: 'digits' | 'text') {
|
||||
return async (ctx: StepContext): Promise<boolean> => {
|
||||
const el = ctx.lastFilled;
|
||||
if (!el) return false;
|
||||
const value = await el.inputValue({ timeout: 1_000 }).catch(() => '');
|
||||
const ok = compare === 'digits' ? digits(value) === digits(expected) : value.trim() === expected.trim();
|
||||
if (!ok) return false;
|
||||
const descriptor = await el
|
||||
.evaluate((node) => {
|
||||
const i = node as HTMLInputElement;
|
||||
const labels = Array.from(i.labels || []).map((l) => l.textContent || '');
|
||||
return [i.id, i.name, i.autocomplete, i.placeholder, i.getAttribute('aria-label'), i.getAttribute('data-elements-stable-field-name'), ...labels].join(' ');
|
||||
})
|
||||
.catch(() => '');
|
||||
return fieldHint.test(descriptor);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Back on our site after paying. Must NOT match the cancel URL
|
||||
* (`gen.nomadkaraoke.com?cancelled=true`, Stripe's "Back" link).
|
||||
*/
|
||||
export function isSuccessRedirect(url: string): boolean {
|
||||
return /nomadkaraoke\.com.*(payment\/success|\/app)/.test(url) && !/cancelled=true/.test(url);
|
||||
}
|
||||
|
||||
/** Rate-limit the server-side paid check (verify polls every 500ms). */
|
||||
function throttled(check: () => Promise<boolean>, intervalMs = 5_000): () => Promise<boolean> {
|
||||
let last = 0;
|
||||
let lastResult = false;
|
||||
return async () => {
|
||||
if (lastResult || Date.now() - last < intervalMs) return lastResult;
|
||||
last = Date.now();
|
||||
lastResult = await check().catch(() => false);
|
||||
return lastResult;
|
||||
};
|
||||
}
|
||||
|
||||
function buildSteps(card: CardDetails, verifyPaid?: () => Promise<boolean>): CheckoutStep[] {
|
||||
const paidCheck = verifyPaid ? throttled(verifyPaid) : undefined;
|
||||
const cardNumberVisible = (ctx: StepContext) =>
|
||||
anyVisible(ctx.page, (f) => cardFieldLocator(f, 'cardNumber'));
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'selectCard',
|
||||
goal: 'Make the credit/debit CARD payment form visible (card number, expiry, CVC inputs). If payment methods are listed (Card, Cash App, Klarna, Bank…), select/expand "Card". Do not choose any other method and do not pay.',
|
||||
verify: cardNumberVisible,
|
||||
verifyTimeoutMs: 8_000,
|
||||
builtins: [
|
||||
{
|
||||
name: 'click Card radio/button/label',
|
||||
run: async ({ page }) => {
|
||||
// Older variants: radio or button named "Card". Oct 2026: plain
|
||||
// "Card" label over a visually-hidden "Pay with card" button.
|
||||
const choice = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) =>
|
||||
f
|
||||
.getByRole('radio', { name: /^(pay with )?card$/i })
|
||||
.or(f.getByRole('button', { name: /^(pay with )?card$/i }))
|
||||
.or(f.getByText('Card', { exact: true })),
|
||||
5_000
|
||||
);
|
||||
if (!choice) throw new Error('no Card chooser visible');
|
||||
await choice.click({ force: true });
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'dispatch click on hidden "Pay with card"',
|
||||
run: async ({ page }) => {
|
||||
let fired = false;
|
||||
for (const frame of page.frames()) {
|
||||
if (frame.isDetached()) continue;
|
||||
const btn = frame.getByRole('button', { name: /^pay with card$/i, includeHidden: true }).first();
|
||||
if (await btn.count().catch(() => 0)) {
|
||||
await btn.dispatchEvent('click');
|
||||
fired = true;
|
||||
}
|
||||
}
|
||||
if (!fired) throw new Error('no hidden "Pay with card" button');
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'fillCardNumber',
|
||||
goal: 'Type the card number into the card number input using value "{{CARD_NUMBER}}".',
|
||||
placeholders: ['CARD_NUMBER'],
|
||||
verify: filledVerify(card.number, /card.?number|cc-number|1234 1234/i, 'digits'),
|
||||
builtins: [fillVariant('card number field', (f) => cardFieldLocator(f, 'cardNumber'), card.number, true)],
|
||||
},
|
||||
{
|
||||
id: 'fillCardExpiry',
|
||||
goal: 'Type the card expiry date into the expiration (MM / YY) input using value "{{CARD_EXPIRY}}".',
|
||||
placeholders: ['CARD_EXPIRY'],
|
||||
verify: filledVerify(card.expiry, /expir|cc-exp|mm ?\/ ?yy/i, 'digits'),
|
||||
builtins: [fillVariant('card expiry field', (f) => cardFieldLocator(f, 'cardExpiry'), card.expiry, true)],
|
||||
},
|
||||
{
|
||||
id: 'fillCardCvc',
|
||||
goal: 'Type the card security code into the CVC input using value "{{CARD_CVC}}".',
|
||||
placeholders: ['CARD_CVC'],
|
||||
verify: filledVerify(card.cvc, /cvc|cvv|security|cc-csc/i, 'digits'),
|
||||
builtins: [fillVariant('card CVC field', (f) => cardFieldLocator(f, 'cardCvc'), card.cvc, true)],
|
||||
},
|
||||
{
|
||||
id: 'fillCardholderName',
|
||||
goal: 'Type the cardholder name into the "Name on card"/cardholder-name input using value "{{CARDHOLDER_NAME}}".',
|
||||
placeholders: ['CARDHOLDER_NAME'],
|
||||
optional: true,
|
||||
verify: filledVerify(card.name, /name/i, 'text'),
|
||||
builtins: [fillVariant('cardholder name field', nameFieldLocator, card.name, false)],
|
||||
},
|
||||
{
|
||||
id: 'fillPostalCode',
|
||||
goal: 'Type the billing ZIP/postal code using value "{{POSTAL_CODE}}".',
|
||||
placeholders: ['POSTAL_CODE'],
|
||||
optional: true,
|
||||
verify: filledVerify(card.zip, /zip|postal/i, 'text'),
|
||||
builtins: [fillVariant('ZIP field', zipFieldLocator, card.zip, false)],
|
||||
},
|
||||
{
|
||||
id: 'uncheckSaveInfo',
|
||||
goal: 'Make sure "Save my information for faster checkout" (Stripe Link) is NOT checked.',
|
||||
optional: true,
|
||||
// Avoids Link's phone-number requirement.
|
||||
verify: async ({ page }) => {
|
||||
const cb = await locateVisibleInFrames(page, (f) => f.getByRole('checkbox', { name: /save my information/i }), 1_000);
|
||||
return !cb || !(await cb.isChecked().catch(() => false));
|
||||
},
|
||||
builtins: [
|
||||
{
|
||||
name: 'uncheck "Save my information"',
|
||||
run: async ({ page }) => {
|
||||
const cb = await locateVisibleInFrames(page, (f) => f.getByRole('checkbox', { name: /save my information/i }), 2_000);
|
||||
if (cb) await cb.uncheck({ force: true });
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'submitPayment',
|
||||
goal: 'Submit the card payment. If the form shows validation errors or empty REQUIRED fields (e.g. name, ZIP/postal code, country), fix them first using the placeholders, then click the main Pay/submit button (NOT Link/Klarna/other express buttons).',
|
||||
allowSubmit: true,
|
||||
placeholders: ['CARD_NUMBER', 'CARD_EXPIRY', 'CARD_CVC', 'CARDHOLDER_NAME', 'POSTAL_CODE'],
|
||||
// Long: the Stripe→site redirect and webhook grant can each take a while,
|
||||
// and a premature LLM fallback risks a second submit.
|
||||
verifyTimeoutMs: 90_000,
|
||||
verify: async ({ page }) => {
|
||||
if (isSuccessRedirect(page.url())) return true;
|
||||
return paidCheck ? paidCheck() : false;
|
||||
},
|
||||
builtins: [
|
||||
{
|
||||
name: 'click Pay',
|
||||
run: async ({ page }) => {
|
||||
const pay = await locateVisibleInFrames(page, (f) => f.getByRole('button', { name: /^Pay$/i }), 10_000);
|
||||
if (!pay) throw new Error('Pay button not visible');
|
||||
await pay.click();
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async function dumpFrames(page: Page, file: string): Promise<void> {
|
||||
// page.content() only covers the main frame; the Payment Element usually
|
||||
// lives in a nested iframe, so dump every frame.
|
||||
const dumps: string[] = [];
|
||||
for (const frame of page.frames()) {
|
||||
if (frame.isDetached()) continue;
|
||||
const html = await frame.content().catch(() => '');
|
||||
dumps.push(`<!-- ===== frame: ${frame.url()} ===== -->\n${html}`);
|
||||
}
|
||||
fs.mkdirSync('test-results', { recursive: true });
|
||||
fs.writeFileSync(file, dumps.join('\n\n'));
|
||||
}
|
||||
|
||||
export const SELF_HEAL_ARTIFACT_DIR = 'test-results/self-heal';
|
||||
|
||||
export interface StripeCheckoutOptions {
|
||||
/**
|
||||
* Server-side "did the purchase land?" check (e.g. credit balance increased).
|
||||
* Used by the submit step's postcondition when the browser redirect is slow,
|
||||
* so the LLM fallback never re-submits a payment that already succeeded.
|
||||
*/
|
||||
verifyPaid?: () => Promise<boolean>;
|
||||
/** Override the LLM planner (tests inject a stub; `null` disables the fallback). Default: Gemini from env. */
|
||||
planner?: Planner | null;
|
||||
/** Override learned variants (tests). Default: self-healing/learned-variants.json. */
|
||||
learned?: LearnedVariantsFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete the Stripe Checkout page with card details from environment.
|
||||
*
|
||||
* @returns `redirected` — whether the browser was observed navigating back to
|
||||
* our site. The redirect can be slow or dropped even when the charge succeeds,
|
||||
* so callers should treat the *server-side* credit grant as the source of
|
||||
* truth. `selfHeal` — call `selfHeal.writeArtifacts(SELF_HEAL_ARTIFACT_DIR,
|
||||
* { flowVerified: true })` once the purchase is confirmed server-side so
|
||||
* any LLM-healed steps get promoted to learned variants.
|
||||
*/
|
||||
export async function completeStripeCheckout(
|
||||
page: Page,
|
||||
opts: StripeCheckoutOptions = {}
|
||||
): Promise<{ redirected: boolean; selfHeal: SelfHealingRunner }> {
|
||||
const card = getCardDetailsFromEnv();
|
||||
const secrets: Secrets = {
|
||||
CARD_NUMBER: card.number,
|
||||
CARD_EXPIRY: card.expiry,
|
||||
CARD_CVC: card.cvc,
|
||||
CARDHOLDER_NAME: card.name,
|
||||
POSTAL_CODE: card.zip,
|
||||
};
|
||||
const planner = opts.planner !== undefined ? opts.planner : GeminiPlanner.fromEnv();
|
||||
if (!planner) console.log(' (no LLM planner — GEMINI_API_KEY unset; self-healing fallback disabled)');
|
||||
const runner = new SelfHealingRunner(page, secrets, planner, opts.learned);
|
||||
|
||||
console.log(' Waiting for Stripe Checkout page...');
|
||||
await page.waitForURL(/checkout\.stripe\.com/, { timeout: 30_000 });
|
||||
// Readiness: any of the Pay button, the card form or a Card chooser. Don't
|
||||
// insist on one — that's exactly what Stripe keeps changing.
|
||||
const ready = await locateVisibleInFrames(
|
||||
page,
|
||||
(f) =>
|
||||
f
|
||||
.getByRole('button', { name: /^Pay\b/i })
|
||||
.or(cardFieldLocator(f, 'cardNumber'))
|
||||
.or(f.getByText('Card', { exact: true })),
|
||||
30_000
|
||||
);
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
|
||||
console.log(ready ? ' Stripe Checkout loaded' : ' ⚠️ Stripe Checkout readiness signal not seen — continuing with self-healing steps');
|
||||
|
||||
try {
|
||||
for (const step of buildSteps(card, opts.verifyPaid)) {
|
||||
const outcome = await runner.run(step);
|
||||
if (step.id === 'selectCard') await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
|
||||
if (step.id === 'uncheckSaveInfo') await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
|
||||
if (outcome.status === 'failed') {
|
||||
await page.screenshot({ path: `test-results/stripe-step-failed-${step.id}.png` }).catch(() => {});
|
||||
await dumpFrames(page, 'test-results/stripe-checkout-dom.html');
|
||||
throw new Error(`Stripe Checkout step "${step.id}" failed: ${outcome.reason}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
runner.writeArtifacts(SELF_HEAL_ARTIFACT_DIR, { flowVerified: false });
|
||||
throw e;
|
||||
}
|
||||
|
||||
const redirected = isSuccessRedirect(page.url());
|
||||
await page.screenshot({ path: `test-results/stripe-checkout-${redirected ? 'complete' : 'no-redirect'}.png` }).catch(() => {});
|
||||
if (redirected) {
|
||||
console.log(' Stripe Checkout complete — redirected to our site');
|
||||
} else {
|
||||
console.warn(' ⚠️ Payment confirmed server-side but no browser redirect observed (slow/dropped redirect)');
|
||||
}
|
||||
await input.click();
|
||||
await input.type(value, { delay: 50 });
|
||||
return { redirected, selfHeal: runner };
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import type { APIRequestContext } from '@playwright/test';
|
||||
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
|
||||
import { completeStripeCheckout } from '../helpers/stripe-checkout';
|
||||
import { completeStripeCheckout, SELF_HEAL_ARTIFACT_DIR } from '../helpers/stripe-checkout';
|
||||
import { getPageAuthToken, clickCompleteSignInGate } from '../helpers/auth';
|
||||
import { URLS, TIMEOUTS } from '../helpers/constants';
|
||||
import * as fs from 'fs';
|
||||
@@ -229,7 +229,14 @@ test.describe('Real Credit Purchase Flow', () => {
|
||||
|
||||
// Complete Stripe Checkout with real card. The redirect back to our site
|
||||
// is best-effort — the authoritative signal is the server-side credit grant.
|
||||
const checkout = await completeStripeCheckout(page);
|
||||
// verifyPaid lets the submit step confirm success server-side when the
|
||||
// redirect is slow, so the self-healing fallback never re-submits.
|
||||
const checkout = await completeStripeCheckout(page, {
|
||||
verifyPaid: async () => {
|
||||
const latest = await getCreditsViaAdmin(request, API_URL, adminToken!, inbox.emailAddress);
|
||||
return latest !== null && latest > baselineCredits;
|
||||
},
|
||||
});
|
||||
|
||||
// ===== STEP 6: Verify the purchase landed (server-side source of truth) =====
|
||||
console.log('\n=== STEP 6: Verify credit grant (server-side) ===');
|
||||
@@ -247,6 +254,17 @@ test.describe('Real Credit Purchase Flow', () => {
|
||||
).not.toBeNull();
|
||||
console.log(` ✅ Server-side credit grant confirmed: ${baselineCredits} → ${newBalance}`);
|
||||
|
||||
// The purchase is proven end-to-end, so any step the LLM fallback healed
|
||||
// is trustworthy: emit the merged learned-variants.json for the workflow
|
||||
// to commit via an auto-merging PR.
|
||||
const runUrl = process.env.GITHUB_RUN_ID
|
||||
? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
|
||||
: undefined;
|
||||
const { learnedWritten } = checkout.selfHeal.writeArtifacts(SELF_HEAL_ARTIFACT_DIR, { flowVerified: true, runUrl });
|
||||
if (learnedWritten) {
|
||||
console.log(' 🩹 Self-healing: LLM-healed step(s) recorded — the workflow will open an auto-merge PR');
|
||||
}
|
||||
|
||||
// Best-effort UX check: if the browser redirected to the success page,
|
||||
// confirm it renders the expected confirmation. A missing redirect is only
|
||||
// a UX nicety here (the charge + grant are already proven above), so don't
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// frontend/e2e/self-healing/checkout-flow.spec.ts
|
||||
import { test, expect } from '@playwright/test';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { completeStripeCheckout } from '../helpers/stripe-checkout';
|
||||
import { emptyFile } from '../helpers/self-healing/learned-store';
|
||||
import type { LearnedVariantsFile } from '../helpers/self-healing/types';
|
||||
import {
|
||||
CHECKOUT_URL,
|
||||
ELEMENTS_FUTURE,
|
||||
ELEMENTS_OCT2026,
|
||||
ScriptedPlanner,
|
||||
TEST_CARD,
|
||||
elementsFrameIndex,
|
||||
serveCheckout,
|
||||
setCardEnv,
|
||||
} from './fixtures';
|
||||
|
||||
test.beforeAll(() => {
|
||||
setCardEnv();
|
||||
fs.mkdirSync('test-results', { recursive: true });
|
||||
});
|
||||
|
||||
function tmpDir(): string {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), 'selfheal-'));
|
||||
}
|
||||
|
||||
test('known layout (Oct 2026 hidden "Pay with card") completes via builtins — no LLM call', async ({ page }) => {
|
||||
await serveCheckout(page, ELEMENTS_OCT2026);
|
||||
await page.goto(CHECKOUT_URL);
|
||||
const planner = new ScriptedPlanner([]);
|
||||
|
||||
const result = await completeStripeCheckout(page, { planner, learned: emptyFile() });
|
||||
|
||||
expect(result.redirected).toBe(true);
|
||||
expect(planner.inputs).toHaveLength(0);
|
||||
const statuses = Object.fromEntries(result.selfHeal.outcomes.map((o) => [o.stepId, o.status]));
|
||||
expect(statuses).toMatchObject({
|
||||
selectCard: 'ok',
|
||||
fillCardNumber: 'ok',
|
||||
fillCardExpiry: 'ok',
|
||||
fillCardCvc: 'ok',
|
||||
fillCardholderName: 'ok',
|
||||
fillPostalCode: 'ok',
|
||||
submitPayment: 'ok',
|
||||
});
|
||||
const dir = tmpDir();
|
||||
expect(result.selfHeal.writeArtifacts(dir, { flowVerified: true }).learnedWritten).toBe(false);
|
||||
});
|
||||
|
||||
test('unknown layout: LLM heals selectCard, recipe is learned, and the next run replays it without the LLM', async ({ page }) => {
|
||||
await serveCheckout(page, ELEMENTS_FUTURE);
|
||||
await page.goto(CHECKOUT_URL);
|
||||
const planner = new ScriptedPlanner([
|
||||
(input) => ({
|
||||
thought: 'Card form is behind the "Credit or debit" tab',
|
||||
status: 'act',
|
||||
action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'role', role: 'tab', name: 'Credit or debit' } },
|
||||
}),
|
||||
]);
|
||||
|
||||
const result = await completeStripeCheckout(page, { planner, learned: emptyFile() });
|
||||
expect(result.redirected).toBe(true);
|
||||
expect(planner.inputs).toHaveLength(1);
|
||||
expect(planner.inputs[0].stepId).toBe('selectCard');
|
||||
|
||||
const healed = result.selfHeal.healed;
|
||||
expect(healed).toHaveLength(1);
|
||||
expect(healed[0].actions[0]).toEqual({
|
||||
type: 'click',
|
||||
target: { frameUrlIncludes: 'js.stripe.com/v3/elements-inner-payment.html', by: 'role', role: 'tab', name: 'Credit or debit' },
|
||||
});
|
||||
|
||||
// Promotion only happens once the flow is verified.
|
||||
const unverifiedDir = tmpDir();
|
||||
expect(result.selfHeal.writeArtifacts(unverifiedDir, { flowVerified: false }).learnedWritten).toBe(false);
|
||||
expect(fs.existsSync(path.join(unverifiedDir, 'learned-variants.json'))).toBe(false);
|
||||
|
||||
const dir = tmpDir();
|
||||
expect(result.selfHeal.writeArtifacts(dir, { flowVerified: true, runUrl: 'https://example/run/1' }).learnedWritten).toBe(true);
|
||||
const learned = JSON.parse(fs.readFileSync(path.join(dir, 'learned-variants.json'), 'utf8')) as LearnedVariantsFile;
|
||||
expect(learned.steps.selectCard).toHaveLength(1);
|
||||
expect(learned.steps.selectCard[0].runUrl).toBe('https://example/run/1');
|
||||
const report = JSON.parse(fs.readFileSync(path.join(dir, 'self-heal-report.json'), 'utf8'));
|
||||
expect(report.llmCalls).toBe(1);
|
||||
|
||||
// Second run: same unknown layout, learned recipe replayed, LLM not consulted.
|
||||
const page2 = await page.context().newPage();
|
||||
await serveCheckout(page2, ELEMENTS_FUTURE);
|
||||
await page2.goto(CHECKOUT_URL);
|
||||
const planner2 = new ScriptedPlanner([]);
|
||||
const rerun = await completeStripeCheckout(page2, { planner: planner2, learned });
|
||||
expect(rerun.redirected).toBe(true);
|
||||
expect(planner2.inputs).toHaveLength(0);
|
||||
expect(rerun.selfHeal.outcomes.find((o) => o.stepId === 'selectCard')).toMatchObject({ status: 'ok', via: 'learned' });
|
||||
});
|
||||
|
||||
test('no secrets reach the LLM — prompts use placeholders and observations are redacted', async ({ page }) => {
|
||||
await serveCheckout(page, ELEMENTS_FUTURE);
|
||||
await page.goto(CHECKOUT_URL);
|
||||
// Force the LLM for a fill step that runs AFTER the card number was typed,
|
||||
// so the card number is present on the page while observing.
|
||||
const planner = new ScriptedPlanner([
|
||||
(input) => ({
|
||||
thought: 'open card tab',
|
||||
status: 'act',
|
||||
action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'role', role: 'tab', name: 'Credit or debit' } },
|
||||
}),
|
||||
(input) => ({
|
||||
thought: 'fill expiry',
|
||||
status: 'act',
|
||||
action: { type: 'fill', target: { frameIndex: elementsFrameIndex(input), by: 'label', text: 'Expiration' }, value: '{{CARD_EXPIRY}}' },
|
||||
}),
|
||||
]);
|
||||
process.env.E2E_SELF_HEAL_FORCE_LLM = 'fillCardExpiry';
|
||||
try {
|
||||
const result = await completeStripeCheckout(page, { planner, learned: emptyFile() });
|
||||
expect(result.redirected).toBe(true);
|
||||
} finally {
|
||||
delete process.env.E2E_SELF_HEAL_FORCE_LLM;
|
||||
}
|
||||
expect(planner.inputs.map((i) => i.stepId)).toEqual(['selectCard', 'fillCardExpiry']);
|
||||
const expiryInput = planner.inputs[1];
|
||||
const everything = JSON.stringify(expiryInput);
|
||||
expect(everything).not.toContain(TEST_CARD.E2E_STRIPE_CARD_NUMBER);
|
||||
expect(everything).not.toContain('4242 4242');
|
||||
expect(everything).not.toContain(TEST_CARD.E2E_STRIPE_CARDHOLDER_NAME);
|
||||
expect(expiryInput.placeholders).toEqual(['CARD_EXPIRY']);
|
||||
});
|
||||
|
||||
test('guardrails: LLM may not click Pay outside the submit step or pick express methods; step fails cleanly', async ({ page }) => {
|
||||
await serveCheckout(page, ELEMENTS_FUTURE);
|
||||
await page.goto(CHECKOUT_URL);
|
||||
const planner = new ScriptedPlanner([
|
||||
(input) => ({ thought: 'just pay', status: 'act', action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'role', role: 'button', name: 'Pay', exact: true } } }),
|
||||
(input) => ({ thought: 'use bank', status: 'act', action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'role', role: 'tab', name: 'Bank' } } }),
|
||||
// css target with no label — must be caught by the resolved-element guard
|
||||
(input) => ({ thought: 'pay via css', status: 'act', action: { type: 'click', target: { frameIndex: elementsFrameIndex(input), by: 'css', css: '#pay' } } }),
|
||||
{ thought: 'cannot', status: 'give_up' },
|
||||
{ thought: 'cannot', status: 'give_up' },
|
||||
{ thought: 'cannot', status: 'give_up' },
|
||||
]);
|
||||
|
||||
await expect(completeStripeCheckout(page, { planner, learned: emptyFile() })).rejects.toThrow(/step "selectCard" failed/);
|
||||
expect(page.url()).toContain('checkout.stripe.com'); // never submitted
|
||||
const history = planner.inputs.at(-1)!.history.join('\n');
|
||||
expect(history).toContain('not allowed in this step');
|
||||
expect(history).toContain('alternative/express payment method');
|
||||
expect(history).toContain('the target element is the final Pay/submit button');
|
||||
});
|
||||
|
||||
test('without a planner, an unknown layout fails with a clear reason (deterministic-only mode)', async ({ page }) => {
|
||||
await serveCheckout(page, ELEMENTS_FUTURE);
|
||||
await page.goto(CHECKOUT_URL);
|
||||
await expect(completeStripeCheckout(page, { planner: null, learned: emptyFile() })).rejects.toThrow(/no LLM planner/);
|
||||
expect(fs.existsSync('test-results/stripe-checkout-dom.html')).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// frontend/e2e/self-healing/fixtures.ts
|
||||
import type { Page } from '@playwright/test';
|
||||
import type { LlmDecision, Planner, PlannerInput } from '../helpers/self-healing/llm-agent';
|
||||
|
||||
export const CHECKOUT_URL = 'https://checkout.stripe.com/c/pay/cs_test_fixture#frag';
|
||||
export const ELEMENTS_URL = 'https://js.stripe.com/v3/elements-inner-payment.html?id=abc';
|
||||
export const SUCCESS_URL = 'https://gen.nomadkaraoke.com/payment/success?session_id=cs_test_fixture';
|
||||
|
||||
export const TEST_CARD = {
|
||||
E2E_STRIPE_CARD_NUMBER: '4242424242424242',
|
||||
E2E_STRIPE_CARD_EXPIRY: '12/34',
|
||||
E2E_STRIPE_CARD_CVC: '123',
|
||||
E2E_STRIPE_CARDHOLDER_NAME: 'Fixture Tester',
|
||||
E2E_STRIPE_ZIP: '10001',
|
||||
};
|
||||
|
||||
export function setCardEnv(): void {
|
||||
Object.assign(process.env, TEST_CARD);
|
||||
}
|
||||
|
||||
const cardFields = `
|
||||
<div id="card-form" style="display:none">
|
||||
<label>Card number <input id="cardNumber" autocomplete="cc-number" placeholder="1234 1234 1234 1234"></label>
|
||||
<label>Expiration <input id="cardExpiry" autocomplete="cc-exp" placeholder="MM / YY"></label>
|
||||
<label>CVC <input id="cardCvc" autocomplete="cc-csc"></label>
|
||||
<label>Name on card <input id="billingName" autocomplete="cc-name"></label>
|
||||
<label>ZIP code <input id="billingPostalCode" autocomplete="postal-code"></label>
|
||||
</div>`;
|
||||
|
||||
/**
|
||||
* Layout "oct2026": plain "Card" label with a visually-hidden "Pay with card"
|
||||
* button — the layout that broke run #192. Builtins handle it.
|
||||
*/
|
||||
export const ELEMENTS_OCT2026 = `<!doctype html><html><body>
|
||||
<div class="accordion">
|
||||
<div class="item" style="position:relative">
|
||||
<span>Card</span>
|
||||
<button aria-label="Pay with card" style="position:absolute;inset:0;opacity:0" onclick="document.getElementById('card-form').style.display='block'"></button>
|
||||
</div>
|
||||
<div class="item"><span>Klarna</span></div>
|
||||
</div>
|
||||
${cardFields}
|
||||
<button id="pay" onclick="window.top.postMessage('pay','*')">Pay</button>
|
||||
</body></html>`;
|
||||
|
||||
/**
|
||||
* Layout "future": a chooser NO builtin knows — a tab named "Credit or debit".
|
||||
* Only the LLM fallback (stubbed here) can get past it.
|
||||
*/
|
||||
export const ELEMENTS_FUTURE = `<!doctype html><html><body>
|
||||
<div role="tablist">
|
||||
<div role="tab" tabindex="0" aria-selected="false" onclick="document.getElementById('card-form').style.display='block';this.setAttribute('aria-selected','true')">Credit or debit</div>
|
||||
<div role="tab" tabindex="0" aria-selected="false">Bank</div>
|
||||
</div>
|
||||
${cardFields}
|
||||
<button id="pay" onclick="window.top.postMessage('pay','*')">Pay</button>
|
||||
</body></html>`;
|
||||
|
||||
const TOP_PAGE = `<!doctype html><html><body>
|
||||
<a href="https://gen.nomadkaraoke.com?cancelled=true">Back to Nomad Karaoke</a>
|
||||
<h2>Pay Nomad Karaoke</h2>
|
||||
<iframe src="${ELEMENTS_URL}" style="width:600px;height:500px"></iframe>
|
||||
<script>
|
||||
window.addEventListener('message', (e) => {
|
||||
if (e.data === 'pay') window.location.href = '${SUCCESS_URL}';
|
||||
});
|
||||
</script>
|
||||
</body></html>`;
|
||||
|
||||
/** Serve a fake Stripe Checkout (top page + Payment Element iframe) and our success page. */
|
||||
export async function serveCheckout(page: Page, elementsHtml: string): Promise<void> {
|
||||
await page.route('https://checkout.stripe.com/**', (r) => r.fulfill({ contentType: 'text/html', body: TOP_PAGE }));
|
||||
await page.route('https://js.stripe.com/**', (r) => r.fulfill({ contentType: 'text/html', body: elementsHtml }));
|
||||
await page.route('https://gen.nomadkaraoke.com/**', (r) =>
|
||||
r.fulfill({ contentType: 'text/html', body: '<h1>Payment successful</h1>' })
|
||||
);
|
||||
}
|
||||
|
||||
/** Planner stub: returns scripted decisions in order and records every prompt input. */
|
||||
export class ScriptedPlanner implements Planner {
|
||||
readonly inputs: PlannerInput[] = [];
|
||||
constructor(private readonly script: Array<LlmDecision | ((input: PlannerInput) => LlmDecision)>) {}
|
||||
async decide(input: PlannerInput) {
|
||||
this.inputs.push(input);
|
||||
const next = this.script.shift();
|
||||
const decision = typeof next === 'function' ? next(input) : next ?? { thought: 'out of script', status: 'give_up' as const };
|
||||
return { decision, model: 'stub-model' };
|
||||
}
|
||||
}
|
||||
|
||||
export function elementsFrameIndex(input: PlannerInput): number {
|
||||
const idx = input.observation.frameKeys.findIndex((k) => k.includes('js.stripe.com'));
|
||||
if (idx < 0) throw new Error('elements frame not in observation');
|
||||
return idx;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// frontend/e2e/self-healing/units.spec.ts — pure-function tests (no browser page needed)
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { frameUrlKey, substitutePlaceholders } from '../helpers/self-healing/actions';
|
||||
import { buildPrompt, checkGuards, checkResolvedClick, toTargetSpec } from '../helpers/self-healing/llm-agent';
|
||||
import { MAX_LEARNED_PER_STEP, emptyFile, mergeLearned, variantId } from '../helpers/self-healing/learned-store';
|
||||
import { redact } from '../helpers/self-healing/observe';
|
||||
import { isSuccessRedirect } from '../helpers/stripe-checkout';
|
||||
import type { Action } from '../helpers/self-healing/types';
|
||||
|
||||
const secrets = { CARD_NUMBER: '4242424242424242', CARD_EXPIRY: '12/34', CARD_CVC: '123', CARDHOLDER_NAME: 'Fixture Tester', POSTAL_CODE: '10001' };
|
||||
|
||||
test.describe('redact', () => {
|
||||
test('blanks textbox values and PAN-shaped digit runs, keeps structure', () => {
|
||||
const snap = [
|
||||
'- textbox "Card number": 4242 4242 4242 4242',
|
||||
'- textbox "Expiration" [active]: 12 / 34',
|
||||
'- textbox "CVC": 123',
|
||||
'- textbox "Name on card"',
|
||||
'- text: Total due $0.50',
|
||||
'- paragraph: ref 4242-4242-4242-4242',
|
||||
'- generic: Fixture Tester',
|
||||
].join('\n');
|
||||
const out = redact(snap, secrets);
|
||||
expect(out).not.toMatch(/4242/);
|
||||
expect(out).not.toContain('12 / 34');
|
||||
expect(out).not.toContain(': 123');
|
||||
expect(out).not.toContain('Fixture Tester');
|
||||
expect(out).toContain('- textbox "Card number": [value redacted]');
|
||||
expect(out).toContain('- textbox "Name on card"');
|
||||
expect(out).toContain('$0.50');
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('checkGuards', () => {
|
||||
const step = { allowSubmit: false, placeholders: ['CARD_NUMBER'] };
|
||||
const click = (name: string) => ({ type: 'click' as const, target: { by: 'role' as const, role: 'button', name } });
|
||||
|
||||
test('blocks final Pay outside submit step but allows "Pay with card"', () => {
|
||||
expect(checkGuards(click('Pay'), step)).toMatch(/not allowed/);
|
||||
expect(checkGuards(click('Pay $0.50'), step)).toMatch(/not allowed/);
|
||||
expect(checkGuards(click('Pay with card'), step)).toBeNull();
|
||||
expect(checkGuards(click('Pay'), { ...step, allowSubmit: true })).toBeNull();
|
||||
});
|
||||
test('blocks express methods and the cancel/back link', () => {
|
||||
for (const n of ['Pay securely with Link', 'Pay with Klarna', 'Cash App Pay', 'Bank', 'Back to Nomad Karaoke']) {
|
||||
expect(checkGuards(click(n), { ...step, allowSubmit: true }), n).not.toBeNull();
|
||||
}
|
||||
});
|
||||
test('only allowed placeholders; no literal card-like digits', () => {
|
||||
const fill = (value: string) => ({ type: 'fill' as const, target: { by: 'label' as const, text: 'Card number' }, value });
|
||||
expect(checkGuards(fill('{{CARD_NUMBER}}'), step)).toBeNull();
|
||||
expect(checkGuards(fill('{{CARD_CVC}}'), step)).toMatch(/not available/);
|
||||
expect(checkGuards(fill('4242424242424242'), step)).toMatch(/literal digits/);
|
||||
expect(checkGuards(fill('United States'), step)).toBeNull();
|
||||
});
|
||||
test('rejects malformed targets', () => {
|
||||
expect(checkGuards({ type: 'click', target: { by: 'css' } }, step)).toMatch(/css/);
|
||||
expect(checkGuards({ type: 'click', target: { by: 'role' } }, step)).toMatch(/role/);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('checkResolvedClick (guards the real element, not the model label)', () => {
|
||||
const fillStep = { allowSubmit: false };
|
||||
test('refuses css/unnamed targets that resolve to the submit button outside submitPayment', () => {
|
||||
expect(checkResolvedClick({ testid: 'hosted-payment-submit-button', text: 'Pay' }, fillStep)).toMatch(/not allowed/);
|
||||
expect(checkResolvedClick({ type: 'submit', text: 'Continue' }, fillStep)).toMatch(/not allowed/);
|
||||
expect(checkResolvedClick({ text: 'Pay $0.50' }, fillStep)).toMatch(/not allowed/);
|
||||
expect(checkResolvedClick({ testid: 'hosted-payment-submit-button', text: 'Pay' }, { allowSubmit: true })).toBeNull();
|
||||
});
|
||||
test('refuses express methods / cancel even in the submit step', () => {
|
||||
expect(checkResolvedClick({ text: 'Pay securely with Link' }, { allowSubmit: true })).not.toBeNull();
|
||||
expect(checkResolvedClick({ testid: 'klarna-accordion-item' }, { allowSubmit: true })).not.toBeNull();
|
||||
expect(checkResolvedClick({ text: 'Back to Nomad Karaoke' }, { allowSubmit: true })).not.toBeNull();
|
||||
});
|
||||
test('allows the card chooser', () => {
|
||||
expect(checkResolvedClick({ testid: 'card-accordion-item', text: 'Card' }, fillStep)).toBeNull();
|
||||
expect(checkResolvedClick({ ariaLabel: 'Pay with card', type: 'button' }, fillStep)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test('toTargetSpec maps frameIndex to a stable frame key and drops empties', () => {
|
||||
const spec = toTargetSpec({ frameIndex: 1, by: 'role', role: 'tab', name: 'Card', css: '' }, ['checkout.stripe.com/c/pay/x', 'js.stripe.com/v3/inner.html']);
|
||||
expect(spec).toEqual({ frameUrlIncludes: 'js.stripe.com/v3/inner.html', by: 'role', role: 'tab', name: 'Card' });
|
||||
});
|
||||
|
||||
test('frameUrlKey strips query, hash and session-id path segments', () => {
|
||||
expect(frameUrlKey('https://js.stripe.com/v3/elements-inner.html?id=abc#x')).toBe('js.stripe.com/v3/elements-inner.html');
|
||||
// Real Stripe Checkout URL shape (run 37137960148): session id lives in the path.
|
||||
expect(frameUrlKey('https://checkout.stripe.com/c/pay/cs_live_a1j0424mRKhVaGMhJ1P7KXkqvcueGqJ2ZWaoGi84JO7ueILw9w6Yd0tEl5#fid=x')).toBe('checkout.stripe.com/c/pay');
|
||||
expect(frameUrlKey('https://checkout.stripe.com/c/pay/cs_test_abc')).toBe('checkout.stripe.com/c/pay');
|
||||
expect(frameUrlKey('https://js.stripe.com/v3/elements-inner-accordion-8f2a.html')).toBe('js.stripe.com/v3/elements-inner-accordion-8f2a.html');
|
||||
});
|
||||
|
||||
test('substitutePlaceholders substitutes known and throws on unknown', () => {
|
||||
expect(substitutePlaceholders('{{CARD_CVC}}', secrets)).toBe('123');
|
||||
expect(() => substitutePlaceholders('{{NOPE}}', secrets)).toThrow(/Unknown placeholder/);
|
||||
});
|
||||
|
||||
test('buildPrompt contains goal/history but never raw secrets', () => {
|
||||
const prompt = buildPrompt({
|
||||
stepId: 'fillCardNumber',
|
||||
goal: 'Type "{{CARD_NUMBER}}"',
|
||||
allowSubmit: false,
|
||||
placeholders: ['CARD_NUMBER'],
|
||||
history: ['FAILED: x'],
|
||||
observation: { url: 'checkout.stripe.com/c/pay', text: '- textbox "Card number": [value redacted]', frameKeys: [] },
|
||||
escalation: 0,
|
||||
});
|
||||
expect(prompt).toContain('{{CARD_NUMBER}}');
|
||||
expect(prompt).toContain('FAILED: x');
|
||||
expect(prompt).toContain('Final Pay/submit button allowed in this step: NO');
|
||||
});
|
||||
|
||||
test.describe('mergeLearned', () => {
|
||||
const a1: Action[] = [{ type: 'click', target: { by: 'role', role: 'tab', name: 'Card' } }];
|
||||
const a2: Action[] = [{ type: 'click', target: { by: 'text', text: 'Card', exact: true } }];
|
||||
|
||||
test('adds newest-first, dedupes identical recipes, is pure', () => {
|
||||
const base = emptyFile();
|
||||
const r1 = mergeLearned(base, [{ stepId: 'selectCard', actions: a1, model: 'm' }], { now: 't1' });
|
||||
expect(r1.changed).toBe(true);
|
||||
expect(base.steps).toEqual({});
|
||||
const r2 = mergeLearned(r1.file, [{ stepId: 'selectCard', actions: a1 }], { now: 't2' });
|
||||
expect(r2.changed).toBe(false);
|
||||
const r3 = mergeLearned(r2.file, [{ stepId: 'selectCard', actions: a2 }], { now: 't3' });
|
||||
expect(r3.file.steps.selectCard.map((v) => v.id)).toEqual([variantId(a2), variantId(a1)]);
|
||||
});
|
||||
|
||||
test(`caps each step at ${MAX_LEARNED_PER_STEP}`, () => {
|
||||
let file = emptyFile();
|
||||
for (let i = 0; i < MAX_LEARNED_PER_STEP + 3; i++) {
|
||||
file = mergeLearned(file, [{ stepId: 's', actions: [{ type: 'click', target: { by: 'text', text: `v${i}` } }] }]).file;
|
||||
}
|
||||
expect(file.steps.s).toHaveLength(MAX_LEARNED_PER_STEP);
|
||||
expect(file.steps.s[0].actions[0].target.text).toBe(`v${MAX_LEARNED_PER_STEP + 2}`);
|
||||
});
|
||||
|
||||
test('skips empty recipes', () => {
|
||||
expect(mergeLearned(emptyFile(), [{ stepId: 's', actions: [] }]).changed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test('isSuccessRedirect accepts success/app URLs but not the cancel link', () => {
|
||||
expect(isSuccessRedirect('https://gen.nomadkaraoke.com/payment/success?session_id=x')).toBe(true);
|
||||
expect(isSuccessRedirect('https://gen.nomadkaraoke.com/en/app')).toBe(true);
|
||||
expect(isSuccessRedirect('https://gen.nomadkaraoke.com?cancelled=true')).toBe(false);
|
||||
expect(isSuccessRedirect('https://checkout.stripe.com/c/pay/x')).toBe(false);
|
||||
});
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
checkFilenameMismatch,
|
||||
getAvailabilityLabel,
|
||||
getSearchConfidence,
|
||||
isConfirmedTitleMatch,
|
||||
isArtistMatch,
|
||||
ExtendedAudioSearchResult,
|
||||
} from '../audio-search-utils'
|
||||
|
||||
@@ -506,3 +508,138 @@ describe('getSearchConfidence', () => {
|
||||
expect(confidence.bestResult?.index).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
// Real search from a live kjbox night (2026-10-01): "Braxton Keith - The Chair"
|
||||
// returned only Spotify results. `title` is the album, `target_file` the track.
|
||||
// The UI used to call this "Limited sources found" and push the singer to YouTube.
|
||||
const spotify = (index: number, album: string, track: string, popularity: number, release_type = 'Album') =>
|
||||
makeResult({
|
||||
index, provider: 'Spotify', title: album, target_file: track, artist: 'Braxton Keith',
|
||||
quality: 'FLAC 16bit WEB', release_type, view_count: popularity * 10000,
|
||||
})
|
||||
const braxtonKeithResults = () => [
|
||||
spotify(0, 'Real Damn Deal', 'I Own This Bar', 40),
|
||||
spotify(1, 'Cozy', 'Cozy', 45),
|
||||
spotify(2, 'The Chair', 'The Chair', 65, 'Single'),
|
||||
spotify(3, 'I Own This Bar', 'I Own This Bar', 40),
|
||||
spotify(4, 'The Chair', 'Prescription', 20, 'Single'),
|
||||
spotify(5, 'Highway Country', 'The Chair', 23, 'Compilation'),
|
||||
spotify(6, 'pov: U fell in love', 'The Chair', 14, 'Compilation'),
|
||||
]
|
||||
|
||||
describe('title-matched best result', () => {
|
||||
it('picks the Spotify track whose name matches, most popular first', () => {
|
||||
expect(getBestResult(braxtonKeithResults(), 'The Chair')?.index).toBe(2)
|
||||
})
|
||||
|
||||
it('without a title keeps the old category/seeders behaviour', () => {
|
||||
expect(getBestResult(braxtonKeithResults())?.index).toBe(2) // popularity tiebreak
|
||||
})
|
||||
|
||||
it('a Spotify title match is a confident tier 2, not "limited sources"', () => {
|
||||
const c = getSearchConfidence(braxtonKeithResults(), 'The Chair')
|
||||
expect(c.tier).toBe(2)
|
||||
expect(c.bestResult?.index).toBe(2)
|
||||
expect(c.warnings).toEqual([])
|
||||
expect(c.reason).toContain('Spotify')
|
||||
})
|
||||
|
||||
it('Spotify with no matching track is still tier 3', () => {
|
||||
const results = [spotify(0, 'Real Damn Deal', 'I Own This Bar', 40)]
|
||||
expect(getSearchConfidence(results, 'The Chair').tier).toBe(3)
|
||||
})
|
||||
|
||||
it('prefers the right track on Spotify over the wrong track on a torrent', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 120, release_type: 'Album', target_file: '03 - Prescription.flac' }),
|
||||
spotify(1, 'The Chair', 'The Chair', 65, 'Single'),
|
||||
]
|
||||
expect(getBestResult(results, 'The Chair')?.index).toBe(1)
|
||||
})
|
||||
|
||||
it('still prefers a matching torrent over matching Spotify', () => {
|
||||
const results = [
|
||||
spotify(0, 'The Chair', 'The Chair', 65, 'Single'),
|
||||
makeResult({ index: 1, is_lossless: true, seeders: 120, release_type: 'Album', target_file: '01 - The Chair.flac' }),
|
||||
]
|
||||
const c = getSearchConfidence(results, 'The Chair')
|
||||
expect(c.bestResult?.index).toBe(1)
|
||||
expect(c.tier).toBe(1)
|
||||
})
|
||||
|
||||
it('a Spotify album named after the song is not a track match', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, provider: 'Spotify', title: 'The Chair', artist: 'Braxton Keith' }),
|
||||
]
|
||||
const c = getSearchConfidence(results, 'The Chair')
|
||||
expect(c.tier).toBe(3)
|
||||
})
|
||||
|
||||
it('isConfirmedTitleMatch needs a compared, matching track filename', () => {
|
||||
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'The Chair', 1))).toBe(true)
|
||||
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'Cozy', 1))).toBe(false)
|
||||
expect(isConfirmedTitleMatch('Up', spotify(0, 'X', 'Up', 1))).toBe(false)
|
||||
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'The Chairman', 1))).toBe(false)
|
||||
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'The Chair (feat. Someone)', 1))).toBe(true)
|
||||
expect(isConfirmedTitleMatch('Hotel California',
|
||||
spotify(0, 'X', 'Hotel California - 2013 Remaster', 1))).toBe(true)
|
||||
expect(isConfirmedTitleMatch('Mr. Brightside', spotify(0, 'X', 'Mr. Brightside', 1))).toBe(true)
|
||||
expect(isConfirmedTitleMatch('7 Rings', spotify(0, 'X', '7 rings', 1))).toBe(true)
|
||||
expect(isConfirmedTitleMatch("(I Can't Get No) Satisfaction",
|
||||
spotify(0, 'X', "(I Can't Get No) Satisfaction - Mono Version", 1))).toBe(true)
|
||||
expect(isConfirmedTitleMatch('The Chair', spotify(0, 'X', 'The Chair (feat. X) [Remastered]', 1))).toBe(true)
|
||||
expect(isConfirmedTitleMatch('Creep',
|
||||
makeResult({ index: 0, is_lossless: true, target_file: 'Pablo Honey/02 - Creep.flac' }))).toBe(true)
|
||||
expect(isConfirmedTitleMatch('The Chair',
|
||||
makeResult({ index: 0, provider: 'Spotify', title: 'The Chair' }))).toBe(false)
|
||||
})
|
||||
|
||||
it('a title-matched live version beats an unranked fallback to results[0]', () => {
|
||||
const results = [
|
||||
spotify(0, 'Real Damn Deal', 'I Own This Bar', 40),
|
||||
makeResult({ index: 1, is_lossless: true, seeders: 5, release_type: 'Live album', target_file: '04 - The Chair.flac' }),
|
||||
]
|
||||
expect(getBestResult(results, 'The Chair')?.index).toBe(1)
|
||||
})
|
||||
|
||||
it('prefers the requested artist over a more popular same-title track', () => {
|
||||
// Real prod search: George Strait's "The Chair" (popularity 68) outranked
|
||||
// Braxton Keith's (65) when only the title was considered.
|
||||
const strait = { ...spotify(7, 'Something Special', 'The Chair', 68), artist: 'George Strait' }
|
||||
const results = [...braxtonKeithResults(), strait]
|
||||
expect(getBestResult(results, 'The Chair')?.index).toBe(7)
|
||||
const c = getSearchConfidence(results, 'The Chair', 'Braxton Keith')
|
||||
expect(c.bestResult?.index).toBe(2)
|
||||
expect(c.tier).toBe(2)
|
||||
})
|
||||
|
||||
it('a well-seeded cover by another artist is not a perfect (tier 1) match', () => {
|
||||
const cover = makeResult({ index: 0, is_lossless: true, seeders: 200, release_type: 'Album',
|
||||
artist: 'Postmodern Jukebox', target_file: '05 - Creep.flac' })
|
||||
expect(getSearchConfidence([cover], 'Creep', 'Radiohead').tier).toBe(2)
|
||||
expect(getSearchConfidence([{ ...cover, artist: 'Radiohead' }], 'Creep', 'Radiohead').tier).toBe(1)
|
||||
})
|
||||
|
||||
it('a Spotify title match by another artist is not a confident pick', () => {
|
||||
const strait = { ...spotify(0, 'Something Special', 'The Chair', 68), artist: 'George Strait' }
|
||||
expect(getSearchConfidence([strait], 'The Chair', 'Braxton Keith').tier).toBe(3)
|
||||
})
|
||||
|
||||
it('isArtistMatch is lenient on featured artists and "The"', () => {
|
||||
const r = (artist: string) => makeResult({ index: 0, artist })
|
||||
expect(isArtistMatch('Braxton Keith', r('Braxton Keith, Someone'))).toBe(true)
|
||||
expect(isArtistMatch('Killers', r('The Killers'))).toBe(true)
|
||||
expect(isArtistMatch('Braxton Keith', r('George Strait'))).toBe(false)
|
||||
expect(isArtistMatch('Kei', r('Braxton Keith'))).toBe(false)
|
||||
expect(isArtistMatch('radiohed', r('Radiohead'))).toBe(true)
|
||||
expect(isArtistMatch('U2', r('UB40'))).toBe(false)
|
||||
})
|
||||
|
||||
it('never promotes YouTube via a title match over a torrent', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 120, release_type: 'Album', target_file: '03 - Prescription.flac' }),
|
||||
makeResult({ index: 1, provider: 'YouTube', title: 'Braxton Keith - The Chair (Official Video)' }),
|
||||
]
|
||||
expect(getBestResult(results, 'The Chair')?.index).toBe(0)
|
||||
})
|
||||
})
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user