fix(deploy): pull a stopping container out of Traefik before its socket closes

- uvicorn --timeout-graceful-shutdown 15: after the drain, stop waiting
  forever on open range downloads. The old container lived the full 900 s
  stop grace with its port already closed, so Traefik alternated 502/200
  for 15 minutes on 2026-08-25.
- /health/ready answers 503 once SIGTERM arrives, and a Dockerfile
  HEALTHCHECK on it lets Traefik drop the instance within ~10 s while it
  can still serve. Coolify's health check now waits on the same path
  before stopping the old container. The marker drain does not flip it:
  the new container is still booting at that point.
- ignore .worktrees
This commit is contained in:
juancarlos.cavero 2026-08-25 12:45:13 +02:00
parent 27b120093b
commit 2935aca896
5 changed files with 80 additions and 2 deletions

1
.gitignore vendored
View file

@ -45,3 +45,4 @@ skills-lock.json
# Cloud env example kept local only (avoid leaking infra hints) # Cloud env example kept local only (avoid leaking infra hints)
.env.cloud.example .env.cloud.example
.worktrees

View file

@ -252,6 +252,20 @@ container before stopping the old one (rolling update) and both share
- SIGTERM (`docker stop`) drains too, up to `DRAIN_TIMEOUT_SECONDS` (840), - SIGTERM (`docker stop`) drains too, up to `DRAIN_TIMEOUT_SECONDS` (840),
then hands the signal to uvicorn. The app's Coolify stop grace period is then hands the signal to uvicorn. The app's Coolify stop grace period is
900 s (`application_settings.stop_grace_period`); keep the timeout below it. 900 s (`application_settings.stop_grace_period`); keep the timeout below it.
After the drain hands the signal to uvicorn, `--timeout-graceful-shutdown 15`
(Dockerfile) caps the wait for in-flight connections: uvicorn's default is
unbounded, and one open range download kept a drained container alive for
the full grace period while Traefik still routed half the traffic to its
closed port.
- `/health/ready` + the Dockerfile `HEALTHCHECK` are what keep Traefik off a
dying container: its docker provider only routes to `healthy` containers,
so an instance answers 503 from the moment it gets SIGTERM (out of rotation
within ~10 s, socket still open) and a booting one gets no traffic until it
answers. Only SIGTERM flips it, not the marker drain: at that point the new
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. `/health` stays a
plain liveness probe for the external watcher.
- `/api/status` answers from disk for a job this instance never held, so a - `/api/status` answers from disk for a job this instance never held, so a
poll landing on either container during the handover is fine. poll landing on either container during the handover is fine.
- `main.py` leaves `.transcript_checkpoint.json` in the job dir so a job that - `main.py` leaves `.transcript_checkpoint.json` in the job dir so a job that

View file

@ -111,4 +111,19 @@ EXPOSE 8000
# Run FastAPI app. --proxy-headers + --forwarded-allow-ips trust the reverse # Run FastAPI app. --proxy-headers + --forwarded-allow-ips trust the reverse
# proxy's X-Forwarded-Proto so generated URLs (e.g. the OAuth redirect_uri) use # proxy's X-Forwarded-Proto so generated URLs (e.g. the OAuth redirect_uri) use
# https in production instead of the internal http scheme. # https in production instead of the internal http scheme.
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*"] # --timeout-graceful-shutdown bounds how long uvicorn waits for in-flight
# connections once app.py's drain has handed it the SIGTERM. Without it the
# default is "forever": an open range download of /api/source kept the old
# container alive for the whole 900 s stop grace period on 2026-08-25, with
# its listening socket already closed, so Traefik sent half of all requests
# to a dead port (alternating 502/200) for 15 minutes.
# Readiness for the reverse proxy: Traefik (docker provider) only routes to
# containers whose health is "healthy", so a new instance gets no traffic until
# it answers and an instance that received SIGTERM (503 from /health/ready)
# is dropped within interval*retries, while its socket is still open. Coolify's
# rolling update also waits on this before stopping the old container. The
# app is up in ~3 s; start-period covers slow disks. No curl in the image.
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=2 \
CMD ["python3", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health/ready', timeout=2).status == 200 else 1)"]
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"]

21
app.py
View file

@ -613,6 +613,9 @@ RESUME_SCAN_INTERVAL = 30 # seconds between looks for stale manifests
HANDOVER_CHECK_INTERVAL = 5 # seconds between looks at the marker HANDOVER_CHECK_INTERVAL = 5 # seconds between looks at the marker
DRAIN_TIMEOUT_SECONDS = int(os.environ.get("DRAIN_TIMEOUT_SECONDS", "840")) DRAIN_TIMEOUT_SECONDS = int(os.environ.get("DRAIN_TIMEOUT_SECONDS", "840"))
_draining = False _draining = False
_stopping = False # SIGTERM received: report not-ready so the
# proxy stops routing here before the
# listening socket closes
_running_jobs: set = set() # job ids with a live subprocess here _running_jobs: set = set() # job ids with a live subprocess here
@ -732,6 +735,8 @@ def _install_drain_signal_handler():
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
def on_sigterm(): def on_sigterm():
global _stopping
_stopping = True
_begin_drain("SIGTERM") _begin_drain("SIGTERM")
asyncio.ensure_future(_drain_then_exit(previous)) asyncio.ensure_future(_drain_then_exit(previous))
@ -1766,9 +1771,23 @@ async def run_job(job_id, job_data):
@app.get("/health") @app.get("/health")
async def health(): async def health():
"""Lightweight liveness probe for uptime monitoring / Coolify health checks.""" """Lightweight liveness probe for uptime monitoring."""
return {"status": "ok"} return {"status": "ok"}
@app.get("/health/ready")
async def health_ready():
"""Readiness probe for the Docker HEALTHCHECK (Dockerfile). Traefik's docker
provider drops a container from the load balancer as soon as it turns
unhealthy, so answering 503 from the moment SIGTERM arrives pulls this
instance out of rotation while it can still serve, instead of after its
socket is gone. Only SIGTERM flips it: a drain triggered by the instance
marker starts while the new container is still booting, and going
unready then would leave nobody routable."""
if _stopping:
return JSONResponse({"status": "stopping"}, status_code=503)
return {"status": "ready"}
@app.get("/api/config") @app.get("/api/config")
async def get_config(): async def get_config():
return { return {

View file

@ -136,6 +136,35 @@ class TestDrain:
assert calls, "must still exit so the deploy can finish" assert calls, "must still exit so the deploy can finish"
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: class TestStatusFromDisk:
def _client(self): def _client(self):
return httpx.AsyncClient(transport=httpx.ASGITransport(app=app_module.app), return httpx.AsyncClient(transport=httpx.ASGITransport(app=app_module.app),