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: keep the exit code and the crash reason when training dies (#11574)

Harshab4718e0a7744
diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.py
index 5bbb76572c6..2726b8b0a3d 100644
--- a/studio/backend/core/training/diffusion_training_service.py
+++ b/studio/backend/core/training/diffusion_training_service.py
@@ -85,10 +85,23 @@ def _run_diffusion_child(*, event_queue: Any, stop_queue: Any, config: dict) ->
run_diffusion_training_process(event_queue = event_queue, stop_queue = stop_queue, config = config)
-def _default_target(*, event_queue: Any, stop_queue: Any, config: dict) -> None:
+def _default_target(
+ *,
+ event_queue: Any,
+ stop_queue: Any,
+ config: dict,
+ unsloth_stderr_mirror_path: Optional[str] = None,
+) -> None:
# First thing in the child (before torch): self-bind to parent death and scrub the native path
# secret, like the other workers. Token policy first of all, ahead of the account branch
# below, which returns: both children need it applied.
+ if unsloth_stderr_mirror_path:
+ # Before the token setup below, so its failure is captured too.
+ try:
+ from utils.worker_stderr import install_worker_stderr_mirror
+ install_worker_stderr_mirror(unsloth_stderr_mirror_path)
+ except Exception:
+ pass
if not config.get("allow_ambient", True):
# Before any huggingface_hub import, as the LLM worker does: a child env is seeded from
# the parent's, so not setting a token is not denying one.
@@ -119,7 +132,10 @@ def _default_target(*, event_queue: Any, stop_queue: Any, config: dict) -> None:
from utils.native_path_leases import run_without_native_path_secret
run_without_native_path_secret(
- _run_diffusion_child, event_queue = event_queue, stop_queue = stop_queue, config = config
+ _run_diffusion_child,
+ event_queue = event_queue,
+ stop_queue = stop_queue,
+ config = config,
)
@@ -467,6 +483,7 @@ class DiffusionTrainingService:
)
self._ctx = ctx if ctx is not None else _CTX
self._target = target if target is not None else _default_target
+ self._stderr_capture = None
self._lock = threading.Lock()
# Set by reserve() while a start is in flight (before the route frees GPU models) so the load guards
# refuse a concurrent load. Cleared by unreserve().
@@ -644,13 +661,20 @@ class DiffusionTrainingService:
self._stop_queue = self._ctx.Queue()
if self.job_account is not None:
config = {**config, "_job_account": self.job_account}
+ child_kwargs = {
+ "event_queue": event_queue,
+ "stop_queue": self._stop_queue,
+ "config": config,
+ }
+ # Test targets take only the three job kwargs.
+ if self._target is _default_target:
+ self._open_worker_stderr_capture()
+ if self._stderr_capture is not None:
+ from utils.native_path_leases import STDERR_MIRROR_KWARG
+ child_kwargs[STDERR_MIRROR_KWARG] = self._stderr_capture.path
self._proc = self._ctx.Process(
target = self._target,
- kwargs = {
- "event_queue": event_queue,
- "stop_queue": self._stop_queue,
- "config": config,
- },
+ kwargs = child_kwargs,
daemon = True,
)
# Keep the lease secret out of the child's env, as other orchestrators do.
@@ -762,6 +786,36 @@ class DiffusionTrainingService:
snap["active"] = self._proc is not None and self._proc.is_alive()
return snap
+ def _open_worker_stderr_capture(self) -> None:
+ previous = self._stderr_capture
+ self._stderr_capture = None
+ if previous is not None:
+ try:
+ previous.close()
+ except Exception:
+ pass
+ try:
+ from utils.worker_stderr import WorkerStderrCapture
+ self._stderr_capture = WorkerStderrCapture(prefix = "unsloth-diffusion-worker-")
+ except Exception:
+ self._stderr_capture = None
+
+ def _unexpected_exit_message(self, proc: Any) -> str:
+ from utils.worker_stderr import unexpected_exit_message
+
+ text = ""
+ capture = self._stderr_capture
+ if capture is not None:
+ try:
+ text = capture.text()
+ except Exception:
+ text = ""
+ return unexpected_exit_message(
+ getattr(proc, "pid", None),
+ getattr(proc, "exitcode", None),
+ text,
+ )
+
# ── event pump ───────────────────────────────────────────────────────────
@job_pump
def _pump_loop(self, event_queue: Any, proc: Any) -> None:
@@ -784,7 +838,7 @@ class DiffusionTrainingService:
self._state.update(
active = False,
status = "error",
- message = "Training process exited unexpectedly.",
+ message = self._unexpected_exit_message(proc),
updated_at = time.time(),
)
discarding = self._discard_requested
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index b24bb72b287..f8dd871c538 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -1240,6 +1240,7 @@ class TrainingBackend:
self._model_download_repo_id: Optional[str] = None
self._xet_fallback_used: bool = False
self._needs_xet_respawn: bool = False
+ self._stderr_capture = None
logger.info("TrainingBackend initialized (subprocess mode)")
@@ -1841,16 +1842,19 @@ class TrainingBackend:
):
event_queue = _CTX.Queue()
stop_queue = _CTX.Queue()
+ self._open_worker_stderr_capture()
process_args, process_kwargs = account_process_spec(
"core.training.worker",
"run_training_process",
cache_env,
- {
- "event_queue": event_queue,
- "stop_queue": stop_queue,
- "config": config,
- },
+ self._with_stderr_mirror(
+ {
+ "event_queue": event_queue,
+ "stop_queue": stop_queue,
+ "config": config,
+ }
+ ),
)
proc = _CTX.Process(
target = run_without_native_path_secret,
@@ -2613,15 +2617,18 @@ class TrainingBackend:
):
event_queue = _CTX.Queue()
stop_queue = _CTX.Queue()
+ self._open_worker_stderr_capture()
process_args, process_kwargs = account_process_spec(
"core.training.worker",
"run_training_process",
cache_env,
- {
- "event_queue": event_queue,
- "stop_queue": stop_queue,
- "config": config,
- },
+ self._with_stderr_mirror(
+ {
+ "event_queue": event_queue,
+ "stop_queue": stop_queue,
+ "config": config,
+ }
+ ),
)
new_proc = _CTX.Process(
target = run_without_native_path_secret,
@@ -2883,6 +2890,45 @@ class TrainingBackend:
etype = event.get("type") if isinstance(event, dict) else type(event).__name__
logger.exception("Training event pump: failed to handle %s event; skipping", etype)
+ def _open_worker_stderr_capture(self) -> None:
+ previous = self._stderr_capture
+ self._stderr_capture = None
+ if previous is not None:
+ try:
+ previous.close()
+ except Exception:
+ logger.debug("Could not close the previous training stderr sink", exc_info = True)
+ try:
+ from utils.worker_stderr import WorkerStderrCapture
+ self._stderr_capture = WorkerStderrCapture(prefix = "unsloth-training-worker-")
+ except Exception as exc:
+ logger.debug("Could not open a training worker stderr mirror: %s", exc)
+
+ def _with_stderr_mirror(self, kwargs: dict) -> dict:
+ capture = self._stderr_capture
+ if capture is None:
+ return kwargs
+ from utils.native_path_leases import STDERR_MIRROR_KWARG
+
+ # Popped by run_without_native_path_secret. It must not reach run_training_process.
+ return {**kwargs, STDERR_MIRROR_KWARG: capture.path}
+
+ def _unexpected_exit_message(self, proc) -> str:
+ from utils.worker_stderr import unexpected_exit_message
+
+ text = ""
+ capture = self._stderr_capture
+ if capture is not None:
+ try:
+ text = capture.text()
+ except Exception:
+ logger.debug("Could not read the training worker stderr sink", exc_info = True)
+ return unexpected_exit_message(
+ getattr(proc, "pid", None),
+ getattr(proc, "exitcode", None),
+ text,
+ )
+
@job_pump
def _pump_loop(self) -> None:
"""Background thread: consume subprocess events and update state.
@@ -2937,6 +2983,15 @@ class TrainingBackend:
):
return
+ with self._lock:
+ report_exit = (
+ self._progress.is_training
+ and not self._should_stop
+ and not self._progress.error
+ )
+ exit_message = self._unexpected_exit_message(proc) if report_exit else None
+ if exit_message:
+ logger.error("%s", exit_message)
with self._lock:
if self._progress.is_training:
if self._should_stop:
@@ -2945,7 +3000,9 @@ class TrainingBackend:
else:
self._progress.is_training = False
self._progress.error = (
- self._progress.error or "Training process exited unexpectedly"
+ self._progress.error
+ or exit_message
+ or "Training process exited unexpectedly"
)
self._ensure_db_run_created()
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 0d40019ac6c..c242961f2f5 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -3643,6 +3643,10 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
service_name = "unsloth-studio-training-worker",
env = os.getenv("ENVIRONMENT_TYPE", "production"),
)
+ # As the inference worker: a recovered traceback reaching fd 2 must not read as the crash.
+ from utils.worker_stderr import mark_log_record_continuations
+
+ mark_log_record_continuations()
apply_gpu_ids(config.get("resolved_gpu_ids"), backend = config.get("device_backend"))
diff --git a/studio/backend/tests/test_training_pump_resilience.py b/studio/backend/tests/test_training_pump_resilience.py
index 2ac4ce38845..be2599362eb 100644
--- a/studio/backend/tests/test_training_pump_resilience.py
+++ b/studio/backend/tests/test_training_pump_resilience.py
@@ -59,11 +59,20 @@ _hw = _types.ModuleType("utils.hardware")
_hw.get_device = lambda: _types.SimpleNamespace(value = "cpu")
_hw.prepare_gpu_selection = lambda *a, **k: (None, None)
_stub("utils.hardware", _hw)
+
+
+def _stub_run_without_native_path_secret(*args, **kwargs):
+ # Not a lambda: the spawn pickles this target on Windows.
+ return None
+
+
_npl = _types.ModuleType("utils.native_path_leases")
_npl.native_path_secret_removed_for_child_start = lambda: contextlib.nullcontext()
-_npl.run_without_native_path_secret = lambda fn: fn
+_npl.run_without_native_path_secret = _stub_run_without_native_path_secret
_stub("utils.native_path_leases", _npl)
_pth = _types.ModuleType("utils.paths")
+_pth.__path__ = [str(Path(_BACKEND_DIR) / "utils" / "paths")]
+_pth.__package__ = "utils.paths"
_pth.is_local_path = lambda *a, **k: False
_pth.outputs_root = lambda *a, **k: "/tmp/outputs"
_stub("utils.paths", _pth)
@@ -276,7 +285,9 @@ def test_pump_finalizes_when_drain_queue_raises_unexpected_error(monkeypatch):
b._pump_loop() # returns once it sees the dead worker
assert b._progress.is_training is False
- assert b._progress.error == "Training process exited unexpectedly"
+ assert b._progress.error.startswith("Training process exited unexpectedly")
+ assert "pid=4321" in b._progress.error
+ assert "exitcode=unknown" in b._progress.error
assert finalized.get("status") == "error"
assert b._pump_running is False
assert b.is_training_active() is False
@@ -498,6 +509,9 @@ def _stub_spawn(monkeypatch):
pl = _types.ModuleType("utils.process_lifetime")
pl.adopt_pid = lambda pid: None
+ pl.forget_pid = lambda pid: None
+ pl.terminate_pid = lambda *args, **kwargs: None
+ pl.child_popen_kwargs = lambda *args, **kwargs: {}
# The spawn also reads the shutdown latch. These tests are about the pump, not about
# quitting, so the double answers "not shutting down" and the spawn proceeds; leaving
# it off makes the import fail and every start_training here return False.
diff --git a/studio/backend/tests/test_training_worker_exit_report.py b/studio/backend/tests/test_training_worker_exit_report.py
new file mode 100644
index 00000000000..7debb3446e1
--- /dev/null
+++ b/studio/backend/tests/test_training_worker_exit_report.py
@@ -0,0 +1,241 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""#11465: a worker dying without an error event keeps its exit code and first stderr reason."""
+
+from __future__ import annotations
+
+import ctypes
+import multiprocessing as mp
+import os
+import queue
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from utils.worker_stderr import ( # noqa: E402
+ WorkerStderrCapture,
+ first_crash_line,
+ format_exit_code,
+ install_worker_stderr_mirror,
+ unexpected_exit_message,
+)
+
+
+def test_windows_breakpoint_status_is_hex():
+ # ExitProcess(0x80000003) came back as this unsigned value on Windows.
+ assert format_exit_code(2147483651) == "0x80000003"
+ assert format_exit_code(-2147483645) == "0x80000003"
+ assert format_exit_code(-9) == "-9"
+ assert format_exit_code(1) == "1"
+ assert format_exit_code(None) == "unknown"
+
+
+def test_the_reason_is_kept_when_the_stack_is_what_follows():
+ reason = "LLVM ERROR: Cannot select: intrinsic %llvm.amdgcn.fdot2.bf16.bf16"
+ text = reason + "\n" + "\n".join(f' File "m.py", line {index} in f' for index in range(400))
+ assert first_crash_line(text) == reason
+ message = unexpected_exit_message(356, 2147483651, text)
+ assert message.startswith("Training process exited unexpectedly (pid=356, exitcode=0x80000003)")
+ assert reason in message
+
+
+def test_linux_segfault_reports_the_reason_not_a_frame():
+ text = (
+ "Fatal Python error: Segmentation fault\n\n"
+ "Current thread 0x0000758f06f62080 (most recent call first):\n"
+ ' File "/usr/lib/python3.13/ctypes/__init__.py", line 546 in string_at\n'
+ "\nExtension modules: numpy._core._multiarray_umath, torch._C (total: 2)\n"
+ )
+ assert first_crash_line(text) == "Fatal Python error: Segmentation fault"
+ assert (
+ first_crash_line('Thread 0x1 (most recent call first):\n File "x.py", line 1 in f\n') == ""
+ )
+
+
+def test_cpp_abort_reports_what_not_a_frame():
+ text = (
+ "terminate called after throwing an instance of 'c10::Error'\n"
+ " what(): CUDA error: an illegal memory access was encountered\n"
+ "Exception raised from c10_cuda_check_implementation (most recent call first):\n"
+ "frame #0: c10::Error::Error() + 0x57 (0x7f1 in libc10.so)\n"
+ )
+ assert first_crash_line(text) == "what(): CUDA error: an illegal memory access was encountered"
+ assert first_crash_line("terminate called without an active exception\n") == (
+ "terminate called without an active exception"
+ )
+
+
+def test_a_killed_worker_does_not_blame_routine_output():
+ text = "Hugging Face endpoint unreachable; HF_HUB_OFFLINE=1 set for this worker.\n 40%|#### | 4/10\n"
+ assert first_crash_line(text) == ""
+ assert unexpected_exit_message(7, -9, text) == (
+ "Training process exited unexpectedly (pid=7, exitcode=-9)"
+ )
+ assert first_crash_line("loading\nRuntimeError: boom\n") == "RuntimeError: boom"
+
+
+def test_a_recovered_warning_is_not_the_cause():
+ text = "CUDA out of memory; reducing batch size and retrying\n" + "step log\n" * 50
+ assert first_crash_line(text) == ""
+ windows = "LLVM ERROR: Cannot select\nWindows fatal exception: code 0x80000003\n"
+ assert (
+ first_crash_line(text + windows + ' File "m.py", line 1 in f\n')
+ == "LLVM ERROR: Cannot select"
+ )
+
+
+def test_the_reason_is_redacted():
+ text = "LLVM ERROR: cannot open /home/alice/secret_project/kernel.so token hf_abcdefghijklmnopqrstuvwxyz0123\n"
+ message = unexpected_exit_message(1, -6, text)
+ assert "LLVM ERROR" in message
+ assert "/home/alice" not in message
+ assert "hf_abcdefghijklmnopqrstuvwxyz0123" not in message
+
+
+def test_a_marked_recovered_traceback_is_not_the_cause():
+ text = (
+ "\x1fretry failed\n"
+ " | Traceback (most recent call last):\n"
+ " | RuntimeError: transient failure\n"
+ "step log\n"
+ )
+ assert first_crash_line(text) == ""
+
+
+def test_native_threads_do_not_push_the_reason_out():
+ threads = "".join(
+ f"Thread 0x{n:04x} (most recent call first):\n <no Python frame>\n" for n in range(40)
+ )
+ text = "Fatal Python error: Aborted\n\n" + threads
+ assert first_crash_line(text) == "Fatal Python error: Aborted"
+
+
+ "reason",
+ [
+ "Bus error",
+ "Illegal instruction",
+ "free(): invalid pointer",
+ "*** stack smashing detected ***: terminated",
+ "GGML_ASSERT(ctx) failed",
+ ],
+)
+def test_other_native_reasons(reason):
+ assert first_crash_line(reason + "\n" + ' File "m.py", line 1 in f\n') == reason
+
+
+def _die_after_a_long_stack(path: str) -> None:
+ assert install_worker_stderr_mirror(path) is True
+ sys.stderr.write("LLVM ERROR: Cannot select: intrinsic %llvm.amdgcn.fdot2.bf16.bf16\n")
+ sys.stderr.write("Windows fatal exception: code 0x80000003\n")
+ sys.stderr.flush()
+ # Longer than the 64 KiB tail window, shorter than the 256 KiB sink cap.
+ os.write(2, b' File "m.py", line 1 in f\n' * 2500)
+ if sys.platform == "win32":
+ ctypes.windll.kernel32.ExitProcess(0x80000003)
+ os._exit(3)
+
+
+def test_the_mirror_keeps_the_reason_that_the_tail_window_drops(tmp_path):
+ capture = WorkerStderrCapture(directory = str(tmp_path), prefix = "unsloth-test-")
+ context = mp.get_context("spawn")
+ proc = context.Process(target = _die_after_a_long_stack, args = (capture.path,))
+ proc.start()
+ proc.join(30)
+ assert not proc.is_alive()
+ body = capture.text()
+ assert "LLVM ERROR: Cannot select" in body
+ assert "LLVM ERROR" not in capture.tail()
+ message = unexpected_exit_message(proc.pid, proc.exitcode, body)
+ assert "LLVM ERROR: Cannot select" in message
+ if sys.platform == "win32":
+ assert "0x80000003" in message
+ assert proc.exitcode == 2147483651
+
+
+def test_the_reason_after_a_long_routine_log_is_read(tmp_path):
+ capture = WorkerStderrCapture(directory = str(tmp_path), prefix = "unsloth-test-")
+ Path(capture.path).write_text(
+ "step log\n" * 35000 + "LLVM ERROR: late\n" + ' File "m.py", line 1 in f\n' * 100,
+ encoding = "utf-8",
+ )
+ assert first_crash_line(capture.text()) == "LLVM ERROR: late"
+
+
+class _DeadProc:
+ def __init__(self, exitcode: int):
+ self.exitcode = exitcode
+ self.pid = 356
+
+ def is_alive(self) -> bool:
+ return False
+
+
+class _EmptyQueue:
+ def get(self, *args, **kwargs):
+ raise queue.Empty
+
+ def get_nowait(self, *args, **kwargs):
+ raise queue.Empty
+
+
+class _OneErrorQueue:
+ def __init__(self):
+ self._pending = [{"type": "error", "error": "CUDA out of memory", "stack": ""}]
+
+ def get(self, *args, **kwargs):
+ if self._pending:
+ return self._pending.pop(0)
+ raise queue.Empty
+
+ def get_nowait(self, *args, **kwargs):
+ if self._pending:
+ return self._pending.pop(0)
+ raise queue.Empty
+
+
+def training_backend(monkeypatch):
+ from core.training.training import TrainingBackend
+
+ backend = TrainingBackend()
+ monkeypatch.setattr(backend, "_ensure_db_run_created", lambda: None)
+ monkeypatch.setattr(backend, "_finalize_run_in_db", lambda **kwargs: None)
+ return backend
+
+
+def test_the_pump_reports_the_exit_code_and_the_llvm_line(training_backend, tmp_path):
+ capture = WorkerStderrCapture(directory = str(tmp_path), prefix = "unsloth-test-")
+ capture_path = Path(capture.path)
+ capture_path.write_text(
+ "LLVM ERROR: Cannot select: intrinsic demo\n" + ' File "m.py", line 1 in f\n' * 2500,
+ encoding = "utf-8",
+ )
+ training_backend._stderr_capture = capture
+ training_backend._proc = _DeadProc(2147483651)
+ training_backend._event_queue = _EmptyQueue()
+ training_backend._progress.is_training = True
+
+ training_backend._pump_loop()
+
+ assert training_backend._progress.is_training is False
+ assert "0x80000003" in training_backend._progress.error
+ assert "LLVM ERROR: Cannot select: intrinsic demo" in training_backend._progress.error
+ assert "m.py" not in training_backend._progress.error
+
+
+def test_a_queued_error_wins_over_the_exit_line(training_backend):
+ training_backend._proc = _DeadProc(2147483651)
+ training_backend._event_queue = _OneErrorQueue()
+ training_backend._progress.is_training = True
+ training_backend._stderr_capture = None
+
+ training_backend._pump_loop()
+
+ assert training_backend._progress.error == "CUDA out of memory"
diff --git a/studio/backend/utils/worker_stderr.py b/studio/backend/utils/worker_stderr.py
index 65caca2752e..2eef2555123 100644
--- a/studio/backend/utils/worker_stderr.py
+++ b/studio/backend/utils/worker_stderr.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import atexit
import collections
import os
+import re
import sys
import tempfile
import threading
@@ -20,9 +21,12 @@ __all__ = [
"STDERR_MIRROR_KWARG",
"WorkerStderrCapture",
"decode_worker_stderr",
+ "first_crash_line",
+ "format_exit_code",
"install_worker_stderr_mirror",
"mark_log_record_continuations",
"stderr_tail_from_bytes",
+ "unexpected_exit_message",
]
# Marks a record's continuation lines: a recovered request's `exc_info` traceback is byte-identical to a dying process's.
@@ -121,6 +125,123 @@ def stderr_tail_from_bytes(
return joined
+_CRASH_LINE_MARKERS = (
+ "llvm error",
+ "fatal exception",
+ "fatal python error",
+ "segmentation fault",
+ "out of memory",
+ "terminate called",
+ "cuda error",
+ "hip error",
+ "cudaerror",
+ # As orchestrator._DIAGNOSTIC_START_RE.
+ "bus error",
+ "illegal instruction",
+ "floating point exception",
+ "trace/breakpoint trap",
+ "stack smashing",
+ "double free",
+ "free():",
+ "malloc():",
+ "munmap_chunk",
+ "corrupted size",
+ "corrupted double-linked",
+ "bad_alloc",
+ "libc++abi",
+ "ggml_assert",
+)
+_STACK_LINE_PREFIXES = (
+ 'File "',
+ "Thread 0x",
+ "Current thread 0x",
+ "Stack (most recent",
+ "Extension modules:",
+ "<no Python frame>",
+ "<truncated rest of calls>",
+ "Garbage-collecting",
+ "frame #",
+ "Exception raised from",
+ "#",
+ "0x",
+)
+_CRASH_LINE_LIMIT = 500
+_CRASH_TAIL_LINES = 12
+_ERROR_LINE = re.compile(r"error|exception|abort|fatal|fault", re.IGNORECASE)
+
+
+def format_exit_code(exitcode: "int | None") -> str:
+ """Hex for a Windows NTSTATUS. Small negatives stay decimal: those are Unix signals."""
+ if not isinstance(exitcode, int):
+ return "unknown"
+ if -64 <= exitcode < 0:
+ return str(exitcode)
+ unsigned = exitcode & 0xFFFFFFFF
+ if unsigned > 255:
+ return f"0x{unsigned:08X}"
+ return str(exitcode)
+
+
+def _is_crash_marker(line: str) -> bool:
+ lowered = line.lower()
+ return any(marker in lowered for marker in _CRASH_LINE_MARKERS)
+
+
+def first_crash_line(text: str) -> str:
+ """The reason in the terminal crash block, else empty (a SIGKILL leaves the exit code alone)."""
+ # Marked log records (a recovered `logger.exception`) are never the cause.
+ lines = [
+ line.strip()
+ for line in (text or "").splitlines()
+ if line.strip()
+ and not line.startswith((LOG_RECORD_START_MARK, LOG_RECORD_CONTINUATION_PREFIX))
+ ]
+ # Last few non-stack lines only: an earlier recovered "out of memory" is not the cause.
+ tail = []
+ for line in reversed(lines):
+ if line.startswith(_STACK_LINE_PREFIXES):
+ continue
+ tail.append(line)
+ if len(tail) == _CRASH_TAIL_LINES:
+ break
+ tail.reverse()
+ marked = [index for index, line in enumerate(tail) if _is_crash_marker(line)]
+ if marked:
+ # The first of the last run: "LLVM ERROR ..." precedes "Windows fatal exception ...".
+ index = marked[-1]
+ while index > 0 and _is_crash_marker(tail[index - 1]):
+ index -= 1
+ line = tail[index]
+ following = tail[index + 1] if index + 1 < len(tail) else ""
+ # C++ abort: "terminate called after throwing ..." then "what(): <reason>".
+ if line.lower().startswith("terminate called") and following.startswith("what():"):
+ line = following
+ return line[:_CRASH_LINE_LIMIT]
+ for line in reversed(tail):
+ if _ERROR_LINE.search(line):
+ return line[:_CRASH_LINE_LIMIT]
+ return ""
+
+
+def unexpected_exit_message(pid, exitcode, text: str) -> str:
+ pid_text = str(pid) if pid is not None else "unknown"
+ message = (
+ "Training process exited unexpectedly "
+ f"(pid={pid_text}, exitcode={format_exit_code(exitcode)})"
+ )
+ line = first_crash_line(text)
+ if line:
+ try:
+ from core.inference.orchestrator import _redact_worker_output
+ except Exception:
+ # Fail closed: the run error and /training/status are user-visible.
+ return message
+ line = _redact_worker_output(line)
+ if line:
+ return f"{message}: {line}"
+ return message
+
+
# Exact paths, never a pattern: Studios share one temporary directory.
_OPEN_SINKS: "set[str]" = set()
_ATEXIT_REGISTERED = False
@@ -184,6 +305,27 @@ class WorkerStderrCapture:
return ""
return stderr_tail_from_bytes(data, max_lines = max_lines, max_chars = max_chars)
+ def text(self, limit: int = 4 * MIRROR_FILE_CAP_BYTES) -> str:
+ """The whole sink (compaction lets it reach 2x the cap); past *limit*, its last *limit* bytes."""
+ try:
+ fd = os.open(self._path, os.O_RDONLY | _O_NOFOLLOW | _O_BINARY)
+ except OSError:
+ return ""
+ try:
+ handle = os.fdopen(fd, "rb")
+ except OSError:
+ os.close(fd)
+ return ""
+ try:
+ size = handle.seek(0, os.SEEK_END)
+ handle.seek(max(0, size - limit))
+ data = handle.read(limit)
+ except OSError:
+ return ""
+ finally:
+ handle.close()
+ return decode_worker_stderr(data)
+
def close(self) -> None:
"""Tolerates a child still holding the sink open, which is the norm on Windows."""
_OPEN_SINKS.discard(self._path)