diff --git a/CLAUDE.md b/CLAUDE.md index aecb2c2..218ca43 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -271,8 +271,16 @@ container before stopping the old one (rolling update) and both share container is still booting and nobody else would be routable. The Coolify app has its health check enabled on that path so it waits for the new container to be `healthy` before stopping the old one. With that option on, - Coolify replaces the Dockerfile HEALTHCHECK with its own curl/wget command, - so the image must ship `curl` or every deploy rolls back as unhealthy. + Coolify replaces the Dockerfile HEALTHCHECK with its own curl/wget command + AND its own interval/retries (5 s × 3), so the image must ship `curl` or + every deploy rolls back as unhealthy, and a stopping container takes 15 s + to turn `unhealthy`. That is why the drain keeps serving for + `PROXY_DRAIN_SECONDS` (20) after the jobs are done before it hands the + signal to uvicorn: closing the socket earlier is 502s until Traefik + notices (measured ~60 s per deploy with retries=12 and no grace). And + `HARD_EXIT_SECONDS` (30) after that the process is ended outright: uvicorn + finishing does not end the interpreter while an executor thread hangs in + a network probe, and that kept a drained container alive for the full 900 s. `/health` stays a plain liveness probe for the external watcher. - `/api/status` answers from disk for a job this instance never held, so a poll landing on either container during the handover is fine. diff --git a/app.py b/app.py index 78b2c65..61319bb 100644 --- a/app.py +++ b/app.py @@ -613,6 +613,21 @@ HEARTBEAT_STALE_AFTER = 60 # no heartbeat for this long = nobody has i RESUME_SCAN_INTERVAL = 30 # seconds between looks for stale manifests HANDOVER_CHECK_INTERVAL = 5 # seconds between looks at the marker DRAIN_TIMEOUT_SECONDS = int(os.environ.get("DRAIN_TIMEOUT_SECONDS", "840")) +# After the jobs are drained, keep SERVING this long with /health/ready at 503 +# before closing the socket: the proxy only drops a container once its Docker +# healthcheck has failed interval*retries times (15 s with the Coolify +# settings), and closing the socket earlier sends that many seconds of +# requests to a dead port. Measured 2026-08-25: ~60 s of alternating 502/200 +# per deploy with retries=12 and no grace at all. +PROXY_DRAIN_SECONDS = float(os.environ.get("PROXY_DRAIN_SECONDS", "20")) +# Once uvicorn has the signal it closes within --timeout-graceful-shutdown +# (15 s), but the interpreter then waits for non-daemon threads, and a +# request cancelled mid-flight can leave an executor thread stuck in a +# network probe (yt-dlp) for as long as that takes. Seen 2026-08-25: "Finished +# server process" printed, container alive until the 900 s SIGKILL, deploy +# stuck in "Removing old containers". So the process is ended outright a +# little after uvicorn was told to stop. Jobs are already drained by then. +HARD_EXIT_SECONDS = float(os.environ.get("HARD_EXIT_SECONDS", "30")) _draining = False _stopping = False # SIGTERM received: report not-ready so the # proxy stops routing here before the @@ -711,9 +726,13 @@ async def _resume_scan(): print(f"⚠️ Resume scan failed: {e}") -async def _drain_then_exit(previous_handler, timeout=None): - """Wait for running jobs (bounded), then hand the signal to uvicorn.""" +async def _drain_then_exit(previous_handler, timeout=None, proxy_grace=None, + hard_exit_after=None): + """Wait for running jobs (bounded), let the proxy notice we are not ready, + then hand the signal to uvicorn.""" timeout = DRAIN_TIMEOUT_SECONDS if timeout is None else timeout + proxy_grace = PROXY_DRAIN_SECONDS if proxy_grace is None else proxy_grace + hard_exit_after = HARD_EXIT_SECONDS if hard_exit_after is None else hard_exit_after deadline = time.time() + timeout while _running_jobs and time.time() < deadline: await asyncio.sleep(1) @@ -721,13 +740,26 @@ async def _drain_then_exit(previous_handler, timeout=None): print(f"⏱️ Drain timeout after {timeout}s with {len(_running_jobs)} job(s) still " f"running — they will resume on the next instance.") else: - print("✅ Drained: no running jobs, shutting down.") + print("✅ Drained: no running jobs.") + if proxy_grace > 0: + print(f"⏳ Serving {proxy_grace:.0f}s more while the proxy drops this instance.") + await asyncio.sleep(proxy_grace) + print("👋 Shutting down.") + if hard_exit_after > 0: + import threading + threading.Timer(hard_exit_after, _hard_exit).start() if callable(previous_handler): previous_handler(signal.SIGTERM, None) else: os._exit(0) +def _hard_exit(): + print(f"⛔ Still alive {HARD_EXIT_SECONDS:.0f}s after the stop signal (a thread " + f"is hanging) — exiting now.", flush=True) + os._exit(0) + + def _install_drain_signal_handler(): """Replace uvicorn's SIGTERM handler with drain-first. uvicorn's own handler closes the listening socket at once, which would make Traefik diff --git a/tests/test_deploy_drain.py b/tests/test_deploy_drain.py index 7d2947e..12e29bc 100644 --- a/tests/test_deploy_drain.py +++ b/tests/test_deploy_drain.py @@ -124,7 +124,8 @@ class TestDrain: 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) + 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 @@ -132,9 +133,31 @@ class TestDrain: 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)) + 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