Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: save a training checkpoint when the container is stopped (#11044)

Nilay5176306098b3
diff --git a/docker/DOCKERHUB.md b/docker/DOCKERHUB.md
index cdd71fda7b7..c898a93e1bd 100644
--- a/docker/DOCKERHUB.md
+++ b/docker/DOCKERHUB.md
@@ -138,6 +138,7 @@ Turing has no bfloat16; Unsloth falls back to float16 there. These images are CU
| `UNSLOTH_SKIP_NOTEBOOK_REFRESH=1` | Do not refresh the notebooks from GitHub on start; the copy baked into the image is still used. |
| `UNSLOTH_SKIP_NOTEBOOK_SYNC=1` | Do not set up the notebooks at all: nothing is created at `/workspace/unsloth-notebooks` or `/workspace/Unsloth Notebooks`. |
| `HF_TOKEN`, `WANDB_API_KEY` | Forwarded to Hugging Face and Weights and Biases. |
+| `UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S` | How long a training run gets to save a checkpoint when the container stops. Default `120`, and capped by `UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S` (default `600`). |
On a CPU-only host a non-login `docker exec` is built from the image, not the container's first process, so `docker exec <c> python -c "import unsloth"` still asks for a GPU. Use `bash -lc '...'` or pass `-e UNSLOTH_ALLOW_CPU=1`.
@@ -163,6 +164,20 @@ Studio's code ships in the image under `/opt/unsloth-studio-app` and is linked i
- A volume from before that split holds an old image's code. The first start of a newer image moves it aside to `/opt/unsloth-studio/.unsloth-studio-legacy/` and links the new code in; nothing is deleted. Delete it once the new image works (`docker exec <c> rm -rf /opt/unsloth-studio/.unsloth-studio-legacy`), along with the 9 GB uv cache at `/opt/unsloth-studio/cache/uv`, or start with `-e UNSLOTH_STUDIO_KEEP_LEGACY=0` to skip keeping it. Going back to a pre-split image needs those entries moved back, or `docker run --rm -v unsloth-studio:/opt/unsloth-studio --entrypoint unsloth-studio-home <current image> --restore`.
- Use a named volume, not a bind mount of a Windows or macOS host directory: the Studio home needs symlinks, and Docker Desktop's file sharing may refuse to create them, stopping the container at start. A Linux directory, including one inside a WSL 2 distribution, works.
+## Stopping while training
+
+On `docker stop` and `docker restart`, Studio stops a running training job at the next step and saves a checkpoint before it exits, so the run can be resumed from the Training page. Docker only waits 10 seconds by default, which is not enough for a large model, so give it the budget:
+
+```bash
+docker stop -t 150 <container>
+```
+
+or `stop_grace_period: 150s` in Compose. `docker/run.sh` sets this for you. `UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S` (default 120) is the time Studio itself waits for the save; the container's own limit is 30 seconds above it.
+
+A save is also bounded by the training stop watchdog, which force-terminates a worker that has not finished after `UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S` (default 600). Raising the shutdown budget past that does nothing on its own; raise both, and `docker/run.sh` forwards both.
+
+A host shutdown is not covered: the daemon stops every container under its own `--shutdown-timeout` (15 seconds by default), so a save that takes longer is cut short. Stop the container yourself before shutting the host down.
+
## Updating inside a running container
On the `latest` image:
diff --git a/docker/Dockerfile.studio b/docker/Dockerfile.studio
index fef3e7d6ca7..c53c193e010 100644
--- a/docker/Dockerfile.studio
+++ b/docker/Dockerfile.studio
@@ -68,6 +68,8 @@ ENV UNSLOTH_STUDIO_HOME=/opt/unsloth-studio \
JUPYTER_PORT=8888 \
UNSLOTH_STUDIO_PORT=8000 \
UNSLOTH_ENABLE_SSHD=false \
+ UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S=120 \
+ UNSLOTH_STUDIO_STOP_WAIT_S=150 \
DEBIAN_FRONTEND=noninteractive
# install.sh needs curl + git; supervisor + openssh-server run the service
diff --git a/docker/run.sh b/docker/run.sh
index 5df9e12b7ad..9ce174e603e 100755
--- a/docker/run.sh
+++ b/docker/run.sh
@@ -42,6 +42,12 @@
# UNSLOTH_STUDIO_VOLUME=unsloth-studio named volume for Studio's data (accounts,
# chats, outputs) at /opt/unsloth-studio;
# set it empty to run without one
+# UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S=120 how long a training run gets to save a
+# checkpoint on docker stop; --stop-timeout is
+# set 30s above it
+# UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S=600 when the training stop watchdog gives up
+# on a saving worker; raise it alongside the
+# budget above, which it caps
# --rocm only:
# UNSLOTH_ROCM=1 same as a leading --rocm
# HSA_OVERRIDE_GFX_VERSION force a gfx target (e.g. 10.3.0)
@@ -310,6 +316,9 @@ declare -a ENV_FORWARD=(-e HF_HUB_ENABLE_HF_TRANSFER=1)
[[ -n "${UNSLOTH_STUDIO_PASSWORD:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_PASSWORD)
[[ -n "${UNSLOTH_STUDIO_PORT:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_PORT)
[[ -n "${UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT)
+# both, or raising only the shutdown budget waits on a save the watchdog kills at its own cap
+[[ -n "${UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S)
+[[ -n "${UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S)
[[ -n "${PUBLIC_KEY:-}" ]] && ENV_FORWARD+=(-e PUBLIC_KEY)
[[ -n "${SSH_KEY:-}" ]] && ENV_FORWARD+=(-e SSH_KEY)
[[ -n "${UNSLOTH_JUPYTER_CLOUDFLARE:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_JUPYTER_CLOUDFLARE)
@@ -319,6 +328,14 @@ declare -a ENV_FORWARD=(-e HF_HUB_ENABLE_HF_TRANSFER=1)
[[ -n "${UNSLOTH_STUDIO_SECURE:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_SECURE)
[[ -n "${UNSLOTH_STUDIO_CLOUDFLARE:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_CLOUDFLARE)
+STOP_BUDGET="${UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S:-120}"
+if ! [[ "$STOP_BUDGET" =~ ^[0-9]+$ ]]; then
+ printf "\033[1;31mERROR:\033[0m UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S=%s is not a number of seconds.\n" "$STOP_BUDGET" >&2
+ exit 1
+fi
+# 10# as in studio_launch.sh: a leading zero must not read as octal
+STOP_TIMEOUT=$(( 10#$STOP_BUDGET + 30 ))
+
declare -a PORT_FLAGS=()
if [[ -n "${UNSLOTH_PORTS:-}" ]]; then
# shellcheck disable=SC2206 # intentional word splitting of "-p X -p Y"
@@ -336,6 +353,7 @@ fi
exec docker run --rm ${TTY_FLAG[@]+"${TTY_FLAG[@]}"} \
${GPU_FLAG[@]+"${GPU_FLAG[@]}"} \
--ipc=host \
+ --stop-timeout "$STOP_TIMEOUT" \
--ulimit memlock=-1 \
--ulimit stack=67108864 \
-v "$HF_CACHE":/workspace/.cache/huggingface \
diff --git a/docker/studio_launch.sh b/docker/studio_launch.sh
index 36edb97150f..8db9fefd0da 100644
--- a/docker/studio_launch.sh
+++ b/docker/studio_launch.sh
@@ -42,6 +42,12 @@ if [[ "$jupyter_port_digits" =~ ^[0-9]+$ ]] && (( 10#$jupyter_port_digits == UNS
printf " Leave JupyterLab on 8888 and map the host side instead: -p 9000:8888\n" >&2
exit 1
fi
+export UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S="${UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S:-120}"
+if ! [[ "$UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S" =~ ^[0-9]+$ ]]; then
+ printf "\033[1;31mERROR:\033[0m UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S=%s is not a number of seconds.\n" "$UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S" >&2
+ exit 1
+fi
+export UNSLOTH_STUDIO_STOP_WAIT_S=$(( 10#$UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S + 30 ))
# tests run this on the host; everything past here writes /etc/profile.d, /root/.jupyter, /workspace
[[ "${UNSLOTH_STUDIO_LAUNCH_CHECK_ONLY:-0}" == 1 ]] && exit 0
export UNSLOTH_STUDIO_HOME="${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}"
diff --git a/docker/supervisord.conf b/docker/supervisord.conf
index f530239fd69..09d4b5976e5 100644
--- a/docker/supervisord.conf
+++ b/docker/supervisord.conf
@@ -36,6 +36,8 @@ autorestart=unexpected
exitcodes=0
startretries=3
startsecs=5
+stopwaitsecs=%(ENV_UNSLOTH_STUDIO_STOP_WAIT_S)s
+killasgroup=true
environment=HOME="/root",USER="root"
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.py
index 862f35264f1..67f31573edf 100644
--- a/studio/backend/core/training/diffusion_training_service.py
+++ b/studio/backend/core/training/diffusion_training_service.py
@@ -721,6 +721,30 @@ class DiffusionTrainingService:
self._state["updated_at"] = time.time()
return True
+ def stop_for_shutdown(self, timeout: float) -> bool:
+ from utils.account_context import run_as
+
+ with self._lock:
+ proc = self._proc
+ pump = self._pump
+ account = self._result_account
+
+ def settled():
+ # The pump writes the run record after the child exits, so wait for it too.
+ return (proc is None or not proc.is_alive()) and (pump is None or not pump.is_alive())
+
+ if settled():
+ return True
+ if proc is not None and proc.is_alive():
+ # The signal path runs as the owner, which job_control refuses for a managed account's run.
+ run_as(account, self.stop, save = True)
+ deadline = time.monotonic() + max(0.0, timeout)
+ while time.monotonic() < deadline:
+ if settled():
+ return True
+ time.sleep(0.25)
+ return False
+
@job_read(
lambda self: {
**_idle_state(),
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index eeb9f6c0488..5d17c2877fe 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -23,7 +23,7 @@ from core.training.account_jobs import (
validate_job_paths,
worker_alive,
)
-from utils.account_context import account_thread, current_account
+from utils.account_context import account_thread, current_account, run_as
import json as _json
import math
import multiprocessing as mp
@@ -72,6 +72,9 @@ _STOP_TIMEOUT_S = _env_int("UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S", 600)
_CANCEL_TIMEOUT_S = _env_int("UNSLOTH_STUDIO_TRAINING_CANCEL_TIMEOUT_S", 120)
# Generous: is_run_finished already unwedges the UI, and a post-run wandb sync can legitimately take a while.
_COMPLETE_EXIT_GRACE_S = _env_int("UNSLOTH_STUDIO_TRAINING_COMPLETE_EXIT_GRACE_S", 120)
+# Also bounded by the stop watchdog above: raising this past _STOP_TIMEOUT_S only waits longer
+# for a worker that gets force-terminated at the watchdog's cap anyway.
+_SHUTDOWN_STOP_TIMEOUT_S = _env_int("UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S", 120)
# A few short retries so a transient SQLite lock doesn't lose the terminal state.
_DB_FINALIZE_RETRIES = 3
@@ -2338,6 +2341,50 @@ class TrainingBackend:
if self.current_job_id == run_id:
self._run_finalized = False
+ def stop_for_shutdown(self, timeout: float = _SHUTDOWN_STOP_TIMEOUT_S) -> bool:
+ """Ask a live run to stop and save, then wait for the worker and for the pump's
+ terminal DB write. True once nothing is left to save; False if the stop was refused
+ or the save outlived ``timeout``, in which case the caller's force_terminate() ends it."""
+ with self._lock:
+ proc = self._proc
+ job_id = self.current_job_id
+ account = self._result_account
+ deadline = time.monotonic() + max(0.0, timeout)
+ if proc is None or not proc.is_alive() or not job_id or self.is_run_finished():
+ return self._await_run_record(proc, deadline)
+ # The signal path runs as the owner, which job_control refuses for a managed account's run.
+ if not run_as(account, self.stop_training, save = True, expected_job_id = job_id):
+ return False
+ logger.info("Shutdown: stopping training run %s and saving a checkpoint", job_id)
+ while time.monotonic() < deadline:
+ if not proc.is_alive() or self.is_run_finished():
+ return self._await_run_record(proc, deadline)
+ time.sleep(0.25)
+ logger.warning(
+ "Shutdown: training run %s did not finish saving within %.0fs", job_id, timeout
+ )
+ return False
+
+ def _await_run_record(self, proc: "Optional[mp.Process]", deadline: float) -> bool:
+ """Wait out the pump's terminal DB write, which lands after _complete_seen is set and can
+ outlast force_terminate's join when SQLite is contended. Exiting first leaves the row
+ running, which the next startup's orphan sweep rewrites to an error; the checkpoint and
+ its output_dir survive, the stopped status and the final metrics do not.
+
+ Only a worker that has exited is waited on, since the pump loops while one is alive. A run
+ whose worker lingers past its save still falls back to that join: telling a write that has
+ not started from one that started and failed needs a signal the finalize paths do not
+ publish, and adding one is a change to terminal-state handling, not to shutdown."""
+ while time.monotonic() < deadline:
+ if proc is not None and proc.is_alive():
+ return True
+ pump = self._pump_thread
+ if pump is None or not pump.is_alive():
+ return True
+ time.sleep(0.25)
+ logger.warning("Shutdown: the training run record was still being written at the deadline")
+ return True
+
def force_terminate(self, target_proc: "Optional[mp.Process]" = None) -> None:
"""Force-kill the training subprocess so state can be reset immediately. With
``target_proc``, terminate only that handle and no-op if a new run has replaced
diff --git a/studio/backend/run.py b/studio/backend/run.py
index bdda33e49ae..d76fe5c2f4c 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -1439,6 +1439,23 @@ def _graceful_shutdown(server = None):
except Exception as e:
logger.warning("Error stopping the LAN listener: %s", e)
+ try:
+ from core.training.training import _training_backend
+ if _training_backend is not None:
+ _training_backend.stop_for_shutdown()
+ except Exception as e:
+ logger.warning("Error stopping the training run for shutdown: %s", e)
+
+ try:
+ # sys.modules: an install that never trained a diffusion LoRA does not import it here.
+ _diffusion = sys.modules.get("core.training.diffusion_training_service")
+ if _diffusion is not None and _diffusion._service is not None:
+ from core.training.training import _SHUTDOWN_STOP_TIMEOUT_S
+ if not _diffusion._service.stop_for_shutdown(_SHUTDOWN_STOP_TIMEOUT_S):
+ logger.warning("Shutdown: diffusion training did not finish saving in time")
+ except Exception as e:
+ logger.warning("Error stopping the diffusion training run for shutdown: %s", e)
+
if server is not None:
server.should_exit = True
diff --git a/studio/backend/tests/test_diffusion_training.py b/studio/backend/tests/test_diffusion_training.py
index 151217fef69..5313b08d63b 100644
--- a/studio/backend/tests/test_diffusion_training.py
+++ b/studio/backend/tests/test_diffusion_training.py
@@ -234,6 +234,52 @@ def test_service_stop_marks_stopped():
assert svc.stop() is False
+def test_service_stop_for_shutdown_saves_and_waits():
+ svc = DiffusionTrainingService(ctx = _FakeCtx(), target = _stoppable_target)
+ svc.start(dict(_CFG))
+ _wait_status(svc, "running")
+ assert svc.stop_for_shutdown(timeout = 5) is True
+ st = svc.status()
+ assert st["status"] == "stopped"
+ assert st["active"] is False
+
+
+def test_service_stop_for_shutdown_is_immediate_when_idle():
+ svc = DiffusionTrainingService(ctx = _FakeCtx(), target = _happy_target)
+ t0 = time.monotonic()
+ assert svc.stop_for_shutdown(timeout = 5) is True
+ assert time.monotonic() - t0 < 1
+
+
+class _ExitedProc:
+ def is_alive(self):
+ return False
+
+
+def test_service_stop_for_shutdown_waits_for_the_pump_after_the_worker_exits():
+ svc = DiffusionTrainingService(ctx = _FakeCtx(), target = _happy_target)
+ written = threading.Event()
+ svc._proc = _ExitedProc()
+ svc._pump = threading.Thread(target = lambda: (time.sleep(0.5), written.set()), daemon = True)
+ svc._pump.start()
+ assert svc.stop_for_shutdown(timeout = 5) is True
+ assert written.is_set()
+
+
+def _ignores_stop_target(*, event_queue, stop_queue, config):
+ event_queue.put({"type": "model_load_completed"})
+ time.sleep(3)
+
+
+def test_service_stop_for_shutdown_wait_is_bounded():
+ svc = DiffusionTrainingService(ctx = _FakeCtx(), target = _ignores_stop_target)
+ svc.start(dict(_CFG))
+ _wait_status(svc, "running")
+ t0 = time.monotonic()
+ assert svc.stop_for_shutdown(timeout = 0.5) is False
+ assert 0.4 < time.monotonic() - t0 < 2
+
+
def test_service_crash_without_terminal_event_is_error():
svc = DiffusionTrainingService(ctx = _FakeCtx(), target = _crashing_target)
svc.start(dict(_CFG))
diff --git a/studio/backend/tests/test_graceful_shutdown_saves_training.py b/studio/backend/tests/test_graceful_shutdown_saves_training.py
new file mode 100644
index 00000000000..e9c791a1fdc
--- /dev/null
+++ b/studio/backend/tests/test_graceful_shutdown_saves_training.py
@@ -0,0 +1,47 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shutdown order: both trainers are asked to stop and save before anything is torn down.
+
+Measured on the published Docker image, a save that overlapped uvicorn's lifespan teardown
+lost the worker mid-write, so the wait has to come before should_exit and the force-kill.
+"""
+
+from types import SimpleNamespace
+
+
+class _Server:
+ def __init__(self, order):
+ self._order = order
+
+ @property
+ def should_exit(self):
+ return False
+
+ @should_exit.setter
+ def should_exit(self, value):
+ self._order.append("should_exit")
+
+
+def test_the_run_is_saved_before_the_server_stops_and_before_the_kill(monkeypatch):
+ import run
+ import core.training.diffusion_training_service as diffusion
+ import core.training.training as training
+
+ order = []
+ fake = SimpleNamespace(
+ stop_for_shutdown = lambda: order.append("stop_for_shutdown") or True,
+ force_terminate = lambda: order.append("force_terminate"),
+ )
+ fake_diffusion = SimpleNamespace(
+ stop_for_shutdown = lambda timeout: order.append(("diffusion", timeout)) or True,
+ )
+ monkeypatch.setattr(training, "_training_backend", fake)
+ monkeypatch.setattr(diffusion, "_service", fake_diffusion)
+ run._graceful_shutdown(_Server(order))
+ assert order == [
+ "stop_for_shutdown",
+ ("diffusion", training._SHUTDOWN_STOP_TIMEOUT_S),
+ "should_exit",
+ "force_terminate",
+ ]
diff --git a/studio/backend/tests/test_job_accounts.py b/studio/backend/tests/test_job_accounts.py
index ea1ede0b3d2..bdb6dd0b092 100644
--- a/studio/backend/tests/test_job_accounts.py
+++ b/studio/backend/tests/test_job_accounts.py
@@ -167,6 +167,19 @@ def test_finished_training_results_remain_private_and_successor_clears_them(trai
assert backend._progress.status_message != "Alice done"
+def test_shutdown_stops_and_saves_a_managed_accounts_run(training):
+ backend, proc, _ = training
+ assert start_training(backend)
+ threading.Timer(0.2, lambda: setattr(proc, "running", False)).start()
+ assert current_account() == OWNER
+ assert backend.stop_for_shutdown(timeout = 5) is True
+ sent = []
+ while not backend._stop_queue.empty():
+ sent.append(backend._stop_queue.get_nowait())
+ assert {"type": "stop", "save": True} in sent
+ assert not proc.terminated
+
+
@pytest.fixture
def export(monkeypatch):
from core.export.orchestrator import ExportOrchestrator
@@ -434,6 +447,20 @@ def test_diffusion_status_and_stop_are_private():
assert service._proc.is_alive()
+def test_shutdown_stops_and_saves_a_managed_accounts_diffusion_run():
+ from core.training.diffusion_training_service import DiffusionTrainingService
+
+ service = DiffusionTrainingService()
+ service._result_account = service.job_account = ALICE
+ service._proc = FakeProcess()
+ service._proc.start()
+ service._stop_queue = queue.Queue()
+ threading.Timer(0.2, lambda: setattr(service._proc, "running", False)).start()
+ assert current_account() == OWNER
+ assert service.stop_for_shutdown(timeout = 5) is True
+ assert service._stop_queue.get_nowait() is True
+
+
def test_diffusion_history_resolves_per_account():
from core.training.diffusion_training_service import _runs_dir
assert run_as(ALICE, _runs_dir) == run_as(ALICE, tensorboard_root) / "diffusion"
diff --git a/studio/backend/tests/test_training_shutdown_stop.py b/studio/backend/tests/test_training_shutdown_stop.py
new file mode 100644
index 00000000000..24255006020
--- /dev/null
+++ b/studio/backend/tests/test_training_shutdown_stop.py
@@ -0,0 +1,165 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A server shutdown asks a running training job to stop and save before anything is killed."""
+
+from __future__ import annotations
+
+import threading
+import time
+
+import pytest
+
+
+class _FakeProc:
+ def __init__(self):
+ self.alive = True
+ self.pid = 4242
+
+ def is_alive(self):
+ return self.alive
+
+
+def backend():
+ from core.training.training import TrainingBackend
+ return TrainingBackend()
+
+
+def _running(backend, job_id = "job_1"):
+ backend._proc = _FakeProc()
+ backend.current_job_id = job_id
+ return backend._proc
+
+
+def _record_stop(
+ monkeypatch,
+ backend,
+ result = True,
+ on_stop = None,
+):
+ calls = []
+
+ def stop_training(**kw):
+ calls.append(kw)
+ if on_stop is not None:
+ on_stop()
+ return result
+
+ monkeypatch.setattr(backend, "stop_training", stop_training)
+ return calls
+
+
+def test_an_idle_backend_needs_no_stop(backend, monkeypatch):
+ calls = _record_stop(monkeypatch, backend)
+ assert backend.stop_for_shutdown(timeout = 1) is True
+ assert calls == []
+
+
+def test_a_running_job_is_stopped_with_save_and_waited_for(backend, monkeypatch):
+ proc = _running(backend)
+ calls = _record_stop(
+ monkeypatch,
+ backend,
+ on_stop = lambda: threading.Timer(0.2, lambda: setattr(proc, "alive", False)).start(),
+ )
+ t0 = time.monotonic()
+ assert backend.stop_for_shutdown(timeout = 5) is True
+ elapsed = time.monotonic() - t0
+ assert calls == [{"save": True, "expected_job_id": "job_1"}]
+ # Returning before the worker is gone would mean the caller kills a mid-save worker.
+ assert not proc.is_alive()
+ assert 0.2 <= elapsed < 4
+
+
+def test_a_saved_run_counts_as_done_even_while_the_worker_lingers(backend, monkeypatch):
+ proc = _running(backend)
+ _record_stop(
+ monkeypatch,
+ backend,
+ on_stop = lambda: threading.Timer(0.2, backend._complete_seen.set).start(),
+ )
+ t0 = time.monotonic()
+ assert backend.stop_for_shutdown(timeout = 5) is True
+ elapsed = time.monotonic() - t0
+ assert proc.is_alive() and backend.is_run_finished()
+ assert 0.2 <= elapsed < 4
+
+
+def test_an_already_finished_run_is_not_stopped_again(backend, monkeypatch):
+ _running(backend)
+ backend._complete_seen.set()
+ calls = _record_stop(monkeypatch, backend)
+ assert backend.stop_for_shutdown(timeout = 5) is True
+ assert calls == []
+
+
+def test_the_wait_is_bounded(backend, monkeypatch):
+ _running(backend)
+ _record_stop(monkeypatch, backend)
+ t0 = time.monotonic()
+ assert backend.stop_for_shutdown(timeout = 0.5) is False
+ assert 0.4 < time.monotonic() - t0 < 3
+
+
+def test_a_refused_stop_is_reported(backend, monkeypatch):
+ _running(backend)
+ _record_stop(monkeypatch, backend, result = False)
+ assert backend.stop_for_shutdown(timeout = 5) is False
+
+
+def _pump(backend, seconds: float) -> threading.Event:
+ """A pump still writing the run record for ``seconds`` after the worker is gone."""
+ written = threading.Event()
+ backend._pump_thread = threading.Thread(
+ target = lambda: (time.sleep(seconds), written.set()), daemon = True
+ )
+ backend._pump_thread.start()
+ return written
+
+
+def test_a_worker_that_exited_still_waits_for_the_run_record(backend, monkeypatch):
+ # Left running, the row is rewritten to an error on the next start, losing the stopped status.
+ proc = _running(backend)
+ proc.alive = False
+ written = _pump(backend, 0.6)
+ calls = _record_stop(monkeypatch, backend)
+ assert backend.stop_for_shutdown(timeout = 5) is True
+ assert written.is_set()
+ assert calls == []
+
+
+def test_the_stop_waits_for_the_run_record_after_the_worker_exits(backend, monkeypatch):
+ proc = _running(backend)
+ written = _pump(backend, 0.6)
+ _record_stop(
+ monkeypatch,
+ backend,
+ on_stop = lambda: threading.Timer(0.2, lambda: setattr(proc, "alive", False)).start(),
+ )
+ assert backend.stop_for_shutdown(timeout = 5) is True
+ assert written.is_set()
+
+
+def test_a_lingering_worker_is_not_held_for_its_pump(backend, monkeypatch):
+ # The pump cannot exit while the worker lives, so waiting on it would burn the whole budget.
+ _running(backend)
+ _pump(backend, 30)
+ _record_stop(
+ monkeypatch,
+ backend,
+ on_stop = lambda: threading.Timer(0.2, backend._complete_seen.set).start(),
+ )
+ t0 = time.monotonic()
+ assert backend.stop_for_shutdown(timeout = 5) is True
+ assert time.monotonic() - t0 < 4
+
+
+def test_the_run_record_wait_is_bounded(backend, monkeypatch):
+ proc = _running(backend)
+ proc.alive = False
+ _pump(backend, 30)
+ _record_stop(monkeypatch, backend)
+ t0 = time.monotonic()
+ assert backend.stop_for_shutdown(timeout = 0.5) is True
+ assert 0.4 < time.monotonic() - t0 < 3
diff --git a/tests/python/test_docker_rocm.py b/tests/python/test_docker_rocm.py
index af566145895..dbfad3d6587 100644
--- a/tests/python/test_docker_rocm.py
+++ b/tests/python/test_docker_rocm.py
@@ -116,7 +116,16 @@ def _run_sh(
def _image_and_cmd(argv):
"""The positional tail of `docker run`: image, then the container command."""
# every option run.sh emits takes a value or is a known flag
- flags_with_value = {"--device", "--group-add", "--ulimit", "-v", "-e", "-p", "--gpus"}
+ flags_with_value = {
+ "--device",
+ "--group-add",
+ "--ulimit",
+ "-v",
+ "-e",
+ "-p",
+ "--gpus",
+ "--stop-timeout",
+ }
i = 0
while i < len(argv):
a = argv[i]
diff --git a/tests/python/test_docker_studio_stop_grace.py b/tests/python/test_docker_studio_stop_grace.py
new file mode 100644
index 00000000000..12d1857861f
--- /dev/null
+++ b/tests/python/test_docker_studio_stop_grace.py
@@ -0,0 +1,167 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-Present the Unsloth team. See /studio/LICENSE.AGPL-3.0
+
+"""docker stop must leave a training run the time to save its checkpoint.
+
+Studio stops the run cooperatively on SIGTERM and waits up to
+UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S for the save. supervisord and docker stop both
+default to a 10 second budget, so the image, the launcher and run.sh carry a matching one.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+DOCKER = REPO_ROOT / "docker"
+LAUNCH = DOCKER / "studio_launch.sh"
+
+pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason = "needs bash")
+
+
+def _program(name: str) -> str:
+ conf = (DOCKER / "supervisord.conf").read_text(encoding = "utf-8")
+ match = re.search(rf"^\[program:{name}\]\n(.*?)(?=^\[|\Z)", conf, re.M | re.S)
+ assert match, name
+ return match.group(1)
+
+
+# Sourced under an EXIT trap so the wait the launcher exports for supervisord can be read
+# back; the check-only exit still runs the trap, and nothing is written to the host.
+_PROBE = r"""trap 'printf "WAIT=%s\n" "${UNSLOTH_STUDIO_STOP_WAIT_S-unset}"' EXIT; . "$1" """
+
+
+def _launch(**env: str) -> subprocess.CompletedProcess:
+ e = dict(os.environ, UNSLOTH_STUDIO_LAUNCH_CHECK_ONLY = "1", JUPYTER_PORT = "8888", **env)
+ return subprocess.run(
+ ["bash", "-c", _PROBE, "_", str(LAUNCH)],
+ capture_output = True,
+ text = True,
+ env = e,
+ timeout = 120,
+ )
+
+
+def test_supervisord_waits_for_the_save_and_then_kills_the_whole_tree():
+ studio = _program("studio")
+ assert "stopwaitsecs=%(ENV_UNSLOTH_STUDIO_STOP_WAIT_S)s" in studio
+ assert "killasgroup=true" in studio
+ # a raw SIGTERM to the group would kill the worker before Studio can ask it to save
+ assert "stopasgroup" not in studio
+
+
+def test_the_image_defaults_resolve_the_placeholder_without_the_launcher():
+ dockerfile = (DOCKER / "Dockerfile.studio").read_text(encoding = "utf-8")
+ assert "UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S=120" in dockerfile
+ assert "UNSLOTH_STUDIO_STOP_WAIT_S=150" in dockerfile
+
+
+# "0600" and "08" would read as octal, and an unset budget must still produce a wait.
+ "value, expected", [(None, "150"), ("0", "30"), ("120", "150"), ("0600", "630"), ("08", "38")]
+)
+def test_the_launcher_derives_supervisords_wait_from_the_budget(value, expected):
+ res = _launch(**({} if value is None else {"UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S": value}))
+ assert res.returncode == 0, res.stderr
+ assert f"WAIT={expected}" in res.stdout, res.stdout
+
+
[email protected]("value", ["soon", "-1", "1.5"])
+def test_a_budget_that_is_not_a_number_of_seconds_is_refused(value: str):
+ res = _launch(UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S = value)
+ assert res.returncode != 0
+ assert f"UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S={value}" in res.stderr, res.stderr
+ assert "WAIT=unset" in res.stdout, res.stdout
+
+
+def test_an_empty_budget_falls_back_to_the_default():
+ res = _launch(UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S = "")
+ assert res.returncode == 0, res.stderr
+ assert "WAIT=150" in res.stdout, res.stdout
+
+
+def _run_sh(
+ tmp_path: Path, budget: "str | None", **extra: str
+) -> "tuple[subprocess.CompletedProcess, list[str]]":
+ bindir = tmp_path / "bin"
+ bindir.mkdir()
+ argv = tmp_path / "argv"
+ stubs = {
+ "docker": 'if [ "$1" = "info" ]; then echo " Runtimes: runc"; exit 0; fi\n'
+ f'printf "%s\\n" "$@" > {argv}\nexit 0\n',
+ "nvidia-smi": "exit 1\n",
+ }
+ for name, body in stubs.items():
+ (bindir / name).write_text("#!/usr/bin/env bash\n" + body)
+ (bindir / name).chmod(0o755)
+ (tmp_path / "root" / "dev").mkdir(parents = True)
+ env = {
+ k: v for k, v in os.environ.items() if not k.startswith(("UNSLOTH_", "HF_TOKEN", "WANDB_"))
+ }
+ env.update(
+ PATH = f"{bindir}:/usr/bin:/bin",
+ HOME = str(tmp_path / "home"),
+ UNSLOTH_DEV_ROOT = str(tmp_path / "root"),
+ UNSLOTH_WORKDIR = str(tmp_path),
+ UNSLOTH_STUDIO_VOLUME = "",
+ )
+ if budget is not None:
+ env["UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S"] = budget
+ env.update(extra)
+ res = subprocess.run(
+ [shutil.which("bash"), str(DOCKER / "run.sh"), "true"],
+ capture_output = True,
+ text = True,
+ env = env,
+ timeout = 120,
+ )
+ return res, argv.read_text().splitlines() if argv.exists() else []
+
+
+_posix_only = pytest.mark.skipif(os.name != "posix", reason = "run.sh needs a POSIX shell")
+
+
+@_posix_only
+ "budget, expected",
+ [(None, "150"), ("120", "150"), ("0", "30"), ("0600", "630"), ("08", "38")],
+)
+def test_run_sh_gives_docker_stop_the_launchers_budget(tmp_path, budget, expected):
+ res, argv = _run_sh(tmp_path, budget)
+ assert res.returncode == 0, res.stderr
+ assert argv[argv.index("--stop-timeout") + 1] == expected
+
+
+@_posix_only
[email protected]("budget", ["soon", "-1", "1.5"])
+def test_run_sh_refuses_a_budget_that_is_not_a_number_of_seconds(tmp_path, budget):
+ res, argv = _run_sh(tmp_path, budget)
+ assert res.returncode != 0
+ assert f"UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S={budget}" in res.stderr, res.stderr
+ assert argv == []
+
+
+# The watchdog cap travels too: a budget raised past it alone waits on a save it kills.
+_BUDGET_VARS = ("UNSLOTH_STUDIO_SHUTDOWN_STOP_TIMEOUT_S", "UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S")
+
+
+@_posix_only
+def test_run_sh_forwards_both_budgets_into_the_container(tmp_path):
+ res, argv = _run_sh(tmp_path, "900", UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S = "900")
+ assert res.returncode == 0, res.stderr
+ for name in _BUDGET_VARS:
+ assert argv[argv.index(name) - 1] == "-e", name
+
+
+@_posix_only
+def test_run_sh_forwards_nothing_the_host_did_not_set(tmp_path):
+ res, argv = _run_sh(tmp_path, None)
+ assert res.returncode == 0, res.stderr
+ for name in _BUDGET_VARS:
+ assert name not in argv
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index c9ec87e43d3..f27cde1d68f 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -1926,6 +1926,7 @@ def studio_default(
run_kwargs["frontend_path"] = resolved_frontend
run_server(**run_kwargs)
+ _graceful_shutdown_on_sigterm()
try:
if run_mod._shutdown_event is not None:
# Event.wait() with no timeout blocks at C level on Linux and swallows SIGINT.
@@ -2690,6 +2691,7 @@ def run(
typer.echo(f"API Key: {api_key}")
typer.secho(_tool_notice, fg = _tool_notice_fg, bold = True)
+ _graceful_shutdown_on_sigterm()
try:
if run_mod._shutdown_event is not None:
while not run_mod._shutdown_event.is_set():
@@ -2834,6 +2836,19 @@ def _pid_is_studio_server(pid: int, created_times: "Sequence[float | None]" = ()
return any(abs(actual - c) < 1.0 for c in known)
+def _graceful_shutdown_on_sigterm() -> None:
+ """Route SIGTERM (docker stop, `unsloth studio stop`) into the wait loop's Ctrl+C path,
+ which stops and saves a running training job before anything is killed."""
+ import signal as _signal
+
+ def _handler(signum, frame):
+ # Restore the default so a second signal force-quits if the shutdown stalls.
+ _signal.signal(_signal.SIGTERM, _signal.SIG_DFL)
+ raise KeyboardInterrupt
+
+ _signal.signal(_signal.SIGTERM, _handler)
+
+
def _signal_stop(pid: int) -> "str | None":
import signal as _signal
diff --git a/unsloth_cli/tests/test_studio_sigterm.py b/unsloth_cli/tests/test_studio_sigterm.py
new file mode 100644
index 00000000000..fbeec02e5cf
--- /dev/null
+++ b/unsloth_cli/tests/test_studio_sigterm.py
@@ -0,0 +1,64 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""SIGTERM (docker stop through supervisord, `unsloth studio stop`) takes the same path as Ctrl+C.
+
+`unsloth studio` and `unsloth start` run the server in-process and caught only
+KeyboardInterrupt, so a SIGTERM died on Python's default action: no `_graceful_shutdown`,
+no stop-and-save for a running training job, no child cleanup.
+"""
+
+import ast
+import signal
+from pathlib import Path
+
+import pytest
+
+from unsloth_cli.commands import studio as studio_mod
+
+STUDIO_SRC = Path(studio_mod.__file__).read_text(encoding = "utf-8")
+
+
+def _installs_before_waiting(fn: ast.FunctionDef) -> bool:
+ waits = [
+ node.lineno
+ for node in ast.walk(fn)
+ if isinstance(node, ast.While)
+ and any(
+ isinstance(inner, ast.Attribute) and inner.attr == "_shutdown_event"
+ for inner in ast.walk(node)
+ )
+ ]
+ if not waits:
+ return False
+ return any(
+ isinstance(stmt, ast.Expr)
+ and isinstance(stmt.value, ast.Call)
+ and isinstance(stmt.value.func, ast.Name)
+ and stmt.value.func.id == "_graceful_shutdown_on_sigterm"
+ and stmt.lineno < min(waits)
+ for stmt in fn.body
+ )
+
+
+def restore_sigterm():
+ previous = signal.getsignal(signal.SIGTERM)
+ yield
+ signal.signal(signal.SIGTERM, previous)
+
+
+def test_sigterm_becomes_a_keyboard_interrupt_once(restore_sigterm):
+ studio_mod._graceful_shutdown_on_sigterm()
+ handler = signal.getsignal(signal.SIGTERM)
+ assert callable(handler) and handler is not signal.SIG_DFL
+ with pytest.raises(KeyboardInterrupt):
+ handler(signal.SIGTERM, None)
+ assert signal.getsignal(signal.SIGTERM) is signal.SIG_DFL
+
+
+def test_both_server_wait_loops_install_the_handler():
+ """Both in-process commands, matched on the parsed tree so a commented-out call fails."""
+ functions = [n for n in ast.walk(ast.parse(STUDIO_SRC)) if isinstance(n, ast.FunctionDef)]
+ installed = sorted(fn.name for fn in functions if _installs_before_waiting(fn))
+ assert installed == ["run", "studio_default"], installed