From ea789999e8c4a980373d5ccb7586db8230a21859 Mon Sep 17 00:00:00 2001 From: victorcavero14 Date: Tue, 22 Sep 2026 20:21:14 +0200 Subject: [PATCH] fix(cleanup): never sweep a job that is still queued or running The hourly sweep deleted job dirs and source uploads by age alone. With the queue backed up (22-sep-2026) free jobs waited over an hour, so their dir was removed under the worker: no clips, and the minute reservation stayed held until the 3 h stuck sweep. 21 free users lost their job that way today, most of them on their first run. - _job_is_active(): running here, queued/processing in memory, or a fresh resume manifest (the other instance's jobs during a handover). Manifests pin a dir for at most ACTIVE_JOB_MAX_SECONDS (24 h). - The age sweeps and both size caps skip active jobs and their sources. - run_job_wrapper settles the reservation from the job record it started with, so a vanished entry releases the minutes instead of holding them. Co-Authored-By: Claude Opus 5.5 --- app.py | 99 ++++++++++++++++----- tests/test_cleanup_live_jobs.py | 151 ++++++++++++++++++++++++++++++++ 2 files changed, 226 insertions(+), 24 deletions(-) create mode 100644 tests/test_cleanup_live_jobs.py diff --git a/app.py b/app.py index 7fe9a02..90899a6 100644 --- a/app.py +++ b/app.py @@ -1065,6 +1065,70 @@ def _dir_size(path: str) -> int: return total +# A job dir older than JOB_RETENTION_SECONDS can still be alive: on a busy day +# a free job waits over an hour in the queue, and a long render runs past the +# hour too. The sweeps used to delete those by age alone, under the worker's +# feet: no clips, and the minute reservation stayed held until the 3 h stuck +# sweep (22-sep-2026: 21 free jobs lost that way, most of them the user's +# first). A manifest pins its dir for at most this long, so one nobody will +# ever resume cannot keep a directory on disk forever. +ACTIVE_JOB_MAX_SECONDS = int(os.environ.get("ACTIVE_JOB_MAX_SECONDS", str(24 * 3600))) + + +def _job_is_active(job_id, now=None) -> bool: + """True while a job is queued or running here, or its resume manifest says + it has not reached a terminal state yet (the other instance's jobs during a + handover included). The disk sweeps must never touch such a job.""" + if job_id in _running_jobs: + return True + if (jobs.get(job_id) or {}).get('status') in ('queued', 'processing'): + return True + try: + age = (time.time() if now is None else now) - os.path.getmtime(_manifest_path(job_id)) + except OSError: + return False + return age <= ACTIVE_JOB_MAX_SECONDS + + +def _upload_job_id(filename: str) -> str: + """Source uploads are stored as ``_``.""" + return filename.split("_", 1)[0] + + +def _sweep_expired_job_dirs(now): + """Drop job dirs older than JOB_RETENTION_SECONDS, except live jobs.""" + for job_id in os.listdir(OUTPUT_DIR): + # Not a job: the thumbnails dir backs a StaticFiles mount, so + # deleting it would 500 every /thumbnails request until reboot. + if job_id == os.path.basename(THUMBNAILS_DIR): + continue + job_path = os.path.join(OUTPUT_DIR, job_id) + if not os.path.isdir(job_path): + continue + try: + expired = now - os.path.getmtime(job_path) > JOB_RETENTION_SECONDS + except OSError: + continue + if not expired or _job_is_active(job_id, now): + continue + print(f"🧹 Purging old job: {job_id}") + shutil.rmtree(job_path, ignore_errors=True) + jobs.pop(job_id, None) + + +def _sweep_expired_uploads(now): + """Drop source uploads older than JOB_RETENTION_SECONDS, except the source + of a job that is still queued or running.""" + for filename in os.listdir(UPLOAD_DIR): + file_path = os.path.join(UPLOAD_DIR, filename) + try: + if (now - os.path.getmtime(file_path) > JOB_RETENTION_SECONDS + and not _job_is_active(_upload_job_id(filename), now)): + os.remove(file_path) + except Exception: + pass + + def _enforce_uploads_size_cap(): """Delete the oldest source uploads while UPLOAD_DIR is over UPLOADS_MAX_GB. @@ -1080,7 +1144,7 @@ def _enforce_uploads_size_cap(): files = [] for name in os.listdir(UPLOAD_DIR): p = os.path.join(UPLOAD_DIR, name) - if os.path.isfile(p): + if os.path.isfile(p) and not _job_is_active(_upload_job_id(name)): try: files.append((os.path.getmtime(p), p, os.path.getsize(p))) except OSError: @@ -1112,7 +1176,7 @@ def _enforce_output_size_cap(): if job_id == thumbs: continue p = os.path.join(OUTPUT_DIR, job_id) - if os.path.isdir(p): + if os.path.isdir(p) and not _job_is_active(job_id): try: candidates.append((os.path.getmtime(p), p, job_id)) except OSError: @@ -1170,18 +1234,7 @@ async def cleanup_jobs(): # Simple directory cleanup based on modification time # Check OUTPUT_DIR - for job_id in os.listdir(OUTPUT_DIR): - # Not a job: the thumbnails dir backs a StaticFiles mount, so - # deleting it would 500 every /thumbnails request until reboot. - if job_id == os.path.basename(THUMBNAILS_DIR): - continue - job_path = os.path.join(OUTPUT_DIR, job_id) - if os.path.isdir(job_path): - if now - os.path.getmtime(job_path) > JOB_RETENTION_SECONDS: - print(f"🧹 Purging old job: {job_id}") - shutil.rmtree(job_path, ignore_errors=True) - if job_id in jobs: - del jobs[job_id] + _sweep_expired_job_dirs(now) for job_id in _sweep_retained_sources(now): print(f"🧹 Dropped retained source for job {job_id}") @@ -1214,12 +1267,7 @@ async def cleanup_jobs(): print(f"🧹 Expired agent upload slot {uid}") # Cleanup Uploads - for filename in os.listdir(UPLOAD_DIR): - file_path = os.path.join(UPLOAD_DIR, filename) - try: - if now - os.path.getmtime(file_path) > JOB_RETENTION_SECONDS: - os.remove(file_path) - except Exception: pass + _sweep_expired_uploads(now) except Exception as e: print(f"⚠️ Cleanup error: {e}") @@ -1306,8 +1354,11 @@ async def _track_proxy_usage(job_id): async def run_job_wrapper(job_id): """Wrapper to run job and release semaphore""" + # Keep the record itself: run_job writes its status into this same dict, + # 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) try: - job = jobs.get(job_id) if job: await run_job(job_id, job) except Exception as e: @@ -1319,7 +1370,7 @@ async def run_job_wrapper(job_id): _clear_resume_manifest(job_id) # Settle the minute reservation (managed jobs only): commit on success, # release otherwise so the minutes go back to the user. - await _settle_reservation(job_id) + await _settle_reservation(job_id, job) # Archive the completed clips to the user's durable R2 library (history). await _archive_managed_job(job_id) # Fire the caller's webhook (after archive, so durable links exist). @@ -1627,10 +1678,10 @@ async def _notify_job_webhook(job_id): asyncio.create_task(_deliver_webhook(url, body, job.get('webhook_secret'))) -async def _settle_reservation(job_id): +async def _settle_reservation(job_id, job=None): if not BILLING_ENABLED: return - job = jobs.get(job_id) or {} + job = job if job is not None else (jobs.get(job_id) or {}) reservation_id = job.get('reservation_id') if not reservation_id: return diff --git a/tests/test_cleanup_live_jobs.py b/tests/test_cleanup_live_jobs.py new file mode 100644 index 0000000..bbcf744 --- /dev/null +++ b/tests/test_cleanup_live_jobs.py @@ -0,0 +1,151 @@ +"""The hourly sweeps must never delete a job that is still queued or running. + +22-sep-2026: with the queue backed up, free jobs waited over an hour and the +age-only sweep removed their dir (and source upload) under the worker. The +user got no clips and the minute reservation stayed held for 3 hours. +""" +import asyncio +import os +import time +import types + +import pytest + +app_module = pytest.importorskip("app") + +OLD = 2 * 3600 # older than JOB_RETENTION_SECONDS in cloud (1 h) + + +@pytest.fixture +def disk(tmp_path, monkeypatch): + out = tmp_path / "output" + up = tmp_path / "uploads" + out.mkdir() + up.mkdir() + monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out)) + monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up)) + monkeypatch.setattr(app_module, "THUMBNAILS_DIR", str(out / "thumbnails")) + monkeypatch.setattr(app_module, "JOB_RETENTION_SECONDS", 3600) + monkeypatch.setattr(app_module, "_running_jobs", set()) + monkeypatch.setattr(app_module, "jobs", {}) + return out, up + + +def _age(path, seconds): + t = time.time() - seconds + os.utime(path, (t, t)) + + +def _job_dir(out, job_id, manifest=False, age=OLD): + d = out / job_id + d.mkdir() + if manifest: + m = d / app_module._RESUME_FILE + m.write_text("{}") + _age(m, age) + _age(d, age) + return d + + +def _upload(up, job_id, age=OLD): + f = up / f"{job_id}_video.mp4" + f.write_bytes(b"x") + _age(f, age) + return f + + +class TestJobDirSweep: + def test_finished_old_job_is_purged(self, disk): + out, _ = disk + d = _job_dir(out, "done") + app_module.jobs["done"] = {"status": "completed"} + app_module._sweep_expired_job_dirs(time.time()) + assert not d.exists() + assert "done" not in app_module.jobs + + def test_queued_old_job_survives(self, disk): + out, _ = disk + d = _job_dir(out, "waiting") + app_module.jobs["waiting"] = {"status": "queued"} + app_module._sweep_expired_job_dirs(time.time()) + assert d.exists() and "waiting" in app_module.jobs + + def test_running_old_job_survives(self, disk): + out, _ = disk + d = _job_dir(out, "busy") + app_module.jobs["busy"] = {"status": "processing"} + app_module._running_jobs.add("busy") + app_module._sweep_expired_job_dirs(time.time()) + assert d.exists() and "busy" in app_module.jobs + + def test_manifest_of_other_instance_survives(self, disk): + out, _ = disk + # Not in this instance's memory, but a fresh manifest says it is live. + d = _job_dir(out, "handover", manifest=True, age=30) + _age(d, OLD) + app_module._sweep_expired_job_dirs(time.time()) + assert d.exists() + + def test_abandoned_manifest_does_not_pin_forever(self, disk): + out, _ = disk + d = _job_dir(out, "ghost", manifest=True, + age=app_module.ACTIVE_JOB_MAX_SECONDS + 60) + app_module._sweep_expired_job_dirs(time.time()) + assert not d.exists() + + def test_size_cap_skips_live_jobs(self, disk, monkeypatch): + out, _ = disk + live = _job_dir(out, "live") + (live / "clip.mp4").write_bytes(b"x" * 2048) + app_module.jobs["live"] = {"status": "queued"} + dead = _job_dir(out, "dead") + (dead / "clip.mp4").write_bytes(b"x" * 2048) + monkeypatch.setattr(app_module, "OUTPUT_MAX_GB", 1 / 1024 ** 3) # 1 byte + app_module._enforce_output_size_cap() + assert live.exists() and not dead.exists() + + +class TestUploadSweep: + def test_source_of_queued_job_survives(self, disk): + _, up = disk + f = _upload(up, "waiting") + app_module.jobs["waiting"] = {"status": "queued"} + app_module._sweep_expired_uploads(time.time()) + assert f.exists() + + def test_source_of_finished_job_is_removed(self, disk): + _, up = disk + f = _upload(up, "done") + app_module.jobs["done"] = {"status": "failed"} + app_module._sweep_expired_uploads(time.time()) + assert not f.exists() + + def test_size_cap_skips_live_sources(self, disk, monkeypatch): + _, up = disk + live = _upload(up, "live") + app_module._running_jobs.add("live") + dead = _upload(up, "dead") + monkeypatch.setattr(app_module, "UPLOADS_MAX_GB", 1 / 1024 ** 3) + app_module._enforce_uploads_size_cap() + assert live.exists() and not dead.exists() + + +class TestSettleWithoutEntry: + def test_reservation_released_when_entry_vanished(self, monkeypatch): + calls = [] + + class FakeMetering: + @staticmethod + async def commit_reservation(rid): + calls.append(("commit", rid)) + + @staticmethod + async def release_reservation(rid): + calls.append(("release", rid)) + + monkeypatch.setattr(app_module, "BILLING_ENABLED", True) + monkeypatch.setattr(app_module, "cloud", types.SimpleNamespace(metering=FakeMetering), raising=False) + monkeypatch.setattr(app_module, "jobs", {}) + job = {"status": "processing", "reservation_id": "res-1"} + asyncio.run(app_module._settle_reservation("gone", job)) + assert calls == [("release", "res-1")]