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.

Fix studio server crash when launched without a console (Windows) (#7932)

benja59ca88086ca
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 590d3850ca7..54c7b0378d5 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -13,6 +13,38 @@ from pathlib import Path
from typing import NoReturn, Optional, Sequence, Tuple
+def _normalize_standard_streams():
+ """Point missing std streams at the null device.
+
+ sys.stdout/stderr/stdin are None in a process with no valid std handles (a
+ Windows pythonw or detached launch), so every .write() / .isatty() on them
+ raises AttributeError. A null-device stream answers like a real one, so
+ nothing downstream needs its own None check.
+
+ MUST run before the `from loggers import ...` below: structlog binds
+ `from sys import stdout` at ITS import time and PrintLogger does
+ `self._file = file or stdout`, so a None stdout is captured permanently.
+ Normalizing inside run_server() is too late to undo that capture.
+ """
+ for name, mode in (("stdin", "r"), ("stdout", "w"), ("stderr", "w")):
+ if getattr(sys, name, None) is not None:
+ continue
+ try:
+ stream = open(os.devnull, mode, encoding = "utf-8", errors = "replace")
+ except Exception:
+ # Normalizing must never itself be what kills startup.
+ continue
+ setattr(sys, name, stream)
+ # sys.__stdout__ & co are None here too, and readers of those (rich reads
+ # sys.__stdout__.fileno() at import) otherwise fall back to fds 0/1/2,
+ # which this process does not have. Point them at the real null fd.
+ if getattr(sys, f"__{name}__", None) is None:
+ setattr(sys, f"__{name}__", stream)
+
+
+_normalize_standard_streams()
+
+
def _fix_torch_cuda_ld_path():
"""Prepend torch's bundled CUDA libs to LD_LIBRARY_PATH.
@@ -1303,6 +1335,8 @@ class _TeeStream:
self._log_fh.write(data)
except Exception:
pass
+ if self._stream is None:
+ return len(data)
return self._stream.write(data)
def flush(self):
@@ -1310,6 +1344,8 @@ class _TeeStream:
self._log_fh.flush()
except Exception:
pass
+ if self._stream is None:
+ return
try:
self._stream.flush()
except Exception:
@@ -1325,12 +1361,16 @@ class _TeeStream:
self._log_fh.flush()
except Exception:
pass
+ if self._stream is None:
+ return
try:
self._stream.close()
except Exception:
pass
def __getattr__(self, name):
+ if self._stream is None:
+ raise AttributeError(name)
return getattr(self._stream, name)
@@ -1374,6 +1414,8 @@ def _harden_console_close(stream):
before and any other error still propagates, so nothing changes off Colab. A
stream whose ``close`` cannot be reassigned keeps its original close().
"""
+ if stream is None:
+ return
try:
_orig_close = stream.close
except Exception:
@@ -1444,6 +1486,8 @@ def _setup_server_disk_logging():
_harden_console_close(sys.stdout)
_harden_console_close(sys.stderr)
+ # _normalize_standard_streams() ran at import, so these are never None; the
+ # tee's own None guards are defence-in-depth for _TeeStream(None, ...).
sys.stdout = _TeeStream(sys.stdout, log_fh)
sys.stderr = _TeeStream(sys.stderr, log_fh)
diff --git a/studio/backend/tests/test_server_disk_logging.py b/studio/backend/tests/test_server_disk_logging.py
index ce733c2aaa2..0d149ce0090 100644
--- a/studio/backend/tests/test_server_disk_logging.py
+++ b/studio/backend/tests/test_server_disk_logging.py
@@ -53,6 +53,62 @@ class TestTeeStream:
# isatty / encoding probes must see the original stream's answers.
assert tee.isatty() == console.isatty()
+ def test_missing_console_is_a_null_sink(self):
+ # Production never builds this, but _TeeStream(None, ...) must not crash.
+ log = io.StringIO()
+ tee = run_mod._TeeStream(None, log)
+ assert tee.write("hello") == len("hello") # text-stream write contract
+ tee.flush()
+ tee.close()
+ assert log.getvalue() == "hello"
+ assert not log.closed # the tee does not own the log handle
+ run_mod._harden_console_close(None) # must not raise
+
+
+class TestNormalizeStandardStreams:
+ """A Windows process with no valid std handles starts with them all None."""
+
+ def test_missing_streams_become_usable_text_streams(self, monkeypatch):
+ for name in ("stdin", "stdout", "stderr"):
+ monkeypatch.setattr(sys, name, None)
+ monkeypatch.setattr(sys, f"__{name}__", None)
+ run_mod._normalize_standard_streams()
+ try:
+ for name in ("stdin", "stdout", "stderr"):
+ stream = getattr(sys, name)
+ assert stream is not None
+ assert getattr(sys, f"__{name}__") is not None
+ # uvicorn's default formatter probes isatty(); logging needs write().
+ assert stream.isatty() is False
+ assert stream.encoding
+ assert stream.fileno() >= 0
+ sys.stdout.write("discarded")
+ sys.stdout.flush()
+ print("also discarded")
+ finally:
+ for name in ("stdin", "stdout", "stderr"):
+ stream = getattr(sys, name)
+ if stream is not None:
+ stream.close()
+
+ def test_existing_streams_are_left_alone(self, monkeypatch):
+ console = io.StringIO()
+ monkeypatch.setattr(sys, "stdout", console)
+ monkeypatch.setattr(sys, "stderr", console)
+ run_mod._normalize_standard_streams()
+ # Identity, not truthiness: replacing a live console would break Colab
+ # (ipykernel OutStream), Tauri's stdout protocol and pytest capture.
+ assert sys.stdout is console
+ assert sys.stderr is console
+
+ def test_runs_before_the_logger_import(self):
+ # structlog binds `from sys import stdout` at import time, so normalizing
+ # after the loggers import leaves None captured forever.
+ src = (Path(_BACKEND_DIR) / "run.py").read_text(encoding = "utf-8")
+ call = "\n_normalize_standard_streams()"
+ assert call in src, "run.py never calls _normalize_standard_streams()"
+ assert src.index(call) < src.index("\nfrom loggers import get_logger")
+
class TestSetupServerDiskLogging:
def test_opt_out_env(self, monkeypatch):
diff --git a/tests/studio/test_tee_stream_none_guard.py b/tests/studio/test_tee_stream_none_guard.py
new file mode 100644
index 00000000000..5a2a41efa25
--- /dev/null
+++ b/tests/studio/test_tee_stream_none_guard.py
@@ -0,0 +1,125 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""AST test that run.py survives being launched with no console.
+
+A process with no valid std handles (a Windows pythonw or detached launch)
+starts with sys.stdout / sys.stderr / sys.stdin as None.
+`_normalize_standard_streams` replaces the missing ones at import time, and the
+_TeeStream guards keep a direct `_TeeStream(None, ...)` from crashing.
+
+Source contract only. The behaviour is pinned at runtime in
+studio/backend/tests/test_server_disk_logging.py, which CI runs on Python
+3.10-3.13 rather than 3.12 alone.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+_RUN_PY = Path(__file__).resolve().parents[2] / "studio" / "backend" / "run.py"
+
+
+def _module() -> ast.Module:
+ return ast.parse(_RUN_PY.read_text(encoding = "utf-8"))
+
+
+def _tee_stream_cls() -> ast.ClassDef:
+ for node in _module().body:
+ if isinstance(node, ast.ClassDef) and node.name == "_TeeStream":
+ return node
+ raise AssertionError("no _TeeStream class in studio/backend/run.py")
+
+
+def _top_level_fn(name: str) -> ast.FunctionDef:
+ for node in _module().body:
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ return node
+ raise AssertionError(f"no {name} in studio/backend/run.py")
+
+
+def _guards_target(fn: ast.FunctionDef, target: str) -> bool:
+ """True if *fn* early-exits on `<target> is None` before dereferencing it.
+
+ Deliberately strict -- the guard must name the target, compare it against
+ None, and return/raise -- so an unrelated `if data is None:` cannot pass.
+ A preceding local alias counts as the target, so hoisting the attribute into
+ a local before the guard stays legal.
+ """
+ aliases = {target}
+ for node in fn.body:
+ if isinstance(node, ast.Assign) and ast.unparse(node.value) in aliases:
+ aliases.update(ast.unparse(t) for t in node.targets)
+ if not isinstance(node, ast.If) or not isinstance(node.test, ast.Compare):
+ continue
+ names = {ast.unparse(node.test.left)}
+ names.update(ast.unparse(c) for c in node.test.comparators)
+ if not names & aliases:
+ continue
+ if not any(
+ isinstance(op, ast.Is) and isinstance(c, ast.Constant) and c.value is None
+ for op, c in zip(node.test.ops, node.test.comparators)
+ ):
+ continue
+ if any(isinstance(stmt, (ast.Return, ast.Raise)) for stmt in node.body):
+ return True
+ return False
+
+
+def test_streams_are_normalized_before_the_logger_import():
+ """The fix has to land before structlog is imported, or it does nothing.
+
+ structlog binds `from sys import stdout` at ITS import time and PrintLogger
+ does `self._file = file or stdout`, so a None stdout is captured permanently
+ the moment `from loggers import get_logger` runs.
+ """
+ src = _RUN_PY.read_text(encoding = "utf-8")
+ assert "\n_normalize_standard_streams()" in src, (
+ "run.py never calls _normalize_standard_streams(); a console-less launch "
+ "keeps sys.stdout/stderr as None and dies on the first log call"
+ )
+ assert src.index("\n_normalize_standard_streams()") < src.index(
+ "\nfrom loggers import get_logger"
+ ), (
+ "_normalize_standard_streams() must be called before the loggers import; "
+ "structlog captures sys.stdout at import time"
+ )
+
+
+def test_normalize_skips_streams_that_already_exist():
+ """Replacing a live console would break Colab, Tauri and pytest capture."""
+ fn = _top_level_fn("_normalize_standard_streams")
+ assert any(
+ isinstance(n, ast.If) and "is not None" in ast.unparse(n.test) for n in ast.walk(fn)
+ ), "_normalize_standard_streams overwrites streams that are already present"
+
+
+def test_tee_stream_write_guards_the_wrapped_stream():
+ """write() must no-op on a None stream instead of delegating to it."""
+ methods = {n.name: n for n in _tee_stream_cls().body if isinstance(n, ast.FunctionDef)}
+ fn = methods.get("write")
+ assert fn is not None, "_TeeStream has no write()"
+ assert _guards_target(fn, "self._stream"), (
+ "write() delegates straight to self._stream.write(data) with no None guard; "
+ "_TeeStream(None, log) then crashes with "
+ "AttributeError: 'NoneType' object has no attribute 'write'"
+ )
+
+
+def test_tee_stream_guards_flush_and_close_too():
+ """flush()/close() must not delegate to a None stream either."""
+ methods = {n.name: n for n in _tee_stream_cls().body if isinstance(n, ast.FunctionDef)}
+ for name in ("flush", "close"):
+ fn = methods.get(name)
+ assert fn is not None, f"_TeeStream has no {name}()"
+ assert _guards_target(
+ fn, "self._stream"
+ ), f"{name}() does not early-return on a None wrapped stream"
+
+
+def test_harden_console_close_accepts_none():
+ """_harden_console_close(None) must be a no-op (never read .close on None)."""
+ assert _guards_target(
+ _top_level_fn("_harden_console_close"), "stream"
+ ), "_harden_console_close does not early-return on a None stream"
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 6b85d42bc8b..f011494d5de 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -1596,7 +1596,17 @@ def studio_default(
if sys.platform == "win32":
import subprocess as _sp
- proc = _sp.Popen(args, **_windows_hidden_subprocess_kwargs())
+ # Hand our std handles to the child: without them CREATE_NO_WINDOW
+ # gives the backend its own hidden console and `unsloth studio > log`
+ # captures nothing -- the same trap noted at the setup.ps1 call below.
+ # Omitting stdin does not withhold it (subprocess still fills it from
+ # GetStdHandle); that would need stdin = DEVNULL.
+ proc = _sp.Popen(
+ args,
+ stdout = _stream_for_subprocess(sys.stdout),
+ stderr = _stream_for_subprocess(sys.stderr),
+ **_windows_hidden_subprocess_kwargs(),
+ )
try:
rc = proc.wait()
except KeyboardInterrupt: