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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: fix training stuck at 100% when the worker will not exit (#7938)
Daniel Hanfa40b0be4629
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 300960210e9..1e41a032224 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -54,6 +54,9 @@ def _env_int(name: str, default: int) -> int:_STOP_GRACE_S = _env_int("UNSLOTH_STUDIO_TRAINING_STOP_GRACE_S", 15)_STOP_TIMEOUT_S = _env_int("UNSLOTH_STUDIO_TRAINING_STOP_TIMEOUT_S", 600)_CANCEL_TIMEOUT_S = _env_int("UNSLOTH_STUDIO_TRAINING_CANCEL_TIMEOUT_S", 120)+# Backstop to reclaim the GPU from a worker wedged in teardown. 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)# Watchdog DB finalize: a few short retries so a transient SQLite lock doesn't lose the# terminal state, since the watchdog is the sole finalizer once _proc is dropped.@@ -1113,6 +1116,11 @@ class TrainingBackend:with self._lock:if self.current_job_id != run_id:return False+ # The pump can finish the run between the route's terminal check and this+ # lock, so re-test: latching _should_stop after the fact would report a+ # saved run as stopped for good.+ if save and self._run_finished_locked():+ return Falseif save or not run_id:self._should_stop = Trueif not save and not run_id:@@ -1136,10 +1144,14 @@ class TrainingBackend:self,cancel: bool,expected_job_id: Optional[str] = None,+ grace_s: Optional[float] = None,+ terminal_seen: bool = False,) -> None:- """Start a daemon that force-terminates the worker if a requested stop does not- exit on its own. No-op if no worker is alive or a live watchdog already watches- this proc (a stale watchdog on an old proc never blocks a new run's watcher)."""+ """Start a daemon that force-terminates a worker that will not exit. Armed by a stop+ and by a run's own terminal event, since a wedged worker strands the UI either way.+ No-op if no worker is alive or a live watchdog already watches this proc (a stale one+ never blocks a new run). ``grace_s`` overrides the post-terminal grace;+ ``terminal_seen`` starts it now, for an ending that never sets ``_complete_seen``."""with self._lock:if expected_job_id is not None and self.current_job_id != expected_job_id:return@@ -1155,6 +1167,7 @@ class TrainingBackend:watchdog = threading.Thread(target = self._stop_watchdog_loop,args = (proc, cancel, self.current_job_id),+ kwargs = {"grace_s": grace_s, "terminal_seen": terminal_seen},name = f"stop-watchdog-{self.current_job_id or 'unknown'}",daemon = True,)@@ -1167,12 +1180,16 @@ class TrainingBackend:target_proc: "mp.Process",cancel: bool,watched_job_id: Optional[str] = None,+ grace_s: Optional[float] = None,+ terminal_seen: bool = False,) -> None:- """Escalate a stuck stop to force_terminate(): grace after "complete", else the- absolute backstop (see the module timeouts). No-ops on a clean exit; exits- silently if a new run replaces the worker."""+ """Escalate a worker that will not exit to force_terminate(): grace after "complete",+ else the absolute backstop (module timeouts). No-ops on a clean exit or once a new run+ replaces the worker. ``grace_s`` overrides ``_STOP_GRACE_S``; ``terminal_seen`` starts+ the grace at entry, so an ending that never sets ``_complete_seen`` (an error) does+ not sit out the whole backstop."""started = time.monotonic()- complete_at: Optional[float] = None+ complete_at: Optional[float] = started if terminal_seen else Nonereason = ""while True:with self._lock:@@ -1184,9 +1201,10 @@ class TrainingBackend:returnnow = time.monotonic()abs_timeout = _CANCEL_TIMEOUT_S if cancelling else _STOP_TIMEOUT_S+ grace = _STOP_GRACE_S if grace_s is None else grace_sif complete_at is None and self._complete_seen.is_set():complete_at = now- if complete_at is not None and now - complete_at >= _STOP_GRACE_S:+ if complete_at is not None and now - complete_at >= grace:reason = "worker still alive after save"breakif now - started >= abs_timeout:@@ -1206,7 +1224,9 @@ class TrainingBackend:reason,)else:- logger.warning("Stop watchdog force-terminating stuck training worker: %s", reason)+ logger.warning(+ "Training watchdog force-terminating a worker that will not exit: %s", reason+ )# force_terminate can raise on a wedged child; finalize regardless.try:self.force_terminate(target_proc = target_proc)@@ -1254,9 +1274,11 @@ class TrainingBackend:with self._lock:if self.current_job_id != run_id:return- self._progress.status_message = error_message or "Training stopped."if error_message:- self._progress.error = error_message+ self._progress.status_message = self._progress.error = error_message+ elif status != "completed":+ self._progress.status_message = "Training stopped."+ # A completed run keeps its message; reaping a wedged worker must not relabel it.# Create the row if a start-time create failed (no-op otherwise; skips when the pump# is mid-create, in which case its create-then-finalize records the run instead).self._ensure_db_run_created()@@ -1402,6 +1424,7 @@ class TrainingBackend:with self._lock:recover = self._in_model_load and not self._xet_fallback_usedproc = self._proc+ run_id = self.current_job_idif recover:self._xet_fallback_used = Trueself._needs_xet_respawn = True@@ -1419,6 +1442,18 @@ class TrainingBackend:# Terminate either way so the pump loop proceeds (respawn or finalize).if proc is not None and proc.is_alive():proc.terminate()+ if not recover:+ # terminate() is only a request: arm the same backstop as the other terminal+ # paths so a worker that ignores it cannot hold the GPU for good. Signal first,+ # since arming no-ops when a watchdog already watches this proc and only this+ # drops it to the grace.+ self._complete_seen.set()+ self._start_stop_watchdog(+ cancel = False,+ expected_job_id = run_id,+ grace_s = _COMPLETE_EXIT_GRACE_S,+ terminal_seen = True,+ )def _respawn_worker_disable_xet(self) -> None:"""Respawn the worker once with HF_HUB_DISABLE_XET=1 after a model-load@@ -1560,6 +1595,25 @@ class TrainingBackend:new_pump.start()return True+ def _run_finished_locked(self) -> bool:+ """is_run_finished()'s terminal test, for callers already holding _lock."""+ if self._start_in_progress:+ return False+ p = self._progress+ return bool(self._complete_seen.is_set() or p.is_completed or p.error)++ def is_run_finished(self) -> bool:+ """Whether the current run reached its own terminal state (saved and finalized).++ is_training_active() is liveness-based, so it stays true until the worker exits, which+ can lag minutes behind a slow teardown or never happen at all, leaving the UI at 100%.+ Status and progress read this so a finished run reports terminal at once; the GPU+ admission guards keep using is_training_active(), since a lingering worker holds VRAM."""+ if getattr(self, "_spawn_in_progress", False):+ return False # a new run is spawning; _progress is still the old run's+ with self._lock:+ return self._run_finished_locked()+def is_training_active(self) -> bool:"""Check if training is currently active."""# A spawn past its sidecar-swap recheck counts as active even before _proc is recorded,@@ -1716,7 +1770,13 @@ class TrainingBackend:self._safe_handle_event(event)continue- if self._proc.is_alive():+ # Snapshot: the watchdog drops _proc last, so a re-read can hit None and kill+ # this thread. A dropped handle means it already finalized.+ proc = self._proc+ if proc is None:+ self._pump_running = False+ return+ if proc.is_alive():continue# Worker exited. Drain the backlog and finalize, guarded so a slow or@@ -2004,6 +2064,9 @@ class TrainingBackend:elif etype == "error":self._progress.is_training = Falseself._progress.error = event.get("error", "Unknown error")+ # Nothing left to save: drop an in-flight watchdog to its grace, not the+ # save backstop.+ self._complete_seen.set()if self._cancel_requested:self._output_dir = self._progress.output_dir = Nonelogger.error("Training error: %s", event.get("error"))@@ -2059,6 +2122,16 @@ class TrainingBackend:elif db_action == "finalize":self._finalize_run_in_db(**db_action_kwargs)+ # Bound how long a worker that will not exit can hold the UI at 100%. No-ops on a+ # prompt exit. Outside the lock: _start_stop_watchdog takes it, not reentrant.+ if etype in ("complete", "error"):+ self._start_stop_watchdog(+ cancel = False,+ expected_job_id = db_action_kwargs.get("expected_job_id"),+ grace_s = _COMPLETE_EXIT_GRACE_S,+ terminal_seen = True,+ )+if etype == "progress":self._log_training_progress()diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex 126d4543bdf..9e5e64dfbf9 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -101,10 +101,10 @@ _PROGRESS_STALL_TIMEOUT_POLLS = 1800 # ~30 min at 1 poll/secdef _is_finalizing(progress, msg_lower: str) -> bool:"""Worker alive past the last step, `complete` not yet drained.- The post-training save emits no step updates, so the bar sat at 100% labelled- "training" for its whole duration, indistinguishable from a hang. Non-terminal- by design: the last step means the optimizer loop ended, not that the save- succeeded, so completion still comes solely from is_completed.+ The save emits no step updates, so the bar sat at 100% labelled "training", which is+ indistinguishable from a hang. Non-terminal by design: the last step means the optimizer+ loop ended, not that the save succeeded, so completion still comes solely from+ is_completed."""if any(k in msg_lower for k in ("saving", "merging")):return True@@ -113,6 +113,14 @@ def _is_finalizing(progress, msg_lower: str) -> bool:return total > 0 and step >= total+def _run_finished(backend) -> bool:+ """Whether the run reported terminal (see TrainingBackend.is_run_finished), so status and+ progress stop waiting on the worker to exit. getattr-guarded like the other backend reads+ here: a stand-in without it keeps the old liveness-only behaviour."""+ check = getattr(backend, "is_run_finished", None)+ return bool(check()) if callable(check) else False++def _validate_local_dataset_paths(paths: list[str], label: str = "Local dataset") -> list[str]:"""Resolve and validate a list of local dataset paths. Returns validated absolute paths."""validated = []@@ -628,7 +636,10 @@ async def stop_training("""try:backend = get_training_backend()- is_active = backend.is_training_active()+ # Terminal-aware like /status and the SSE: otherwise a late Stop on a finished run+ # latches _should_stop and overwrites the finished banner with "Stopping training...",+ # which nothing clears, so /status reports the saved run as "stopped" for good.+ is_active = backend.is_training_active() and not _run_finished(backend)logger.info("Stop requested: save=%s is_active=%s", body.save, is_active)if not is_active:@@ -665,7 +676,7 @@ async def reset_training(current_subject: str = Depends(get_current_subject)):if is_active:if backend._cancel_requested:- # Cancel (save=False) requested — force-terminate to reset immediately.+ # Cancel (save=False) requested -- force-terminate to reset immediately.logger.info("Force-terminating subprocess for immediate reset (cancel path)")backend.force_terminate()else:@@ -714,7 +725,8 @@ async def get_training_status(current_subject: str = Depends(get_current_subjectbackend = get_training_backend()job_id: str = getattr(backend, "current_job_id", "") or ""- is_active = backend.is_training_active()+ # A run still tearing down is not training: report terminal without waiting on exit.+ is_active = backend.is_training_active() and not _run_finished(backend)try:progress = backend.trainer.get_training_progress()@@ -864,6 +876,10 @@ async def stream_training_progress(job_id: str = getattr(backend, "current_job_id", "") or ""# ── Helpers ──────────────────────────────────────────────+ def run_active() -> bool:+ """A run that reported terminal is done, even while its worker tears down."""+ return backend.is_training_active() and not _run_finished(backend)+def build_progress(step: int,loss: Optional[float],@@ -962,7 +978,7 @@ async def stream_training_progress(# ── Initial status (only on fresh connections) ───────────if resume_from_step is None:- is_active = backend.is_training_active()+ is_active = run_active()tp = getattr(getattr(backend, "trainer", None), "training_progress", None)initial_total_steps = getattr(tp, "total_steps", 0) if tp else 0initial_epoch = getattr(tp, "epoch", None) if tp else None@@ -1022,7 +1038,7 @@ async def stream_training_progress(backend.step_history)- while backend.is_training_active():+ while run_active():# Client gone: end the generator without falling through to the final# "complete" frame, which a buffered/proxy consumer could otherwise read# as a finished run while training is still active.diff --git a/studio/backend/tests/test_training_status_terminal.py b/studio/backend/tests/test_training_status_terminal.pynew file mode 100644index 00000000000..ed3cf31c879--- /dev/null+++ b/studio/backend/tests/test_training_status_terminal.py@@ -0,0 +1,253 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The two surfaces that hung at 100% when a finished worker would not exit (#7897).++/api/train/status and the progress SSE keyed off liveness-based is_training_active(), so a+worker wedged in post-save teardown kept reporting "training" forever; they now consult+is_run_finished() too. A live run must be unaffected, and /api/train/stop must be+terminal-aware too: a late Stop must not latch _should_stop over the finished banner.+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path+++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++import routes.training as rt+from core.training.training import TrainingBackend, TrainingProgress+++class _WedgedProc:+ """A worker that reported terminal and then never exits."""++ pid = 999++ def __init__(self):+ self._alive = True++ def is_alive(self):+ return self._alive++ def terminate(self):+ self._alive = False++ def kill(self):+ self._alive = False++ def join(self, timeout = None):+ pass+++def _running(monkeypatch, job_id = "job_1"):+ b = TrainingBackend()+ b.current_job_id = job_id+ b._proc = _WedgedProc()+ b._progress = TrainingProgress(is_training = True, status_message = "Training in progress...")+ b._finalize_run_in_db = lambda **kw: None+ b._ensure_db_run_created = lambda: None+ b._start_stop_watchdog = lambda **kw: None # keep the worker wedged on purpose+ monkeypatch.setattr(rt, "get_training_backend", lambda: b)+ return b+++_DONE = {+ "type": "complete",+ "output_dir": "/tmp/out",+ "status_message": "Training completed! Model saved to /tmp/out",+}+++class _Req:+ headers: dict = {}++ async def is_disconnected(self):+ return False+++async def _sse_events(timeout = 10.0):+ """Event names the real SSE generator yields until it closes."""+ resp = await rt.stream_training_progress(_Req(), current_subject = "t")+ names: list[str] = []++ async def pump():+ async for chunk in resp.body_iterator:+ for line in str(chunk).splitlines():+ if line.startswith("event: "):+ names.append(line[7:].strip())+ if names and names[-1] in ("complete", "error"):+ return++ try:+ await asyncio.wait_for(pump(), timeout = timeout)+ except asyncio.TimeoutError:+ pass+ return names+++def test_status_reports_completed_while_worker_still_wedged(monkeypatch):+ b = _running(monkeypatch)+ b._handle_event(dict(_DONE))+ st = asyncio.run(rt.get_training_status(current_subject = "t"))+ assert st.is_training_running is False+ assert st.phase == "completed"+ assert st.message.startswith("Training completed!")+ assert b._proc.is_alive() is True+++def test_status_reports_error_while_worker_still_wedged(monkeypatch):+ b = _running(monkeypatch)+ b._handle_event({"type": "error", "error": "CUDA OOM", "stack": ""})+ st = asyncio.run(rt.get_training_status(current_subject = "t"))+ assert st.is_training_running is False+ assert st.phase == "error"+++def test_status_unchanged_mid_run(monkeypatch):+ _running(monkeypatch)+ st = asyncio.run(rt.get_training_status(current_subject = "t"))+ assert st.is_training_running is True+ assert st.phase == "training"+++def test_progress_stream_completes_on_a_wedged_worker(monkeypatch):+ b = _running(monkeypatch)+ b.step_history.extend([1, 2])+ b.loss_history.extend([1.0, 0.5])+ b.lr_history.extend([1e-4, 9e-5])+ b._handle_event(dict(_DONE))+ names = asyncio.run(_sse_events())+ assert "complete" in names, names+ assert b._proc.is_alive() is True+++def test_progress_stream_stays_open_while_training(monkeypatch):+ b = _running(monkeypatch)+ b.step_history.append(1)+ b.loss_history.append(1.0)+ b.lr_history.append(1e-4)++ async def _run():+ resp = await rt.stream_training_progress(_Req(), current_subject = "t")+ names: list[str] = []++ async def pump():+ async for chunk in resp.body_iterator:+ for line in str(chunk).splitlines():+ if line.startswith("event: "):+ names.append(line[7:].strip())++ task = asyncio.create_task(pump())+ await asyncio.sleep(1.5)+ assert "complete" not in names, names+ b._handle_event(dict(_DONE)) # run ends; worker still lingers+ for _ in range(100):+ if "complete" in names:+ break+ await asyncio.sleep(0.05)+ task.cancel()+ return names++ assert "complete" in asyncio.run(_run())+++def test_late_stop_does_not_unfinish_a_completed_run(monkeypatch):+ """Stop clicked in the poll window after the run already finished.++ The button greys out only once /api/train/status reports is_training_running=False (3s+ poll), so a click can still land on a run that has saved. /stop is terminal-aware, so it+ reports idle instead of latching _should_stop and overwriting the finished banner with a+ "Stopping..." message no later path clears.+ """+ b = _running(monkeypatch)+ b._handle_event(dict(_DONE))++ resp = asyncio.run(rt.stop_training(rt.TrainingStopRequest(save = True), current_subject = "t"))+ assert resp.status == "idle"+ assert b._should_stop is False++ st = asyncio.run(rt.get_training_status(current_subject = "t"))+ assert st.phase == "completed"+ assert st.message.startswith("Training completed!")++ # ... and it survives the watchdog reaping the wedged worker.+ b._finalize_stopped_after_escalation(target_proc = b._proc, watched_job_id = "job_1")+ st = asyncio.run(rt.get_training_status(current_subject = "t"))+ assert st.phase == "completed"+ assert st.message.startswith("Training completed!")+++def test_stop_and_save_losing_the_race_to_the_pump_keeps_the_run_completed(monkeypatch):+ """The same late Stop, except the run finishes *after* the route's terminal check.++ The pump publishes terminal state under the backend lock, so the re-test has to sit+ inside stop_training() next to the mutation it guards. Without it, /status derives+ "stopped" for a run the DB finalized as completed.+ """+ b = _running(monkeypatch)+ b._db_run_created = True+ real_stop, fired = b.stop_training, []++ def stop_after_complete(save = True):+ if not fired:+ fired.append(True)+ b._handle_event(dict(_DONE)) # the pump wins the gap+ return real_stop(save = save)++ b.stop_training = stop_after_complete++ resp = asyncio.run(rt.stop_training(rt.TrainingStopRequest(save = True), current_subject = "t"))+ assert resp.status == "idle"+ assert b._should_stop is False, "a run that finished in the gap must not latch a stop"+ assert (b._terminal_finalize_payload or {}).get("status") == "completed"++ st = asyncio.run(rt.get_training_status(current_subject = "t"))+ assert st.phase == "completed"+ assert st.message.startswith("Training completed!")+++def test_stop_mid_run_still_works(monkeypatch):+ b = _running(monkeypatch)+ resp = asyncio.run(rt.stop_training(rt.TrainingStopRequest(save = True), current_subject = "t"))+ assert resp.status == "stopped"+ assert b._should_stop is True+++def test_cancel_mid_run_still_works(monkeypatch):+ # save=False takes the other branch, which the guard skips: it has already mutated state.+ b = _running(monkeypatch)+ b._db_run_created = True+ monkeypatch.setattr(+ "storage.studio_db.mark_run_cancel_requested", lambda *a, **k: True, raising = False+ )+ resp = asyncio.run(rt.stop_training(rt.TrainingStopRequest(save = False), current_subject = "t"))+ assert resp.status == "stopped"+ assert b._cancel_requested is True+++def test_surfaces_tolerate_a_backend_without_is_run_finished(monkeypatch):+ # A stand-in backend lacking the new method must fall back to liveness, not raise.+ class _Minimal:+ current_job_id = "job_min"+ step_history: list = []+ loss_history: list = []+ lr_history: list = []+ eval_loss_history: list = []+ eval_step_history: list = []+ eval_enabled = False+ trainer = None+ _should_stop = False++ def is_training_active(self):+ return False++ monkeypatch.setattr(rt, "get_training_backend", lambda: _Minimal())+ st = asyncio.run(rt.get_training_status(current_subject = "t"))+ assert st.is_training_running is False+ assert rt._run_finished(_Minimal()) is Falsediff --git a/studio/backend/tests/test_training_stop_watchdog.py b/studio/backend/tests/test_training_stop_watchdog.pyindex cbe2082e821..60579bef155 100644--- a/studio/backend/tests/test_training_stop_watchdog.py+++ b/studio/backend/tests/test_training_stop_watchdog.py@@ -1,13 +1,18 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Stop-watchdog escalation for a stuck training stop.+"""Watchdog escalation for a training worker that will not exit.A save-stop signals the worker and waits for it to save and exit. On some platforms theworker saves but then wedges in post-save GPU/driver teardown and never exits, leaving therun stuck in "Stopping..." forever. These tests pin the bounded recovery: the watchdogescalates to force_terminate() a short grace after "complete" (save done) or after anabsolute timeout (hang during save), and never force-kills a worker that exits cleanly.++Section (d) covers the same wedge on a run that ends by itself: the model is on disk but the+process lingers, so the liveness-based bar sits at 100% forever (#7897). The pump arms the+same watchdog on a terminal event, and escalation must not relabel a completed run.+Fakes only; no GPU, network, or subprocess."""@@ -48,6 +53,7 @@ _stub("matplotlib", _mpl)_stub("matplotlib.pyplot", _plt)_hw = _types.ModuleType("utils.hardware")_hw.prepare_gpu_selection = lambda *a, **k: (None, None)+_hw.get_device = lambda *a, **k: None_stub("utils.hardware", _hw)_npl = _types.ModuleType("utils.native_path_leases")_npl.native_path_secret_removed_for_child_start = lambda: contextlib.nullcontext()@@ -61,7 +67,10 @@ _stub("utils.paths", _pth)# evict it below if we were the one to create the (stub-bound) module instance._TRAINING_PRE_IMPORTED = "core.training.training" in sys.modules-from core.training.training import TrainingBackend+from core.training.training import TrainingBackend, TrainingProgress as _TP++# Captured before the eviction below, so it survives the sys.modules cleanup.+_TRAINING_MODULE_FILE = sys.modules["core.training.training"].__file__# Restore every stubbed module so this file never pollutes the shared session.for _name in (@@ -266,6 +275,8 @@ def test_new_run_gets_its_own_watchdog(monkeypatch):target_proc,cancel,watched_job_id = None,+ grace_s = None,+ terminal_seen = False,):started.append(target_proc)# No timeout: the finally always releases this, so a superseded watchdog stays@@ -905,3 +916,406 @@ def test_finish_stopped_run_error_leaves_new_run_untouched(monkeypatch):b._finish_stopped_run("job_old", None, [{"step": 1}], 1, None, None, [])assert b._run_finalized is True, "must not unclaim the new run's finalize"+++# ----------------------------------------------------------------------------+# (d) A run that ends on its own and whose worker then wedges in teardown.+# ----------------------------------------------------------------------------+++def _complete_event(output_dir = "/tmp/out"):+ return {+ "type": "complete",+ "output_dir": output_dir,+ "status_message": f"Training completed! Model saved to {output_dir}",+ }+++def test_terminal_event_arms_watchdog_and_reaps_wedged_worker(monkeypatch):+ # Saved, reported "complete", never exited: nothing reaped it, so the UI sat at 100%.+ monkeypatch.setitem(_G, "_COMPLETE_EXIT_GRACE_S", 0.05)+ monkeypatch.setitem(_G, "_STOP_TIMEOUT_S", 100.0) # ensure the grace fires, not the cap+ b = TrainingBackend()+ calls = _record_force_terminate(monkeypatch, b)+ monkeypatch.setattr(b, "_finalize_run_in_db", lambda **kw: None)++ proc = _FakeProc(alive = True)+ b._proc = proc+ b.current_job_id = "job_1"++ b._handle_event(_complete_event())++ assert b._complete_seen.is_set()+ assert b._stop_watchdog is not None, "a terminal event must arm the exit watchdog"+ assert _wait_until(+ lambda: calls == ["force", "final"]+ ), "a worker still alive after the completion grace must be force-terminated"+ b._stop_watchdog.join(timeout = 5)+++def test_terminal_error_event_also_arms_watchdog(monkeypatch):+ # A terminal error signals _complete_seen too, so the grace starts either way.+ monkeypatch.setitem(_G, "_COMPLETE_EXIT_GRACE_S", 0.05)+ monkeypatch.setitem(_G, "_STOP_TIMEOUT_S", 100.0)+ b = TrainingBackend()+ calls = _record_force_terminate(monkeypatch, b)+ monkeypatch.setattr(b, "_finalize_run_in_db", lambda **kw: None)++ b._proc = _FakeProc(alive = True)+ b.current_job_id = "job_1"++ b._handle_event({"type": "error", "error": "boom", "stack": ""})++ assert b._complete_seen.is_set(), "a terminal error leaves nothing to save"+ assert _wait_until(lambda: calls == ["force", "final"])+ b._stop_watchdog.join(timeout = 5)+++def test_normal_completion_never_force_terminates(monkeypatch):+ # The common path: the worker exits shortly after "complete", so arming stays invisible.+ monkeypatch.setitem(_G, "_COMPLETE_EXIT_GRACE_S", 5.0)+ monkeypatch.setitem(_G, "_STOP_TIMEOUT_S", 10.0)+ b = TrainingBackend()+ calls = _record_force_terminate(monkeypatch, b)+ monkeypatch.setattr(b, "_finalize_run_in_db", lambda **kw: None)++ proc = _FakeProc(alive = True)+ b._proc = proc+ b.current_job_id = "job_1"++ b._handle_event(_complete_event())+ time.sleep(0.1)+ proc._alive = False # worker exits on its own, well inside the grace++ b._stop_watchdog.join(timeout = 5)+ assert calls == [], "a worker that exits on its own must never be force-terminated"+++def test_completion_watchdog_does_not_preempt_a_stop_watchdog(monkeypatch):+ # A user stop armed the tighter grace; the terminal event must not replace it.+ b = TrainingBackend()+ monkeypatch.setattr(b, "_finalize_run_in_db", lambda **kw: None)+ monkeypatch.setattr(b, "_stop_watchdog_loop", lambda *a, **k: None)++ b._proc = _FakeProc(alive = True)+ b.current_job_id = "job_1"+ b._start_stop_watchdog(cancel = False)+ first = b._stop_watchdog+ first.join(timeout = 5)++ # Still the watcher of record for this proc while it is alive.+ b._stop_watchdog = first+ b._handle_event(_complete_event())+ assert b._stop_watchdog is first or not first.is_alive()+++def test_escalation_finalize_keeps_completed_status_message(monkeypatch):+ # Reaping a wedged worker after a successful save must not relabel the run.+ b = TrainingBackend()+ b.current_job_id = "job_1"+ b._output_dir = "/tmp/out"+ b._progress.is_completed = True+ b._progress.status_message = "Training completed! Model saved to /tmp/out"+ b._terminal_finalize_payload = {+ "status": "completed",+ "output_dir": "/tmp/out",+ "clear_output_dir": False,+ "expected_job_id": "job_1",+ }+ b._run_finalized = True # the pump already recorded the terminal DB state+ monkeypatch.setattr(b, "_ensure_db_run_created", lambda: None)++ proc = _FakeProc(alive = False)+ b._proc = proc+ b._finalize_stopped_after_escalation(target_proc = proc, watched_job_id = "job_1")++ assert b._progress.status_message == "Training completed! Model saved to /tmp/out"+ assert b._progress.error is None+ assert b._progress.is_completed is True+ assert b._progress.is_training is False+ assert b._proc is None, "the handle must be dropped so is_training_active() goes false"+++def test_escalation_finalize_still_reports_a_stop_as_stopped(monkeypatch):+ # The pre-existing stop path keeps its message.+ b = TrainingBackend()+ b.current_job_id = "job_1"+ b._should_stop = True+ b._output_dir = "/tmp/out"+ b._terminal_finalize_payload = {+ "status": "stopped",+ "output_dir": "/tmp/out",+ "clear_output_dir": False,+ "expected_job_id": "job_1",+ }+ b._run_finalized = True+ monkeypatch.setattr(b, "_ensure_db_run_created", lambda: None)++ proc = _FakeProc(alive = False)+ b._proc = proc+ b._finalize_stopped_after_escalation(target_proc = proc, watched_job_id = "job_1")++ assert b._progress.status_message == "Training stopped."+++def test_pump_loop_exits_when_the_watchdog_drops_the_handle(monkeypatch):+ # The watchdog drops _proc last; a drop between the pump's two reads killed the pump.+ b = TrainingBackend()+ proc = _FakeProc(alive = True)+ b._proc = proc+ b._event_queue = queue.Queue()++ def _read_queue(_q, timeout_sec = None):+ b._proc = None # watchdog finalizes concurrently+ return None++ monkeypatch.setattr(b, "_read_queue", _read_queue)++ done = threading.Event()++ def _run():+ b._pump_loop()+ done.set()++ t = threading.Thread(target = _run, daemon = True)+ t.start()+ assert done.wait(timeout = 5), "pump must return cleanly, not die on a dropped handle"+ assert b._pump_running is False+++# ----------------------------------------------------------------------------+# (e) A finished run reports terminal at once, without waiting on the worker.+# ----------------------------------------------------------------------------+++def _running_backend(job_id = "job_1"):+ b = TrainingBackend()+ b.current_job_id = job_id+ b._proc = _FakeProc(alive = True)+ b._progress = _TP(is_training = True, status_message = "Training in progress...")+ b._finalize_run_in_db = lambda **kw: None+ b._ensure_db_run_created = lambda: None+ b._start_stop_watchdog = lambda **kw: None+ return b+++def test_is_run_finished_false_while_training():+ b = _running_backend()+ assert b.is_run_finished() is False+ assert b.is_training_active() is True+++def test_is_run_finished_true_once_terminal_even_though_worker_lives():+ # The whole point: the UI must not wait on a worker wedged in teardown.+ b = _running_backend()+ b._handle_event(_complete_event())+ assert b.is_run_finished() is True+ assert b.is_training_active() is True, "admission guards still see the live worker"+++def test_is_run_finished_true_on_error():+ b = _running_backend()+ b._handle_event({"type": "error", "error": "boom", "stack": ""})+ assert b.is_run_finished() is True+++def test_is_run_finished_untrue_for_a_fresh_backend():+ assert TrainingBackend().is_run_finished() is False+++def test_is_run_finished_does_not_leak_into_the_next_run():+ b = _running_backend()+ b._handle_event(_complete_event())+ assert b.is_run_finished() is True+ # start_training's reset block.+ b._complete_seen.clear()+ b._progress = _TP(is_training = True, status_message = "Initializing training...")+ b.current_job_id = "job_2"+ b._proc = _FakeProc(alive = True)+ assert b.is_run_finished() is False+++def test_is_run_finished_false_during_spawn_and_start_windows():+ # _progress holds the previous run until start_training resets it.+ b = _running_backend()+ b._handle_event(_complete_event())+ b._spawn_in_progress = True+ assert b.is_run_finished() is False+ b._spawn_in_progress = False+ b._start_in_progress = True+ assert b.is_run_finished() is False+++def test_is_training_active_still_liveness_only():+ # A lingering worker still holds its VRAM, so the admission guards must see it active.+ b = _running_backend()+ b._handle_event(_complete_event())+ assert b.is_training_active() is True+ b._proc._alive = False+ assert b.is_training_active() is False+++def test_is_run_finished_false_across_an_xet_respawn():+ # A stall respawns the worker over HTTP; the run is still going, so no terminal phase.+ b = _running_backend()+ b._in_model_load = True+ b._handle_event({"type": "stall", "message": "no progress"})+ assert b._needs_xet_respawn is True+ assert b._progress.error is None+ assert b.is_run_finished() is False+++def test_is_run_finished_true_when_a_stall_is_unrecoverable():+ # Already fell back to HTTP: the stall is terminal, so the UI should say so.+ b = _running_backend()+ b._in_model_load = True+ b._xet_fallback_used = True+ b._handle_event({"type": "stall", "message": "no progress"})+ assert b._needs_xet_respawn is False+ assert b.is_run_finished() is True+++# ----------------------------------------------------------------------------+# (f) The terminal event must be the worker's last act.+# ----------------------------------------------------------------------------+++def test_mlx_worker_never_withholds_a_terminal_send_behind_tracking_teardown():+ """MLX teardown closes the TensorBoard writer and calls wandb_run.finish(), either of+ which can block for minutes. Ahead of `complete` that would withhold the event the UI+ waits on, so the teardown stays in the finally and runs only after the send.+ """+ import ast+ from pathlib import Path as _P++ # Beside the training module we imported, so the test travels with the package.+ src = (_P(_TRAINING_MODULE_FILE).resolve().parent / "worker.py").read_text()+ tree = ast.parse(src)+ fn = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.FunctionDef) and n.name == "_run_mlx_training"+ )++ def _is_complete_send(node):+ return (+ isinstance(node, ast.Call)+ and getattr(node.func, "id", "") == "_send"+ and node.args+ and isinstance(node.args[0], ast.Constant)+ and node.args[0].value == "complete"+ )++ def _teardown_lines(nodes):+ return {+ c.lineno+ for n in nodes+ for c in ast.walk(n)+ if isinstance(c, ast.Call) and getattr(c.func, "id", "") == "_finish_tracking"+ }++ saves = [+ n+ for n in ast.walk(fn)+ if isinstance(n, ast.Try)+ and any(_is_complete_send(c) for stmt in n.body for c in ast.walk(stmt))+ ]+ assert len(saves) == 1, "expected one save/finalize try block with the terminal sends"+ everywhere = _teardown_lines([fn])+ assert everywhere, "expected the tracking teardown to still run"+ assert everywhere == _teardown_lines(saves[0].finalbody), (+ f"_finish_tracking() is called at worker.py:{sorted(everywhere)} but only "+ f"{sorted(_teardown_lines(saves[0].finalbody))} is in the finally; a blocking "+ "wandb_run.finish() ahead of _send('complete') strands the UI at 100%"+ )+++def test_terminal_stall_arms_the_exit_watchdog(monkeypatch):+ # An unrecoverable stall is terminal, but terminate() is only a request: without a+ # backstop a worker that ignores it holds the GPU and blocks every later start.+ monkeypatch.setitem(_G, "_COMPLETE_EXIT_GRACE_S", 0.05)+ monkeypatch.setitem(_G, "_STOP_TIMEOUT_S", 100.0)+ b = _running_backend()+ b._start_stop_watchdog = TrainingBackend._start_stop_watchdog.__get__(b)+ calls = _record_force_terminate(monkeypatch, b)+ b._in_model_load = True+ b._xet_fallback_used = True # already on HTTP, so the stall is unrecoverable++ proc = b._proc+ proc.terminate = lambda: None # worker ignores the terminate request+ b._handle_event({"type": "stall", "message": "no progress"})++ assert b.is_run_finished() is True+ assert _wait_until(+ lambda: calls == ["force", "final"]+ ), "a wedged worker on the terminal stall path must still be reaped"+ if b._stop_watchdog:+ b._stop_watchdog.join(timeout = 5)+++def test_recoverable_stall_does_not_arm_the_watchdog(monkeypatch):+ # The Xet fallback respawns the worker, so the run is not terminal and nothing may reap it.+ monkeypatch.setitem(_G, "_COMPLETE_EXIT_GRACE_S", 0.05)+ b = _running_backend()+ b._start_stop_watchdog = TrainingBackend._start_stop_watchdog.__get__(b)+ calls = _record_force_terminate(monkeypatch, b)+ b._in_model_load = True++ b._handle_event({"type": "stall", "message": "no progress"})++ assert b._needs_xet_respawn is True+ assert b.is_run_finished() is False+ time.sleep(0.3)+ assert calls == [], "a respawning run must not be force-terminated"+++def test_terminal_error_releases_an_in_flight_stop_watchdog(monkeypatch):+ # Stop and Save, then the worker fails its checkpoint and reports error. The stop+ # watchdog already watches this proc so arming no-ops; without a terminal signal it+ # would sit out the full 600s save backstop with the GPU still blocked.+ monkeypatch.setitem(_G, "_STOP_GRACE_S", 0.05)+ monkeypatch.setitem(_G, "_STOP_TIMEOUT_S", 100.0)+ b = _running_backend()+ b._start_stop_watchdog = TrainingBackend._start_stop_watchdog.__get__(b)+ calls = _record_force_terminate(monkeypatch, b)++ b._should_stop = True+ b._start_stop_watchdog(cancel = False) # the stop's own watchdog, now in flight+ first = b._stop_watchdog+ assert first is not None and first.is_alive()++ b._handle_event({"type": "error", "error": "checkpoint failed", "stack": ""})++ assert b._complete_seen.is_set(), "a terminal error must signal the in-flight watchdog"+ assert b._stop_watchdog is first, "the existing watcher stays; arming again is a no-op"+ assert _wait_until(+ lambda: calls == ["force", "final"]+ ), "the in-flight watchdog must escalate on the grace, not the save backstop"+ first.join(timeout = 5)+++def test_terminal_stall_releases_an_in_flight_stop_watchdog(monkeypatch):+ # Same shape as the error path, via an unrecoverable stall: arming again no-ops, so only+ # the terminal signal keeps the in-flight watchdog off the 600s save backstop.+ monkeypatch.setitem(_G, "_STOP_GRACE_S", 0.05)+ monkeypatch.setitem(_G, "_STOP_TIMEOUT_S", 100.0)+ b = _running_backend()+ b._start_stop_watchdog = TrainingBackend._start_stop_watchdog.__get__(b)+ calls = _record_force_terminate(monkeypatch, b)+ b._in_model_load = True+ b._xet_fallback_used = True # already on HTTP, so the stall is unrecoverable+ b._proc.terminate = lambda: None # worker ignores the terminate request++ b._should_stop = True+ b._start_stop_watchdog(cancel = False) # the stop's own watchdog, now in flight+ first = b._stop_watchdog+ assert first is not None and first.is_alive()++ b._handle_event({"type": "stall", "message": "no progress"})++ assert b._complete_seen.is_set(), "a terminal stall must signal the in-flight watchdog"+ assert b._stop_watchdog is first, "the existing watcher stays; arming again is a no-op"+ assert _wait_until(+ lambda: calls == ["force", "final"]+ ), "the in-flight watchdog must escalate on the grace, not the save backstop"+ first.join(timeout = 5)