clipwright/tests/test_deploy_drain.py
juancarlos.cavero b308f6e00e fix(deploy): keep serving until the proxy drops us, then exit for real
- PROXY_DRAIN_SECONDS (20): after the jobs are drained, keep the socket
  open with /health/ready at 503 so Traefik pulls the instance out of
  rotation while it can still answer. Coolify builds the container's
  HEALTHCHECK from its own interval*retries, so closing earlier was up to
  60 s of alternating 502/200 per deploy (retries lowered to 3 as well).
- HARD_EXIT_SECONDS (30): uvicorn finishing does not end the interpreter
  while an executor thread hangs in a network probe (a /api/process cut
  off mid-shutdown left yt-dlp running), which kept a drained container
  alive for the full 900 s grace and the deploy in "Removing old
  containers". Exit outright a little after handing uvicorn the signal.
2026-08-25 15:11:55 +02:00

237 lines
9.5 KiB
Python

"""Deploy handover: two instances, one disk, no job run twice and none lost.
Coolify starts the new container before stopping the old one and both share
OUTPUT_DIR. The old one must drain (finish what it runs, start nothing new);
the new one must resume only manifests nobody is heartbeating; a status poll
landing on either instance must answer from disk.
"""
import asyncio
import json
import os
import time
import httpx
import pytest
app_module = pytest.importorskip("app")
@pytest.fixture
def out(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, "_running_jobs", set())
# Isolate the in-memory job table and queue from other tests.
monkeypatch.setattr(app_module, "jobs", {})
monkeypatch.setattr(app_module, "job_queue", asyncio.PriorityQueue())
return root
def _manifest(out, job_id, **extra):
d = out / job_id
d.mkdir(exist_ok=True)
m = {"cmd": ["python", "main.py"], "priority": 2, "user_id": None,
"reservation_id": f"res-{job_id}", "watermark": False, "attempts": 0}
m.update(extra)
(d / app_module._RESUME_FILE).write_text(json.dumps(m))
return d
class TestHeartbeat:
def test_touch_stamps_instance_and_time(self, out):
_manifest(out, "j1")
app_module._touch_manifest("j1", now=1000.0)
m = app_module._read_manifest("j1")
assert m["instance"] == "me" and m["heartbeat"] == 1000.0
def test_fresh_heartbeat_from_another_instance_is_busy(self, out):
m = {"instance": "other", "heartbeat": 1000.0}
assert app_module._manifest_busy_elsewhere(m, now=1030.0)
def test_stale_heartbeat_is_free(self, out):
m = {"instance": "other", "heartbeat": 1000.0}
assert not app_module._manifest_busy_elsewhere(
m, now=1000.0 + app_module.HEARTBEAT_STALE_AFTER + 1)
def test_own_heartbeat_is_free(self, out):
# Same container restarted (same hostname): that job is ours to resume.
m = {"instance": "me", "heartbeat": 1000.0}
assert not app_module._manifest_busy_elsewhere(m, now=1001.0)
def test_no_heartbeat_is_free(self, out):
assert not app_module._manifest_busy_elsewhere({}, now=5.0)
class TestResumeScan:
def test_busy_elsewhere_is_skipped_but_reservation_kept(self, out):
_manifest(out, "j1", instance="other", heartbeat=time.time())
keep = app_module._resume_interrupted_jobs()
assert "j1" not in app_module.jobs
assert keep == {"res-j1"}, "the other instance's job must not be refunded as an orphan"
def test_stale_and_never_started_are_resumed(self, out):
_manifest(out, "stale", instance="other", heartbeat=time.time() - 600)
_manifest(out, "queued")
keep = app_module._resume_interrupted_jobs()
assert app_module.jobs["stale"]["status"] == "queued"
assert app_module.jobs["queued"]["status"] == "queued"
assert keep == {"res-stale", "res-queued"}
assert app_module._read_manifest("stale")["attempts"] == 1
def test_a_job_we_already_hold_is_not_enqueued_twice(self, out):
_manifest(out, "j1")
app_module.jobs["j1"] = {"status": "processing", "logs": []}
app_module._resume_interrupted_jobs()
assert app_module.job_queue.qsize() == 0
assert app_module._read_manifest("j1")["attempts"] == 0
def test_poison_job_is_dropped_and_refundable(self, out):
_manifest(out, "bad", attempts=app_module.MAX_RESUME_ATTEMPTS)
keep = app_module._resume_interrupted_jobs()
assert "bad" not in app_module.jobs
assert keep == set()
assert app_module._read_manifest("bad") is None
class TestDrain:
def test_marker_of_another_instance_starts_draining(self, out):
(out / app_module._INSTANCE_MARKER).write_text("newer")
assert app_module._check_instance_marker() is True
assert app_module._draining is True
def test_own_marker_does_not_drain(self, out):
app_module._write_instance_marker()
assert app_module._check_instance_marker() is False
assert app_module._draining is False
def test_scan_stays_quiet_while_draining(self, out):
_manifest(out, "j1")
app_module._begin_drain("test")
# The draining instance must not adopt manifests: they belong to the
# next one. (_resume_scan checks the flag; the worker drops dispatches.)
assert app_module._draining
def test_exit_waits_for_running_jobs_then_hands_the_signal_on(self, out):
calls = []
app_module._running_jobs.add("j1")
async def scenario():
async def finish_soon():
await asyncio.sleep(0.2)
app_module._running_jobs.discard("j1")
asyncio.create_task(finish_soon())
t = time.time()
await app_module._drain_then_exit(lambda sig, frame: calls.append(sig),
timeout=5, proxy_grace=0, hard_exit_after=0)
return time.time() - t
waited = asyncio.run(scenario())
assert calls and waited >= 0.2
def test_exit_gives_up_at_the_timeout(self, out):
calls = []
app_module._running_jobs.add("stuck")
asyncio.run(app_module._drain_then_exit(lambda sig, frame: calls.append(sig),
timeout=0.3, proxy_grace=0, hard_exit_after=0))
assert calls, "must still exit so the deploy can finish"
def test_keeps_serving_for_the_proxy_grace_after_draining(self, out):
calls = []
t = time.time()
asyncio.run(app_module._drain_then_exit(lambda sig, frame: calls.append(sig),
timeout=1, proxy_grace=0.3, hard_exit_after=0))
assert calls and time.time() - t >= 0.3
def test_arms_a_hard_exit_after_handing_the_signal_on(self, out, monkeypatch):
armed = []
import threading
class FakeTimer:
def __init__(self, delay, fn):
armed.append((delay, fn))
def start(self):
pass
monkeypatch.setattr(threading, "Timer", FakeTimer)
asyncio.run(app_module._drain_then_exit(lambda sig, frame: None, timeout=1,
proxy_grace=0, hard_exit_after=7))
assert armed and armed[0][0] == 7 and armed[0][1] is app_module._hard_exit
class TestReadiness:
"""Traefik drops a container the moment its Docker healthcheck fails, so
/health/ready must go 503 on SIGTERM (socket still open, proxy stops
sending traffic) but stay 200 on a marker drain (the newer instance is
still booting and nobody else is routable yet)."""
def _get(self):
async def go():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app_module.app),
base_url="http://t") as c:
return await c.get("/health/ready")
return asyncio.run(go())
def test_ready_by_default(self, out, monkeypatch):
monkeypatch.setattr(app_module, "_stopping", False)
assert self._get().status_code == 200
def test_marker_drain_stays_ready(self, out, monkeypatch):
monkeypatch.setattr(app_module, "_stopping", False)
(out / app_module._INSTANCE_MARKER).write_text("newer")
app_module._check_instance_marker()
assert app_module._draining
assert self._get().status_code == 200
def test_sigterm_turns_unready(self, out, monkeypatch):
monkeypatch.setattr(app_module, "_stopping", True)
assert self._get().status_code == 503
class TestStatusFromDisk:
def _client(self):
return httpx.AsyncClient(transport=httpx.ASGITransport(app=app_module.app),
base_url="http://t")
def test_unknown_job_with_live_manifest_is_processing(self, out):
_manifest(out, "j1", instance="other", heartbeat=time.time())
async def go():
async with self._client() as c:
return await c.get("/api/status/j1")
r = asyncio.run(go())
assert r.status_code == 200
assert r.json()["status"] == "processing"
def test_unknown_job_with_idle_manifest_is_queued(self, out):
_manifest(out, "j1")
async def go():
async with self._client() as c:
return await c.get("/api/status/j1")
r = asyncio.run(go())
assert r.json()["status"] == "queued"
def test_unknown_job_with_metadata_is_completed(self, out):
d = out / "j1"
d.mkdir()
(d / "vid_metadata.json").write_text(json.dumps({"shorts": [{"start": 0, "end": 1}]}))
async def go():
async with self._client() as c:
return await c.get("/api/status/j1")
r = asyncio.run(go())
assert r.json()["status"] == "completed"
assert r.json()["result"]["clips"]
def test_truly_unknown_job_is_404(self, out):
async def go():
async with self._client() as c:
return await c.get("/api/status/nope")
assert asyncio.run(go()).status_code == 404
def test_queued_here_but_started_elsewhere_reads_processing(self, out):
_manifest(out, "j1", instance="other", heartbeat=time.time())
app_module.jobs["j1"] = {"status": "queued", "logs": ["Job queued"]}
app_module._begin_drain("test")
assert app_module._presented_status("j1", app_module.jobs["j1"]) == "processing"