YTShortMakerArchx commited on
Commit
96d375d
·
verified ·
1 Parent(s): c877e71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +428 -259
app.py CHANGED
@@ -1,35 +1,11 @@
1
  """
2
- ArchNemix Controller Space v1.7
3
  ════════════════════════════════════════════════════════════════════════════════
4
- ADDED: Admin API Key bypass for rate limiting (ADMIN_KEY secret)
5
- ADDED: IP-based rate limiting (10 pipelines/hour per IP)
6
- ADDED: Admin analytics endpoints for tracking job success/failure rates
7
- ADDED: Detailed session logging with failure reasons
8
- ADDED: Real-time job monitoring with stage-level metrics
9
-
10
- Orchestrates 12 backend HuggingFace Spaces in a staged pipeline:
11
-
12
- TTS (×4) → Aligner/Qwen (×8) → FFmpeg (×1)
13
-
14
- Pipeline stages — user can re-run any stage independently:
15
- 1. TTS — text → audio (saved to HF dataset)
16
- 2. Align — audio → word timestamps (saved to HF dataset)
17
- 3. Video — audio + subtitles → MP4 (dataset first, FFmpeg fallback)
18
-
19
- Video storage strategy:
20
- - Primary: Upload to HF dataset (permanent, reliable)
21
- - Fallback: If dataset upload fails → use FFmpeg /tmp URLs (temporary, 1-hour TTL)
22
- - Frontend receives direct URLs (either dataset or FFmpeg, depending on upload success)
23
-
24
- HF Secrets required:
25
- APP_KEY — must match all FFmpeg spaces
26
- HF_TOKEN — write access to your pipeline dataset
27
- HF_DATASET — e.g. "YourOrg/archnemix-pipelines"
28
- HF_DATASET_2 — optional secondary dataset for dual-dataset mode
29
- ADMIN_KEY — optional: secret key that bypasses rate limiting
30
  """
31
 
32
-
33
  import os
34
  import uuid
35
  import asyncio
@@ -37,7 +13,7 @@ import logging
37
  from datetime import datetime, timedelta
38
  from typing import Dict, Any, Optional, Tuple, List
39
  from enum import Enum
40
- from dataclasses import dataclass, asdict
41
  from collections import defaultdict
42
 
43
  import httpx
@@ -69,8 +45,22 @@ FRONTEND_HEARTBEAT_GRACE = 45
69
  FFMPEG_QUEUE_DEPTH = 2
70
 
71
  # ═════════════════════════════════════════════════════════════════════════════
72
- # ADMIN ANALYTICS STORAGE - NEW IN v1.7
73
  # ═════════════════════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  @dataclass
75
  class JobAnalytics:
76
  """Track detailed analytics for a single job/pipeline"""
@@ -80,25 +70,34 @@ class JobAnalytics:
80
  is_admin: bool
81
  rate_limited: bool = False
82
 
83
- # Stage tracking
84
  tts_submitted_at: Optional[datetime] = None
85
  tts_completed_at: Optional[datetime] = None
86
  tts_status: str = "idle"
87
  tts_error: Optional[str] = None
88
- tts_backend: Optional[str] = None
 
 
 
89
 
90
  align_submitted_at: Optional[datetime] = None
91
  align_completed_at: Optional[datetime] = None
92
  align_status: str = "idle"
93
  align_error: Optional[str] = None
94
- align_backend: Optional[str] = None
 
 
 
95
 
96
  video_submitted_at: Optional[datetime] = None
97
  video_completed_at: Optional[datetime] = None
98
  video_status: str = "idle"
99
  video_error: Optional[str] = None
100
- video_backend: Optional[str] = None
 
 
101
  video_storage_method: Optional[str] = None # "dataset" or "ffmpeg_fallback"
 
102
 
103
  # Final outcome
104
  final_status: str = "pending" # "success", "failed", "cancelled"
@@ -110,11 +109,26 @@ class JobAnalytics:
110
  for key, value in d.items():
111
  if isinstance(value, datetime):
112
  d[key] = value.isoformat()
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  return d
114
 
115
  # Global analytics storage
116
  analytics_storage: Dict[str, JobAnalytics] = {} # pipeline_id -> analytics
117
  stage_failure_stats: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
 
 
118
 
119
  # Rate limiting storage
120
  rate_limit_storage: Dict[str, list[datetime]] = {}
@@ -203,18 +217,14 @@ def _get_client_ip(request: Request) -> str:
203
  2. X-Forwarded-For (standard proxy header)
204
  3. request.client.host (direct connection)
205
  """
206
- # Cloudflare passes real IP in CF-Connecting-IP
207
  cf_ip = request.headers.get("CF-Connecting-IP")
208
  if cf_ip:
209
  return cf_ip.strip()
210
 
211
- # Standard X-Forwarded-For (might be comma-separated list)
212
  forwarded = request.headers.get("X-Forwarded-For")
213
  if forwarded:
214
- # Take first IP in the chain (original client)
215
  return forwarded.split(",")[0].strip()
216
 
217
- # Fallback to direct connection IP
218
  return request.client.host if request.client else "unknown"
219
 
220
  def _anonymize_ip(ip: str) -> str:
@@ -225,23 +235,14 @@ def _anonymize_ip(ip: str) -> str:
225
  return "unknown"
226
 
227
  def _is_admin_request(request: Request) -> bool:
228
- """
229
- Check if request has admin credentials via API key header.
230
- Returns True if admin bypass should be applied.
231
- """
232
- # Check for admin key in headers
233
  admin_header = request.headers.get("X-Admin-Key")
234
  if ADMIN_KEY and admin_header and admin_header == ADMIN_KEY:
235
- logger.info("Rate limit bypassed for admin (API key)")
236
  return True
237
-
238
  return False
239
 
240
  def _cleanup_old_timestamps(ip: str) -> None:
241
- """
242
- Remove timestamps older than RATE_LIMIT_WINDOW_HOURS from storage.
243
- Called before checking rate limit to keep storage clean.
244
- """
245
  if ip not in rate_limit_storage:
246
  return
247
 
@@ -251,21 +252,11 @@ def _cleanup_old_timestamps(ip: str) -> None:
251
  if ts > cutoff
252
  ]
253
 
254
- # Remove IP entirely if no recent requests
255
  if not rate_limit_storage[ip]:
256
  del rate_limit_storage[ip]
257
 
258
  def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
259
- """
260
- Check if IP has exceeded rate limit.
261
-
262
- Returns:
263
- (allowed, current_count, seconds_until_oldest_expires)
264
-
265
- Examples:
266
- (True, 5, 1200) — allowed, 5 requests in last hour, oldest expires in 20 min
267
- (False, 10, 300) — blocked, 10 requests in last hour, retry in 5 min
268
- """
269
  _cleanup_old_timestamps(ip)
270
 
271
  if ip not in rate_limit_storage:
@@ -274,7 +265,6 @@ def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
274
  current_count = len(rate_limit_storage[ip])
275
 
276
  if current_count >= RATE_LIMIT_MAX_PER_HOUR:
277
- # Calculate when oldest request expires
278
  oldest_timestamp = min(rate_limit_storage[ip])
279
  expires_at = oldest_timestamp + timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
280
  seconds_until_expiry = int((expires_at - datetime.utcnow()).total_seconds())
@@ -284,32 +274,66 @@ def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
284
  return True, current_count, 0
285
 
286
  def _record_request(ip: str) -> None:
287
- """
288
- Record a new pipeline start request for this IP.
289
- Automatically cleans old timestamps first.
290
- """
291
  _cleanup_old_timestamps(ip)
292
 
293
  if ip not in rate_limit_storage:
294
  rate_limit_storage[ip] = []
295
 
296
  rate_limit_storage[ip].append(datetime.utcnow())
297
-
298
- logger.info(
299
- f"Rate limit: IP now has {len(rate_limit_storage[ip])} "
300
- f"request(s) in last {RATE_LIMIT_WINDOW_HOURS}h"
301
- )
302
 
303
  # =============================================================================
304
- # ANALYTICS HELPERS
305
  # =============================================================================
306
 
307
- def _record_failure(stage: str, error_type: str):
308
- """Record a stage failure for analytics"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  stage_failure_stats[stage][error_type] += 1
 
 
 
 
 
310
 
311
  def _get_analytics_summary() -> Dict:
312
- """Generate comprehensive analytics summary"""
313
  total_pipelines = len(analytics_storage)
314
  if total_pipelines == 0:
315
  return {
@@ -339,7 +363,7 @@ def _get_analytics_summary() -> Dict:
339
  align_failed = sum(1 for a in analytics_storage.values() if a.align_status == "failed")
340
  video_failed = sum(1 for a in analytics_storage.values() if a.video_status == "failed")
341
 
342
- # Calculate average processing times (for completed stages)
343
  tts_times = []
344
  for a in analytics_storage.values():
345
  if a.tts_submitted_at and a.tts_completed_at:
@@ -365,10 +389,51 @@ def _get_analytics_summary() -> Dict:
365
  "video": dict(stage_failure_stats.get("video", {})),
366
  }
367
 
368
- # Storage method stats (video)
369
  dataset_storage = sum(1 for a in analytics_storage.values() if a.video_storage_method == "dataset")
370
  ffmpeg_fallback = sum(1 for a in analytics_storage.values() if a.video_storage_method == "ffmpeg_fallback")
371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  return {
373
  "total_pipelines": total_pipelines,
374
  "successful": successful,
@@ -397,6 +462,7 @@ def _get_analytics_summary() -> Dict:
397
  "ffmpeg_fallback": ffmpeg_fallback,
398
  "fallback_rate": round(ffmpeg_fallback / (dataset_storage + ffmpeg_fallback) * 100, 1) if (dataset_storage + ffmpeg_fallback) > 0 else 0,
399
  },
 
400
  "time_range": {
401
  "oldest": min((a.created_at for a in analytics_storage.values()), default=datetime.utcnow()).isoformat(),
402
  "newest": max((a.created_at for a in analytics_storage.values()), default=datetime.utcnow()).isoformat(),
@@ -408,7 +474,6 @@ def _get_active_jobs() -> List[Dict]:
408
  active_jobs = []
409
 
410
  for pid, pipeline in pipelines.items():
411
- # Check if pipeline has any running stage
412
  running_stages = []
413
  for stage_name in [Stage.TTS, Stage.ALIGN, Stage.VIDEO]:
414
  s = pipeline["stages"][stage_name]
@@ -423,7 +488,6 @@ def _get_active_jobs() -> List[Dict]:
423
  })
424
 
425
  if running_stages:
426
- # Get analytics for this pipeline
427
  analytics = analytics_storage.get(pid)
428
  active_jobs.append({
429
  "pipeline_id": pid,
@@ -440,13 +504,8 @@ def _get_active_jobs() -> List[Dict]:
440
  # =============================================================================
441
 
442
  async def _rate_limit_cleanup_loop():
443
- """
444
- Background task that periodically cleans up old timestamps from all IPs.
445
- Runs every 5 minutes to keep memory usage low.
446
- """
447
  while True:
448
- await asyncio.sleep(300) # 5 minutes
449
-
450
  cutoff = datetime.utcnow() - timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
451
  cleaned_ips = 0
452
 
@@ -497,7 +556,7 @@ class VideoSubmitRequest(BaseModel):
497
 
498
  app = FastAPI(
499
  title="ArchNemix Controller v1",
500
- version="1.7.0",
501
  docs_url="/docs",
502
  redoc_url=None,
503
  )
@@ -544,7 +603,7 @@ def _safe_json(r: httpx.Response) -> Any:
544
  }
545
 
546
  # =============================================================================
547
- # STATUS CACHE
548
  # =============================================================================
549
 
550
  async def _check_one(url: str, stype: str) -> Dict[str, Any]:
@@ -566,8 +625,6 @@ async def _check_one(url: str, stype: str) -> Dict[str, Any]:
566
 
567
  d = r.json()
568
 
569
- # ALL space types now return running + waiting counts
570
- # FFmpeg, TTS, MFA, Qwen all use the same format after the queue update
571
  running = int(d.get("running", 0))
572
  waiting = int(d.get("waiting", 0))
573
  total = running + waiting
@@ -609,7 +666,6 @@ def _status_summary() -> Dict[str, Any]:
609
  """Enhanced status summary with queue info and separate MFA/Qwen stats"""
610
  out: Dict[str, Any] = {}
611
 
612
- # Process each space type
613
  for stype, urls in ALL_SPACES.items():
614
  spaces = []
615
  free = busy = 0
@@ -625,14 +681,11 @@ def _status_summary() -> Dict[str, Any]:
625
  "waiting": 0,
626
  })
627
 
628
- # Calculate available slots (each space has depth 2)
629
  running = c.get("running", 0)
630
  waiting = c.get("waiting", 0)
631
- depth = 2 # Each space can handle 2 jobs total (1 running + 1 waiting)
632
-
633
- # Available slots = depth - (running + waiting)
634
  available_slots = max(0, depth - (running + waiting))
635
- queue_available = waiting < 1 # Can queue if waiting < 1
636
 
637
  spaces.append({
638
  "url": url,
@@ -664,7 +717,6 @@ def _status_summary() -> Dict[str, Any]:
664
  "spaces": spaces,
665
  }
666
 
667
- # Separate MFA and Qwen stats
668
  mfa_free = out["mfa"]["free"]
669
  mfa_total = out["mfa"]["total"]
670
  mfa_slots = out["mfa"]["total_slots"]
@@ -693,7 +745,6 @@ def _status_summary() -> Dict[str, Any]:
693
  "total_queue": qwen_queue,
694
  }
695
 
696
- # Combined aligners (for backward compatibility)
697
  aligner_free = mfa_free + qwen_free
698
  aligner_total = mfa_total + qwen_total
699
  aligner_slots = mfa_slots + qwen_slots
@@ -711,7 +762,7 @@ def _status_summary() -> Dict[str, Any]:
711
  return out
712
 
713
  # =============================================================================
714
- # SPACE PICKER
715
  # =============================================================================
716
 
717
  def _release_reservation(url: str):
@@ -723,13 +774,7 @@ async def _pick(stype: str) -> Optional[str]:
723
  urls = ALL_SPACES[stype]
724
  best_url = None
725
  best_load = float("inf")
726
-
727
- # Per-space depth: how many jobs (running + waiting) are allowed on one space
728
- # TTS: 4 spaces × depth 2 = 8 total slots
729
- # MFA: 4 spaces × depth 2 = 8 total slots ┐ aligner pool = 16
730
- # Qwen: 4 spaces × depth 2 = 8 total slots ┘
731
- # FFmpeg: 1 space × depth 2 = 2 total slots
732
- depth = FFMPEG_QUEUE_DEPTH # all types use depth 2
733
 
734
  for url in urls:
735
  c = status_cache.get(url, {})
@@ -745,7 +790,6 @@ async def _pick(stype: str) -> Optional[str]:
745
  best_load = load
746
  best_url = url
747
 
748
- # live fallback if cache gave us nothing usable
749
  if best_url is None:
750
  results = await asyncio.gather(*[_check_one(url, stype) for url in urls])
751
  for r in results:
@@ -766,7 +810,6 @@ async def _pick(stype: str) -> Optional[str]:
766
  best_load = load
767
  best_url = url
768
 
769
- # optimistic reservation
770
  if best_url and best_url in status_cache:
771
  c = status_cache[best_url]
772
  c["_reserved"] = c.get("_reserved", 0) + 1
@@ -811,12 +854,11 @@ def _new_pipeline(config: PipelineStartRequest) -> Dict[str, Any]:
811
  Stage.VIDEO: _blank_stage(),
812
  },
813
  "assets": {
814
- "audio_url": None, # HF dataset
815
- "timestamps_url": None, # HF dataset
816
- "video_url": None, # HF dataset (permanent backup)
817
- # ── FFmpeg /tmp URLs (fast, but deleted after 1 hour) ──────────────
818
- "video_download_url": None, # direct download URL from FFmpeg space
819
- "video_stream_url": None, # direct stream URL from FFmpeg space
820
  },
821
  }
822
 
@@ -861,7 +903,7 @@ def _client_id(pid: str) -> str:
861
  return f"ctrl_{pid[:10]}"
862
 
863
  # =============================================================================
864
- # BACKEND JOB POLLER
865
  # =============================================================================
866
 
867
  async def _poll_backend_stage(p: Dict, stage: str) -> None:
@@ -872,6 +914,7 @@ async def _poll_backend_stage(p: Dict, stage: str) -> None:
872
  url = s["backend_url"]
873
  jid = s["backend_job_id"]
874
  pid = p["pipeline_id"]
 
875
 
876
  try:
877
  r = await http().get(
@@ -879,33 +922,64 @@ async def _poll_backend_stage(p: Dict, stage: str) -> None:
879
  params={"slim": "true"} if stage != Stage.VIDEO else {},
880
  timeout=HTTP_TIMEOUT,
881
  )
 
 
 
 
 
 
 
 
 
 
 
 
882
  except Exception as e:
883
  logger.warning(f"Poll error {pid}/{stage}: {e}")
 
 
 
 
 
884
  return
885
 
886
  if r.status_code == 404:
887
  s["status"] = StageStatus.FAILED
888
- s["error"] = "Job expired on backend (5 min TTL). Please re-run this step."
 
 
 
 
 
 
889
  return
890
 
891
- data = _safe_json(r)
892
  bk_status = data.get("status", "unknown")
893
 
894
  if bk_status == "completed":
895
  await _finalise_stage(p, stage, url, jid, data)
896
 
897
  elif bk_status in ("failed", "abandoned"):
898
- s["status"] = StageStatus.FAILED
899
- s["error"] = data.get("error", bk_status)
 
900
  s["completed_at"] = datetime.utcnow().isoformat()
 
 
 
 
 
 
 
901
 
902
  elif bk_status in ("running", "queued", "processing"):
903
- s["progress"] = data.get("progress", s.get("progress", 0))
904
- s["chunks_done"] = data.get("chunks_done", s.get("chunks_done", 0))
905
- s["chunks_total"] = data.get("chunks_total", s.get("chunks_total", 0))
906
- s["elapsed_s"] = data.get("elapsed_s", s.get("elapsed_s"))
907
  s["estimated_remaining_s"] = data.get("estimated_remaining_s", s.get("estimated_remaining_s"))
908
- s["message"] = data.get("message", s.get("message", ""))
909
  if "encode_stats" in data:
910
  s["encode_stats"] = data["encode_stats"]
911
 
@@ -938,7 +1012,6 @@ async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Di
938
  p["assets"]["audio_url"] = audio_url
939
  p["assets"]["timestamps_url"] = ts_url
940
 
941
- # Update analytics
942
  if analytics:
943
  analytics.tts_completed_at = datetime.utcnow()
944
  analytics.tts_status = "done"
@@ -955,7 +1028,6 @@ async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Di
955
  ts_url = await store().save(pid, "align_timestamps.json", ts_bytes, content_type="application/json")
956
  p["assets"]["timestamps_url"] = ts_url
957
 
958
- # Update analytics
959
  if analytics:
960
  analytics.align_completed_at = datetime.utcnow()
961
  analytics.align_status = "done"
@@ -963,9 +1035,7 @@ async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Di
963
 
964
  logger.info(f"Pipeline {pid[:8]} Align done → {ts_url}")
965
 
966
- # ── VIDEO — TRY DATASET FIRST, FALLBACK TO FFMPEG ────────────────────────
967
  elif stage == Stage.VIDEO:
968
- # Get the direct FFmpeg URLs as fallback
969
  raw_download = slim_data.get("download_url", f"/download/{jid}")
970
  raw_stream = slim_data.get("stream_url", f"/stream/{jid}")
971
 
@@ -978,14 +1048,12 @@ async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Di
978
  else f"{url}{raw_stream}"
979
  )
980
 
981
- # Try to upload to dataset first
982
  dataset_success = False
983
  video_dataset_url = None
984
 
985
  logger.info(f"Pipeline {pid[:8]}: Attempting to upload video to HF dataset...")
986
 
987
  try:
988
- # Download video from FFmpeg space
989
  headers = {"X-APP-KEY": APP_KEY} if APP_KEY else {}
990
  video_response = await http().get(
991
  ffmpeg_download_url,
@@ -996,7 +1064,6 @@ async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Di
996
  video_response.raise_for_status()
997
  video_bytes = video_response.content
998
 
999
- # Save to HF dataset
1000
  video_dataset_url = await store().save(
1001
  pid,
1002
  "video.mp4",
@@ -1006,88 +1073,71 @@ async def _finalise_stage(p: Dict, stage: str, url: str, jid: str, slim_data: Di
1006
 
1007
  dataset_success = True
1008
  size_mb = len(video_bytes) / 1024 / 1024
1009
- logger.info(
1010
- f"Pipeline {pid[:8]} Video uploaded to dataset successfully "
1011
- f"({size_mb:.1f}MB) → {video_dataset_url}"
1012
- )
1013
 
1014
  except Exception as dataset_err:
1015
- logger.warning(
1016
- f"Pipeline {pid[:8]}: Dataset upload failed: {dataset_err}. "
1017
- f"Falling back to FFmpeg URLs."
1018
- )
1019
  dataset_success = False
1020
 
1021
- # Decide which URLs to return to frontend
1022
  if dataset_success and video_dataset_url:
1023
- # SUCCESS: Use dataset URLs (permanent, reliable)
1024
  p["assets"]["video_url"] = video_dataset_url
1025
  p["assets"]["video_download_url"] = video_dataset_url
1026
  p["assets"]["video_stream_url"] = video_dataset_url
1027
  if analytics:
1028
  analytics.video_storage_method = "dataset"
1029
- logger.info(
1030
- f"Pipeline {pid[:8]} Video done → Dataset URL: {video_dataset_url}"
1031
- )
1032
  else:
1033
- # FALLBACK: Use FFmpeg URLs (temporary, will be deleted in 1 hour)
1034
  p["assets"]["video_url"] = None
1035
  p["assets"]["video_download_url"] = ffmpeg_download_url
1036
  p["assets"]["video_stream_url"] = ffmpeg_stream_url
1037
  if analytics:
1038
  analytics.video_storage_method = "ffmpeg_fallback"
1039
- logger.info(
1040
- f"Pipeline {pid[:8]} Video done → FFmpeg URLs (temporary): "
1041
- f"download={ffmpeg_download_url} stream={ffmpeg_stream_url}"
1042
- )
1043
 
1044
- # Update analytics
1045
  if analytics:
1046
  analytics.video_completed_at = datetime.utcnow()
1047
  analytics.video_status = "done"
1048
  analytics.video_error = None
1049
  analytics.final_status = "success"
1050
  analytics.completed_at = datetime.utcnow()
1051
- # ─────────────────────────────────────────────────────────────────────
1052
-
1053
- s["status"] = StageStatus.DONE
1054
  s["completed_at"] = datetime.utcnow().isoformat()
1055
 
 
 
 
 
 
 
 
 
 
 
1056
  except Exception as e:
1057
  logger.exception(f"Finalise failed {pid}/{stage}")
1058
  s["status"] = StageStatus.FAILED
1059
- s["error"] = f"Failed to save result: {e}"
1060
 
1061
- # Record failure in analytics
1062
  if analytics:
1063
- if stage == Stage.TTS:
1064
- analytics.tts_status = "failed"
1065
- analytics.tts_error = str(e)
1066
- analytics.final_status = "failed"
1067
- analytics.completed_at = datetime.utcnow()
1068
- _record_failure("tts", "save_failed")
1069
- elif stage == Stage.ALIGN:
1070
- analytics.align_status = "failed"
1071
- analytics.align_error = str(e)
1072
- analytics.final_status = "failed"
1073
- analytics.completed_at = datetime.utcnow()
1074
- _record_failure("align", "save_failed")
1075
- elif stage == Stage.VIDEO:
1076
- analytics.video_status = "failed"
1077
- analytics.video_error = str(e)
1078
- analytics.final_status = "failed"
1079
- analytics.completed_at = datetime.utcnow()
1080
- _record_failure("video", "save_failed")
1081
 
1082
  # =============================================================================
1083
- # STAGE SUBMISSION HELPERS
1084
  # =============================================================================
1085
 
1086
  async def _submit_tts(p: Dict, text: str, voice: str, rate: float) -> Optional[JSONResponse]:
1087
  pid = p["pipeline_id"]
 
1088
 
1089
  backend_url = await _pick("tts")
1090
  if not backend_url:
 
 
 
 
 
1091
  return JSONResponse(status_code=503, content={
1092
  "error": "all_tts_busy",
1093
  "detail": "All 4 TTS spaces are currently busy. Try again in ~20s.",
@@ -1101,35 +1151,61 @@ async def _submit_tts(p: Dict, text: str, voice: str, rate: float) -> Optional[J
1101
  json={"text": text, "voice": voice, "rate": rate, "client_id": cid},
1102
  timeout=HTTP_TIMEOUT,
1103
  )
 
 
 
 
 
 
 
1104
  except httpx.RequestError as e:
 
 
 
 
 
1105
  raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
1106
 
1107
  if r.status_code == 503:
 
 
 
 
 
 
1108
  return JSONResponse(status_code=503, content={
1109
  "error": "all_tts_busy",
1110
  "detail": "TTS space became busy just before submission. Retry.",
1111
  "retry_after": 15,
1112
  })
1113
  if r.status_code != 200:
1114
- raise HTTPException(r.status_code, _safe_json(r))
 
 
 
 
 
 
 
 
1115
 
1116
  data = r.json()
1117
  jid = data["job_id"]
1118
 
1119
  s = p["stages"][Stage.TTS]
1120
- s["status"] = StageStatus.RUNNING
1121
- s["backend_url"] = backend_url
1122
  s["backend_job_id"] = jid
1123
- s["backend_type"] = "tts"
1124
- s["submitted_at"] = datetime.utcnow().isoformat()
1125
- s["error"] = None
1126
 
1127
- # Update analytics
1128
- analytics = analytics_storage.get(pid)
1129
  if analytics:
1130
  analytics.tts_submitted_at = datetime.utcnow()
1131
  analytics.tts_status = "running"
1132
  analytics.tts_backend = backend_url
 
 
1133
 
1134
  return None
1135
 
@@ -1141,9 +1217,15 @@ async def _submit_align(
1141
  aligner_type: str = "mfa"
1142
  ) -> str:
1143
  pid = p["pipeline_id"]
 
1144
 
1145
  audio_url = p["assets"].get("audio_url")
1146
  if not audio_url:
 
 
 
 
 
1147
  raise HTTPException(400, {
1148
  "error": "no_audio",
1149
  "detail": "TTS stage has not completed yet. Complete TTS first.",
@@ -1160,9 +1242,14 @@ async def _submit_align(
1160
  except HTTPException:
1161
  raise
1162
  except Exception as e:
 
 
 
 
 
1163
  raise HTTPException(503, {"error": "audio_fetch_failed", "detail": str(e)})
1164
 
1165
- backend_url = None
1166
  backend_type = None
1167
 
1168
  if aligner_type == "qwen":
@@ -1185,6 +1272,11 @@ async def _submit_align(
1185
  logger.info(f"Pipeline {pid[:8]}: MFA requested but full, using Qwen fallback")
1186
 
1187
  if not backend_url:
 
 
 
 
 
1188
  raise HTTPException(503, {
1189
  "error": "all_aligners_busy",
1190
  "detail": "All MFA and Qwen spaces are currently busy. Try again in ~30s.",
@@ -1204,35 +1296,61 @@ async def _submit_align(
1204
  },
1205
  timeout=HTTP_TIMEOUT,
1206
  )
 
 
 
 
 
 
 
1207
  except httpx.RequestError as e:
 
 
 
 
 
1208
  raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
1209
 
1210
  if r.status_code == 503:
 
 
 
 
 
 
1211
  raise HTTPException(503, {
1212
  "error": "aligner_busy",
1213
  "detail": "Aligner became busy just before submission. Retry.",
1214
  "retry_after": 20,
1215
  })
1216
  if r.status_code != 200:
1217
- raise HTTPException(r.status_code, _safe_json(r))
 
 
 
 
 
 
 
 
1218
 
1219
  data = r.json()
1220
  jid = data["job_id"]
1221
 
1222
  s = p["stages"][Stage.ALIGN]
1223
- s["status"] = StageStatus.RUNNING
1224
- s["backend_url"] = backend_url
1225
  s["backend_job_id"] = jid
1226
- s["backend_type"] = backend_type
1227
- s["submitted_at"] = datetime.utcnow().isoformat()
1228
- s["error"] = None
1229
 
1230
- # Update analytics
1231
- analytics = analytics_storage.get(pid)
1232
  if analytics:
1233
  analytics.align_submitted_at = datetime.utcnow()
1234
  analytics.align_status = "running"
1235
  analytics.align_backend = backend_url
 
 
1236
 
1237
  logger.info(f"Pipeline {pid[:8]}: Alignment submitted to {backend_type.upper()} ({backend_url})")
1238
  return backend_type
@@ -1240,15 +1358,26 @@ async def _submit_align(
1240
 
1241
  async def _submit_video(p: Dict, subtitles_ass: str, background: str, duration: Optional[float]) -> Optional[JSONResponse]:
1242
  pid = p["pipeline_id"]
 
1243
 
1244
  if not APP_KEY:
 
 
 
 
 
1245
  raise HTTPException(500, {
1246
- "error": "controller_misconfigured",
1247
  "detail": "APP_KEY secret not set on controller space.",
1248
  })
1249
 
1250
  audio_url = p["assets"].get("audio_url")
1251
  if not audio_url:
 
 
 
 
 
1252
  raise HTTPException(400, {"error": "no_audio", "detail": "TTS not completed yet."})
1253
 
1254
  try:
@@ -1262,10 +1391,20 @@ async def _submit_video(p: Dict, subtitles_ass: str, background: str, duration:
1262
  except HTTPException:
1263
  raise
1264
  except Exception as e:
 
 
 
 
 
1265
  raise HTTPException(503, {"error": "audio_fetch_failed", "detail": str(e)})
1266
 
1267
  backend_url = await _pick("ffmpeg")
1268
  if not backend_url:
 
 
 
 
 
1269
  return JSONResponse(status_code=503, content={
1270
  "error": "all_video_busy",
1271
  "detail": "All video spaces are busy. Try again in ~2 min.",
@@ -1285,35 +1424,61 @@ async def _submit_video(p: Dict, subtitles_ass: str, background: str, duration:
1285
  headers={"X-APP-KEY": APP_KEY, "X-Client-ID": cid},
1286
  timeout=30.0,
1287
  )
 
 
 
 
 
 
 
1288
  except httpx.RequestError as e:
 
 
 
 
 
1289
  raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
1290
 
1291
  if r.status_code == 503:
 
 
 
 
 
 
1292
  return JSONResponse(status_code=503, content={
1293
  "error": "all_video_busy",
1294
  "detail": "Video space became busy just before submission. Retry.",
1295
  "retry_after": 60,
1296
  })
1297
  if r.status_code not in (200, 201):
1298
- raise HTTPException(r.status_code, _safe_json(r))
 
 
 
 
 
 
 
 
1299
 
1300
  data = r.json()
1301
  jid = data["job_id"]
1302
 
1303
  s = p["stages"][Stage.VIDEO]
1304
- s["status"] = StageStatus.RUNNING
1305
- s["backend_url"] = backend_url
1306
  s["backend_job_id"] = jid
1307
- s["backend_type"] = "ffmpeg"
1308
- s["submitted_at"] = datetime.utcnow().isoformat()
1309
- s["error"] = None
1310
 
1311
- # Update analytics
1312
- analytics = analytics_storage.get(pid)
1313
  if analytics:
1314
  analytics.video_submitted_at = datetime.utcnow()
1315
  analytics.video_status = "running"
1316
  analytics.video_backend = backend_url
 
 
1317
 
1318
  return None
1319
 
@@ -1331,11 +1496,9 @@ def _pipeline_view(p: Dict) -> Dict:
1331
  "error": s["error"],
1332
  }
1333
  if s["status"] == StageStatus.RUNNING:
1334
- # ── Add job verification fields ──
1335
  stage_out["backend_url"] = s.get("backend_url")
1336
  stage_out["backend_job_id"] = s.get("backend_job_id")
1337
  stage_out["backend_type"] = s.get("backend_type")
1338
- # ── Existing progress fields ──
1339
  stage_out["progress"] = s.get("progress", 0)
1340
  stage_out["chunks_done"] = s.get("chunks_done", 0)
1341
  stage_out["chunks_total"] = s.get("chunks_total", 0)
@@ -1421,7 +1584,6 @@ async def _check_dataset_reachability(repo: str, name: str) -> bool:
1421
 
1422
  api = HfApi(token=HF_TOKEN)
1423
 
1424
- # Try to read the dataset info
1425
  try:
1426
  info = api.repo_info(repo_id=repo, repo_type="dataset")
1427
  logger.info(f"Dataset {name} ({repo}): ✓ readable - found {info.id}")
@@ -1429,7 +1591,6 @@ async def _check_dataset_reachability(repo: str, name: str) -> bool:
1429
  logger.error(f"Dataset {name} ({repo}): ✗ NOT readable - {e}")
1430
  return False
1431
 
1432
- # Try a test write (upload a tiny file then delete it)
1433
  test_path = "_health_check.txt"
1434
  test_data = b"health check"
1435
 
@@ -1443,7 +1604,6 @@ async def _check_dataset_reachability(repo: str, name: str) -> bool:
1443
  )
1444
  logger.info(f"Dataset {name} ({repo}): ✓ writable - test upload succeeded")
1445
 
1446
- # Clean up the test file
1447
  try:
1448
  api.delete_file(
1449
  path_in_repo=test_path,
@@ -1522,6 +1682,14 @@ async def _frontend_heartbeat_watchdog():
1522
 
1523
  s["status"] = StageStatus.FAILED
1524
  s["error"] = "Cancelled — client disconnected"
 
 
 
 
 
 
 
 
1525
 
1526
  # =============================================================================
1527
  # STARTUP / SHUTDOWN
@@ -1531,17 +1699,11 @@ async def _frontend_heartbeat_watchdog():
1531
  async def startup():
1532
  global _http, _store
1533
 
1534
- # ══════════════════════════════════════════════════════════════════════════
1535
- # ADMIN KEY CONFIGURATION
1536
- # ══════════════════════════════════════════════════════════════════════════
1537
  if ADMIN_KEY:
1538
  logger.info(f"✓ ADMIN_KEY configured (rate limit bypass active for key holders)")
1539
  else:
1540
  logger.info("ℹ ADMIN_KEY not configured (rate limiting active for all users)")
1541
 
1542
- # ══════════════════════════════════════════════════════════════════════════
1543
- # DATASET REACHABILITY CHECK — FIRST THING AT STARTUP
1544
- # ══════════════════════════════════════════════════════════════════════════
1545
  logger.info("=" * 80)
1546
  logger.info("DATASET REACHABILITY CHECK (at space build/startup)")
1547
  logger.info("=" * 80)
@@ -1585,7 +1747,6 @@ async def startup():
1585
  logger.info("MODE: ✓ SINGLE-DATASET — Only primary dataset configured")
1586
  logger.info("=" * 80)
1587
 
1588
- # ── Now initialize HTTP client and DatasetStore ───────────────────────────
1589
  logger.info("Initializing HTTP client and DatasetStore...")
1590
  _http = httpx.AsyncClient(timeout=HTTP_TIMEOUT)
1591
  _store = DatasetStore(hf_token=HF_TOKEN, dataset_repo=HF_DATASET, dataset_repo_2=HF_DATASET_2)
@@ -1609,9 +1770,9 @@ async def startup():
1609
  logger.info(f"RATE LIMITING: {RATE_LIMIT_MAX_PER_HOUR} pipelines per IP per {RATE_LIMIT_WINDOW_HOURS}h")
1610
  if ADMIN_KEY:
1611
  logger.info("ADMIN BYPASS: Active — admin key holders bypass rate limits")
1612
- logger.info("ANALYTICS: Active — tracking job success/failure rates")
1613
  logger.info("=" * 80)
1614
- logger.info("ArchNemix Controller v1.7 ready (admin analytics + rate limiting + video dataset-first with FFmpeg fallback).")
1615
 
1616
 
1617
  @app.on_event("shutdown")
@@ -1627,7 +1788,7 @@ async def shutdown():
1627
  async def root():
1628
  return {
1629
  "name": "ArchNemix Controller",
1630
- "version": "1.7.0",
1631
  "endpoints": {
1632
  "POST /pipeline/start": "Start new pipeline (rate limited: 10/hour per IP, admin key bypass available)",
1633
  "GET /pipeline/{id}": "Poll pipeline state + per-stage status",
@@ -1644,28 +1805,27 @@ async def root():
1644
  "GET /debug/dataset-routing/{id}": "Debug dataset routing logic",
1645
  "GET /debug/rate-limit-status": "Check rate limit status for current IP",
1646
  # Admin endpoints (require X-Admin-Key header)
1647
- "GET /admin/analytics": "📊 Comprehensive analytics summary (admin only)",
1648
- "GET /admin/active-jobs": "🔄 List all currently running jobs (admin only)",
1649
- "GET /admin/failures": "❌ Detailed failure breakdown (admin only)",
1650
- "GET /admin/rate-limit-status": "⏱️ Rate limit status for all IPs (admin only)",
1651
- "GET /admin/pipeline/{id}/analytics": "🔍 Analytics for specific pipeline (admin only)",
1652
- "GET /admin/clear-analytics": "🗑️ Clear all analytics data (admin only)",
1653
  },
1654
  "rate_limit": f"{RATE_LIMIT_MAX_PER_HOUR} pipelines per {RATE_LIMIT_WINDOW_HOURS} hour(s) per IP",
1655
  "admin_bypass": bool(ADMIN_KEY),
1656
  "analytics_enabled": True,
 
1657
  "video_storage": "Dataset first (permanent), fallback to FFmpeg /tmp URLs (1-hour TTL) if upload fails",
1658
  }
1659
 
1660
 
1661
  @app.post("/pipeline/start")
1662
  async def start_pipeline(req: PipelineStartRequest, request: Request):
1663
- # STEP 1: CHECK RATE LIMIT (BEFORE ANYTHING ELSE)
1664
  client_ip = _get_client_ip(request)
1665
  is_admin = _is_admin_request(request)
1666
  anonymized_ip = _anonymize_ip(client_ip)
1667
 
1668
- # Admin bypass - skip all rate limit checks
1669
  rate_limited = False
1670
  if not is_admin:
1671
  allowed, current_count, retry_after = _check_rate_limit(client_ip)
@@ -1678,7 +1838,6 @@ async def start_pipeline(req: PipelineStartRequest, request: Request):
1678
  "retry_after": retry_after,
1679
  })
1680
 
1681
- # STEP 2: CHECK GLOBAL CAPACITY
1682
  active_count = sum(
1683
  1 for p in pipelines.values()
1684
  if any(
@@ -1693,12 +1852,10 @@ async def start_pipeline(req: PipelineStartRequest, request: Request):
1693
  "retry_after": 120,
1694
  })
1695
 
1696
- # STEP 3: CREATE PIPELINE AND ANALYTICS
1697
  p = _new_pipeline(req)
1698
  pid = p["pipeline_id"]
1699
  pipelines[pid] = p
1700
 
1701
- # Create analytics record
1702
  analytics = JobAnalytics(
1703
  pipeline_id=pid,
1704
  created_at=datetime.utcnow(),
@@ -1708,19 +1865,19 @@ async def start_pipeline(req: PipelineStartRequest, request: Request):
1708
  )
1709
  analytics_storage[pid] = analytics
1710
 
1711
- # Record this request for rate limiting (skip for admin)
1712
  if not is_admin and not rate_limited:
1713
  _record_request(client_ip)
1714
 
1715
- # STEP 4: SUBMIT TTS JOB
1716
  err = await _submit_tts(p, req.text, req.voice, req.rate)
1717
  if err:
1718
- # Record TTS failure
1719
  analytics.tts_status = "failed"
1720
  analytics.tts_error = "All TTS spaces busy at submission"
1721
  analytics.final_status = "failed"
1722
  analytics.completed_at = datetime.utcnow()
1723
- _record_failure("tts", "all_spaces_busy")
 
 
 
1724
 
1725
  p["stages"][Stage.TTS]["status"] = StageStatus.FAILED
1726
  p["stages"][Stage.TTS]["error"] = "All TTS spaces busy at submission time."
@@ -1920,7 +2077,6 @@ async def finalize_pipeline(pipeline_id: str):
1920
  p["finalized"] = True
1921
  pipeline_heartbeats.pop(pipeline_id, None)
1922
 
1923
- # Delete intermediates (audio + timestamps) but keep video.mp4 in dataset
1924
  asyncio.create_task(_run_delete_intermediates(pipeline_id))
1925
 
1926
  logger.info(f"Pipeline {pipeline_id[:8]} finalized (video kept in dataset).")
@@ -1945,7 +2101,6 @@ async def _run_delete_intermediates(pipeline_id: str):
1945
  async def get_status():
1946
  summary = _status_summary()
1947
 
1948
- # Add human-readable descriptions
1949
  return {
1950
  "tts": {
1951
  **summary["tts"],
@@ -2124,21 +2279,11 @@ async def cancel_stage(pipeline_id: str, stage: str, request: Request):
2124
  s["status"] = StageStatus.FAILED
2125
  s["error"] = "Cancelled by user"
2126
 
2127
- # Update analytics
2128
  if analytics:
2129
- if stage == Stage.TTS:
2130
- analytics.tts_status = "failed"
2131
- analytics.tts_error = "Cancelled by user"
2132
- elif stage == Stage.ALIGN:
2133
- analytics.align_status = "failed"
2134
- analytics.align_error = "Cancelled by user"
2135
- elif stage == Stage.VIDEO:
2136
- analytics.video_status = "failed"
2137
- analytics.video_error = "Cancelled by user"
2138
-
2139
- analytics.final_status = "cancelled"
2140
- analytics.completed_at = datetime.utcnow()
2141
- _record_failure(stage, "user_cancelled")
2142
 
2143
  return {
2144
  "ok": True,
@@ -2149,12 +2294,12 @@ async def cancel_stage(pipeline_id: str, stage: str, request: Request):
2149
  }
2150
 
2151
  # =============================================================================
2152
- # ADMIN ANALYTICS ENDPOINTS
2153
  # =============================================================================
2154
 
2155
  @app.get("/admin/analytics")
2156
  async def admin_analytics(request: Request):
2157
- """Get comprehensive analytics summary (admin only)"""
2158
  if not _is_admin_request(request):
2159
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2160
 
@@ -2162,7 +2307,7 @@ async def admin_analytics(request: Request):
2162
 
2163
  @app.get("/admin/active-jobs")
2164
  async def admin_active_jobs(request: Request):
2165
- """Get all currently running jobs with details (admin only)"""
2166
  if not _is_admin_request(request):
2167
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2168
 
@@ -2176,7 +2321,7 @@ async def admin_active_jobs(request: Request):
2176
 
2177
  @app.get("/admin/pipeline/{pipeline_id}/analytics")
2178
  async def admin_pipeline_analytics(pipeline_id: str, request: Request):
2179
- """Get detailed analytics for a specific pipeline (admin only)"""
2180
  if not _is_admin_request(request):
2181
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2182
 
@@ -2188,37 +2333,61 @@ async def admin_pipeline_analytics(pipeline_id: str, request: Request):
2188
 
2189
  @app.get("/admin/failures")
2190
  async def admin_failures(request: Request):
2191
- """Get detailed failure breakdown (admin only)"""
2192
  if not _is_admin_request(request):
2193
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2194
 
2195
  failures = []
2196
  for pid, analytics in analytics_storage.items():
2197
  if analytics.final_status == "failed":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2198
  failures.append({
2199
  "pipeline_id": pid,
2200
  "created_at": analytics.created_at.isoformat(),
2201
  "user_ip": analytics.user_ip,
2202
  "is_admin": analytics.is_admin,
2203
- "tts_error": analytics.tts_error,
2204
- "align_error": analytics.align_error,
2205
- "video_error": analytics.video_error,
2206
- "failed_stage": next(
2207
- (s for s in ["tts", "align", "video"]
2208
- if getattr(analytics, f"{s}_status") == "failed"),
2209
- "unknown"
2210
- ),
 
 
 
 
 
 
 
2211
  })
2212
 
2213
  return {
2214
  "total_failures": len(failures),
2215
  "failures": failures,
2216
  "failure_stats_by_stage": dict(stage_failure_stats),
 
 
 
2217
  }
2218
 
2219
  @app.get("/admin/rate-limit-status")
2220
  async def admin_rate_limit_status(request: Request):
2221
- """Get rate limit status for all IPs (admin only)"""
2222
  if not _is_admin_request(request):
2223
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2224
 
@@ -2243,7 +2412,7 @@ async def admin_rate_limit_status(request: Request):
2243
 
2244
  @app.get("/admin/clear-analytics")
2245
  async def admin_clear_analytics(request: Request):
2246
- """Clear all analytics data (admin only)"""
2247
  if not _is_admin_request(request):
2248
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2249
 
 
1
  """
2
+ ArchNemix Controller Space v1.8
3
  ════════════════════════════════════════════════════════════════════════════════
4
+ ADDED: Enhanced error tracking with exact backend URL for each failed stage
5
+ ADDED: Detailed debugging information for pipeline failures
6
+ ADDED: Failure context including stage, backend URL, job ID, and error message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  """
8
 
 
9
  import os
10
  import uuid
11
  import asyncio
 
13
  from datetime import datetime, timedelta
14
  from typing import Dict, Any, Optional, Tuple, List
15
  from enum import Enum
16
+ from dataclasses import dataclass, asdict, field
17
  from collections import defaultdict
18
 
19
  import httpx
 
45
  FFMPEG_QUEUE_DEPTH = 2
46
 
47
  # ═════════════════════════════════════════════════════════════════════════════
48
+ # ENHANCED ADMIN ANALYTICS STORAGE - v1.8
49
  # ═════════════════════════════════════════════════════════════════════════════
50
+ @dataclass
51
+ class StageFailureDetail:
52
+ """Detailed information about a stage failure"""
53
+ stage: str
54
+ backend_url: str
55
+ backend_type: str
56
+ job_id: str
57
+ error_message: str
58
+ error_type: str # e.g., "timeout", "backend_error", "save_failed", "user_cancelled"
59
+ submitted_at: Optional[datetime] = None
60
+ failed_at: datetime = field(default_factory=datetime.utcnow)
61
+ http_status: Optional[int] = None
62
+ response_body: Optional[str] = None
63
+
64
  @dataclass
65
  class JobAnalytics:
66
  """Track detailed analytics for a single job/pipeline"""
 
70
  is_admin: bool
71
  rate_limited: bool = False
72
 
73
+ # Stage tracking with backend details
74
  tts_submitted_at: Optional[datetime] = None
75
  tts_completed_at: Optional[datetime] = None
76
  tts_status: str = "idle"
77
  tts_error: Optional[str] = None
78
+ tts_backend: Optional[str] = None # Exact URL of backend space
79
+ tts_backend_type: Optional[str] = None
80
+ tts_job_id: Optional[str] = None
81
+ tts_failure_detail: Optional[StageFailureDetail] = None
82
 
83
  align_submitted_at: Optional[datetime] = None
84
  align_completed_at: Optional[datetime] = None
85
  align_status: str = "idle"
86
  align_error: Optional[str] = None
87
+ align_backend: Optional[str] = None # Exact URL of backend space
88
+ align_backend_type: Optional[str] = None
89
+ align_job_id: Optional[str] = None
90
+ align_failure_detail: Optional[StageFailureDetail] = None
91
 
92
  video_submitted_at: Optional[datetime] = None
93
  video_completed_at: Optional[datetime] = None
94
  video_status: str = "idle"
95
  video_error: Optional[str] = None
96
+ video_backend: Optional[str] = None # Exact URL of backend space
97
+ video_backend_type: Optional[str] = None
98
+ video_job_id: Optional[str] = None
99
  video_storage_method: Optional[str] = None # "dataset" or "ffmpeg_fallback"
100
+ video_failure_detail: Optional[StageFailureDetail] = None
101
 
102
  # Final outcome
103
  final_status: str = "pending" # "success", "failed", "cancelled"
 
109
  for key, value in d.items():
110
  if isinstance(value, datetime):
111
  d[key] = value.isoformat()
112
+ elif isinstance(value, StageFailureDetail):
113
+ d[key] = {
114
+ "stage": value.stage,
115
+ "backend_url": value.backend_url,
116
+ "backend_type": value.backend_type,
117
+ "job_id": value.job_id,
118
+ "error_message": value.error_message,
119
+ "error_type": value.error_type,
120
+ "submitted_at": value.submitted_at.isoformat() if value.submitted_at else None,
121
+ "failed_at": value.failed_at.isoformat(),
122
+ "http_status": value.http_status,
123
+ "response_body": value.response_body[:500] if value.response_body else None, # Truncate long responses
124
+ }
125
  return d
126
 
127
  # Global analytics storage
128
  analytics_storage: Dict[str, JobAnalytics] = {} # pipeline_id -> analytics
129
  stage_failure_stats: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
130
+ # stage_failure_stats["tts"]["timeout"] = 5
131
+ # stage_failure_stats["tts"]["backend_error"] = 3
132
 
133
  # Rate limiting storage
134
  rate_limit_storage: Dict[str, list[datetime]] = {}
 
217
  2. X-Forwarded-For (standard proxy header)
218
  3. request.client.host (direct connection)
219
  """
 
220
  cf_ip = request.headers.get("CF-Connecting-IP")
221
  if cf_ip:
222
  return cf_ip.strip()
223
 
 
224
  forwarded = request.headers.get("X-Forwarded-For")
225
  if forwarded:
 
226
  return forwarded.split(",")[0].strip()
227
 
 
228
  return request.client.host if request.client else "unknown"
229
 
230
  def _anonymize_ip(ip: str) -> str:
 
235
  return "unknown"
236
 
237
  def _is_admin_request(request: Request) -> bool:
238
+ """Check if request has admin credentials via API key header."""
 
 
 
 
239
  admin_header = request.headers.get("X-Admin-Key")
240
  if ADMIN_KEY and admin_header and admin_header == ADMIN_KEY:
 
241
  return True
 
242
  return False
243
 
244
  def _cleanup_old_timestamps(ip: str) -> None:
245
+ """Remove timestamps older than RATE_LIMIT_WINDOW_HOURS from storage."""
 
 
 
246
  if ip not in rate_limit_storage:
247
  return
248
 
 
252
  if ts > cutoff
253
  ]
254
 
 
255
  if not rate_limit_storage[ip]:
256
  del rate_limit_storage[ip]
257
 
258
  def _check_rate_limit(ip: str) -> Tuple[bool, int, int]:
259
+ """Check if IP has exceeded rate limit."""
 
 
 
 
 
 
 
 
 
260
  _cleanup_old_timestamps(ip)
261
 
262
  if ip not in rate_limit_storage:
 
265
  current_count = len(rate_limit_storage[ip])
266
 
267
  if current_count >= RATE_LIMIT_MAX_PER_HOUR:
 
268
  oldest_timestamp = min(rate_limit_storage[ip])
269
  expires_at = oldest_timestamp + timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
270
  seconds_until_expiry = int((expires_at - datetime.utcnow()).total_seconds())
 
274
  return True, current_count, 0
275
 
276
  def _record_request(ip: str) -> None:
277
+ """Record a new pipeline start request for this IP."""
 
 
 
278
  _cleanup_old_timestamps(ip)
279
 
280
  if ip not in rate_limit_storage:
281
  rate_limit_storage[ip] = []
282
 
283
  rate_limit_storage[ip].append(datetime.utcnow())
 
 
 
 
 
284
 
285
  # =============================================================================
286
+ # ENHANCED ANALYTICS HELPERS
287
  # =============================================================================
288
 
289
+ def _record_stage_failure(
290
+ analytics: JobAnalytics,
291
+ stage: str,
292
+ backend_url: str,
293
+ backend_type: str,
294
+ job_id: str,
295
+ error_message: str,
296
+ error_type: str,
297
+ http_status: Optional[int] = None,
298
+ response_body: Optional[str] = None
299
+ ):
300
+ """Record detailed stage failure information"""
301
+ failure_detail = StageFailureDetail(
302
+ stage=stage,
303
+ backend_url=backend_url,
304
+ backend_type=backend_type,
305
+ job_id=job_id,
306
+ error_message=error_message,
307
+ error_type=error_type,
308
+ http_status=http_status,
309
+ response_body=response_body,
310
+ submitted_at=datetime.utcnow() if stage == "tts" else None
311
+ )
312
+
313
+ # Store failure detail in the appropriate stage
314
+ if stage == "tts":
315
+ analytics.tts_failure_detail = failure_detail
316
+ analytics.tts_error = error_message
317
+ analytics.tts_status = "failed"
318
+ elif stage == "align":
319
+ analytics.align_failure_detail = failure_detail
320
+ analytics.align_error = error_message
321
+ analytics.align_status = "failed"
322
+ elif stage == "video":
323
+ analytics.video_failure_detail = failure_detail
324
+ analytics.video_error = error_message
325
+ analytics.video_status = "failed"
326
+
327
+ # Update global failure stats
328
  stage_failure_stats[stage][error_type] += 1
329
+
330
+ logger.error(
331
+ f"Pipeline {analytics.pipeline_id[:8]} {stage} failed on {backend_url} "
332
+ f"(job: {job_id}) - {error_type}: {error_message[:200]}"
333
+ )
334
 
335
  def _get_analytics_summary() -> Dict:
336
+ """Generate comprehensive analytics summary with backend breakdown"""
337
  total_pipelines = len(analytics_storage)
338
  if total_pipelines == 0:
339
  return {
 
363
  align_failed = sum(1 for a in analytics_storage.values() if a.align_status == "failed")
364
  video_failed = sum(1 for a in analytics_storage.values() if a.video_status == "failed")
365
 
366
+ # Calculate average processing times
367
  tts_times = []
368
  for a in analytics_storage.values():
369
  if a.tts_submitted_at and a.tts_completed_at:
 
389
  "video": dict(stage_failure_stats.get("video", {})),
390
  }
391
 
392
+ # Storage method stats
393
  dataset_storage = sum(1 for a in analytics_storage.values() if a.video_storage_method == "dataset")
394
  ffmpeg_fallback = sum(1 for a in analytics_storage.values() if a.video_storage_method == "ffmpeg_fallback")
395
 
396
+ # Backend usage statistics
397
+ backend_usage = defaultdict(int)
398
+ for a in analytics_storage.values():
399
+ if a.tts_backend:
400
+ backend_usage[a.tts_backend] += 1
401
+ if a.align_backend:
402
+ backend_usage[a.align_backend] += 1
403
+ if a.video_backend:
404
+ backend_usage[a.video_backend] += 1
405
+
406
+ # Backend failure rates
407
+ backend_failures = defaultdict(int)
408
+ backend_total_usage = defaultdict(int)
409
+ for a in analytics_storage.values():
410
+ if a.tts_backend:
411
+ backend_total_usage[a.tts_backend] += 1
412
+ if a.tts_status == "failed":
413
+ backend_failures[a.tts_backend] += 1
414
+ if a.align_backend:
415
+ backend_total_usage[a.align_backend] += 1
416
+ if a.align_status == "failed":
417
+ backend_failures[a.align_backend] += 1
418
+ if a.video_backend:
419
+ backend_total_usage[a.video_backend] += 1
420
+ if a.video_status == "failed":
421
+ backend_failures[a.video_backend] += 1
422
+
423
+ backend_stats = {}
424
+ for url in set(list(backend_total_usage.keys()) + list(backend_failures.keys())):
425
+ total = backend_total_usage.get(url, 0)
426
+ failed_count = backend_failures.get(url, 0)
427
+ backend_stats[url] = {
428
+ "total_uses": total,
429
+ "failures": failed_count,
430
+ "failure_rate": round(failed_count / total * 100, 1) if total > 0 else 0,
431
+ "backend_type": next(
432
+ (t for t, urls in ALL_SPACES.items() if url in urls),
433
+ "unknown"
434
+ )
435
+ }
436
+
437
  return {
438
  "total_pipelines": total_pipelines,
439
  "successful": successful,
 
462
  "ffmpeg_fallback": ffmpeg_fallback,
463
  "fallback_rate": round(ffmpeg_fallback / (dataset_storage + ffmpeg_fallback) * 100, 1) if (dataset_storage + ffmpeg_fallback) > 0 else 0,
464
  },
465
+ "backend_stats": backend_stats,
466
  "time_range": {
467
  "oldest": min((a.created_at for a in analytics_storage.values()), default=datetime.utcnow()).isoformat(),
468
  "newest": max((a.created_at for a in analytics_storage.values()), default=datetime.utcnow()).isoformat(),
 
474
  active_jobs = []
475
 
476
  for pid, pipeline in pipelines.items():
 
477
  running_stages = []
478
  for stage_name in [Stage.TTS, Stage.ALIGN, Stage.VIDEO]:
479
  s = pipeline["stages"][stage_name]
 
488
  })
489
 
490
  if running_stages:
 
491
  analytics = analytics_storage.get(pid)
492
  active_jobs.append({
493
  "pipeline_id": pid,
 
504
  # =============================================================================
505
 
506
  async def _rate_limit_cleanup_loop():
 
 
 
 
507
  while True:
508
+ await asyncio.sleep(300)
 
509
  cutoff = datetime.utcnow() - timedelta(hours=RATE_LIMIT_WINDOW_HOURS)
510
  cleaned_ips = 0
511
 
 
556
 
557
  app = FastAPI(
558
  title="ArchNemix Controller v1",
559
+ version="1.8.0",
560
  docs_url="/docs",
561
  redoc_url=None,
562
  )
 
603
  }
604
 
605
  # =============================================================================
606
+ # STATUS CACHE (keep all existing functions)
607
  # =============================================================================
608
 
609
  async def _check_one(url: str, stype: str) -> Dict[str, Any]:
 
625
 
626
  d = r.json()
627
 
 
 
628
  running = int(d.get("running", 0))
629
  waiting = int(d.get("waiting", 0))
630
  total = running + waiting
 
666
  """Enhanced status summary with queue info and separate MFA/Qwen stats"""
667
  out: Dict[str, Any] = {}
668
 
 
669
  for stype, urls in ALL_SPACES.items():
670
  spaces = []
671
  free = busy = 0
 
681
  "waiting": 0,
682
  })
683
 
 
684
  running = c.get("running", 0)
685
  waiting = c.get("waiting", 0)
686
+ depth = 2
 
 
687
  available_slots = max(0, depth - (running + waiting))
688
+ queue_available = waiting < 1
689
 
690
  spaces.append({
691
  "url": url,
 
717
  "spaces": spaces,
718
  }
719
 
 
720
  mfa_free = out["mfa"]["free"]
721
  mfa_total = out["mfa"]["total"]
722
  mfa_slots = out["mfa"]["total_slots"]
 
745
  "total_queue": qwen_queue,
746
  }
747
 
 
748
  aligner_free = mfa_free + qwen_free
749
  aligner_total = mfa_total + qwen_total
750
  aligner_slots = mfa_slots + qwen_slots
 
762
  return out
763
 
764
  # =============================================================================
765
+ # SPACE PICKER (keep existing)
766
  # =============================================================================
767
 
768
  def _release_reservation(url: str):
 
774
  urls = ALL_SPACES[stype]
775
  best_url = None
776
  best_load = float("inf")
777
+ depth = FFMPEG_QUEUE_DEPTH
 
 
 
 
 
 
778
 
779
  for url in urls:
780
  c = status_cache.get(url, {})
 
790
  best_load = load
791
  best_url = url
792
 
 
793
  if best_url is None:
794
  results = await asyncio.gather(*[_check_one(url, stype) for url in urls])
795
  for r in results:
 
810
  best_load = load
811
  best_url = url
812
 
 
813
  if best_url and best_url in status_cache:
814
  c = status_cache[best_url]
815
  c["_reserved"] = c.get("_reserved", 0) + 1
 
854
  Stage.VIDEO: _blank_stage(),
855
  },
856
  "assets": {
857
+ "audio_url": None,
858
+ "timestamps_url": None,
859
+ "video_url": None,
860
+ "video_download_url": None,
861
+ "video_stream_url": None,
 
862
  },
863
  }
864
 
 
903
  return f"ctrl_{pid[:10]}"
904
 
905
  # =============================================================================
906
+ # BACKEND JOB POLLER (with enhanced error tracking)
907
  # =============================================================================
908
 
909
  async def _poll_backend_stage(p: Dict, stage: str) -> None:
 
914
  url = s["backend_url"]
915
  jid = s["backend_job_id"]
916
  pid = p["pipeline_id"]
917
+ analytics = analytics_storage.get(pid)
918
 
919
  try:
920
  r = await http().get(
 
922
  params={"slim": "true"} if stage != Stage.VIDEO else {},
923
  timeout=HTTP_TIMEOUT,
924
  )
925
+ except httpx.TimeoutException as e:
926
+ logger.warning(f"Poll timeout {pid}/{stage}: {e}")
927
+ if analytics:
928
+ _record_stage_failure(
929
+ analytics, stage, url, s["backend_type"], jid,
930
+ f"Polling timeout after {HTTP_TIMEOUT}s",
931
+ "poll_timeout",
932
+ http_status=None
933
+ )
934
+ s["status"] = StageStatus.FAILED
935
+ s["error"] = f"Polling timeout: {e}"
936
+ return
937
  except Exception as e:
938
  logger.warning(f"Poll error {pid}/{stage}: {e}")
939
+ if analytics:
940
+ _record_stage_failure(
941
+ analytics, stage, url, s["backend_type"], jid,
942
+ str(e), "poll_error"
943
+ )
944
  return
945
 
946
  if r.status_code == 404:
947
  s["status"] = StageStatus.FAILED
948
+ s["error"] = "Job expired on backend (5 min TTL). Please re-run this step."
949
+ if analytics:
950
+ _record_stage_failure(
951
+ analytics, stage, url, s["backend_type"], jid,
952
+ "Job expired on backend (5 min TTL)", "job_expired",
953
+ http_status=404
954
+ )
955
  return
956
 
957
+ data = _safe_json(r)
958
  bk_status = data.get("status", "unknown")
959
 
960
  if bk_status == "completed":
961
  await _finalise_stage(p, stage, url, jid, data)
962
 
963
  elif bk_status in ("failed", "abandoned"):
964
+ error_msg = data.get("error", bk_status)
965
+ s["status"] = StageStatus.FAILED
966
+ s["error"] = error_msg
967
  s["completed_at"] = datetime.utcnow().isoformat()
968
+ if analytics:
969
+ _record_stage_failure(
970
+ analytics, stage, url, s["backend_type"], jid,
971
+ error_msg, "backend_job_failed",
972
+ http_status=r.status_code,
973
+ response_body=str(data)[:500]
974
+ )
975
 
976
  elif bk_status in ("running", "queued", "processing"):
977
+ s["progress"] = data.get("progress", s.get("progress", 0))
978
+ s["chunks_done"] = data.get("chunks_done", s.get("chunks_done", 0))
979
+ s["chunks_total"] = data.get("chunks_total", s.get("chunks_total", 0))
980
+ s["elapsed_s"] = data.get("elapsed_s", s.get("elapsed_s"))
981
  s["estimated_remaining_s"] = data.get("estimated_remaining_s", s.get("estimated_remaining_s"))
982
+ s["message"] = data.get("message", s.get("message", ""))
983
  if "encode_stats" in data:
984
  s["encode_stats"] = data["encode_stats"]
985
 
 
1012
  p["assets"]["audio_url"] = audio_url
1013
  p["assets"]["timestamps_url"] = ts_url
1014
 
 
1015
  if analytics:
1016
  analytics.tts_completed_at = datetime.utcnow()
1017
  analytics.tts_status = "done"
 
1028
  ts_url = await store().save(pid, "align_timestamps.json", ts_bytes, content_type="application/json")
1029
  p["assets"]["timestamps_url"] = ts_url
1030
 
 
1031
  if analytics:
1032
  analytics.align_completed_at = datetime.utcnow()
1033
  analytics.align_status = "done"
 
1035
 
1036
  logger.info(f"Pipeline {pid[:8]} Align done → {ts_url}")
1037
 
 
1038
  elif stage == Stage.VIDEO:
 
1039
  raw_download = slim_data.get("download_url", f"/download/{jid}")
1040
  raw_stream = slim_data.get("stream_url", f"/stream/{jid}")
1041
 
 
1048
  else f"{url}{raw_stream}"
1049
  )
1050
 
 
1051
  dataset_success = False
1052
  video_dataset_url = None
1053
 
1054
  logger.info(f"Pipeline {pid[:8]}: Attempting to upload video to HF dataset...")
1055
 
1056
  try:
 
1057
  headers = {"X-APP-KEY": APP_KEY} if APP_KEY else {}
1058
  video_response = await http().get(
1059
  ffmpeg_download_url,
 
1064
  video_response.raise_for_status()
1065
  video_bytes = video_response.content
1066
 
 
1067
  video_dataset_url = await store().save(
1068
  pid,
1069
  "video.mp4",
 
1073
 
1074
  dataset_success = True
1075
  size_mb = len(video_bytes) / 1024 / 1024
1076
+ logger.info(f"Pipeline {pid[:8]} Video uploaded to dataset successfully ({size_mb:.1f}MB)")
 
 
 
1077
 
1078
  except Exception as dataset_err:
1079
+ logger.warning(f"Pipeline {pid[:8]}: Dataset upload failed: {dataset_err}. Falling back to FFmpeg URLs.")
 
 
 
1080
  dataset_success = False
1081
 
 
1082
  if dataset_success and video_dataset_url:
 
1083
  p["assets"]["video_url"] = video_dataset_url
1084
  p["assets"]["video_download_url"] = video_dataset_url
1085
  p["assets"]["video_stream_url"] = video_dataset_url
1086
  if analytics:
1087
  analytics.video_storage_method = "dataset"
 
 
 
1088
  else:
 
1089
  p["assets"]["video_url"] = None
1090
  p["assets"]["video_download_url"] = ffmpeg_download_url
1091
  p["assets"]["video_stream_url"] = ffmpeg_stream_url
1092
  if analytics:
1093
  analytics.video_storage_method = "ffmpeg_fallback"
 
 
 
 
1094
 
 
1095
  if analytics:
1096
  analytics.video_completed_at = datetime.utcnow()
1097
  analytics.video_status = "done"
1098
  analytics.video_error = None
1099
  analytics.final_status = "success"
1100
  analytics.completed_at = datetime.utcnow()
1101
+
1102
+ s["status"] = StageStatus.DONE
 
1103
  s["completed_at"] = datetime.utcnow().isoformat()
1104
 
1105
+ except httpx.TimeoutException as e:
1106
+ logger.exception(f"Finalise timeout {pid}/{stage}")
1107
+ s["status"] = StageStatus.FAILED
1108
+ s["error"] = f"Timeout during finalization: {e}"
1109
+ if analytics:
1110
+ _record_stage_failure(
1111
+ analytics, stage, url, s["backend_type"], jid,
1112
+ str(e), "finalize_timeout",
1113
+ http_status=None
1114
+ )
1115
  except Exception as e:
1116
  logger.exception(f"Finalise failed {pid}/{stage}")
1117
  s["status"] = StageStatus.FAILED
1118
+ s["error"] = f"Failed to save result: {e}"
1119
 
 
1120
  if analytics:
1121
+ _record_stage_failure(
1122
+ analytics, stage, url, s["backend_type"], jid,
1123
+ str(e), "save_failed"
1124
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1125
 
1126
  # =============================================================================
1127
+ # STAGE SUBMISSION HELPERS (with enhanced error tracking)
1128
  # =============================================================================
1129
 
1130
  async def _submit_tts(p: Dict, text: str, voice: str, rate: float) -> Optional[JSONResponse]:
1131
  pid = p["pipeline_id"]
1132
+ analytics = analytics_storage.get(pid)
1133
 
1134
  backend_url = await _pick("tts")
1135
  if not backend_url:
1136
+ if analytics:
1137
+ _record_stage_failure(
1138
+ analytics, "tts", "N/A", "tts", "N/A",
1139
+ "All TTS spaces are busy", "all_spaces_busy"
1140
+ )
1141
  return JSONResponse(status_code=503, content={
1142
  "error": "all_tts_busy",
1143
  "detail": "All 4 TTS spaces are currently busy. Try again in ~20s.",
 
1151
  json={"text": text, "voice": voice, "rate": rate, "client_id": cid},
1152
  timeout=HTTP_TIMEOUT,
1153
  )
1154
+ except httpx.TimeoutException as e:
1155
+ if analytics:
1156
+ _record_stage_failure(
1157
+ analytics, "tts", backend_url, "tts", "N/A",
1158
+ f"Submission timeout: {e}", "submission_timeout"
1159
+ )
1160
+ raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
1161
  except httpx.RequestError as e:
1162
+ if analytics:
1163
+ _record_stage_failure(
1164
+ analytics, "tts", backend_url, "tts", "N/A",
1165
+ str(e), "request_error"
1166
+ )
1167
  raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
1168
 
1169
  if r.status_code == 503:
1170
+ if analytics:
1171
+ _record_stage_failure(
1172
+ analytics, "tts", backend_url, "tts", "N/A",
1173
+ "Space became busy just before submission", "space_busy",
1174
+ http_status=503
1175
+ )
1176
  return JSONResponse(status_code=503, content={
1177
  "error": "all_tts_busy",
1178
  "detail": "TTS space became busy just before submission. Retry.",
1179
  "retry_after": 15,
1180
  })
1181
  if r.status_code != 200:
1182
+ error_data = _safe_json(r)
1183
+ if analytics:
1184
+ _record_stage_failure(
1185
+ analytics, "tts", backend_url, "tts", "N/A",
1186
+ str(error_data), "backend_error",
1187
+ http_status=r.status_code,
1188
+ response_body=str(error_data)[:500]
1189
+ )
1190
+ raise HTTPException(r.status_code, error_data)
1191
 
1192
  data = r.json()
1193
  jid = data["job_id"]
1194
 
1195
  s = p["stages"][Stage.TTS]
1196
+ s["status"] = StageStatus.RUNNING
1197
+ s["backend_url"] = backend_url
1198
  s["backend_job_id"] = jid
1199
+ s["backend_type"] = "tts"
1200
+ s["submitted_at"] = datetime.utcnow().isoformat()
1201
+ s["error"] = None
1202
 
 
 
1203
  if analytics:
1204
  analytics.tts_submitted_at = datetime.utcnow()
1205
  analytics.tts_status = "running"
1206
  analytics.tts_backend = backend_url
1207
+ analytics.tts_backend_type = "tts"
1208
+ analytics.tts_job_id = jid
1209
 
1210
  return None
1211
 
 
1217
  aligner_type: str = "mfa"
1218
  ) -> str:
1219
  pid = p["pipeline_id"]
1220
+ analytics = analytics_storage.get(pid)
1221
 
1222
  audio_url = p["assets"].get("audio_url")
1223
  if not audio_url:
1224
+ if analytics:
1225
+ _record_stage_failure(
1226
+ analytics, "align", "N/A", aligner_type, "N/A",
1227
+ "TTS stage not completed", "tts_not_done"
1228
+ )
1229
  raise HTTPException(400, {
1230
  "error": "no_audio",
1231
  "detail": "TTS stage has not completed yet. Complete TTS first.",
 
1242
  except HTTPException:
1243
  raise
1244
  except Exception as e:
1245
+ if analytics:
1246
+ _record_stage_failure(
1247
+ analytics, "align", "N/A", aligner_type, "N/A",
1248
+ f"Failed to fetch audio: {e}", "audio_fetch_failed"
1249
+ )
1250
  raise HTTPException(503, {"error": "audio_fetch_failed", "detail": str(e)})
1251
 
1252
+ backend_url = None
1253
  backend_type = None
1254
 
1255
  if aligner_type == "qwen":
 
1272
  logger.info(f"Pipeline {pid[:8]}: MFA requested but full, using Qwen fallback")
1273
 
1274
  if not backend_url:
1275
+ if analytics:
1276
+ _record_stage_failure(
1277
+ analytics, "align", "N/A", aligner_type, "N/A",
1278
+ "All aligner spaces are busy", "all_spaces_busy"
1279
+ )
1280
  raise HTTPException(503, {
1281
  "error": "all_aligners_busy",
1282
  "detail": "All MFA and Qwen spaces are currently busy. Try again in ~30s.",
 
1296
  },
1297
  timeout=HTTP_TIMEOUT,
1298
  )
1299
+ except httpx.TimeoutException as e:
1300
+ if analytics:
1301
+ _record_stage_failure(
1302
+ analytics, "align", backend_url, backend_type, "N/A",
1303
+ f"Submission timeout: {e}", "submission_timeout"
1304
+ )
1305
+ raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
1306
  except httpx.RequestError as e:
1307
+ if analytics:
1308
+ _record_stage_failure(
1309
+ analytics, "align", backend_url, backend_type, "N/A",
1310
+ str(e), "request_error"
1311
+ )
1312
  raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
1313
 
1314
  if r.status_code == 503:
1315
+ if analytics:
1316
+ _record_stage_failure(
1317
+ analytics, "align", backend_url, backend_type, "N/A",
1318
+ "Space became busy just before submission", "space_busy",
1319
+ http_status=503
1320
+ )
1321
  raise HTTPException(503, {
1322
  "error": "aligner_busy",
1323
  "detail": "Aligner became busy just before submission. Retry.",
1324
  "retry_after": 20,
1325
  })
1326
  if r.status_code != 200:
1327
+ error_data = _safe_json(r)
1328
+ if analytics:
1329
+ _record_stage_failure(
1330
+ analytics, "align", backend_url, backend_type, "N/A",
1331
+ str(error_data), "backend_error",
1332
+ http_status=r.status_code,
1333
+ response_body=str(error_data)[:500]
1334
+ )
1335
+ raise HTTPException(r.status_code, error_data)
1336
 
1337
  data = r.json()
1338
  jid = data["job_id"]
1339
 
1340
  s = p["stages"][Stage.ALIGN]
1341
+ s["status"] = StageStatus.RUNNING
1342
+ s["backend_url"] = backend_url
1343
  s["backend_job_id"] = jid
1344
+ s["backend_type"] = backend_type
1345
+ s["submitted_at"] = datetime.utcnow().isoformat()
1346
+ s["error"] = None
1347
 
 
 
1348
  if analytics:
1349
  analytics.align_submitted_at = datetime.utcnow()
1350
  analytics.align_status = "running"
1351
  analytics.align_backend = backend_url
1352
+ analytics.align_backend_type = backend_type
1353
+ analytics.align_job_id = jid
1354
 
1355
  logger.info(f"Pipeline {pid[:8]}: Alignment submitted to {backend_type.upper()} ({backend_url})")
1356
  return backend_type
 
1358
 
1359
  async def _submit_video(p: Dict, subtitles_ass: str, background: str, duration: Optional[float]) -> Optional[JSONResponse]:
1360
  pid = p["pipeline_id"]
1361
+ analytics = analytics_storage.get(pid)
1362
 
1363
  if not APP_KEY:
1364
+ if analytics:
1365
+ _record_stage_failure(
1366
+ analytics, "video", "N/A", "ffmpeg", "N/A",
1367
+ "APP_KEY not configured", "config_error"
1368
+ )
1369
  raise HTTPException(500, {
1370
+ "error": "controller_misconfigured",
1371
  "detail": "APP_KEY secret not set on controller space.",
1372
  })
1373
 
1374
  audio_url = p["assets"].get("audio_url")
1375
  if not audio_url:
1376
+ if analytics:
1377
+ _record_stage_failure(
1378
+ analytics, "video", "N/A", "ffmpeg", "N/A",
1379
+ "TTS not completed", "tts_not_done"
1380
+ )
1381
  raise HTTPException(400, {"error": "no_audio", "detail": "TTS not completed yet."})
1382
 
1383
  try:
 
1391
  except HTTPException:
1392
  raise
1393
  except Exception as e:
1394
+ if analytics:
1395
+ _record_stage_failure(
1396
+ analytics, "video", "N/A", "ffmpeg", "N/A",
1397
+ f"Failed to fetch audio: {e}", "audio_fetch_failed"
1398
+ )
1399
  raise HTTPException(503, {"error": "audio_fetch_failed", "detail": str(e)})
1400
 
1401
  backend_url = await _pick("ffmpeg")
1402
  if not backend_url:
1403
+ if analytics:
1404
+ _record_stage_failure(
1405
+ analytics, "video", "N/A", "ffmpeg", "N/A",
1406
+ "All video spaces are busy", "all_spaces_busy"
1407
+ )
1408
  return JSONResponse(status_code=503, content={
1409
  "error": "all_video_busy",
1410
  "detail": "All video spaces are busy. Try again in ~2 min.",
 
1424
  headers={"X-APP-KEY": APP_KEY, "X-Client-ID": cid},
1425
  timeout=30.0,
1426
  )
1427
+ except httpx.TimeoutException as e:
1428
+ if analytics:
1429
+ _record_stage_failure(
1430
+ analytics, "video", backend_url, "ffmpeg", "N/A",
1431
+ f"Submission timeout: {e}", "submission_timeout"
1432
+ )
1433
+ raise HTTPException(503, {"error": "backend_timeout", "detail": str(e)})
1434
  except httpx.RequestError as e:
1435
+ if analytics:
1436
+ _record_stage_failure(
1437
+ analytics, "video", backend_url, "ffmpeg", "N/A",
1438
+ str(e), "request_error"
1439
+ )
1440
  raise HTTPException(503, {"error": "backend_unreachable", "detail": str(e)})
1441
 
1442
  if r.status_code == 503:
1443
+ if analytics:
1444
+ _record_stage_failure(
1445
+ analytics, "video", backend_url, "ffmpeg", "N/A",
1446
+ "Space became busy just before submission", "space_busy",
1447
+ http_status=503
1448
+ )
1449
  return JSONResponse(status_code=503, content={
1450
  "error": "all_video_busy",
1451
  "detail": "Video space became busy just before submission. Retry.",
1452
  "retry_after": 60,
1453
  })
1454
  if r.status_code not in (200, 201):
1455
+ error_data = _safe_json(r)
1456
+ if analytics:
1457
+ _record_stage_failure(
1458
+ analytics, "video", backend_url, "ffmpeg", "N/A",
1459
+ str(error_data), "backend_error",
1460
+ http_status=r.status_code,
1461
+ response_body=str(error_data)[:500]
1462
+ )
1463
+ raise HTTPException(r.status_code, error_data)
1464
 
1465
  data = r.json()
1466
  jid = data["job_id"]
1467
 
1468
  s = p["stages"][Stage.VIDEO]
1469
+ s["status"] = StageStatus.RUNNING
1470
+ s["backend_url"] = backend_url
1471
  s["backend_job_id"] = jid
1472
+ s["backend_type"] = "ffmpeg"
1473
+ s["submitted_at"] = datetime.utcnow().isoformat()
1474
+ s["error"] = None
1475
 
 
 
1476
  if analytics:
1477
  analytics.video_submitted_at = datetime.utcnow()
1478
  analytics.video_status = "running"
1479
  analytics.video_backend = backend_url
1480
+ analytics.video_backend_type = "ffmpeg"
1481
+ analytics.video_job_id = jid
1482
 
1483
  return None
1484
 
 
1496
  "error": s["error"],
1497
  }
1498
  if s["status"] == StageStatus.RUNNING:
 
1499
  stage_out["backend_url"] = s.get("backend_url")
1500
  stage_out["backend_job_id"] = s.get("backend_job_id")
1501
  stage_out["backend_type"] = s.get("backend_type")
 
1502
  stage_out["progress"] = s.get("progress", 0)
1503
  stage_out["chunks_done"] = s.get("chunks_done", 0)
1504
  stage_out["chunks_total"] = s.get("chunks_total", 0)
 
1584
 
1585
  api = HfApi(token=HF_TOKEN)
1586
 
 
1587
  try:
1588
  info = api.repo_info(repo_id=repo, repo_type="dataset")
1589
  logger.info(f"Dataset {name} ({repo}): ✓ readable - found {info.id}")
 
1591
  logger.error(f"Dataset {name} ({repo}): ✗ NOT readable - {e}")
1592
  return False
1593
 
 
1594
  test_path = "_health_check.txt"
1595
  test_data = b"health check"
1596
 
 
1604
  )
1605
  logger.info(f"Dataset {name} ({repo}): ✓ writable - test upload succeeded")
1606
 
 
1607
  try:
1608
  api.delete_file(
1609
  path_in_repo=test_path,
 
1682
 
1683
  s["status"] = StageStatus.FAILED
1684
  s["error"] = "Cancelled — client disconnected"
1685
+
1686
+ # Update analytics
1687
+ analytics = analytics_storage.get(pid)
1688
+ if analytics:
1689
+ _record_stage_failure(
1690
+ analytics, running_stage, url or "N/A", backend_type or "unknown", jid or "N/A",
1691
+ "Cancelled — client disconnected", "client_disconnected"
1692
+ )
1693
 
1694
  # =============================================================================
1695
  # STARTUP / SHUTDOWN
 
1699
  async def startup():
1700
  global _http, _store
1701
 
 
 
 
1702
  if ADMIN_KEY:
1703
  logger.info(f"✓ ADMIN_KEY configured (rate limit bypass active for key holders)")
1704
  else:
1705
  logger.info("ℹ ADMIN_KEY not configured (rate limiting active for all users)")
1706
 
 
 
 
1707
  logger.info("=" * 80)
1708
  logger.info("DATASET REACHABILITY CHECK (at space build/startup)")
1709
  logger.info("=" * 80)
 
1747
  logger.info("MODE: ✓ SINGLE-DATASET — Only primary dataset configured")
1748
  logger.info("=" * 80)
1749
 
 
1750
  logger.info("Initializing HTTP client and DatasetStore...")
1751
  _http = httpx.AsyncClient(timeout=HTTP_TIMEOUT)
1752
  _store = DatasetStore(hf_token=HF_TOKEN, dataset_repo=HF_DATASET, dataset_repo_2=HF_DATASET_2)
 
1770
  logger.info(f"RATE LIMITING: {RATE_LIMIT_MAX_PER_HOUR} pipelines per IP per {RATE_LIMIT_WINDOW_HOURS}h")
1771
  if ADMIN_KEY:
1772
  logger.info("ADMIN BYPASS: Active — admin key holders bypass rate limits")
1773
+ logger.info("ANALYTICS v1.8: Enhanced tracking with exact backend URLs and failure details")
1774
  logger.info("=" * 80)
1775
+ logger.info("ArchNemix Controller v1.8 ready (enhanced debugging + backend failure tracking).")
1776
 
1777
 
1778
  @app.on_event("shutdown")
 
1788
  async def root():
1789
  return {
1790
  "name": "ArchNemix Controller",
1791
+ "version": "1.8.0",
1792
  "endpoints": {
1793
  "POST /pipeline/start": "Start new pipeline (rate limited: 10/hour per IP, admin key bypass available)",
1794
  "GET /pipeline/{id}": "Poll pipeline state + per-stage status",
 
1805
  "GET /debug/dataset-routing/{id}": "Debug dataset routing logic",
1806
  "GET /debug/rate-limit-status": "Check rate limit status for current IP",
1807
  # Admin endpoints (require X-Admin-Key header)
1808
+ "GET /admin/analytics": "📊 Comprehensive analytics summary with backend stats",
1809
+ "GET /admin/active-jobs": "🔄 List all currently running jobs with details",
1810
+ "GET /admin/failures": "❌ Detailed failure breakdown with exact backend URLs",
1811
+ "GET /admin/rate-limit-status": "⏱️ Rate limit status for all IPs",
1812
+ "GET /admin/pipeline/{id}/analytics": "🔍 Analytics for specific pipeline with failure details",
1813
+ "GET /admin/clear-analytics": "🗑️ Clear all analytics data",
1814
  },
1815
  "rate_limit": f"{RATE_LIMIT_MAX_PER_HOUR} pipelines per {RATE_LIMIT_WINDOW_HOURS} hour(s) per IP",
1816
  "admin_bypass": bool(ADMIN_KEY),
1817
  "analytics_enabled": True,
1818
+ "analytics_version": "1.8",
1819
  "video_storage": "Dataset first (permanent), fallback to FFmpeg /tmp URLs (1-hour TTL) if upload fails",
1820
  }
1821
 
1822
 
1823
  @app.post("/pipeline/start")
1824
  async def start_pipeline(req: PipelineStartRequest, request: Request):
 
1825
  client_ip = _get_client_ip(request)
1826
  is_admin = _is_admin_request(request)
1827
  anonymized_ip = _anonymize_ip(client_ip)
1828
 
 
1829
  rate_limited = False
1830
  if not is_admin:
1831
  allowed, current_count, retry_after = _check_rate_limit(client_ip)
 
1838
  "retry_after": retry_after,
1839
  })
1840
 
 
1841
  active_count = sum(
1842
  1 for p in pipelines.values()
1843
  if any(
 
1852
  "retry_after": 120,
1853
  })
1854
 
 
1855
  p = _new_pipeline(req)
1856
  pid = p["pipeline_id"]
1857
  pipelines[pid] = p
1858
 
 
1859
  analytics = JobAnalytics(
1860
  pipeline_id=pid,
1861
  created_at=datetime.utcnow(),
 
1865
  )
1866
  analytics_storage[pid] = analytics
1867
 
 
1868
  if not is_admin and not rate_limited:
1869
  _record_request(client_ip)
1870
 
 
1871
  err = await _submit_tts(p, req.text, req.voice, req.rate)
1872
  if err:
 
1873
  analytics.tts_status = "failed"
1874
  analytics.tts_error = "All TTS spaces busy at submission"
1875
  analytics.final_status = "failed"
1876
  analytics.completed_at = datetime.utcnow()
1877
+ _record_stage_failure(
1878
+ analytics, "tts", "N/A", "tts", "N/A",
1879
+ "All TTS spaces busy at submission", "all_spaces_busy"
1880
+ )
1881
 
1882
  p["stages"][Stage.TTS]["status"] = StageStatus.FAILED
1883
  p["stages"][Stage.TTS]["error"] = "All TTS spaces busy at submission time."
 
2077
  p["finalized"] = True
2078
  pipeline_heartbeats.pop(pipeline_id, None)
2079
 
 
2080
  asyncio.create_task(_run_delete_intermediates(pipeline_id))
2081
 
2082
  logger.info(f"Pipeline {pipeline_id[:8]} finalized (video kept in dataset).")
 
2101
  async def get_status():
2102
  summary = _status_summary()
2103
 
 
2104
  return {
2105
  "tts": {
2106
  **summary["tts"],
 
2279
  s["status"] = StageStatus.FAILED
2280
  s["error"] = "Cancelled by user"
2281
 
 
2282
  if analytics:
2283
+ _record_stage_failure(
2284
+ analytics, stage, url or "N/A", btype or "unknown", jid or "N/A",
2285
+ "Cancelled by user", "user_cancelled"
2286
+ )
 
 
 
 
 
 
 
 
 
2287
 
2288
  return {
2289
  "ok": True,
 
2294
  }
2295
 
2296
  # =============================================================================
2297
+ # ENHANCED ADMIN ANALYTICS ENDPOINTS
2298
  # =============================================================================
2299
 
2300
  @app.get("/admin/analytics")
2301
  async def admin_analytics(request: Request):
2302
+ """Get comprehensive analytics summary with backend stats"""
2303
  if not _is_admin_request(request):
2304
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2305
 
 
2307
 
2308
  @app.get("/admin/active-jobs")
2309
  async def admin_active_jobs(request: Request):
2310
+ """Get all currently running jobs with details"""
2311
  if not _is_admin_request(request):
2312
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2313
 
 
2321
 
2322
  @app.get("/admin/pipeline/{pipeline_id}/analytics")
2323
  async def admin_pipeline_analytics(pipeline_id: str, request: Request):
2324
+ """Get detailed analytics for a specific pipeline with failure details"""
2325
  if not _is_admin_request(request):
2326
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2327
 
 
2333
 
2334
  @app.get("/admin/failures")
2335
  async def admin_failures(request: Request):
2336
+ """Get detailed failure breakdown with exact backend URLs"""
2337
  if not _is_admin_request(request):
2338
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2339
 
2340
  failures = []
2341
  for pid, analytics in analytics_storage.items():
2342
  if analytics.final_status == "failed":
2343
+ # Determine which stage failed and get its failure detail
2344
+ failed_stage = None
2345
+ failure_detail = None
2346
+
2347
+ if analytics.tts_status == "failed":
2348
+ failed_stage = "tts"
2349
+ failure_detail = analytics.tts_failure_detail
2350
+ elif analytics.align_status == "failed":
2351
+ failed_stage = "align"
2352
+ failure_detail = analytics.align_failure_detail
2353
+ elif analytics.video_status == "failed":
2354
+ failed_stage = "video"
2355
+ failure_detail = analytics.video_failure_detail
2356
+
2357
  failures.append({
2358
  "pipeline_id": pid,
2359
  "created_at": analytics.created_at.isoformat(),
2360
  "user_ip": analytics.user_ip,
2361
  "is_admin": analytics.is_admin,
2362
+ "failed_stage": failed_stage,
2363
+ "failure": {
2364
+ "backend_url": failure_detail.backend_url if failure_detail else None,
2365
+ "backend_type": failure_detail.backend_type if failure_detail else None,
2366
+ "job_id": failure_detail.job_id if failure_detail else None,
2367
+ "error_message": failure_detail.error_message if failure_detail else None,
2368
+ "error_type": failure_detail.error_type if failure_detail else None,
2369
+ "failed_at": failure_detail.failed_at.isoformat() if failure_detail else None,
2370
+ "http_status": failure_detail.http_status if failure_detail else None,
2371
+ },
2372
+ "stage_errors": {
2373
+ "tts_error": analytics.tts_error,
2374
+ "align_error": analytics.align_error,
2375
+ "video_error": analytics.video_error,
2376
+ }
2377
  })
2378
 
2379
  return {
2380
  "total_failures": len(failures),
2381
  "failures": failures,
2382
  "failure_stats_by_stage": dict(stage_failure_stats),
2383
+ "error_type_breakdown": {
2384
+ stage: dict(errors) for stage, errors in stage_failure_stats.items()
2385
+ }
2386
  }
2387
 
2388
  @app.get("/admin/rate-limit-status")
2389
  async def admin_rate_limit_status(request: Request):
2390
+ """Get rate limit status for all IPs"""
2391
  if not _is_admin_request(request):
2392
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2393
 
 
2412
 
2413
  @app.get("/admin/clear-analytics")
2414
  async def admin_clear_analytics(request: Request):
2415
+ """Clear all analytics data"""
2416
  if not _is_admin_request(request):
2417
  raise HTTPException(403, {"error": "admin_required", "detail": "This endpoint requires admin authentication"})
2418