fix(deploy): hold new jobs while the draining instance still fills the GPU

During a rolling deploy the old container finishes its running jobs on the
same GPU while the new one starts its own full MAX_CONCURRENT_JOBS. On
22-sep-2026 that was 7 old + 3 new jobs on a 20 GB card: TransNetV2 and
NVENC ran out of memory and 5 of 12 managed jobs failed. The new instance
now counts the jobs another instance is heartbeating and waits until the
total fits (bounded by the drain timeout; a killed instance goes stale in 60 s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
victorcavero14 2026-09-22 22:18:09 +02:00
parent b7b5e95e7c
commit faf633ed43
2 changed files with 96 additions and 0 deletions

54
app.py
View file

@ -801,6 +801,53 @@ def _manifest_busy_elsewhere(m, now=None):
and now - float(m.get("heartbeat") or 0) < HEARTBEAT_STALE_AFTER)
def _jobs_busy_elsewhere(now=None) -> int:
"""How many jobs another instance is running right now (fresh heartbeat).
During a deploy the old container keeps running its jobs while it drains,
on the same GPU. Counting them is what stops the new container from
stacking its own full MAX_CONCURRENT_JOBS on top: 22-sep-2026, 7 old + 3
new jobs filled the 20 GB card and 5 of 12 jobs died of CUDA OOM.
"""
now = time.time() if now is None else now
busy = 0
try:
entries = os.listdir(OUTPUT_DIR)
except FileNotFoundError:
return 0
for name in entries:
path = os.path.join(OUTPUT_DIR, name, _RESUME_FILE)
if not os.path.exists(path):
continue
m = _read_manifest(name)
if m and _manifest_busy_elsewhere(m, now):
busy += 1
return busy
SHARED_GPU_WAIT_SECONDS = 5
SHARED_GPU_MAX_WAIT = DRAIN_TIMEOUT_SECONDS + 120
async def _wait_for_shared_gpu():
"""Hold a new job while this instance's jobs plus the ones another
instance is still draining already fill MAX_CONCURRENT_JOBS. Bounded: a
killed instance stops heartbeating within HEARTBEAT_STALE_AFTER anyway,
and the drain itself cannot outlive DRAIN_TIMEOUT_SECONDS."""
waited = 0.0
logged = False
while waited < SHARED_GPU_MAX_WAIT:
elsewhere = _jobs_busy_elsewhere()
if len(_running_jobs) + elsewhere < MAX_CONCURRENT_JOBS:
return
if not logged:
print(f"⏳ GPU shared with a draining instance ({elsewhere} job(s) there, "
f"{len(_running_jobs)} here): holding the next job.")
logged = True
await asyncio.sleep(SHARED_GPU_WAIT_SECONDS)
waited += SHARED_GPU_WAIT_SECONDS
def _write_instance_marker():
try:
os.makedirs(OUTPUT_DIR, exist_ok=True)
@ -1288,6 +1335,13 @@ async def process_queue():
# Acquire semaphore slot (waits if max jobs are running)
await concurrency_semaphore.acquire()
if _draining:
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()
if _draining:
concurrency_semaphore.release()
job_queue.task_done()

View file

@ -235,3 +235,45 @@ class TestStatusFromDisk:
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"
class TestSharedGpu:
"""The new instance must not stack a full set of jobs on top of the ones
the draining instance is still running on the same GPU."""
def test_counts_only_fresh_jobs_of_other_instances(self, out):
now = time.time()
_manifest(out, "a", instance="old", heartbeat=now - 5)
_manifest(out, "b", instance="old", heartbeat=now - 5)
_manifest(out, "c", instance="old", heartbeat=now - 600) # stale
_manifest(out, "d", instance="me", heartbeat=now - 5) # ours
_manifest(out, "e") # queued, no heartbeat
(out / "no-manifest").mkdir()
assert app_module._jobs_busy_elsewhere(now) == 2
def test_waits_while_the_gpu_is_full(self, out, monkeypatch):
monkeypatch.setattr(app_module, "MAX_CONCURRENT_JOBS", 3)
monkeypatch.setattr(app_module, "SHARED_GPU_WAIT_SECONDS", 0.01)
busy = {"n": 3}
monkeypatch.setattr(app_module, "_jobs_busy_elsewhere", lambda now=None: busy["n"])
calls = {"n": 0}
real_sleep = asyncio.sleep
async def fake_sleep(sec):
calls["n"] += 1
if calls["n"] == 3:
busy["n"] = 1 # the old instance finished two jobs
await real_sleep(0)
monkeypatch.setattr(app_module.asyncio, "sleep", fake_sleep)
asyncio.run(app_module._wait_for_shared_gpu())
assert calls["n"] == 3
def test_no_wait_when_alone(self, out, monkeypatch):
monkeypatch.setattr(app_module, "MAX_CONCURRENT_JOBS", 3)
monkeypatch.setattr(app_module, "_running_jobs", {"x", "y"})
monkeypatch.setattr(app_module, "_jobs_busy_elsewhere", lambda now=None: 0)
async def boom(sec):
raise AssertionError("should not wait")
monkeypatch.setattr(app_module.asyncio, "sleep", boom)
asyncio.run(app_module._wait_for_shared_gpu())