feat(queue): auto-retry transient failures, resume on shutdown, queue position

- A job that fails for a reason on our side (CUDA/OOM, NVENC, cublas,
  Gemini 5xx, no clip rendered) is re-queued once after 30 s, keeping its
  reservation and transcript checkpoint. Content failures stay final.
- main.py renders clips best-score first and retries each failed clip once.
- A deploy's drain timeout no longer fails and refunds running jobs: the
  child is killed, the manifest kept, and the next instance resumes it
  (22-sep-2026: 6 jobs failed at once this way). Mid-render manifests are
  resumed instead of being recovered as completed.
- /api/status returns the queue position and an ETA; the dashboard shows
  it with a 'paid plans skip the line' upsell.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
victorcavero14 2026-09-22 23:48:23 +02:00
parent fed9395022
commit d4480c6257
6 changed files with 462 additions and 11 deletions

View file

@ -459,6 +459,22 @@ per hour at peak with `MAX_CONCURRENT_JOBS=8`):
`nvidia-smi` reports at least `GPU_MIN_FREE_MB` (4500) free; an idle card
always starts, and the wait is bounded by the drain timeout.
Failures the user should never see (`app.run_job_wrapper`):
- **Auto-retry**: a failed job whose error text is transient (CUDA/OOM,
NVENC "Generic error in an external library", cublas, Gemini 5xx, "No clips
could be rendered") is re-queued once after `AUTO_RETRY_DELAY_SECONDS` (30),
keeping its reservation and transcript checkpoint (`AUTO_RETRY_LIMIT`=1).
Content failures (no audio, private video, no clips found, policy block)
are final as before. Inside a job, `main.py` retries each failed clip once,
alone, after a pause, and renders clips best-score first.
- **Shutdown is not failure**: when the drain timeout cancels a running job,
the child is killed and the manifest + reservation are kept, so the next
instance resumes it. A manifest next to a metadata file means "stopped
mid-render" and is resumed, not recovered as completed.
- `/api/status` returns `queue: {position, ahead, eta_seconds}` while queued;
the dashboard shows it with a "paid plans skip the line" upsell (paid plans
do dispatch first: `PLAN_PRIORITY`).
### Paid proxy accounting (`cloud/proxy_ledger.py`)
Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB),

181
app.py
View file

@ -478,6 +478,62 @@ publish_jobs: Dict[str, Dict] = {} # {publish_id: {status, result, error}}
concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS)
# Queue position + ETA for /api/status. ``_admitting`` holds jobs already taken
# off the queue that wait for a free slot / GPU room: they go before anything
# still queued. Durations are a rolling sample of this instance's finished jobs.
_admitting: set = set()
_recent_job_seconds: list = []
DEFAULT_JOB_SECONDS = 240
def _record_job_duration(seconds):
if seconds and seconds > 0:
_recent_job_seconds.append(float(seconds))
del _recent_job_seconds[:-30]
def queue_estimate(ahead: int, running: int, slots: int, typical_seconds: float) -> int:
"""Seconds until a job with ``ahead`` jobs in front of it starts.
With a slot free it starts right away (a few seconds of admission);
otherwise each full round of ``slots`` jobs ahead costs about one typical
job, since the running ones are on average half done.
"""
slots = max(1, int(slots))
free = max(0, slots - int(running))
if ahead < free:
return 15
waiting = ahead - free + 1
rounds = waiting / slots
return int(max(30, round(typical_seconds * (0.5 + rounds - 1 / slots))))
def queue_snapshot(job_id):
"""``{position, ahead, eta_seconds}`` for a queued job, else None."""
job = jobs.get(job_id) or {}
if job.get('status') != 'queued':
return None
try:
entries = sorted(job_queue._queue) # (priority, seq, job_id)
except Exception:
entries = []
queued_ids = [e[2] for e in entries
if (jobs.get(e[2]) or {}).get('status') == 'queued']
if job_id in _admitting:
ahead = len([j for j in _admitting if j != job_id])
elif job_id in queued_ids:
ahead = len(_admitting) + queued_ids.index(job_id)
else:
return None
sample = sorted(_recent_job_seconds)
typical = sample[len(sample) // 2] if sample else DEFAULT_JOB_SECONDS
return {
"position": ahead + 1,
"ahead": ahead,
"eta_seconds": queue_estimate(ahead, len(_running_jobs), MAX_CONCURRENT_JOBS, typical),
}
def _enqueue_job(job_id: str, priority: int = 2):
job_queue.put_nowait((priority, next(_job_seq), job_id))
@ -678,6 +734,8 @@ def _recover_jobs_from_disk():
job_path = os.path.join(OUTPUT_DIR, job_id)
if not os.path.isdir(job_path) or job_id in jobs:
continue
if os.path.isfile(os.path.join(job_path, _RESUME_FILE)):
continue # in flight (interrupted or on the other instance): resume, not recover
json_files = glob.glob(os.path.join(job_path, "*_metadata.json"))
if not json_files:
continue
@ -1065,10 +1123,9 @@ def _resume_interrupted_jobs() -> set:
manifest_path = os.path.join(job_path, _RESUME_FILE)
if not os.path.isfile(manifest_path):
continue
if glob.glob(os.path.join(job_path, "*_metadata.json")):
# Finished after all — recovered as completed already.
_clear_resume_manifest(job_id)
continue
# A manifest outlives only an interrupted run (the job wrapper drops it
# at every terminal state), so a metadata file next to it means the job
# was stopped mid-render, not that it finished: resume it too.
try:
with open(manifest_path) as f:
m = json.load(f)
@ -1380,14 +1437,17 @@ async def process_queue():
continue
# Acquire semaphore slot (waits if max jobs are running)
_admitting.add(job_id)
await concurrency_semaphore.acquire()
if _draining:
_admitting.discard(job_id)
concurrency_semaphore.release()
job_queue.task_done()
print(f"⏸️ Draining — leaving {job_id} for the next instance.")
continue
# The old container may still be draining its jobs on this GPU.
await _wait_for_shared_gpu()
_admitting.discard(job_id)
if _draining:
concurrency_semaphore.release()
job_queue.task_done()
@ -1458,12 +1518,37 @@ async def run_job_wrapper(job_id):
# and if the entry is dropped from ``jobs`` mid-run the reservation must
# still be settled (released) instead of staying held for hours.
job = jobs.get(job_id)
interrupted = False
started = time.monotonic()
try:
if job:
await run_job(job_id, job)
if job.get('status') == 'completed':
_record_job_duration(time.monotonic() - started)
except asyncio.CancelledError:
# The server is shutting down (drain timeout of a deploy) and took this
# task with it. Not a failure: the manifest stays on disk and the next
# instance resumes the job (22-sep-2026: 6 jobs were marked failed and
# refunded at once this way instead).
interrupted = True
except Exception as e:
print(f"❌ Job wrapper error {job_id}: {e}")
finally:
if interrupted or (_stopping and job and job.get('status') != 'completed'):
_running_jobs.discard(job_id)
concurrency_semaphore.release()
job_queue.task_done()
print(f"♻️ Server stopping: leaving {job_id} for the next instance.")
if interrupted:
raise asyncio.CancelledError()
return
if _should_auto_retry(job):
_schedule_auto_retry(job_id, job)
_running_jobs.discard(job_id)
concurrency_semaphore.release()
job_queue.task_done()
print(f"🔁 Released slot for job {job_id} (auto-retry scheduled).")
return
# The subprocess returned (success or genuine failure) — a terminal
# state, so drop the resume manifest. It only survives if the container
# was killed mid-run, which is exactly when we want to resume.
@ -1493,6 +1578,79 @@ async def run_job_wrapper(job_id):
print(f"✅ Released slot for job: {job_id}")
# --- Automatic retry of transient failures ----------------------------------
# A job that dies of a condition on OUR side (a full GPU, an NVENC session
# refused, a Gemini 5xx) is run once more by itself instead of showing the user
# "failed". Content problems (no audio, private video, nothing clip-shaped,
# policy block) fail as before: retrying cannot fix them.
AUTO_RETRY_LIMIT = int(os.environ.get("AUTO_RETRY_LIMIT", "1"))
AUTO_RETRY_DELAY_SECONDS = float(os.environ.get("AUTO_RETRY_DELAY_SECONDS", "30"))
_TRANSIENT_MARKERS = (
"out of memory", "outofmemory", "cuda", "cublas", "cudnn", "nvenc",
"generic error in an external library", "exit code 187", "broken pipe",
"no clips could be rendered", "resource_exhausted", "resource exhausted",
"503", "502", "500 internal", "overloaded", "deadline exceeded",
"exit code -9", "exit code -15", "killed",
)
_PERMANENT_MARKERS = (
"no audio", "no_audio", "video unavailable", "private video", "members-only",
"prohibited_content", "blocked this video", "blocked its answer",
"did not return usable clips", "clip detection failed", "short-form content",
"sign in to confirm your age", "not available in your country",
)
def is_transient_failure(logs) -> bool:
"""Whether a failed job's logs describe something a second run can fix."""
text = _job_error_text(list(logs or [])).lower()
if any(m in text for m in _PERMANENT_MARKERS):
return False
return any(m in text for m in _TRANSIENT_MARKERS)
def _should_auto_retry(job) -> bool:
return bool(job and job.get('status') == 'failed' and not _draining
and int(job.get('auto_retries') or 0) < AUTO_RETRY_LIMIT
and job.get('cmd') and is_transient_failure(job.get('logs')))
def _clean_for_retry(output_dir):
"""Drop the half-made outputs of a failed run; keep the source, the
transcript checkpoint (the retry skips transcription), owner and manifest."""
try:
names = os.listdir(output_dir)
except OSError:
return
for name in names:
if ("_clip_" in name or name.endswith("_metadata.json")
or name.startswith(("temp_", "hooked_", "autosubs_"))):
try:
os.remove(os.path.join(output_dir, name))
except OSError:
pass
def _schedule_auto_retry(job_id, job):
job['auto_retries'] = int(job.get('auto_retries') or 0) + 1
job['status'] = 'queued'
job['result'] = None
job['ready_files'] = {}
job['logs'].append("🔁 A temporary server problem interrupted your video. "
"Retrying it automatically, no minutes are charged twice.")
_clean_for_retry(job.get('output_dir') or os.path.join(OUTPUT_DIR, job_id))
m = _read_manifest(job_id) or {}
priority = int(m.get("priority", 1))
print(f"🔁 Auto-retry {job['auto_retries']}/{AUTO_RETRY_LIMIT} for {job_id} "
f"in {AUTO_RETRY_DELAY_SECONDS:.0f}s.")
async def _later():
await asyncio.sleep(AUTO_RETRY_DELAY_SECONDS)
if job_id in jobs and jobs[job_id].get('status') == 'queued':
_enqueue_job(job_id, priority)
asyncio.create_task(_later())
async def _archive_managed_job(job_id):
if not BILLING_ENABLED:
return
@ -2109,7 +2267,16 @@ async def run_job(job_id, job_data):
start_wait = time.time()
last_heartbeat = time.time()
while process.poll() is None:
try:
await asyncio.sleep(2)
except asyncio.CancelledError:
# Shutting down: stop the child so it cannot keep writing into
# the job dir while the next instance resumes the same job.
try:
process.kill()
except Exception:
pass
raise
if time.time() - last_heartbeat >= HEARTBEAT_EVERY:
_touch_manifest(job_id)
last_heartbeat = time.time()
@ -2823,11 +2990,11 @@ def _job_view_from_disk(job_id):
job_path = os.path.join(OUTPUT_DIR, job_id)
if not os.path.isdir(job_path):
return None
m = _read_manifest(job_id)
if m is None:
if glob.glob(os.path.join(job_path, "*_metadata.json")):
_recover_jobs_from_disk()
return jobs.get(job_id)
m = _read_manifest(job_id)
if m is None:
return None
alive = time.time() - float(m.get("heartbeat") or 0) < HEARTBEAT_STALE_AFTER
owner = m.get("user_id")
@ -2862,6 +3029,8 @@ async def get_status(job_id: str, request: Request):
"status": _presented_status(job_id, job),
"logs": _visible_logs(job['logs']),
"result": job.get('result'),
# Position in line and a rough wait while the job is still queued.
"queue": queue_snapshot(job_id),
# Set when only the first part of the source was clipped (quota wall
# offer), so the dashboard can say so next to the clips.
"partial": job.get('partial'),

View file

@ -261,6 +261,8 @@ function App() {
// {processed_minutes, total_minutes} when the running/finished job clips
// only the first part of the source (the quota wall's free offer).
const [partialJob, setPartialJob] = useState(null);
// {position, ahead, eta_seconds} while the job waits in line, else null.
const [queueInfo, setQueueInfo] = useState(null);
// Durable R2 URLs (per clip index) for the current job — used as a fallback when
// the ephemeral local /videos/ files have been cleaned up (e.g. after a reload).
const [durableClips, setDurableClips] = useState({});
@ -716,8 +718,10 @@ function App() {
}
if (data.partial) setPartialJob(data.partial);
setQueueInfo(data.status === 'queued' && data.queue ? data.queue : null);
if (data.status === 'completed') {
setQueueInfo(null);
setStatus('complete');
clearInterval(interval);
refreshMe();
@ -1079,6 +1083,7 @@ function App() {
setProjectState(null);
setNoSource(false);
setPartialJob(null);
setQueueInfo(null);
localStorage.removeItem(SESSION_KEY);
};
@ -1929,6 +1934,26 @@ function App() {
</span>
</div>
{/* Waiting in line: say where and for how long, and that paid
plans go first (they do: plan priority in the job queue). */}
{status === 'processing' && queueInfo && (
<div className="mb-4 rounded-card border border-brass/40 bg-brass/5 px-4 py-3 text-sm">
<p className="text-ink">
{queueInfo.ahead === 0
? 'You are next in line. Starting in a moment…'
: <>You are <b>#{queueInfo.position}</b> in line · about <b>{Math.max(1, Math.round(queueInfo.eta_seconds / 60))} min</b></>}
</p>
{billingEnabled && !['starter', 'creator', 'pro'].includes(plan) && queueInfo.ahead > 0 && (
<button
onClick={() => { track('QueueUpsellClick', { props: { position: String(queueInfo.position) } }); setShowPlanChoice(true); }}
className="mt-2 text-xs lowercase text-brass hover:underline"
>
paid plans skip the line →
</button>
)}
</div>
)}
{/* Video Preview */}
{processingMedia && (
<ProcessingAnimation

49
main.py
View file

@ -1532,6 +1532,29 @@ def clear_transcript_checkpoint(output_dir):
print(f"⚠️ Could not remove transcript checkpoint: {e}")
CLIP_RETRY_PAUSE_SECONDS = float(os.environ.get("CLIP_RETRY_PAUSE_SECONDS", "10"))
def clip_render_order(shorts):
"""Indices of ``shorts`` best-first by ``predicted_score`` (ties and
unscored clips keep their original order, after the scored ones)."""
def score(i):
try:
return float(shorts[i].get("predicted_score"))
except (TypeError, ValueError, AttributeError):
return float("-inf")
return sorted(range(len(shorts)), key=lambda i: (-score(i), i))
def _free_gpu_cache():
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception:
pass
def transcribe_video(video_path):
print("🎙️ Transcribing video...")
from transcribe_backends import transcribe_media, release_models, host_asr_slot
@ -2140,15 +2163,35 @@ if __name__ == '__main__':
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "3")), 1)
shorts = clips_data['shorts']
failed = []
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
futures = {pool.submit(_process_one_clip, i, clip): i
for i, clip in enumerate(shorts)}
# Best clip first: the pool starts work in submission order, so
# the user's first delivered clip is the strongest one instead
# of whatever came first in the video.
futures = {pool.submit(_process_one_clip, i, shorts[i]): i
for i in clip_render_order(shorts)}
for future in as_completed(futures):
i = futures[future]
try:
future.result()
if not future.result():
failed.append(i)
except Exception as e:
print(f" ❌ Clip {i+1} failed: {type(e).__name__}: {e}")
failed.append(i)
# A clip that failed mid-render is usually a transient GPU / NVENC
# condition on a busy card (22-sep-2026: 2 of 3 clips of a job "never
# rendered" during a CUDA OOM burst). Try each one once more, alone,
# after a pause and with the cache freed, before giving up on it.
for i in sorted(failed, key=lambda k: clip_render_order(shorts).index(k)):
print(f" 🔁 Retrying clip {i+1} once…")
time.sleep(CLIP_RETRY_PAUSE_SECONDS)
_free_gpu_cache()
try:
if not _process_one_clip(i, shorts[i]):
print(f" ❌ Clip {i+1} failed again.")
except Exception as e:
print(f" ❌ Clip {i+1} failed again: {type(e).__name__}: {e}")
# Persist per-clip render results added by the workers (auto_hook)
# so the editor can see what is already burned into each clip.

180
tests/test_auto_retry.py Normal file
View file

@ -0,0 +1,180 @@
"""Transient failures retry by themselves; a shutdown never fails a job.
22-sep-2026: 30-60% of jobs per hour failed at peak on a full GPU, and a
deploy's drain timeout marked six running jobs failed and refunded at once.
Users saw "failed" for problems that were entirely ours.
"""
import asyncio
import json
import os
import pytest
app_module = pytest.importorskip("app")
@pytest.fixture
def env(tmp_path, monkeypatch):
root = tmp_path / "output"
root.mkdir()
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(root))
monkeypatch.setattr(app_module, "INSTANCE_ID", "me")
monkeypatch.setattr(app_module, "_draining", False)
monkeypatch.setattr(app_module, "_stopping", False)
monkeypatch.setattr(app_module, "_running_jobs", set())
monkeypatch.setattr(app_module, "jobs", {})
monkeypatch.setattr(app_module, "AUTO_RETRY_DELAY_SECONDS", 0)
calls = {"settled": [], "enqueued": []}
async def fake_settle(job_id, job=None):
calls["settled"].append(job_id)
for name in ("_archive_managed_job", "_notify_job_webhook", "_record_job_alert",
"_track_proxy_usage", "_notify_clips_ready", "_notify_clip_activity"):
async def _noop(*a, **k):
return None
monkeypatch.setattr(app_module, name, _noop)
async def _noop2(*a, **k):
return None
monkeypatch.setattr(app_module, "_autopilot_job_finished", _noop2)
monkeypatch.setattr(app_module, "_settle_reservation", fake_settle)
monkeypatch.setattr(app_module, "_enqueue_job",
lambda job_id, priority=2: calls["enqueued"].append((job_id, priority)))
return root, calls
def _job(root, job_id, logs):
d = root / job_id
d.mkdir()
(d / app_module._RESUME_FILE).write_text(json.dumps({"cmd": ["x"], "priority": 1}))
(d / "My_Video.mp4").write_bytes(b"src")
(d / ".transcript_checkpoint.json").write_text("{}")
(d / "My_Video_metadata.json").write_text("{}")
(d / "My_Video_clip_1.mp4").write_bytes(b"half")
job = {"status": "queued", "logs": list(logs), "cmd": ["x"], "env": {},
"output_dir": str(d), "user_id": "u", "reservation_id": "r"}
app_module.jobs[job_id] = job
return d, job
def _run_wrapper(monkeypatch, job_id, final_status, raise_cancel=False):
async def fake_run_job(jid, job):
if raise_cancel:
raise asyncio.CancelledError()
job["status"] = final_status
monkeypatch.setattr(app_module, "run_job", fake_run_job)
async def go():
sem = asyncio.Semaphore(1)
await sem.acquire()
monkeypatch.setattr(app_module, "concurrency_semaphore", sem)
q = asyncio.PriorityQueue()
q.put_nowait((1, 0, job_id))
await q.get()
monkeypatch.setattr(app_module, "job_queue", q)
try:
await app_module.run_job_wrapper(job_id)
except asyncio.CancelledError:
pass
await asyncio.sleep(0.05) # let the scheduled retry fire
return sem
return asyncio.run(go())
class TestClassification:
def test_gpu_oom_is_transient(self):
assert app_module.is_transient_failure(
["❌ Clip 1 failed: RuntimeError: CUDA out of memory"])
def test_nvenc_is_transient(self):
assert app_module.is_transient_failure(
["ERROR: Generic error in an external library", "Process failed with exit code 187"])
def test_content_problems_are_not(self):
assert not app_module.is_transient_failure(
["❌ RuntimeError: Clip detection failed — the AI model did not return usable clips"])
assert not app_module.is_transient_failure(["ERROR: [youtube] x: Video unavailable"])
assert not app_module.is_transient_failure(["❌ This video has no audio track."])
def test_unknown_is_not(self):
assert not app_module.is_transient_failure(["Process failed with exit code 1"])
class TestWrapper:
def test_transient_failure_is_retried_once(self, env, monkeypatch):
root, calls = env
d, job = _job(root, "j1", ["❌ CUDA out of memory"])
sem = _run_wrapper(monkeypatch, "j1", "failed")
assert job["status"] == "queued" and job["auto_retries"] == 1
assert calls["enqueued"] == [("j1", 1)]
assert calls["settled"] == [] # reservation kept
assert (d / app_module._RESUME_FILE).exists() # still resumable
assert (d / "My_Video.mp4").exists() and (d / ".transcript_checkpoint.json").exists()
assert not (d / "My_Video_clip_1.mp4").exists()
assert not (d / "My_Video_metadata.json").exists()
assert sem._value == 1 # slot released
def test_second_failure_is_final(self, env, monkeypatch):
root, calls = env
d, job = _job(root, "j2", ["❌ CUDA out of memory"])
job["auto_retries"] = 1
_run_wrapper(monkeypatch, "j2", "failed")
assert job["status"] == "failed"
assert calls["settled"] == ["j2"] and calls["enqueued"] == []
assert not (d / app_module._RESUME_FILE).exists()
def test_content_failure_is_not_retried(self, env, monkeypatch):
root, calls = env
d, job = _job(root, "j3", ["❌ Clip detection failed"])
_run_wrapper(monkeypatch, "j3", "failed")
assert job["status"] == "failed" and calls["enqueued"] == []
def test_shutdown_leaves_the_job_for_the_next_instance(self, env, monkeypatch):
root, calls = env
d, job = _job(root, "j4", [])
sem = _run_wrapper(monkeypatch, "j4", None, raise_cancel=True)
assert calls["settled"] == [] # no refund, no failure
assert (d / app_module._RESUME_FILE).exists()
assert sem._value == 1
class TestResumeMidRender:
def test_manifest_with_metadata_is_resumed_not_recovered(self, env, monkeypatch):
root, calls = env
d = root / "j5"
d.mkdir()
(d / app_module._RESUME_FILE).write_text(json.dumps(
{"cmd": ["python", "main.py"], "priority": 1, "attempts": 0}))
(d / "V_metadata.json").write_text(json.dumps({"shorts": [{}]}))
app_module._recover_jobs_from_disk()
assert "j5" not in app_module.jobs # not "completed"
app_module._resume_interrupted_jobs()
assert app_module.jobs["j5"]["status"] == "queued"
assert calls["enqueued"] == [("j5", 1)]
class TestQueueEstimate:
def test_free_slot_starts_now(self):
assert app_module.queue_estimate(ahead=0, running=3, slots=8, typical_seconds=240) == 15
def test_grows_with_the_line(self):
a = app_module.queue_estimate(ahead=8, running=8, slots=8, typical_seconds=240)
b = app_module.queue_estimate(ahead=16, running=8, slots=8, typical_seconds=240)
assert 30 <= a < b
def test_snapshot_positions(self, env, monkeypatch):
import asyncio as _a
q = _a.PriorityQueue()
for i, (prio, jid) in enumerate([(1, "a"), (2, "b"), (1, "c")]):
q.put_nowait((prio, i, jid))
app_module.jobs[jid] = {"status": "queued", "logs": []}
monkeypatch.setattr(app_module, "job_queue", q)
monkeypatch.setattr(app_module, "_admitting", {"z"})
app_module.jobs["z"] = {"status": "queued", "logs": []}
assert app_module.queue_snapshot("z")["position"] == 1
assert app_module.queue_snapshot("a")["position"] == 2
assert app_module.queue_snapshot("c")["position"] == 3
assert app_module.queue_snapshot("b")["position"] == 4
app_module.jobs["a"]["status"] = "processing"
assert app_module.queue_snapshot("a") is None

View file

@ -0,0 +1,18 @@
"""The strongest clip renders first, so it is the first one the user sees."""
import pytest
main = pytest.importorskip("main")
def test_best_score_first():
shorts = [{"predicted_score": 40}, {"predicted_score": 91}, {"predicted_score": 77}]
assert main.clip_render_order(shorts) == [1, 2, 0]
def test_unscored_keep_order_after_scored():
shorts = [{}, {"predicted_score": "60"}, {"predicted_score": None}, {}]
assert main.clip_render_order(shorts) == [1, 0, 2, 3]
def test_empty():
assert main.clip_render_order([]) == []