Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 5.5 374be827c0 fix(storage): retention job exits non-zero when any job errored
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 01:00:51 -04:00
Andrew BeveridgeandClaude Opus 5.5 d042a155dc fix(storage): clear the screens idempotency mark around stems restore
The regenerate E2E stalled after the stems restore: the first screens dispatch
had marked screens_progress=running, so the restore's re-trigger was skipped as
'already running'. Drop the mark when the gate hands off (and on completion),
and let recover-stuck-jobs re-trigger re-render/regenerate jobs left parked at
lyrics_complete for >10 min.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 00:50:14 -04:00
Andrew BeveridgeandClaude Opus 5.5 e9d2157546 fix(storage): run the retention pass as a Cloud Run Job (v0.265.1)
The scheduled endpoint ran the pass as a FastAPI BackgroundTask, which starves
on the API service (CPU throttled outside requests), and Cloudflare cuts
synchronous requests at 100s. Start a dedicated storage-retention-job Cloud Run
Job (Pulumi, applied) with the dry-run flag and report path as args; scoped
job_ids runs stay synchronous.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 00:30:30 -04:00
27 changed files with 55 additions and 1381 deletions

No files matched your search

+2 -22
View File
@@ -294,19 +294,8 @@ jobs:
--reporter=list \
--timeout=3600000
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report
- name: Upload test artifacts
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-results
@@ -2038,7 +2027,7 @@ jobs:
--max-instances 20 \
--min-instances 0 \
--clear-vpc-connector \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,STORAGE_RETENTION_DRY_RUN=false,STORAGE_RETENTION_MAX_JOBS_PER_RUN=50,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,GEMINI_API_KEY=gemini-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
@@ -2127,15 +2116,6 @@ jobs:
--project ${{ env.PROJECT_ID }} \
--quiet
# Storage-retention job (CPU, us-east4): pin to this commit's image so
# the deletion code (generation-pinned deletes + audit log) always
# matches the API that starts it.
gcloud run jobs update storage-retention-job \
--image "$CPU_JOBS_IMAGE" \
--region us-east4 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Audio separation job (GPU, us-east4) — uses GPU image
gcloud run jobs update audio-separation-job \
--image "$GPU_IMAGE" \
+7 -45
View File
@@ -58,7 +58,6 @@ jobs:
outputs:
session_token: ${{ steps.extract_token.outputs.token }}
result: ${{ steps.test_result.outputs.result }}
failure_reason: ${{ steps.test_result.outputs.failure_reason }}
healed: ${{ steps.self_heal.outputs.healed }}
env:
HAS_GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY != '' }}
@@ -171,13 +170,6 @@ jobs:
echo "result=success" >> "$GITHUB_OUTPUT"
else
echo "result=failure" >> "$GITHUB_OUTPUT"
# A declined card is an issuer/card problem, not a broken checkout —
# say so in the alerts (marker comes from e2e/helpers/stripe-checkout.ts).
REASON=$(grep -m1 -o 'STRIPE_CARD_DECLINED:.*' frontend/test-output-payment.log 2>/dev/null | sed 's/ — .*//' | tr -d '"\\' || true)
if [ -n "$REASON" ]; then
echo "failure_reason=Test card declined, not a checkout bug (${REASON#STRIPE_CARD_DECLINED: }). Check the card/issuer for a fraud hold, then re-run." >> "$GITHUB_OUTPUT"
echo "::error::$REASON"
fi
fi
- name: Detect self-healed Stripe steps
@@ -226,21 +218,8 @@ jobs:
echo "token=" >> $GITHUB_OUTPUT
fi
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_STRIPE_CARD_NUMBER: ${{ secrets.E2E_STRIPE_CARD_NUMBER }}
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
E2E_SESSION_TOKEN: ${{ steps.extract_token.outputs.token }}
run: node e2e/scripts/scrub-artifacts.mjs --drop-videos --blank-inputs test-results test-output-payment.log
- name: Upload artifacts
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-payment-results-${{ github.run_number }}
@@ -251,16 +230,10 @@ jobs:
- name: Discord notification (failure)
if: steps.test_result.outputs.result == 'failure'
env:
# Via env + jq, never ${{ }} in the script: the reason contains Stripe's message text.
REASON: ${{ steps.test_result.outputs.failure_reason || 'Payment flow is broken. Customers may not be receiving credits.' }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
RUN_NUMBER: ${{ github.run_number }}
WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
run: |
jq -n --arg reason "$REASON" --arg run "$RUN_NUMBER" --arg url "$RUN_URL" \
'{embeds: [{title: "🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase", description: "\($reason)\n\n**Run:** #\($run)\n**Details:** \($url)", color: 15158332}]}' |
curl -s -H "Content-Type: application/json" -d @- "$WEBHOOK"
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase\", \"description\": \"Payment flow is broken. Customers may not be receiving credits.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
- name: Fail if test failed
if: steps.test_result.outputs.result == 'failure'
@@ -526,19 +499,8 @@ jobs:
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || needs.e2e-credit-purchase.outputs.session_token || '' }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report test-output-happy-path.log
- name: Upload test artifacts
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-results-${{ github.run_number }}
@@ -549,7 +511,7 @@ jobs:
retention-days: 30
- name: Upload video recordings
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-videos-${{ github.run_number }}
@@ -619,7 +581,7 @@ jobs:
E2E Daily Test Results
======================
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}${{ needs.e2e-credit-purchase.outputs.failure_reason && format(' — {0}', needs.e2e-credit-purchase.outputs.failure_reason) || '' }}
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' }}
+1 -10
View File
@@ -83,17 +83,8 @@ jobs:
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report e2e-output.log
- name: Upload logs
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
-44
View File
@@ -776,50 +776,6 @@ async def storage_retention_run_endpoint(
}
ORPHAN_DELETE_CONFIRMATION = "delete-orphan-job-folders"
@router.post("/storage-retention/orphans")
async def storage_retention_orphans_endpoint(
dry_run: bool = True,
confirm: Optional[str] = None,
max_folders: Optional[int] = None,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""
One-off cleanup of ``jobs/{id}/`` folders with no job record: keep ``input/``,
delete everything else (backend/services/storage_retention.py purge_orphans).
DRY-RUN unless ``dry_run=false&confirm=delete-orphan-job-folders``. Independent
of STORAGE_RETENTION_DRY_RUN and never run by the scheduler. Runs as the
storage-retention-job Cloud Run Job; the report path is returned.
"""
from datetime import datetime, timezone
from backend.config import get_settings
from backend.services.storage_retention import REPORT_PREFIX
from backend.services.worker_service import get_worker_service
if not dry_run and confirm != ORPHAN_DELETE_CONFIRMATION:
raise HTTPException(
status_code=400,
detail=f"A real orphan cleanup needs confirm={ORPHAN_DELETE_CONFIRMATION}",
)
settings = get_settings()
now = datetime.now(timezone.utc)
report_path = f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-orphans-{'dry-run' if dry_run else 'run'}.json"
started = await get_worker_service().trigger_storage_retention_job(
dry_run=dry_run, report_path=report_path, mode="orphans", max_folders=max_folders,
)
if not started:
raise HTTPException(status_code=503, detail="Couldn't start the storage-retention job")
return {
"status": "started",
"mode": "orphans",
"dry_run": 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,
+10 -327
View File
@@ -52,16 +52,6 @@ logger = logging.getLogger(__name__)
POLICY_VERSION = 1
REPORT_PREFIX = "storage-retention/reports"
# Audit trail of every object deleted (kept forever; never touched by any purge
# or lifecycle rule — see docs/STORAGE-RETENTION.md).
DELETION_LOG_PREFIX = "storage-retention/deletion-logs"
MODE_JOB_PURGE = "job_purge"
MODE_ORPHAN = "orphan"
ORPHAN_QUIET_DAYS = 30
# Firestore collections whose doc id == the jobs/{id}/ folder name and that mean
# "this folder still belongs to something". encoding_worker_jobs is NOT one: it's
# the encoder's expiring result cache, left behind by deleted jobs.
ORPHAN_RECORD_COLLECTIONS = ("jobs", "jobs-dev", "youtube_upload_queue")
STATE_COLLECTION = "storage_retention"
STATE_DOC = "state"
SCAN_PAGE_SIZE = 200
@@ -244,7 +234,6 @@ class JobPlan:
stems_purgeable: bool = True
stems_note: Optional[str] = None
skip_reason: Optional[str] = None
generations: Dict[str, Any] = field(default_factory=dict)
@property
def purge_bytes(self) -> int:
@@ -265,26 +254,12 @@ class JobPlan:
return any(c in STEM_CATEGORIES for _, _, c in self.purge)
def _listing_entries(listing) -> List[Tuple[str, int, Any]]:
"""Normalise a listing of ``(name, size)``, ``(name, size, gen)`` or meta dicts."""
out = []
for item in listing:
if isinstance(item, dict):
out.append((item["name"], int(item.get("size") or 0), item.get("generation")))
elif len(item) >= 3:
out.append((item[0], int(item[1] or 0), item[2]))
else:
out.append((item[0], int(item[1] or 0), None))
return out
def plan_job(job: Dict[str, Any], listing) -> JobPlan:
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)
entries = _listing_entries(listing)
names = {name for name, _, _ in entries}
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
@@ -301,7 +276,7 @@ def plan_job(job: Dict[str, Any], listing) -> JobPlan:
plan.stems_purgeable = False
plan.stems_note = "existing_instrumental"
for name, size, generation in entries:
for name, size in listing:
if not name.startswith(prefix): # defence in depth: never outside jobs/{id}/
continue
action, category = classify_file(
@@ -309,152 +284,11 @@ def plan_job(job: Dict[str, Any], listing) -> JobPlan:
)
if action == PURGE:
plan.purge.append((name, size, category))
plan.generations[name] = generation
else:
plan.kept_bytes += size
return plan
def assert_deletable(path: str) -> None:
"""Hard guard: retention code only ever deletes inside a jobs/{id}/ folder."""
parts = path.split("/")
if len(parts) < 3 or parts[0] != "jobs" or not parts[1] or path.startswith(DELETION_LOG_PREFIX):
raise ValueError(f"refusing to delete outside jobs/{{id}}/: {path}")
def log_category(category: str) -> str:
"""Category label used in the deletion log (finals, review-audio, screens-mov, ...)."""
return category.replace("_", "-")
class DeletionLog:
"""Append-only JSONL audit log of one run's deletions, flushed to GCS in batches.
``storage-retention/deletion-logs/<run-ts>-<mode>.jsonl`` holds one line per
attempted delete; it is re-uploaded (whole) after every batch so a crash
mid-run still leaves a complete record of what was deleted up to the last
flush (the batch in flight is at most ``flush_every`` lines / one job).
"""
def __init__(self, storage, run_ts: datetime, mode: str, flush_every: int = 200):
self.storage = storage
self.mode = mode
self.run_id = f"{run_ts.strftime('%Y%m%dT%H%M%SZ')}-{mode}"
self.path = f"{DELETION_LOG_PREFIX}/{self.run_id}.jsonl"
self.summary_path = f"{DELETION_LOG_PREFIX}/{self.run_id}.summary.json"
self.flush_every = flush_every
self._lines: List[str] = []
self._unflushed = 0
self.totals: Counter = Counter()
self.counts: Counter = Counter()
self.failures = 0
self.jobs: set = set()
# Set when the audit log couldn't be written: callers stop deleting.
self.flush_error: Optional[str] = None
def record(self, job_id: str, path: str, size: int, generation, category: str,
result: str, error: Optional[str] = None) -> None:
import json
entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"run_id": self.run_id,
"mode": self.mode,
"job_id": job_id,
"path": path,
"size_bytes": int(size or 0),
"generation": str(generation) if generation is not None else None,
"category": category,
"result": result,
}
if error:
entry["error"] = error[:500]
self._lines.append(json.dumps(entry, ensure_ascii=False))
self._unflushed += 1
if result == "deleted":
self.totals[category] += int(size or 0)
self.counts[category] += 1
self.jobs.add(job_id)
elif result == "failed":
self.failures += 1
if self._unflushed >= self.flush_every:
self.flush()
def flush(self) -> None:
if not self._lines:
return
try:
self.storage.upload_text(self.path, "\n".join(self._lines) + "\n", content_type="application/x-ndjson")
self._unflushed = 0
self.flush_error = None
except Exception as e: # noqa: BLE001 - recorded; the run stops deleting
self.flush_error = str(e)
logger.error(f"storage retention: deletion log flush failed ({self.path}): {e}")
def write_summary(self, extra: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
summary = {
"run_id": self.run_id,
"mode": self.mode,
"deletion_log": self.path,
"objects_deleted": sum(self.counts.values()),
"jobs": len(self.jobs),
"bytes_deleted": sum(self.totals.values()),
"gib_deleted": round(sum(self.totals.values()) / 2**30, 3),
"bytes_by_category": dict(self.totals),
"objects_by_category": dict(self.counts),
"failures": self.failures,
"log_flush_error": self.flush_error,
"written_at": datetime.now(timezone.utc).isoformat(),
**(extra or {}),
}
self.flush()
try:
self.storage.upload_json(self.summary_path, summary)
except Exception as e: # noqa: BLE001
logger.error(f"storage retention: summary write failed ({self.summary_path}): {e}")
return summary
def orphan_candidates(entries: Iterable[Dict[str, Any]], known_ids: set) -> Dict[str, List[Dict[str, Any]]]:
"""Group ``jobs/{id}/...`` objects whose id has no job record."""
folders: Dict[str, List[Dict[str, Any]]] = {}
for meta in entries:
parts = meta["name"].split("/")
if len(parts) < 3 or parts[0] != "jobs" or not parts[1]:
continue
if parts[1] in known_ids:
continue
folders.setdefault(parts[1], []).append(meta)
return folders
def plan_orphan_folder(job_id: str, objects: List[Dict[str, Any]], now: datetime,
quiet_days: int = ORPHAN_QUIET_DAYS) -> Dict[str, Any]:
"""Keep ``input/``; everything else in an orphan folder is deleted (if quiet)."""
prefix = f"jobs/{job_id}/"
latest = None
for meta in objects:
updated = _parse_ts(meta.get("updated"))
if updated and (latest is None or updated > latest):
latest = updated
keep, purge = [], []
for meta in objects:
if not meta["name"].startswith(prefix):
continue
(keep if meta["name"][len(prefix):].startswith("input/") else purge).append(meta)
skip = None
if latest is None or now - latest < timedelta(days=quiet_days):
skip = "recently_modified"
return {
"job_id": job_id,
"latest_update": latest.isoformat() if latest else None,
"skip_reason": skip,
"purge": purge,
"keep": keep,
"purge_bytes": sum(int(m.get("size") or 0) for m in purge),
"keep_bytes": sum(int(m.get("size") or 0) for m in keep),
}
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)
@@ -561,10 +395,6 @@ class StorageRetentionService:
"errors": [],
}
totals: Counter = Counter()
deletion_log = None if dry_run else DeletionLog(self.storage, now, MODE_JOB_PURGE)
if deletion_log:
report["deletion_log"] = deletion_log.path
report["deletion_summary"] = deletion_log.summary_path
processed = 0
scanned = 0
last_id = None
@@ -583,7 +413,7 @@ class StorageRetentionService:
report["skipped"][reason] += 1
continue
try:
listing = self.storage.list_blob_meta(f"jobs/{job['job_id']}/")
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")
@@ -608,18 +438,12 @@ class StorageRetentionService:
}
if not dry_run:
try:
entry["result"] = self._execute(job["job_id"], plan, now, min_age, excluded, deletion_log)
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 deletion_log and deletion_log.flush_error:
# The audit log is a required safety record: no more deletes.
report["errors"].append({"job_id": plan.job_id,
"error": f"deletion log not persisted, run stopped: {deletion_log.flush_error}"})
exhausted = False
break
if not dry_run and entry["result"].get("status") != "purged":
continue
processed += 1
@@ -628,9 +452,6 @@ class StorageRetentionService:
if use_cursor:
self._save_cursor(None if exhausted else last_id)
if deletion_log:
report["deletion_totals"] = deletion_log.write_summary(
{"report_path": report_path or self.default_report_path(now, dry_run)})
report["skipped"] = dict(report["skipped"])
report["summary"] = {
@@ -772,8 +593,7 @@ class StorageRetentionService:
return _run_in_transaction(self.db, claim)
def _execute(self, job_id: str, plan: JobPlan, now: datetime, min_age: int, excluded: List[str],
deletion_log: Optional["DeletionLog"] = None) -> Dict[str, Any]:
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):
@@ -786,19 +606,11 @@ class StorageRetentionService:
for path, size, category in plan.purge:
if not path.startswith(f"jobs/{job_id}/"):
continue
generation = plan.generations.get(path)
try:
assert_deletable(path)
self.storage.delete_file(path, ignore_missing=True, if_generation_match=generation)
self.storage.delete_file(path, ignore_missing=True)
deleted.append((path, size, category))
if deletion_log:
deletion_log.record(job_id, path, size, generation, log_category(category), "deleted")
except Exception as e: # noqa: BLE001
failures.append({"path": path, "error": str(e)})
if deletion_log:
deletion_log.record(job_id, path, size, generation, log_category(category), "failed", str(e))
if deletion_log:
deletion_log.flush()
snap = ref.get()
file_urls = (snap.to_dict() or {}).get("file_urls") or {} if snap.exists else {}
@@ -818,11 +630,8 @@ class StorageRetentionService:
"policy_version": POLICY_VERSION,
"bytes": sum(by_category.values()),
"bytes_by_category": dict(by_category),
"files": [{"path": p, "bytes": s, "category": c,
"generation": str(plan.generations.get(p)) if plan.generations.get(p) is not None else None}
for p, s, c in deleted],
"files": [{"path": p, "bytes": s, "category": c} for p, s, c in deleted],
"failures": failures,
"deletion_log": deletion_log.path if deletion_log else None,
}
ref.update(update)
except Exception:
@@ -848,14 +657,11 @@ class StorageRetentionService:
"failures": failures,
}
# --- orphan folders -----------------------------------------------------------
def _known_job_ids(self) -> set:
return {snap.id for snap in self.jobs_collection.select(["status"]).stream()}
# --- orphans (report only, never deleted) -------------------------------------
def orphan_job_folders(self) -> Dict[str, Any]:
"""``jobs/{id}/`` folders with no Firestore job doc (report only)."""
known = self._known_job_ids()
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("/")
@@ -867,126 +673,3 @@ class StorageRetentionService:
"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)],
}
def _record_holder(self, job_id: str) -> Optional[str]:
"""Collection that (still) has a record for this folder id, checked live."""
for name in ORPHAN_RECORD_COLLECTIONS:
if self.db.collection(name).document(job_id).get().exists:
return name
return None
def purge_orphans(
self,
dry_run: bool = True,
max_folders: Optional[int] = None,
quiet_days: int = ORPHAN_QUIET_DAYS,
report_path: Optional[str] = None,
now: Optional[datetime] = None,
) -> Dict[str, Any]:
"""Delete everything but ``input/`` from job folders that have no job record.
Candidates come from one bucket listing vs. the ``jobs`` collection; each
folder is then re-checked LIVE before acting: no record in any of
ORPHAN_RECORD_COLLECTIONS, re-listed fresh, and no object modified in the
last ``quiet_days`` days. Dry-run by default.
"""
started = time.time()
now = now or datetime.now(timezone.utc)
known = self._known_job_ids()
candidates = orphan_candidates(self.storage.list_blob_meta("jobs/"), known)
deletion_log = None if dry_run else DeletionLog(self.storage, now, MODE_ORPHAN)
report: Dict[str, Any] = {
"mode": MODE_ORPHAN,
"dry_run": dry_run,
"started_at": now.isoformat(),
"quiet_days": quiet_days,
"record_collections": list(ORPHAN_RECORD_COLLECTIONS),
"candidates": len(candidates),
"folders": [],
"skipped": Counter(),
"not_orphans": [],
"errors": [],
}
if deletion_log:
report["deletion_log"] = deletion_log.path
report["deletion_summary"] = deletion_log.summary_path
acted = 0
purge_bytes = keep_bytes = skipped_bytes = 0
by_ext: Counter = Counter()
for job_id in sorted(candidates):
if max_folders is not None and acted >= max_folders:
report["skipped"]["batch_limit"] += 1
continue
try:
holder = self._record_holder(job_id)
if holder:
report["skipped"]["has_record"] += 1
report["not_orphans"].append({"job_id": job_id, "collection": holder})
continue
fresh = self.storage.list_blob_meta(f"jobs/{job_id}/")
plan = plan_orphan_folder(job_id, fresh, now, quiet_days)
except Exception as e: # noqa: BLE001
report["errors"].append({"job_id": job_id, "error": str(e)})
continue
if plan["skip_reason"]:
report["skipped"][plan["skip_reason"]] += 1
skipped_bytes += plan["purge_bytes"] + plan["keep_bytes"]
continue
if not plan["purge"]:
report["skipped"]["nothing_to_purge"] += 1
keep_bytes += plan["keep_bytes"]
continue
acted += 1
purge_bytes += plan["purge_bytes"]
keep_bytes += plan["keep_bytes"]
for meta in plan["purge"]:
rel = meta["name"].split("/", 2)[2]
by_ext[rel.split("/", 1)[0] if "/" in rel else "(root)"] += int(meta.get("size") or 0)
folder = {
"job_id": job_id, "latest_update": plan["latest_update"],
"purge_bytes": plan["purge_bytes"], "keep_bytes": plan["keep_bytes"],
"purge_objects": len(plan["purge"]), "kept_input_objects": len(plan["keep"]),
}
if not dry_run:
deleted = failed = 0
for meta in plan["purge"]:
path, size, gen = meta["name"], int(meta.get("size") or 0), meta.get("generation")
try:
assert_deletable(path)
self.storage.delete_file(path, ignore_missing=True, if_generation_match=gen)
deletion_log.record(job_id, path, size, gen, "orphan-nonInput", "deleted")
deleted += 1
except Exception as e: # noqa: BLE001
deletion_log.record(job_id, path, size, gen, "orphan-nonInput", "failed", str(e))
failed += 1
deletion_log.flush()
folder.update({"deleted": deleted, "failed": failed})
report["folders"].append(folder)
if deletion_log and deletion_log.flush_error:
report["errors"].append({"job_id": job_id,
"error": f"deletion log not persisted, run stopped: {deletion_log.flush_error}"})
break
report["skipped"] = dict(report["skipped"])
report["summary"] = {
"folders_acted" if not dry_run else "folders_to_purge": acted,
"gib_to_delete" if dry_run else "gib_deleted": round(purge_bytes / 2**30, 2),
"gib_input_kept": round(keep_bytes / 2**30, 2),
"gib_skipped_recent": round(skipped_bytes / 2**30, 2),
"gib_by_top_level_dir": {k: round(v / 2**30, 2) for k, v in by_ext.most_common()},
"duration_seconds": round(time.time() - started, 1),
}
report["report_path"] = report_path or (
f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-orphans-{'dry-run' if dry_run else 'run'}.json")
if deletion_log:
report["deletion_totals"] = deletion_log.write_summary({"report_path": report["report_path"]})
try:
self.storage.upload_json(report["report_path"], report)
except Exception as e: # noqa: BLE001
report["report_write_error"] = str(e)
logger.info(
f"STORAGE_RETENTION ORPHANS {'DRY-RUN' if dry_run else 'RUN'}: candidates={len(candidates)} "
f"summary={report['summary']} skipped={report['skipped']} errors={len(report['errors'])} "
f"report=gs://{self.settings.gcs_bucket_name}/{report['report_path']}"
)
return report
+2 -26
View File
@@ -298,8 +298,7 @@ class StorageService:
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
raise
def delete_file(self, blob_path: str, ignore_missing: bool = False,
if_generation_match: Optional[int] = None) -> bool:
def delete_file(self, blob_path: str, ignore_missing: bool = False) -> bool:
"""Delete a file from GCS.
Args:
@@ -315,12 +314,7 @@ class StorageService:
"""
try:
blob = self.bucket.blob(blob_path)
if if_generation_match is not None:
# Only delete the exact version that was planned/logged; a newer
# write since then raises PreconditionFailed.
blob.delete(if_generation_match=if_generation_match)
else:
blob.delete()
blob.delete()
logger.info(f"Deleted gs://{settings.gcs_bucket_name}/{blob_path}")
return True
except NotFound:
@@ -379,24 +373,6 @@ class StorageService:
logger.error(f"Error listing files with prefix {prefix}: {e}")
raise
def list_blob_meta(self, prefix: str) -> list:
"""List ``{name, size, generation, updated}`` for every object under ``prefix``."""
try:
return [
{"name": b.name, "size": int(b.size or 0), "generation": b.generation, "updated": b.updated}
for b in self.bucket.list_blobs(prefix=prefix)
]
except Exception as e:
logger.error(f"Error listing files with prefix {prefix}: {e}")
raise
def upload_text(self, destination_path: str, text: str, content_type: str = "text/plain") -> str:
"""Upload a text object (overwrites)."""
blob = self.bucket.blob(destination_path)
blob.cache_control = NO_STORE_CACHE_CONTROL
blob.upload_from_string(text, content_type=content_type)
return destination_path
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)
-6
View File
@@ -459,8 +459,6 @@ class WorkerService:
report_path: str,
max_jobs: Optional[int] = None,
include_orphans: bool = False,
mode: str = "job_purge",
max_folders: Optional[int] = None,
) -> bool:
"""Start the storage-retention pass as the ``storage-retention-job`` Cloud Run Job.
@@ -472,10 +470,6 @@ class WorkerService:
args += ["--max-jobs", str(int(max_jobs))]
if include_orphans:
args.append("--include-orphans")
if mode != "job_purge":
args += ["--mode", mode]
if max_folders is not None:
args += ["--max-folders", str(int(max_folders))]
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:
-41
View File
@@ -723,35 +723,6 @@ class TestInternalRetentionEndpoint:
assert kwargs["dry_run"] is True and kwargs["include_orphans"] is True
assert kwargs["report_path"] == body["report_path"].removeprefix("gs://bucket/")
def _orphans(self, client, url):
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
ws = MagicMock()
ws.trigger_storage_retention_job = AsyncMock(return_value=True)
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
return test_client.post(url), ws
def test_orphan_endpoint_defaults_to_dry_run(self, client):
resp, ws = self._orphans(client, "/api/internal/storage-retention/orphans")
assert resp.status_code == 200 and resp.json()["dry_run"] is True
kwargs = ws.trigger_storage_retention_job.await_args.kwargs
assert kwargs["mode"] == "orphans" and kwargs["dry_run"] is True
assert "-orphans-dry-run.json" in kwargs["report_path"]
def test_orphan_real_run_needs_confirmation(self, client):
resp, ws = self._orphans(client, "/api/internal/storage-retention/orphans?dry_run=false")
assert resp.status_code == 400
ws.trigger_storage_retention_job.assert_not_awaited()
resp, ws = self._orphans(
client, "/api/internal/storage-retention/orphans?dry_run=false&confirm=delete-orphan-job-folders")
assert resp.status_code == 200
assert ws.trigger_storage_retention_job.await_args.kwargs["dry_run"] is False
def test_job_trigger_failure_is_503(self, client):
ws = MagicMock()
ws.trigger_storage_retention_job = AsyncMock(return_value=False)
@@ -943,15 +914,6 @@ class TestStorageRetentionWorker:
assert svc.run.call_args.kwargs == {"dry_run": False, "max_jobs": 5, "include_orphans": True,
"report_path": "r.json"}
def test_cli_orphan_mode(self):
from backend.workers import storage_retention_worker
svc = MagicMock()
svc.purge_orphans.return_value = {}
with patch("backend.services.storage_retention.StorageRetentionService", return_value=svc):
assert storage_retention_worker.main(["--mode", "orphans", "--max-folders", "7"]) == 0
assert svc.purge_orphans.call_args.kwargs == {"dry_run": True, "max_folders": 7, "report_path": None}
svc.run.assert_not_called()
def test_cli_defaults_to_dry_run(self):
from backend.workers import storage_retention_worker
svc = MagicMock()
@@ -986,9 +948,6 @@ class TestStorageRetentionWorker:
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"]
await ws.trigger_storage_retention_job(True, "o.json", mode="orphans", max_folders=2)
args = list(ws._run_job_with_retry.await_args.args[1].overrides.container_overrides[0].args)
assert args[3:] == ["--dry-run", "true", "--report-path", "o.json", "--mode", "orphans", "--max-folders", "2"]
+7 -218
View File
@@ -310,25 +310,16 @@ class TestFileUrlDeletions:
# --- Service ----------------------------------------------------------------------
class FakeStorage:
def __init__(self, files, updated=None):
def __init__(self, files):
self.files = dict(files)
self.updated = dict(updated or {})
self.deleted = []
self.reports = {}
self.texts = {}
self.delete_generations = {}
def list_files_with_sizes(self, prefix):
return [(k, v) for k, v in sorted(self.files.items()) if k.startswith(prefix)]
def list_blob_meta(self, prefix):
old = datetime(2026, 1, 1, tzinfo=timezone.utc)
return [{"name": k, "size": v, "generation": 1000 + i, "updated": self.updated.get(k, old)}
for i, (k, v) in enumerate(sorted(self.files.items())) if k.startswith(prefix)]
def delete_file(self, path, ignore_missing=False, if_generation_match=None):
def delete_file(self, path, ignore_missing=False):
self.deleted.append(path)
self.delete_generations[path] = if_generation_match
self.files.pop(path, None)
return True
@@ -336,10 +327,6 @@ class FakeStorage:
self.reports[path] = data
return path
def upload_text(self, path, text, content_type="text/plain"):
self.texts[path] = text
return path
class FakeDoc:
def __init__(self, db, doc_id):
@@ -601,10 +588,10 @@ class TestServiceRealRun:
svc, db, storage = _service([_job(job_id="a")])
real_delete = storage.delete_file
def flaky(path, ignore_missing=False, if_generation_match=None):
def flaky(path, ignore_missing=False):
if path.endswith("lossy_4k_mp4.mp4"):
raise RuntimeError("boom")
return real_delete(path, ignore_missing, if_generation_match)
return real_delete(path, ignore_missing)
storage.delete_file = flaky
svc.run(dry_run=False, now=NOW)
@@ -656,7 +643,7 @@ class TestInterruptedPurge:
svc, db, storage = _service([_job(job_id="a")])
seen = {}
def delete(path, ignore_missing=False, if_generation_match=None):
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"]
@@ -675,11 +662,11 @@ class TestInterruptedPurge:
calls = {"n": 0}
real = storage.delete_file
def dies_after_two(path, ignore_missing=False, if_generation_match=None):
def dies_after_two(path, ignore_missing=False):
calls["n"] += 1
if calls["n"] > 2:
raise SystemExit("instance killed")
return real(path, ignore_missing, if_generation_match)
return real(path, ignore_missing)
storage.delete_file = dies_after_two
with pytest.raises(SystemExit):
@@ -692,201 +679,3 @@ class TestInterruptedPurge:
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"
# --- Deletion audit log -------------------------------------------------------------
import json as _json
def _log_lines(storage, path):
return [_json.loads(line) for line in storage.texts[path].splitlines() if line]
class TestDeletionLog:
def test_real_run_logs_every_deleted_object_with_generation(self):
svc, db, storage = _service([_job(job_id="a")])
report = svc.run(dry_run=False, now=NOW)
log_path = report["deletion_log"]
assert log_path == "storage-retention/deletion-logs/20261003T120000Z-job_purge.jsonl"
lines = _log_lines(storage, log_path)
assert {l["path"] for l in lines} == set(storage.deleted)
assert all(l["result"] == "deleted" and l["mode"] == "job_purge" and l["job_id"] == "a" for l in lines)
assert all(l["generation"] is not None for l in lines)
cats = {l["category"] for l in lines}
assert {"finals", "videos", "stems", "review-audio", "previews", "screens-mov"} == cats
# deletes are generation-pinned to exactly the logged version
for l in lines:
assert str(storage.delete_generations[l["path"]]) == l["generation"]
summary = storage.reports[report["deletion_summary"]]
assert summary["objects_deleted"] == len(lines)
assert summary["bytes_deleted"] == sum(l["size_bytes"] for l in lines)
assert summary["jobs"] == 1 and summary["failures"] == 0
# manifest on the job doc carries generations + log path
manifest = db.data["a"]["storage_purge"]
assert manifest["deletion_log"] == log_path
assert all(f["generation"] for f in manifest["files"])
def test_dry_run_writes_no_deletion_log(self):
svc, db, storage = _service([_job(job_id="a")])
report = svc.run(dry_run=True, now=NOW)
assert "deletion_log" not in report and storage.texts == {}
def test_failures_are_logged(self):
svc, db, storage = _service([_job(job_id="a")])
real = storage.delete_file
def flaky(path, ignore_missing=False, if_generation_match=None):
if path.endswith("lossy_4k_mp4.mp4"):
raise RuntimeError("412 precondition failed")
return real(path, ignore_missing, if_generation_match)
storage.delete_file = flaky
report = svc.run(dry_run=False, now=NOW)
failed = [l for l in _log_lines(storage, report["deletion_log"]) if l["result"] == "failed"]
assert len(failed) == 1 and "precondition" in failed[0]["error"]
assert storage.reports[report["deletion_summary"]]["failures"] == 1
def test_log_is_flushed_per_job_so_a_crash_keeps_the_record(self):
jobs = [_job(job_id="a"), _job(job_id="b")]
svc, db, storage = _service(jobs)
real = storage.delete_file
def die_on_b(path, ignore_missing=False, if_generation_match=None):
if path.startswith("jobs/b/"):
raise SystemExit("killed")
return real(path, ignore_missing, if_generation_match)
storage.delete_file = die_on_b
with pytest.raises(SystemExit):
svc.run(dry_run=False, now=NOW)
path = "storage-retention/deletion-logs/20261003T120000Z-job_purge.jsonl"
lines = _log_lines(storage, path)
assert lines and {l["job_id"] for l in lines} == {"a"}
assert {l["path"] for l in lines} == {p for p in storage.deleted if p.startswith("jobs/a/")}
@pytest.mark.parametrize("path", [
"storage-retention/deletion-logs/x.jsonl", "uploads/a/x.flac", "jobs/", "jobs//x", "temp/x",
])
def test_guard_refuses_paths_outside_job_folders(self, path):
with pytest.raises(ValueError):
sr.assert_deletable(path)
def test_guard_allows_job_files(self):
sr.assert_deletable("jobs/a/finals/x.mp4")
# --- Orphan folders ----------------------------------------------------------------
def _orphan_service(files, updated=None, records=None):
db = FakeDb([_job(job_id="live")])
for coll, ids in (records or {}).items():
db.extra = getattr(db, "extra", {})
db.extra.update({(coll, i): True for i in ids})
real_collection = db.collection
def collection(name):
if name in ("jobs-dev", "youtube_upload_queue"):
extra = getattr(db, "extra", {})
return SimpleNamespace(document=lambda i: SimpleNamespace(
get=lambda: SimpleNamespace(exists=extra.get((name, i), False))))
return real_collection(name)
db.collection = collection
storage = FakeStorage(files, updated)
return StorageRetentionService(db=db, storage=storage, settings=_settings()), db, storage
ORPHAN_FILES = {
"jobs/live/finals/lossy_4k_mp4.mp4": 10,
"jobs/ghost/input/song.flac": 100,
"jobs/ghost/finals/lossy_720p_mp4.mp4": 30,
"jobs/ghost/videos/with_vocals.mkv": 200,
"jobs/ghost/stems/custom_instrumental.flac": 40,
"jobs/ghost/custom_instrumental.mp3": 9,
"jobs/fresh/finals/x.mp4": 50,
"jobs/queued/finals/x.mp4": 70,
"jobs/_preview123/review-audio/mixed.ogg": 4,
"storage-retention/deletion-logs/old.jsonl": 1,
"uploads/ghost/audio/x.flac": 5,
}
class TestOrphans:
def _svc(self):
updated = {"jobs/fresh/finals/x.mp4": NOW - timedelta(days=2)}
return _orphan_service(ORPHAN_FILES, updated, records={"youtube_upload_queue": ["queued"]})
def test_plan_keeps_only_input(self):
objs = [{"name": k, "size": v, "updated": NOW - timedelta(days=90)}
for k, v in ORPHAN_FILES.items() if k.startswith("jobs/ghost/")]
plan = sr.plan_orphan_folder("ghost", objs, NOW)
assert [m["name"] for m in plan["keep"]] == ["jobs/ghost/input/song.flac"]
assert plan["purge_bytes"] == 30 + 200 + 40 + 9 and plan["skip_reason"] is None
def test_recent_folder_is_skipped(self):
plan = sr.plan_orphan_folder("x", [{"name": "jobs/x/a.mp4", "size": 1, "updated": NOW - timedelta(days=29)}], NOW)
assert plan["skip_reason"] == "recently_modified"
def test_dry_run_reports_without_deleting(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=True, now=NOW)
assert storage.deleted == [] and storage.texts == {}
assert report["candidates"] == 4 # ghost, fresh, queued, _preview123 (never "live")
assert sorted(f["job_id"] for f in report["folders"]) == ["_preview123", "ghost"]
assert report["skipped"] == {"recently_modified": 1, "has_record": 1}
assert report["not_orphans"] == [{"job_id": "queued", "collection": "youtube_upload_queue"}]
assert report["summary"]["gib_input_kept"] == round(100 / 2**30, 2)
assert report["report_path"].endswith("-orphans-dry-run.json")
def test_real_run_deletes_non_input_and_logs(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=False, now=NOW)
assert sorted(storage.deleted) == sorted([
"jobs/ghost/finals/lossy_720p_mp4.mp4", "jobs/ghost/videos/with_vocals.mkv",
"jobs/ghost/stems/custom_instrumental.flac", "jobs/ghost/custom_instrumental.mp3",
"jobs/_preview123/review-audio/mixed.ogg",
])
for kept in ("jobs/ghost/input/song.flac", "jobs/live/finals/lossy_4k_mp4.mp4",
"jobs/fresh/finals/x.mp4", "jobs/queued/finals/x.mp4",
"storage-retention/deletion-logs/old.jsonl", "uploads/ghost/audio/x.flac"):
assert kept in storage.files
lines = _log_lines(storage, report["deletion_log"])
assert report["deletion_log"].endswith("-orphan.jsonl")
assert {l["category"] for l in lines} == {"orphan-nonInput"} and {l["mode"] for l in lines} == {"orphan"}
assert storage.reports[report["deletion_summary"]]["objects_deleted"] == 5
def test_record_created_after_listing_is_respected(self):
svc, db, storage = self._svc()
db.extra = {("jobs-dev", "ghost"): True}
svc.purge_orphans(dry_run=False, now=NOW)
assert not any(p.startswith("jobs/ghost/") for p in storage.deleted)
def test_batch_limit(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=False, max_folders=1, now=NOW)
assert len(report["folders"]) == 1 and report["skipped"]["batch_limit"] == 3
class TestDeletionLogFlushFailure:
def test_run_stops_deleting_when_log_cannot_be_written(self):
svc, db, storage = _service([_job(job_id="a"), _job(job_id="b")])
def broken(path, text, content_type="text/plain"):
raise RuntimeError("gcs write denied")
storage.upload_text = broken
report = svc.run(dry_run=False, now=NOW)
assert not any(p.startswith("jobs/b/") for p in storage.deleted)
assert report["errors"] and "deletion log not persisted" in report["errors"][0]["error"]
assert storage.reports[report["deletion_summary"]]["log_flush_error"] == "gcs write denied"
def test_orphan_run_stops_too(self):
files = {"jobs/g1/finals/a.mp4": 1, "jobs/g2/finals/b.mp4": 1}
svc, db, storage = _orphan_service(files)
storage.upload_text = lambda *a, **k: (_ for _ in ()).throw(RuntimeError("denied"))
report = svc.purge_orphans(dry_run=False, now=NOW)
assert storage.deleted == ["jobs/g1/finals/a.mp4"]
assert "deletion log not persisted" in report["errors"][0]["error"]
+4 -11
View File
@@ -25,23 +25,16 @@ def main(argv=None) -> int:
parser.add_argument("--max-jobs", type=int, default=None)
parser.add_argument("--include-orphans", action="store_true")
parser.add_argument("--report-path", default=None)
parser.add_argument("--mode", choices=["job_purge", "orphans"], default="job_purge")
parser.add_argument("--max-folders", type=int, 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:
if args.mode == "orphans":
report = StorageRetentionService().purge_orphans(
dry_run=args.dry_run, max_folders=args.max_folders, report_path=args.report_path,
)
else:
report = StorageRetentionService().run(
dry_run=args.dry_run, max_jobs=args.max_jobs,
include_orphans=args.include_orphans, report_path=args.report_path,
)
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
+2 -5
View File
@@ -253,11 +253,8 @@ jobs completed (newest `complete` timeline entry) more than `STORAGE_RETENTION_M
(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, noncurrent (overwritten or deleted) versions kept 7 days, soft delete 7 days —
purged bytes remain recoverable for about two weeks.
- Every deleted object is logged (path, size, generation) under
`storage-retention/deletion-logs/`; review/restore commands and the one-off orphan-folder cleanup are in
`docs/STORAGE-RETENTION.md`.
- Bucket: versioning on, overwritten versions kept 7 days, soft delete 7 days — purged bytes remain
recoverable for about a week.
## LyricsTranscriber Integration
-15
View File
@@ -6,21 +6,6 @@ Key insights for future AI agents working on this codebase.
---
## Public-repo CI artifacts published the real test card and the admin token (Oct 2026)
Investigating E2E Daily #200 ("Stage 1 failed", Stripe self-heal "not needed") showed two things:
- **The failure was the issuer declining the card** (`confirm` → 402 `card_error/generic_decline`,
likely a fraud hold after ~8 live $0.50 charges in a day), but the self-healing runner treated it
like a layout change: 90s verify wait, then 6 Gemini calls "re-entering" a correct form. Detect
non-recoverable outcomes from the network (the confirm response), not from the UI, and abort.
- **Every run's artifacts held the full card number/expiry/CVC** (manual screenshots, Playwright
auto-screenshots, videos, `error-context.md` ARIA snapshot, DOM dump) **and `X-Admin-Token`**
(trace network logs) — in a public repo, downloadable by anyone signed in to GitHub. `::add-mask::`
only protects *logs*, never artifacts. Fix: scrub before every upload (`e2e/scripts/scrub-artifacts.mjs`),
traces off on CI, masked screenshots. All 140 existing e2e artifacts were deleted; the exposed admin token
and test card must be rotated.
## 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.
-73
View File
@@ -1,73 +0,0 @@
# Storage retention: operations
Policy + design: `docs/ARCHITECTURE.md` § Storage Retention. Code:
`backend/services/storage_retention.py`, `backend/workers/storage_retention_worker.py`.
## Runs
| Mode | Trigger | Deletes |
|---|---|---|
| `job_purge` | Cloud Scheduler `storage-retention-daily` (10:30 UTC) → `POST /api/internal/storage-retention/run` → Cloud Run Job `storage-retention-job` (us-east4) | Regenerable files of jobs completed >30 days ago, up to `STORAGE_RETENTION_MAX_JOBS_PER_RUN` (50) per run. Real deletion is on (`STORAGE_RETENTION_DRY_RUN=false` in the CI `--set-env-vars` of the backend deploy — the API passes the flag to the job; that's the only place it's set). |
| `orphan` | Manual: `POST /api/internal/storage-retention/orphans` (dry-run) / `?dry_run=false&confirm=delete-orphan-job-folders` | Everything except `input/` in `jobs/{id}/` folders with no record in `jobs`, `jobs-dev` or `youtube_upload_queue` (checked live per folder) and nothing modified in the last 30 days. |
Manual trigger (admin token):
```bash
TOK=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d, -f1)
curl -X POST https://api.nomadkaraoke.com/api/internal/storage-retention/run -H "X-Admin-Token: $TOK"
curl -X POST https://api.nomadkaraoke.com/api/internal/storage-retention/orphans -H "X-Admin-Token: $TOK" # dry-run
```
## Where the record is
- `gs://karaoke-gen-storage-nomadkaraoke/storage-retention/reports/<ts>-{dry-run,run}.json`,
`<ts>-orphans-{dry-run,run}.json`: the plan/outcome of each pass (dry-runs included).
- `gs://karaoke-gen-storage-nomadkaraoke/storage-retention/deletion-logs/<ts>-<mode>.jsonl`: **one line
per object a real run deleted (or failed to)**:
`timestamp, run_id, mode (job_purge|orphan), job_id, path, size_bytes, generation, category
(finals|videos|stems|review-audio|previews|screens-mov|encoded|quick|orphan-nonInput), result
(deleted|failed), error`. Rewritten after every job/folder, so a crash leaves a complete record up to
the last finished job.
- `.../deletion-logs/<ts>-<mode>.summary.json`: totals by category, job count, GiB, failures.
- Each purged job's Firestore doc: `storage_purge` (files + generations + `deletion_log`),
`renders_purged_at`, `stems_purged_at`.
The `storage-retention/` prefix is never touched by retention code (it only deletes inside
`jobs/{id}/`, enforced by `assert_deletable`) and no lifecycle rule matches live objects there
(the rules are: age 7 on `temp/`+`uploads/`, and noncurrent versions after 7 days). Logs are kept
forever.
## Reviewing
```bash
B=gs://karaoke-gen-storage-nomadkaraoke/storage-retention/deletion-logs
gcloud storage ls "$B/" # all runs
RUN=20261004T150000Z-job_purge # pick one from the listing
gcloud storage cat "$B/$RUN.summary.json" | jq . # one run's totals
gcloud storage cat "$B/$RUN.jsonl" | jq -s 'map(select(.result=="deleted")) | group_by(.category)
| map({category: .[0].category, objects: length, gib: (map(.size_bytes)|add/1073741824)})'
gcloud storage cat "$B/$RUN.jsonl" | jq -s 'group_by(.job_id) | map({job: .[0].job_id,
gib: (map(.size_bytes)|add/1073741824)}) | sort_by(-.gib)' # per job
gcloud storage cat "$B/$RUN.jsonl" | jq -c 'select(.result=="failed")'
JOB=abc12345
gcloud storage cat "$B/*.jsonl" | jq -c --arg j "$JOB" 'select(.job_id==$j)' # everything deleted for a job
```
Or: `python scripts/storage_retention_report.py` (all runs), `... <run_id>` (one run, per category and
job), `... --find <job_id|path>` (which run deleted it, with a restore command).
## Restoring
The bucket keeps deleted objects as noncurrent versions for 7 days, then soft delete keeps them 7 more
days. With the `generation` from the log:
```bash
OBJ='jobs/abc12345/finals/lossy_4k_mp4.mp4'; GEN=1790000000000000 # from a result=="deleted" log line
# within ~7 days (noncurrent version):
gcloud storage cp --no-clobber "gs://karaoke-gen-storage-nomadkaraoke/$OBJ#$GEN" "gs://karaoke-gen-storage-nomadkaraoke/$OBJ"
# days 7-14 (soft-deleted):
gcloud storage restore "gs://karaoke-gen-storage-nomadkaraoke/$OBJ#$GEN"
```
After restoring a purged job's files, prefer simply using "Regenerate video" (or
`POST /api/admin/jobs/{id}/regenerate`) — it rebuilds everything and clears the purge markers.
-25
View File
@@ -518,13 +518,6 @@ defaults it to `true` (server-side, ~Aug 2026), which silently blocks bot-author
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.
**Declined card ≠ layout change.** The helper watches Stripe's
`/v1/payment_pages/<id>/confirm` response; a `card_error` (e.g. `card_declined/generic_decline`)
fails `submitPayment` immediately with `STRIPE_CARD_DECLINED: …` — no LLM calls, no second Pay
click. The workflow surfaces it as the Stage 1 `failure_reason` in Discord and the daily email
("Test card declined, not a checkout bug"). Fix it on the card side (issuer fraud hold — e.g.
after many live $0.50 runs in a day — or an expired/replaced card), then re-run.
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.
@@ -537,24 +530,6 @@ npx playwright test --config=playwright.selfheal.config.ts
# self_heal_force_llm = selectCard (forces that step through Gemini; opens a PR)
```
## E2E Artifacts Are Public — Scrub Before Upload
karaoke-gen is a **public** repo: any signed-in GitHub user can download Actions artifacts.
Every workflow that uploads production-E2E output runs `frontend/e2e/scripts/scrub-artifacts.mjs`
first and only uploads if the scrub succeeded:
- deletes Playwright traces (`*.zip` — they contain every request header incl. `X-Admin-Token`
and every typed value) and `e2e-session-token.txt`;
- replaces literal secret values (admin token, testmail key, card number, session tokens…) and
card-number-shaped digit runs in text files; deletes any text file still containing a secret;
- Stage 1 also passes `--drop-videos --blank-inputs` (videos of the Stripe page; `<input value>`
and ARIA-snapshot textbox values in DOM dumps / `error-context.md`).
In addition, `playwright.production.config.ts` turns traces **off on CI** (`E2E_TRACE=on` to
override), the credit-purchase spec disables trace/video/auto-screenshots, and the Stripe helper's
own screenshots mask every input. When adding a new secret to a production E2E job, add its env
var to `SECRET_ENV_VARS` in the scrubber and to the job's scrub step.
## Concurrent-Load Regression Test (review pages)
`scripts/load-test-review.py` replays the 2026-09-18 "10 tabs melt the backend"
@@ -152,7 +152,6 @@ export async function pollVerify(step: CheckoutStep, ctx: StepContext, timeoutMs
const deadline = Date.now() + timeoutMs;
do {
if (await step.verify(ctx).catch(() => false)) return true;
if (step.abortReason?.()) return false;
await ctx.page.waitForTimeout(500);
} while (Date.now() < deadline);
return false;
@@ -166,8 +165,6 @@ export async function healStep(step: CheckoutStep, ctx: StepContext, planner: Pl
let model = '';
for (let i = 0; i < MAX_ITERATIONS; i++) {
const aborted = step.abortReason?.();
if (aborted) return { success: false, actions: executed, model, llmCalls, reason: aborted };
const observation = await observe(ctx.page, ctx.secrets);
let decision: LlmDecision;
try {
@@ -52,10 +52,6 @@ export class SelfHealingRunner {
const forced = this.forceLlm.has(step.id);
if (forced) console.log(` ⚙️ step ${step.id}: E2E_SELF_HEAL_FORCE_LLM — skipping deterministic variants`);
const aborted = (): StepOutcome | null => {
const reason = step.abortReason?.();
return reason ? { stepId: step.id, status: 'failed', reason, llmCalls: 0 } : null;
};
if (!forced) {
for (const v of this.learned.steps[step.id] || []) {
@@ -70,8 +66,6 @@ export class SelfHealingRunner {
} catch (e) {
console.log(` learned variant ${v.id} failed: ${(e as Error).message.split('\n')[0]}`);
}
const stop = aborted();
if (stop) return stop;
}
for (const b of step.builtins) {
try {
@@ -82,8 +76,6 @@ export class SelfHealingRunner {
} catch (e) {
console.log(` builtin "${b.name}" failed: ${(e as Error).message.split('\n')[0]}`);
}
const stop = aborted();
if (stop) return stop;
}
}
@@ -103,8 +95,7 @@ export class SelfHealingRunner {
// 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' };
}
const reason = step.abortReason?.() || heal.reason || 'LLM fallback failed';
return { stepId: step.id, status: 'failed', reason, llmCalls: heal.llmCalls };
return { stepId: step.id, status: 'failed', reason: heal.reason || 'LLM fallback failed', llmCalls: heal.llmCalls };
}
get healed() {
@@ -69,11 +69,6 @@ export interface CheckoutStep {
allowSubmit?: boolean;
/** Placeholders the LLM may use in this step, e.g. ['CARD_NUMBER']. */
placeholders?: string[];
/**
* Non-recoverable condition that no variant or LLM can fix (e.g. the issuer
* declined the card). Returns a reason to fail the step immediately, or null.
*/
abortReason?: () => string | null;
}
export interface LearnedVariant {
+12 -83
View File
@@ -1,8 +1,7 @@
// frontend/e2e/helpers/stripe-checkout.ts
import { Page, Frame, Locator, Response } from '@playwright/test';
import { Page, Frame, Locator } from '@playwright/test';
import * as fs from 'fs';
import { GeminiPlanner, type Planner } from './self-healing/llm-agent';
import { redact } from './self-healing/observe';
import { SelfHealingRunner } from './self-healing/step-runner';
import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext } from './self-healing/types';
@@ -33,13 +32,6 @@ import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext } from './
*
* You can still add builtin variants by hand, but you shouldn't need to.
*
* A *declined card* is not a layout change: Stripe's confirm call returns a
* `card_error`, and the submit step fails immediately with a message starting
* `STRIPE_CARD_DECLINED` (no LLM retries, no further Pay clicks).
*
* Artifacts: test-results/ is uploaded from a PUBLIC repo, so every screenshot
* here masks inputs and the DOM dump has field values redacted.
*
* Environment variables:
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC,
* E2E_STRIPE_CARDHOLDER_NAME (optional), E2E_STRIPE_ZIP (optional)
@@ -217,49 +209,7 @@ function throttled(check: () => Promise<boolean>, intervalMs = 5_000): () => Pro
};
}
/** Marker the daily workflow greps for to report "card declined" instead of "checkout broken". */
export const CARD_DECLINED_MARKER = 'STRIPE_CARD_DECLINED';
/**
* Turn a failed Stripe Checkout `/payment_pages/<id>/confirm` response body
* into an abort reason — only for `card_error`s (declines, incorrect CVC,
* expired card…), which no UI retry can fix. Other errors (e.g. a missing
* required field) return null so the LLM fallback can still repair the form.
*/
export function cardErrorReason(status: number, body: unknown): string | null {
const err = (body as { error?: Record<string, unknown> } | null)?.error;
if (!err || err.type !== 'card_error') return null;
const codes = [err.code, err.decline_code].filter(Boolean).join('/');
return (
`${CARD_DECLINED_MARKER}: Stripe rejected the test card (HTTP ${status}, ${codes || 'card_error'}): ` +
`${err.message || 'no message'} — the issuer/card needs attention; this is not a Checkout layout change`
);
}
export function isCheckoutConfirmUrl(url: string): boolean {
try {
return /\/v1\/payment_pages\/[^/]+\/confirm$/.test(new URL(url).pathname);
} catch {
return false;
}
}
/** Screenshot with every input in every frame masked (artifacts are public). */
async function maskedScreenshot(page: Page, file: string): Promise<void> {
await page
.screenshot({
path: file,
mask: page.frames().filter((f) => !f.isDetached()).map((f) => f.locator('input, textarea, select')),
maskColor: '#888888',
})
.catch(() => {});
}
function buildSteps(
card: CardDetails,
verifyPaid?: () => Promise<boolean>,
cardError?: () => string | null
): CheckoutStep[] {
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'));
@@ -370,7 +320,6 @@ function buildSteps(
// 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,
abortReason: cardError,
verify: async ({ page }) => {
if (isSuccessRedirect(page.url())) return true;
return paidCheck ? paidCheck() : false;
@@ -389,16 +338,14 @@ function buildSteps(
];
}
async function dumpFrames(page: Page, file: string, secrets: Secrets): Promise<void> {
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(() => ''))
// Typed card data lives in value="…" attributes.
.replace(/(<input\b[^>]*?\bvalue=)("[^"]*"|'[^']*')/gi, '$1"[redacted]"');
dumps.push(`<!-- ===== frame: ${frame.url()} ===== -->\n${redact(html, secrets)}`);
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'));
@@ -445,22 +392,6 @@ export async function completeStripeCheckout(
if (!planner) console.log(' (no LLM planner — GEMINI_API_KEY unset; self-healing fallback disabled)');
const runner = new SelfHealingRunner(page, secrets, planner, opts.learned);
// Watch Stripe's confirm call so a declined card fails fast with a clear reason
// instead of sending the LLM fallback to "fix" a form that is already correct.
let cardError: string | null = null;
const onResponse = async (res: Response) => {
if (res.status() < 400 || !isCheckoutConfirmUrl(res.url())) return;
const body = await res.json().catch(() => null);
const reason = cardErrorReason(res.status(), body);
if (reason) {
cardError = reason;
console.log(` ✘ ${reason}`);
} else {
console.log(` ⚠️ Stripe confirm returned HTTP ${res.status()} (not a card error — self-healing continues)`);
}
};
page.on('response', onResponse);
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
@@ -474,29 +405,27 @@ export async function completeStripeCheckout(
.or(f.getByText('Card', { exact: true })),
30_000
);
await maskedScreenshot(page, 'test-results/stripe-checkout-loaded.png');
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, () => cardError)) {
for (const step of buildSteps(card, opts.verifyPaid)) {
const outcome = await runner.run(step);
if (step.id === 'selectCard') await maskedScreenshot(page, 'test-results/stripe-card-selected.png');
if (step.id === 'uncheckSaveInfo') await maskedScreenshot(page, 'test-results/stripe-checkout-filled.png');
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 maskedScreenshot(page, `test-results/stripe-step-failed-${step.id}.png`);
await dumpFrames(page, 'test-results/stripe-checkout-dom.html', secrets);
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;
} finally {
page.off('response', onResponse);
}
const redirected = isSuccessRedirect(page.url());
await maskedScreenshot(page, `test-results/stripe-checkout-${redirected ? 'complete' : 'no-redirect'}.png`);
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 {
@@ -82,13 +82,6 @@ async function waitForCreditIncrease(
const PROD_URL = URLS.production.frontend;
const API_URL = URLS.production.api;
// The real card is typed into Stripe's page: traces (every typed value +
// X-Admin-Token headers), videos and Playwright's automatic screenshots would
// all capture it, and test-results/ is uploaded from a PUBLIC repo. The
// checkout helper takes its own input-masked screenshots instead.
// (Must be top-level: these options force a new worker, so describe-level use() fails to load.)
test.use({ trace: 'off', video: 'off', screenshot: 'off' });
test.describe('Real Credit Purchase Flow', () => {
test('purchase 1 credit via Stripe Checkout with referral discount', async ({ page, request }) => {
// ===== PREREQUISITES =====
-142
View File
@@ -1,142 +0,0 @@
#!/usr/bin/env node
// frontend/e2e/scripts/scrub-artifacts.mjs
/**
* Scrub secrets from Playwright output before it is uploaded as a GitHub
* Actions artifact. karaoke-gen is a PUBLIC repo, so any signed-in GitHub user
* can download run artifacts — anything left in test-results/ is published.
*
* What it does, recursively under each given path:
* - deletes Playwright traces (any *.zip — trace.zip, or <sha>.zip inside an
* HTML report): they hold every request header
* (X-Admin-Token) and every typed value, and can't be scrubbed in place;
* - deletes e2e-session-token.txt (a live bearer token for the test user);
* - with --drop-videos, deletes *.webm (videos of the Stripe page show the card);
* - in text files, replaces the literal values of known secret env vars and
* card-number-shaped digit runs; with --blank-inputs also blanks <input
* value="…"> attributes and ARIA-snapshot textbox values (error-context.md);
* - finally deletes any text file that still contains a secret value.
*
* Usage (CI): node e2e/scripts/scrub-artifacts.mjs [--drop-videos] [--blank-inputs] <path>...
* Secret values are read from the env vars in SECRET_ENV_VARS (unset ones are ignored).
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';
export const SECRET_ENV_VARS = [
'E2E_ADMIN_TOKEN',
'KARAOKE_ADMIN_TOKEN',
'KARAOKE_ACCESS_TOKEN',
'TESTMAIL_API_KEY',
'GEMINI_API_KEY',
'E2E_STRIPE_CARD_NUMBER',
'E2E_STRIPE_CARD_EXPIRY',
'E2E_STRIPE_CARD_CVC',
'E2E_SESSION_TOKEN',
'E2E_TEST_TOKEN',
'E2E_BYPASS_KEY',
];
// Everything else is treated as text and checked (unknown/no extension included).
const BINARY_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.webm', '.mp4', '.woff', '.woff2', '.ttf']);
const ALWAYS_DELETE = new Set(['e2e-session-token.txt']);
// Short values (CVC "123", "09/29") would scrub unrelated text everywhere;
// --blank-inputs covers them where they actually appear (form fields).
const MIN_LITERAL_LENGTH = 5;
/** Literal variants of a secret worth searching for (card numbers appear grouped in 4s in the UI). */
export function secretVariants(value) {
const v = (value || '').trim();
if (v.replace(/\s/g, '').length < MIN_LITERAL_LENGTH) return [];
const out = new Set([v]);
const digits = v.replace(/[\s-]/g, '');
if (/^\d{12,19}$/.test(digits)) {
out.add(digits);
out.add(digits.replace(/(\d{4})(?=\d)/g, '$1 '));
out.add(digits.replace(/(\d{4})(?=\d)/g, '$1-'));
}
return [...out];
}
export function scrubText(text, secretValues, { blankInputs = false } = {}) {
let out = text;
if (blankInputs) {
out = out
// HTML dumps: <input ... value="4242 ...">
.replace(/(<input\b[^>]*?\bvalue=)("[^"]*"|'[^']*')/gi, '$1"[redacted]"')
// Playwright error-context.md ARIA snapshot: `- textbox "Card number" [ref=e1]:` then `- text: 4242…` on the next line,
// or the value inline after the colon.
.replace(/^(\s*- (?:textbox|combobox|spinbutton|searchbox)\b[^\n]*?):[ \t]+\S.*$/gm, '$1: [value redacted]')
.replace(/^(\s*- (?:textbox|combobox|spinbutton|searchbox)\b[^\n]*:\n(?:\s*- \/placeholder:[^\n]*\n)?\s*- text:)[^\n]*$/gm, '$1 [value redacted]');
}
// Anything shaped like a card number (13-19 digits, optional space/dash separators)
out = out.replace(/\b(?:\d[ -]?){12,18}\d\b/g, '[redacted-digits]');
for (const secret of secretValues) {
for (const variant of secretVariants(secret)) out = out.split(variant).join('[redacted]');
}
return out;
}
export function containsSecret(text, secretValues) {
return secretValues.some((s) => secretVariants(s).some((v) => text.includes(v)));
}
function* walk(p) {
if (!fs.existsSync(p)) return;
const st = fs.statSync(p);
if (st.isFile()) {
yield p;
return;
}
for (const entry of fs.readdirSync(p)) yield* walk(path.join(p, entry));
}
export function scrubPaths(paths, secretValues, { dropVideos = false, blankInputs = false } = {}) {
const stats = { deleted: 0, scrubbed: 0, deletedUnscrubbable: 0 };
for (const root of paths) {
for (const file of walk(root)) {
const base = path.basename(file);
const ext = path.extname(file).toLowerCase();
if (ALWAYS_DELETE.has(base) || ext === '.zip' || (dropVideos && ext === '.webm')) {
fs.rmSync(file);
stats.deleted++;
continue;
}
if (BINARY_EXTENSIONS.has(ext)) continue;
const original = fs.readFileSync(file, 'utf8');
const cleaned = scrubText(original, secretValues, { blankInputs });
if (containsSecret(cleaned, secretValues)) {
fs.rmSync(file);
stats.deletedUnscrubbable++;
continue;
}
if (cleaned !== original) {
fs.writeFileSync(file, cleaned);
stats.scrubbed++;
}
}
}
return stats;
}
function main(argv) {
const flags = new Set(argv.filter((a) => a.startsWith('--')));
const paths = argv.filter((a) => !a.startsWith('--'));
if (!paths.length) {
console.error('usage: scrub-artifacts.mjs [--drop-videos] [--blank-inputs] <path>...');
process.exit(2);
}
const secretValues = SECRET_ENV_VARS.map((k) => process.env[k]).filter(Boolean);
const stats = scrubPaths(paths, secretValues, {
dropVideos: flags.has('--drop-videos'),
blankInputs: flags.has('--blank-inputs'),
});
console.log(
`scrub-artifacts: ${secretValues.length} secret value(s) checked; deleted ${stats.deleted} trace/token/video file(s), ` +
`scrubbed ${stats.scrubbed} text file(s), deleted ${stats.deletedUnscrubbable} unscrubbable file(s)`
);
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main(process.argv.slice(2));
}
@@ -7,7 +7,6 @@ import { completeStripeCheckout } from '../helpers/stripe-checkout';
import { emptyFile } from '../helpers/self-healing/learned-store';
import type { LearnedVariantsFile } from '../helpers/self-healing/types';
import {
CARD_DECLINED_RESPONSE,
CHECKOUT_URL,
ELEMENTS_FUTURE,
ELEMENTS_OCT2026,
@@ -157,34 +156,3 @@ test('without a planner, an unknown layout fails with a clear reason (determinis
await expect(completeStripeCheckout(page, { planner: null, learned: emptyFile() })).rejects.toThrow(/no LLM planner/);
expect(fs.existsSync('test-results/stripe-checkout-dom.html')).toBe(true);
});
test('declined card fails fast with STRIPE_CARD_DECLINED — no LLM calls, no second Pay click', async ({ page }) => {
await serveCheckout(page, ELEMENTS_OCT2026, CARD_DECLINED_RESPONSE);
let confirmCalls = 0;
page.on('request', (r) => {
if (r.url().endsWith('/confirm') && r.method() === 'POST') confirmCalls++;
});
await page.goto(CHECKOUT_URL);
const planner = new ScriptedPlanner([]);
const started = Date.now();
await expect(completeStripeCheckout(page, { planner, learned: emptyFile() })).rejects.toThrow(
/STRIPE_CARD_DECLINED: .*card_declined\/generic_decline.*Your card was declined/
);
// Without the abort the submit step would poll its full 90s verify, then hand off to the LLM.
expect(Date.now() - started).toBeLessThan(60_000);
expect(planner.inputs).toHaveLength(0);
expect(confirmCalls).toBe(1);
});
test('failure artifacts never contain typed card data', async ({ page }) => {
await serveCheckout(page, ELEMENTS_OCT2026, CARD_DECLINED_RESPONSE);
await page.goto(CHECKOUT_URL);
await expect(completeStripeCheckout(page, { planner: null, learned: emptyFile() })).rejects.toThrow(/STRIPE_CARD_DECLINED/);
const dom = fs.readFileSync('test-results/stripe-checkout-dom.html', 'utf8');
expect(dom).toContain('id="cardNumber"');
for (const value of [TEST_CARD.E2E_STRIPE_CARD_NUMBER, TEST_CARD.E2E_STRIPE_CARD_EXPIRY, TEST_CARD.E2E_STRIPE_CARD_CVC]) {
expect(dom).not.toContain(`value="${value}"`);
}
expect(dom).not.toContain(TEST_CARD.E2E_STRIPE_CARD_NUMBER);
});
+3 -30
View File
@@ -5,7 +5,6 @@ import type { LlmDecision, Planner, PlannerInput } from '../helpers/self-healing
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 CONFIRM_URL = 'https://api.stripe.com/v1/payment_pages/cs_test_fixture/confirm';
export const TEST_CARD = {
E2E_STRIPE_CARD_NUMBER: '4242424242424242',
@@ -63,39 +62,13 @@ const TOP_PAGE = `<!doctype html><html><body>
<iframe src="${ELEMENTS_URL}" style="width:600px;height:500px"></iframe>
<script>
window.addEventListener('message', (e) => {
// Like real Checkout: Pay → confirm API call → redirect only if it succeeded.
if (e.data === 'pay') {
fetch('${CONFIRM_URL}', { method: 'POST' }).then((r) => {
if (r.ok) window.location.href = '${SUCCESS_URL}';
});
}
if (e.data === 'pay') window.location.href = '${SUCCESS_URL}';
});
</script>
</body></html>`;
/** Stripe's confirm response for a declined card. */
export const CARD_DECLINED_RESPONSE = {
status: 402,
body: { error: { type: 'card_error', code: 'card_declined', decline_code: 'generic_decline', message: 'Your card was declined.' } },
};
/**
* Serve a fake Stripe Checkout (top page + Payment Element iframe) and our
* success page. `confirm` overrides the confirm API response (default 200).
*/
export async function serveCheckout(
page: Page,
elementsHtml: string,
confirm: { status: number; body: unknown } = { status: 200, body: { status: 'complete' } }
): Promise<void> {
await page.route(CONFIRM_URL, (r) =>
r.fulfill({
status: confirm.status,
contentType: 'application/json',
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify(confirm.body),
})
);
/** 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) =>
@@ -1,70 +0,0 @@
// frontend/e2e/self-healing/scrub-artifacts.spec.ts — tests for e2e/scripts/scrub-artifacts.mjs
import { test, expect } from '@playwright/test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
let scrub: any;
test.beforeAll(async () => {
scrub = await import('../scripts/scrub-artifacts.mjs');
});
const CARD = '4242424242424242';
const ADMIN = 'admin-token-0123456789abcdef';
const SECRETS = [CARD, ADMIN, '12/34', '123'];
test('scrubText removes literal secrets, grouped card numbers and PAN-shaped digits', () => {
const out = scrub.scrubText(`X-Admin-Token: ${ADMIN}\ncard 4242 4242 4242 4242 and 4242-4242-4242-4242 and 5555555555554444`, SECRETS);
expect(out).not.toContain(ADMIN);
expect(out).not.toMatch(/4242/);
expect(out).not.toContain('5555555555554444');
expect(out).toContain('X-Admin-Token: [redacted]');
});
test('short secrets (CVC/expiry) are not scrubbed globally, only in inputs with --blank-inputs', () => {
const text = [
'took 123ms',
'<input id="cardCvc" value="123"><input id="exp" value=\'12/34\'>',
'- textbox "Credit or debit card CVC/CVV" [ref=e162]:',
' - /placeholder: CVC',
' - text: "123"',
'- textbox "Expiration" [ref=e157]: 12 / 34',
].join('\n');
expect(scrub.scrubText(text, SECRETS)).toContain('value="123"');
const blanked = scrub.scrubText(text, SECRETS, { blankInputs: true });
expect(blanked).toContain('took 123ms');
expect(blanked).not.toContain('value="123"');
expect(blanked).not.toContain("12/34");
expect(blanked).toContain('- text: [value redacted]');
expect(blanked).toContain('- textbox "Expiration" [ref=e157]: [value redacted]');
});
test('scrubPaths deletes traces/tokens/videos, scrubs text, leaves images', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scrub-'));
const sub = path.join(dir, 'spec-chromium');
fs.mkdirSync(path.join(dir, 'report', 'data'), { recursive: true });
fs.mkdirSync(sub);
fs.writeFileSync(path.join(sub, 'trace.zip'), 'zip');
fs.writeFileSync(path.join(dir, 'report', 'data', 'abc123.zip'), 'zip');
fs.writeFileSync(path.join(sub, 'video.webm'), 'webm');
fs.writeFileSync(path.join(dir, 'e2e-session-token.txt'), 'tok');
fs.writeFileSync(path.join(sub, 'error-context.md'), `- textbox "Card number" [ref=e1]:\n - text: ${CARD}\n`);
fs.writeFileSync(path.join(sub, 'shot.png'), 'png');
const stats = scrub.scrubPaths([dir, path.join(dir, 'missing.log')], SECRETS, { dropVideos: true, blankInputs: true });
expect(fs.existsSync(path.join(sub, 'trace.zip'))).toBe(false);
expect(fs.existsSync(path.join(dir, 'report', 'data', 'abc123.zip'))).toBe(false);
expect(fs.existsSync(path.join(sub, 'video.webm'))).toBe(false);
expect(fs.existsSync(path.join(dir, 'e2e-session-token.txt'))).toBe(false);
expect(fs.existsSync(path.join(sub, 'shot.png'))).toBe(true);
expect(fs.readFileSync(path.join(sub, 'error-context.md'), 'utf8')).not.toContain(CARD);
expect(stats).toEqual({ deleted: 4, scrubbed: 1, deletedUnscrubbable: 0 });
});
test('videos are kept without --drop-videos', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scrub-'));
fs.writeFileSync(path.join(dir, 'video.webm'), 'webm');
scrub.scrubPaths([dir], SECRETS);
expect(fs.existsSync(path.join(dir, 'video.webm'))).toBe(true);
});
+1 -25
View File
@@ -4,7 +4,7 @@ import { frameUrlKey, substitutePlaceholders } from '../helpers/self-healing/act
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 { cardErrorReason, isCheckoutConfirmUrl, isSuccessRedirect } from '../helpers/stripe-checkout';
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' };
@@ -146,27 +146,3 @@ test('isSuccessRedirect accepts success/app URLs but not the cancel link', () =>
expect(isSuccessRedirect('https://gen.nomadkaraoke.com?cancelled=true')).toBe(false);
expect(isSuccessRedirect('https://checkout.stripe.com/c/pay/x')).toBe(false);
});
test.describe('card decline detection', () => {
test('card_error → abort reason with marker, codes and message', () => {
const reason = cardErrorReason(402, {
error: { type: 'card_error', code: 'card_declined', decline_code: 'generic_decline', message: 'Your card was declined.' },
});
expect(reason).toMatch(/^STRIPE_CARD_DECLINED: /);
expect(reason).toContain('HTTP 402, card_declined/generic_decline');
expect(reason).toContain('Your card was declined.');
});
test('non-card errors and junk bodies do not abort (the LLM may still fix the form)', () => {
expect(cardErrorReason(400, { error: { type: 'invalid_request_error', message: 'Missing postal code' } })).toBeNull();
expect(cardErrorReason(500, null)).toBeNull();
expect(cardErrorReason(402, 'not json')).toBeNull();
});
test('isCheckoutConfirmUrl matches only the payment page confirm endpoint', () => {
expect(isCheckoutConfirmUrl('https://api.stripe.com/v1/payment_pages/cs_live_abc/confirm')).toBe(true);
expect(isCheckoutConfirmUrl('https://api.stripe.com/v1/payment_pages/cs_live_abc/init')).toBe(false);
expect(isCheckoutConfirmUrl('https://api.stripe.com/v1/payment_methods')).toBe(false);
expect(isCheckoutConfirmUrl('not a url')).toBe(false);
});
});
+2 -4
View File
@@ -55,10 +55,8 @@ export default defineConfig({
// Base URL for production
baseURL: 'https://gen.nomadkaraoke.com',
// Traces record every request header (X-Admin-Token) and typed value, and
// CI uploads test-results/ as artifacts of a PUBLIC repo — so on CI they're
// off unless explicitly requested (E2E_TRACE=on, e.g. for a private re-run).
trace: (process.env.E2E_TRACE as 'on' | 'off' | 'retain-on-failure' | undefined) ?? (process.env.CI ? 'off' : 'on'),
// Collect trace always for debugging production issues
trace: 'on',
// Always capture screenshots
screenshot: 'on',
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.266.2"
version = "0.265.1"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
-101
View File
@@ -1,101 +0,0 @@
#!/usr/bin/env python3
"""
Review what the storage-retention process deleted (docs/STORAGE-RETENTION.md).
python scripts/storage_retention_report.py # list all runs (summaries)
python scripts/storage_retention_report.py RUN_ID # one run: totals by category + per job
python scripts/storage_retention_report.py --find jobs/abc/finals/x.mp4 # which run deleted it
python scripts/storage_retention_report.py --find abc123 # everything deleted for a job id
RUN_ID is the log name without extension, e.g. 20261004T103000Z-job_purge.
Uses Application Default Credentials (read-only access is enough).
"""
import argparse
import json
import sys
from collections import Counter, defaultdict
from google.cloud import storage
BUCKET = "karaoke-gen-storage-nomadkaraoke"
PREFIX = "storage-retention/deletion-logs/"
def _bucket():
return storage.Client(project="nomadkaraoke").bucket(BUCKET)
def _gib(n):
return f"{n / 2**30:.2f} GiB"
def list_runs(bucket):
for blob in sorted(bucket.list_blobs(prefix=PREFIX), key=lambda b: b.name):
if not blob.name.endswith(".summary.json"):
continue
s = json.loads(blob.download_as_text())
print(f"{s['run_id']:<40} jobs={s['jobs']:<5} objects={s['objects_deleted']:<6} "
f"{_gib(s['bytes_deleted']):>11} failures={s['failures']}")
def _lines(bucket, run_id):
blob = bucket.blob(f"{PREFIX}{run_id}.jsonl")
for line in blob.download_as_text().splitlines():
if line.strip():
yield json.loads(line)
def show_run(bucket, run_id):
by_cat, n_cat, by_job = Counter(), Counter(), defaultdict(Counter)
failures = []
for e in _lines(bucket, run_id):
if e["result"] == "deleted":
by_cat[e["category"]] += e["size_bytes"]
n_cat[e["category"]] += 1
by_job[e["job_id"]][e["category"]] += e["size_bytes"]
else:
failures.append(e)
print(f"Run {run_id}: {len(by_job)} jobs, {sum(n_cat.values())} objects, {_gib(sum(by_cat.values()))}")
for cat, size in by_cat.most_common():
print(f" {cat:<18} {n_cat[cat]:>6} objects {_gib(size):>11}")
print("Per job:")
for job_id, cats in sorted(by_job.items(), key=lambda kv: -sum(kv[1].values())):
print(f" {job_id:<16} {_gib(sum(cats.values())):>11} " + ", ".join(f"{c}={_gib(v)}" for c, v in cats.items()))
if failures:
print(f"Failures ({len(failures)}):")
for e in failures:
print(f" {e['path']}: {e.get('error')}")
def find(bucket, needle):
for blob in sorted(bucket.list_blobs(prefix=PREFIX), key=lambda b: b.name):
if not blob.name.endswith(".jsonl"):
continue
run_id = blob.name[len(PREFIX):-len(".jsonl")]
for e in _lines(bucket, run_id):
if needle == e["job_id"] or needle in e["path"]:
# Only offer a restore for objects actually deleted at a known
# generation (a failed delete may have a newer live version).
restore = ""
if e["result"] == "deleted" and e.get("generation"):
restore = (f" restore: gcloud storage cp --no-clobber 'gs://{BUCKET}/{e['path']}#{e['generation']}' "
f"'gs://{BUCKET}/{e['path']}'")
print(f"{run_id} {e['result']:<7} {e['path']} gen={e.get('generation')} {e['size_bytes']}B{restore}")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("run_id", nargs="?")
parser.add_argument("--find")
args = parser.parse_args()
bucket = _bucket()
if args.find:
find(bucket, args.find)
elif args.run_id:
show_run(bucket, args.run_id)
else:
list_runs(bucket)
if __name__ == "__main__":
sys.exit(main())