From be4510aa4302075062e6e66e1ef77fb37ceb5cee Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 23 Jul 2026 00:24:31 +0200 Subject: [PATCH] fix(jobs): reintentar los fallos transitorios en vez de tumbar el job MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- app.py | 22 ++++++++- main.py | 60 ++++++++++++++++--------- tests/test_gemini_retry.py | 86 ++++++++++++++++++++++++++++++++++++ tests/test_job_error_text.py | 60 +++++++++++++++++++++++++ 4 files changed, 205 insertions(+), 23 deletions(-) create mode 100644 tests/test_gemini_retry.py create mode 100644 tests/test_job_error_text.py diff --git a/app.py b/app.py index c8d6628..7a9e564 100644 --- a/app.py +++ b/app.py @@ -836,6 +836,26 @@ async def _notify_clip_activity(job_id): 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): if not BILLING_ENABLED: return @@ -843,7 +863,7 @@ async def _record_job_alert(job_id): if not job.get('user_id'): return # only track managed jobs 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: await _alerts.record_job_outcome(ok, err) except Exception as e: diff --git a/main.py b/main.py index 1957401..69bc009 100644 --- a/main.py +++ b/main.py @@ -632,15 +632,26 @@ def download_youtube_video(url, output_dir="."): last_err = None used_proxy = False for label, ea, fmt, proxy in attempts: - try: - print(f"📥 Download attempt: {label}") - sanitized_title = _attempt(ea, fmt, proxy) - used_proxy = proxy is not None - print(f"✅ Download succeeded ({label}).") + # 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: + print(f"📥 Download attempt: {label}" + (f" (retry {retry})" if retry else "")) + sanitized_title = _attempt(ea, fmt, proxy) + used_proxy = proxy is not None + print(f"✅ Download succeeded ({label}).") + break + except Exception as e: + last_err = e + 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 - except Exception as e: - last_err = e - print(f"⚠️ Download attempt '{label}' failed: {str(e)[:200]}") if sanitized_title is None: import sys @@ -998,30 +1009,33 @@ def _run_gemini_stage(client, model_name, prompt, schema): response_schema=schema, ) max_attempts = 3 - response = None for attempt in range(1, max_attempts + 1): try: 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: msg = str(e) transient = any(tok in msg for tok in ( '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: raise wait = 5 * (2 ** (attempt - 1)) print(f"⚠️ Gemini transient error (attempt {attempt}/{max_attempts}), retrying in {wait}s: {msg[:150]}") 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): """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) if not clips_data or 'shorts' not in clips_data: - print("❌ Failed to identify clips. Converting whole video as fallback.") - output_file = os.path.join(output_dir, f"{video_title}_vertical.mp4") - render_clip(input_video, output_file, output_format) + # Deliberately fail instead of reframing the whole video: that path + # wrote no metadata.json, so app.py marked the job failed anyway + # (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: print(f"🔥 Found {len(clips_data['shorts'])} clips!") diff --git a/tests/test_gemini_retry.py b/tests/test_gemini_retry.py new file mode 100644 index 0000000..5354600 --- /dev/null +++ b/tests/test_gemini_retry.py @@ -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 diff --git a/tests/test_job_error_text.py b/tests/test_job_error_text.py new file mode 100644 index 0000000..e60ff90 --- /dev/null +++ b/tests/test_job_error_text.py @@ -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