Coolify starts the new container before stopping the old one and both share output/, so the new one used to re-enqueue at startup the very jobs the old one was still rendering, and the old one had 30 s to live regardless. - Each instance stamps output/.instance; an instance that sees another id drains: finishes what it runs, starts nothing, leaves queued manifests. - A running job heartbeats its manifest every 10 s; the resume scan (startup and every 30 s) adopts only manifests nobody heartbeated for 60 s, so no job runs twice and none is lost. Reservations of live-elsewhere jobs are kept out of the orphan refund; poison jobs stay refundable. - SIGTERM drains too (up to DRAIN_TIMEOUT_SECONDS, default 840) before the signal reaches uvicorn, so the socket stays open and Traefik keeps getting answers. The app's Coolify stop grace period is now 900 s. - /api/status answers from disk for a job this instance never held, so a poll landing on either container during the handover works. Verified in the local stack: SIGTERM mid-job -> job finished its clips, 'Drained', exit 0; status polled 200 throughout an 8 min drain; a job submitted during the drain was left for, and resumed by, the next instance.
185 lines
7.2 KiB
Python
185 lines
7.2 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)
|
|
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))
|
|
assert calls, "must still exit so the deploy can finish"
|
|
|
|
|
|
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"
|