fix(jobs): reintentar los fallos transitorios en vez de tumbar el job
Tres jobs de prod murieron el 22-jul porque Gemini contestó 200 con el cuerpo vacío. Eso revienta al parsear, no al llamar, así que se escapaba del bucle de reintentos: un parpadeo de la API bastaba para perder el job. El mismo payload funciona 5 de 5 al reintentarlo. - gemini: el parseo pasa a estar dentro del bucle, y la respuesta vacía o no parseable cuenta como error transitorio. - descarga: reintento del 403 de YouTube, que casi siempre viene de que el proxy residencial rota la IP de salida entre la extracción y la descarga (3 de 62 descargas en 24h). - se elimina el fallback de reframear el vídeo entero: no escribía metadata.json, así que app.py marcaba el job como fallido igualmente después de gastar GPU en un render que nadie llegaba a ver. - alertas: la clasificación lee ahora las líneas de error del log en vez de las 10 últimas, que eran ruido de progreso y hacían culpar al subsistema equivocado (un parpadeo de Gemini se reportó como ffmpeg).
This commit is contained in:
parent
ed3bdc45a8
commit
be4510aa43
4 changed files with 205 additions and 23 deletions
22
app.py
22
app.py
|
|
@ -836,6 +836,26 @@ async def _notify_clip_activity(job_id):
|
||||||
print(f"⚠️ Clip-activity notify error for {job_id}: {e}")
|
print(f"⚠️ Clip-activity notify error for {job_id}: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
# Markers that identify a line as an actual error rather than progress noise.
|
||||||
|
_ERROR_MARKERS = ("❌", "ERROR:", "Traceback", "FATAL", "Exception",
|
||||||
|
"Process failed with exit code", "No metadata file generated",
|
||||||
|
"Execution error:")
|
||||||
|
|
||||||
|
|
||||||
|
def _job_error_text(logs) -> str:
|
||||||
|
"""The lines that explain WHY a job failed, for the alert's classifier.
|
||||||
|
|
||||||
|
The tail of the log is usually progress noise (scene detection, ffmpeg
|
||||||
|
banners), which made alerts blame whatever word happened to be nearby —
|
||||||
|
a silent upload got reported as a broken download path, and a Gemini blip
|
||||||
|
as an ffmpeg problem. Pick the error-bearing lines instead, newest last.
|
||||||
|
"""
|
||||||
|
hits = [ln for ln in logs if any(m in ln for m in _ERROR_MARKERS)]
|
||||||
|
if not hits:
|
||||||
|
return " ".join(logs[-10:]) # nothing recognisable — fall back to the tail
|
||||||
|
return " ".join(hits[-6:])
|
||||||
|
|
||||||
|
|
||||||
async def _record_job_alert(job_id):
|
async def _record_job_alert(job_id):
|
||||||
if not BILLING_ENABLED:
|
if not BILLING_ENABLED:
|
||||||
return
|
return
|
||||||
|
|
@ -843,7 +863,7 @@ async def _record_job_alert(job_id):
|
||||||
if not job.get('user_id'):
|
if not job.get('user_id'):
|
||||||
return # only track managed jobs
|
return # only track managed jobs
|
||||||
ok = job.get('status') == 'completed'
|
ok = job.get('status') == 'completed'
|
||||||
err = "" if ok else " ".join(job.get('logs', [])[-10:])
|
err = "" if ok else _job_error_text(job.get('logs', []))
|
||||||
try:
|
try:
|
||||||
await _alerts.record_job_outcome(ok, err)
|
await _alerts.record_job_outcome(ok, err)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
||||||
46
main.py
46
main.py
|
|
@ -632,8 +632,13 @@ def download_youtube_video(url, output_dir="."):
|
||||||
last_err = None
|
last_err = None
|
||||||
used_proxy = False
|
used_proxy = False
|
||||||
for label, ea, fmt, proxy in attempts:
|
for label, ea, fmt, proxy in attempts:
|
||||||
|
# A 403 on the media fetch is usually transient: the googlevideo URL is
|
||||||
|
# bound to the IP that extracted it, and the residential proxy rotates
|
||||||
|
# its exit IP between requests. Retrying re-extracts and usually lands
|
||||||
|
# on a consistent IP (3 of 62 downloads hit this on 22-jul-2026).
|
||||||
|
for retry in range(2):
|
||||||
try:
|
try:
|
||||||
print(f"📥 Download attempt: {label}")
|
print(f"📥 Download attempt: {label}" + (f" (retry {retry})" if retry else ""))
|
||||||
sanitized_title = _attempt(ea, fmt, proxy)
|
sanitized_title = _attempt(ea, fmt, proxy)
|
||||||
used_proxy = proxy is not None
|
used_proxy = proxy is not None
|
||||||
print(f"✅ Download succeeded ({label}).")
|
print(f"✅ Download succeeded ({label}).")
|
||||||
|
|
@ -641,6 +646,12 @@ def download_youtube_video(url, output_dir="."):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
last_err = e
|
last_err = e
|
||||||
print(f"⚠️ Download attempt '{label}' failed: {str(e)[:200]}")
|
print(f"⚠️ Download attempt '{label}' failed: {str(e)[:200]}")
|
||||||
|
retryable = '403' in str(e) or 'Forbidden' in str(e)
|
||||||
|
if not retryable or retry == 1:
|
||||||
|
break
|
||||||
|
time.sleep(3)
|
||||||
|
if sanitized_title is not None:
|
||||||
|
break
|
||||||
|
|
||||||
if sanitized_title is None:
|
if sanitized_title is None:
|
||||||
import sys
|
import sys
|
||||||
|
|
@ -998,30 +1009,33 @@ def _run_gemini_stage(client, model_name, prompt, schema):
|
||||||
response_schema=schema,
|
response_schema=schema,
|
||||||
)
|
)
|
||||||
max_attempts = 3
|
max_attempts = 3
|
||||||
response = None
|
|
||||||
for attempt in range(1, max_attempts + 1):
|
for attempt in range(1, max_attempts + 1):
|
||||||
try:
|
try:
|
||||||
response = client.models.generate_content(model=model_name, contents=prompt, config=config)
|
response = client.models.generate_content(model=model_name, contents=prompt, config=config)
|
||||||
break
|
# Parsing lives inside the retry loop on purpose: Gemini sometimes
|
||||||
|
# returns 200 with an empty body, which raises here rather than at
|
||||||
|
# the call. Retrying that recovered every occurrence seen in prod
|
||||||
|
# (22-jul-2026) — the same payload succeeds on the next attempt.
|
||||||
|
parsed_obj = getattr(response, "parsed", None)
|
||||||
|
if parsed_obj is not None:
|
||||||
|
parsed = parsed_obj.model_dump() if hasattr(parsed_obj, "model_dump") else parsed_obj
|
||||||
|
else:
|
||||||
|
parsed = gemini_worker._parse_json_response_text(
|
||||||
|
gemini_worker._get_response_text(response))
|
||||||
|
return parsed, gemini_worker._calculate_cost_analysis(response, model_name)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
msg = str(e)
|
msg = str(e)
|
||||||
transient = any(tok in msg for tok in (
|
transient = any(tok in msg for tok in (
|
||||||
'503', 'UNAVAILABLE', '429', 'RESOURCE_EXHAUSTED',
|
'503', 'UNAVAILABLE', '429', 'RESOURCE_EXHAUSTED',
|
||||||
'500', 'INTERNAL', 'overloaded', 'Deadline'))
|
'500', 'INTERNAL', 'overloaded', 'Deadline',
|
||||||
|
'empty response body', 'did not contain a JSON object',
|
||||||
|
'Failed to parse Gemini JSON response'))
|
||||||
if attempt == max_attempts or not transient:
|
if attempt == max_attempts or not transient:
|
||||||
raise
|
raise
|
||||||
wait = 5 * (2 ** (attempt - 1))
|
wait = 5 * (2 ** (attempt - 1))
|
||||||
print(f"⚠️ Gemini transient error (attempt {attempt}/{max_attempts}), retrying in {wait}s: {msg[:150]}")
|
print(f"⚠️ Gemini transient error (attempt {attempt}/{max_attempts}), retrying in {wait}s: {msg[:150]}")
|
||||||
time.sleep(wait)
|
time.sleep(wait)
|
||||||
|
|
||||||
parsed_obj = getattr(response, "parsed", None)
|
|
||||||
if parsed_obj is not None:
|
|
||||||
parsed = parsed_obj.model_dump() if hasattr(parsed_obj, "model_dump") else parsed_obj
|
|
||||||
else:
|
|
||||||
parsed = gemini_worker._parse_json_response_text(gemini_worker._get_response_text(response))
|
|
||||||
cost = gemini_worker._calculate_cost_analysis(response, model_name)
|
|
||||||
return parsed, cost
|
|
||||||
|
|
||||||
|
|
||||||
def get_viral_clips(transcript_result, video_duration):
|
def get_viral_clips(transcript_result, video_duration):
|
||||||
"""Two-pass clip selection: score transcript windows, then detail the best.
|
"""Two-pass clip selection: score transcript windows, then detail the best.
|
||||||
|
|
@ -1274,9 +1288,11 @@ if __name__ == '__main__':
|
||||||
clips_data = get_visual_clips(input_video, duration)
|
clips_data = get_visual_clips(input_video, duration)
|
||||||
|
|
||||||
if not clips_data or 'shorts' not in clips_data:
|
if not clips_data or 'shorts' not in clips_data:
|
||||||
print("❌ Failed to identify clips. Converting whole video as fallback.")
|
# Deliberately fail instead of reframing the whole video: that path
|
||||||
output_file = os.path.join(output_dir, f"{video_title}_vertical.mp4")
|
# wrote no metadata.json, so app.py marked the job failed anyway
|
||||||
render_clip(input_video, output_file, output_format)
|
# (app.py:1087) after burning GPU on a render nobody could see.
|
||||||
|
raise RuntimeError(
|
||||||
|
"Clip detection failed — Gemini did not return usable clips for this video.")
|
||||||
else:
|
else:
|
||||||
print(f"🔥 Found {len(clips_data['shorts'])} clips!")
|
print(f"🔥 Found {len(clips_data['shorts'])} clips!")
|
||||||
|
|
||||||
|
|
|
||||||
86
tests/test_gemini_retry.py
Normal file
86
tests/test_gemini_retry.py
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
"""Retry behaviour of the Gemini scoring/detail stage.
|
||||||
|
|
||||||
|
Prod (22-jul-2026) lost 3 jobs to Gemini answering 200 with an empty body.
|
||||||
|
That raises while parsing, not while calling, so it used to escape the retry
|
||||||
|
loop and kill the job on the first blip.
|
||||||
|
"""
|
||||||
|
import types
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import main
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeResponse:
|
||||||
|
def __init__(self, parsed=None):
|
||||||
|
self.parsed = parsed
|
||||||
|
self.candidates = []
|
||||||
|
self.usage_metadata = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def text(self):
|
||||||
|
return "" if self.parsed is None else "{}"
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeModels:
|
||||||
|
"""Returns an empty body for the first `blips` calls, then a good one."""
|
||||||
|
|
||||||
|
def __init__(self, blips, payload=None):
|
||||||
|
self.blips = blips
|
||||||
|
self.calls = 0
|
||||||
|
self.payload = payload if payload is not None else {"windows": [{"id": "w0", "score": 90}]}
|
||||||
|
|
||||||
|
def generate_content(self, **kwargs):
|
||||||
|
self.calls += 1
|
||||||
|
if self.calls <= self.blips:
|
||||||
|
return _FakeResponse(parsed=None)
|
||||||
|
return _FakeResponse(parsed=self.payload)
|
||||||
|
|
||||||
|
|
||||||
|
def _client(models):
|
||||||
|
return types.SimpleNamespace(models=models)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _no_sleep(monkeypatch):
|
||||||
|
monkeypatch.setattr(main.time, "sleep", lambda *_: None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_recovers_from_a_single_empty_body(monkeypatch):
|
||||||
|
models = _FakeModels(blips=1)
|
||||||
|
parsed, _cost = main._run_gemini_stage(_client(models), "m", "prompt", object)
|
||||||
|
assert models.calls == 2
|
||||||
|
assert parsed["windows"][0]["score"] == 90
|
||||||
|
|
||||||
|
|
||||||
|
def test_recovers_from_two_consecutive_blips():
|
||||||
|
models = _FakeModels(blips=2)
|
||||||
|
parsed, _cost = main._run_gemini_stage(_client(models), "m", "prompt", object)
|
||||||
|
assert models.calls == 3
|
||||||
|
assert parsed["windows"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_gives_up_after_three_attempts():
|
||||||
|
models = _FakeModels(blips=99)
|
||||||
|
with pytest.raises(Exception) as exc:
|
||||||
|
main._run_gemini_stage(_client(models), "m", "prompt", object)
|
||||||
|
assert models.calls == 3
|
||||||
|
assert "empty response body" in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_non_transient_errors_are_not_retried():
|
||||||
|
class _Boom:
|
||||||
|
calls = 0
|
||||||
|
|
||||||
|
def generate_content(self, **kwargs):
|
||||||
|
_Boom.calls += 1
|
||||||
|
raise ValueError("400 INVALID_ARGUMENT: bad request")
|
||||||
|
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
main._run_gemini_stage(_client(_Boom()), "m", "prompt", object)
|
||||||
|
assert _Boom.calls == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_succeeds_without_retrying_when_the_first_call_is_fine():
|
||||||
|
models = _FakeModels(blips=0)
|
||||||
|
main._run_gemini_stage(_client(models), "m", "prompt", object)
|
||||||
|
assert models.calls == 1
|
||||||
60
tests/test_job_error_text.py
Normal file
60
tests/test_job_error_text.py
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
"""Picking the real error out of a job log, for the failure-rate alert.
|
||||||
|
|
||||||
|
Regression cover for two prod alerts (22-jul-2026) that named the wrong
|
||||||
|
subsystem because the classifier read the tail of the log instead of the error:
|
||||||
|
a Gemini blip was reported as "ffmpeg/render" and a silent upload as a broken
|
||||||
|
download path.
|
||||||
|
"""
|
||||||
|
import app
|
||||||
|
from cloud.alerts import _classify_failure
|
||||||
|
|
||||||
|
|
||||||
|
def _classify(logs):
|
||||||
|
return _classify_failure(app._job_error_text(logs))
|
||||||
|
|
||||||
|
|
||||||
|
def test_gemini_blip_is_not_blamed_on_ffmpeg():
|
||||||
|
# The render noise that followed the error used to win, because it was last.
|
||||||
|
logs = [
|
||||||
|
"🤖 Analyzing with Gemini (2-pass: score → detail)...",
|
||||||
|
" Built 5 scoring window(s).",
|
||||||
|
"❌ Gemini Error: Gemini returned an empty response body.",
|
||||||
|
"🚀 Reframe engine v2 (ffmpeg-native render)",
|
||||||
|
"/app/scene_detection.py:109: UserWarning: The given NumPy array is not writable",
|
||||||
|
"🎬 Scene engine: TransNetV2 — 67 scenes",
|
||||||
|
"Analyzing Scenes: 0%| | 0/67 [00:00<?, ?it/s]",
|
||||||
|
"Process failed with exit code 1",
|
||||||
|
]
|
||||||
|
assert _classify(logs) == "gemini"
|
||||||
|
|
||||||
|
|
||||||
|
def test_download_failure_survives_trailing_noise():
|
||||||
|
logs = [
|
||||||
|
"📥 Download attempt: HD",
|
||||||
|
"⚠️ Download attempt 'HD' failed: ERROR: unable to download video data: HTTP Error 403: Forbidden",
|
||||||
|
"❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED (all strategies)",
|
||||||
|
"🗑️ Cleaned up downloaded video.",
|
||||||
|
"⏱️ Total execution time: 12.00s",
|
||||||
|
]
|
||||||
|
assert _classify(logs) == "youtube download"
|
||||||
|
|
||||||
|
|
||||||
|
def test_silent_upload_reports_no_audio():
|
||||||
|
logs = [
|
||||||
|
"🎙️ Transcribing video...",
|
||||||
|
"❌ NO_AUDIO: This video has no audio track.",
|
||||||
|
"Process failed with exit code 1",
|
||||||
|
]
|
||||||
|
assert _classify(logs) == "no audio"
|
||||||
|
|
||||||
|
|
||||||
|
def test_falls_back_to_tail_when_nothing_looks_like_an_error():
|
||||||
|
logs = [f"line {i}" for i in range(20)]
|
||||||
|
assert app._job_error_text(logs) == " ".join(f"line {i}" for i in range(10, 20))
|
||||||
|
|
||||||
|
|
||||||
|
def test_keeps_only_the_most_recent_errors():
|
||||||
|
logs = [f"❌ error {i}" for i in range(12)]
|
||||||
|
out = app._job_error_text(logs)
|
||||||
|
assert "❌ error 11" in out
|
||||||
|
assert "❌ error 0" not in out
|
||||||
Loading…
Reference in a new issue