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 a Windows console stderr writable while the worker mirror owns fd 2 (#15734)

Daniel Haneb536715b6f8
diff --git a/studio/backend/tests/test_worker_stderr_windows_console.py b/studio/backend/tests/test_worker_stderr_windows_console.py
new file mode 100644
index 00000000000..2fd5777d380
--- /dev/null
+++ b/studio/backend/tests/test_worker_stderr_windows_console.py
@@ -0,0 +1,104 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""#15583: a worker whose sys.stderr is a Windows console must keep writing once the mirror owns fd 2."""
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+
+_CHILD = r"""
+import atexit, json, os, sys, tempfile
+backend, out_path, sink_dir = sys.argv[1:4]
+sys.path.insert(0, backend)
+from utils.worker_stderr import install_worker_stderr_mirror
+
+def raw_name(stream):
+ buffer = getattr(stream, "buffer", None)
+ return type(getattr(buffer, "raw", buffer)).__name__
+
+def write_stderr(text):
+ try:
+ print(text, file = sys.stderr, flush = True)
+ return None
+ except OSError as exc:
+ return repr(exc)
+
+result = {"raw_before": raw_name(sys.stderr)}
+original = sys.stderr
+handle, sink = tempfile.mkstemp(dir = sink_dir, suffix = ".stderr")
+os.close(handle)
+result["installed"] = install_worker_stderr_mirror(sink)
+result["same_stream"] = sys.stderr is original
+result["error"] = write_stderr("written through sys.stderr")
+with open(sink, "rb") as handle:
+ result["sink"] = handle.read().decode("utf-8", "replace")
+atexit._run_exitfuncs()
+result["restored"] = sys.stderr is original
+result["error_after_stop"] = write_stderr("written after the mirror stopped")
+with open(out_path, "w", encoding = "utf-8") as handle:
+ json.dump(result, handle)
+os._exit(0)
+"""
+
+
+def _run_child(
+ tmp_path,
+ unbuffered = False,
+ **popen_kwargs,
+) -> dict:
+ out = tmp_path / "result.json"
+ env = dict(os.environ)
+ for key in ("PYTHONLEGACYWINDOWSSTDIO", "PYTHONIOENCODING", "PYTHONUNBUFFERED"):
+ env.pop(key, None)
+ if unbuffered:
+ env["PYTHONUNBUFFERED"] = "1"
+ subprocess.run(
+ [sys.executable, "-c", _CHILD, _BACKEND_DIR, str(out), str(tmp_path)],
+ env = env,
+ timeout = 120,
+ check = True,
+ **popen_kwargs,
+ )
+ return json.loads(out.read_text(encoding = "utf-8"))
+
+
[email protected](sys.platform != "win32", reason = "a Windows console is Windows only")
[email protected]("unbuffered", [False, True], ids = ["buffered", "unbuffered"])
+def test_a_console_stderr_keeps_working_while_the_mirror_owns_fd_2(tmp_path, unbuffered):
+ startupinfo = subprocess.STARTUPINFO()
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
+ startupinfo.wShowWindow = 0 # SW_HIDE
+ # No std handles passed: the child gets the new console's, as a worker spawned from `unsloth studio` in a terminal.
+ result = _run_child(
+ tmp_path,
+ unbuffered = unbuffered,
+ creationflags = subprocess.CREATE_NEW_CONSOLE,
+ startupinfo = startupinfo,
+ )
+
+ # Fails rather than skips: without a console this proves nothing.
+ assert result["raw_before"] == "_WindowsConsoleIO", result
+ assert result["installed"] is True, result
+ assert result["error"] is None, result
+ assert "written through sys.stderr" in result["sink"], result
+ assert result["restored"] is True, result
+ assert result["error_after_stop"] is None, result
+
+
[email protected]("unbuffered", [False, True], ids = ["buffered", "unbuffered"])
+def test_a_stderr_that_is_not_a_console_is_left_as_it_was(tmp_path, unbuffered):
+ result = _run_child(tmp_path, unbuffered = unbuffered, stderr = subprocess.DEVNULL)
+
+ assert result["raw_before"] != "_WindowsConsoleIO", result
+ assert result["installed"] is True, result
+ assert result["same_stream"] is True, result
+ assert result["error"] is None, result
+ assert "written through sys.stderr" in result["sink"], result
+ assert result["restored"] is True, result
diff --git a/studio/backend/utils/worker_stderr.py b/studio/backend/utils/worker_stderr.py
index 20480b43af0..b689a87aad1 100644
--- a/studio/backend/utils/worker_stderr.py
+++ b/studio/backend/utils/worker_stderr.py
@@ -527,11 +527,39 @@ def _tail_sink_to_stderr(
pass
+def _is_windows_console(stream) -> bool:
+ """A console stream calls WriteConsoleW on whatever fd 2 is now, so on the sink every write fails with WinError 6 (#15583)."""
+ buffer = getattr(stream, "buffer", None)
+ # Under -u / PYTHONUNBUFFERED the buffer IS the raw console object.
+ raw = getattr(buffer, "raw", buffer)
+ return type(raw).__name__ == "_WindowsConsoleIO"
+
+
+def _rebind_console_stderr():
+ console = sys.stderr
+ if not _is_windows_console(console):
+ return None
+ try:
+ replacement = open(
+ 2,
+ "w",
+ buffering = 1,
+ encoding = "utf-8",
+ errors = "backslashreplace",
+ closefd = False,
+ )
+ except OSError:
+ return None
+ sys.stderr = replacement
+ return console, replacement
+
+
def _stop_mirror(
inherited_fd: int,
pump: threading.Thread,
stop = None,
relay = None,
+ rebound = None,
) -> None:
"""The pump must be a daemon or BaseProcess._bootstrap waits forever; multiprocessing prints tracebacks before atexit, so drain here still catches them."""
try:
@@ -542,6 +570,9 @@ def _stop_mirror(
os.dup2(inherited_fd, 2)
except OSError:
pass
+ else:
+ if rebound is not None and sys.stderr is rebound[1]:
+ sys.stderr = rebound[0]
if stop is not None:
# fd 2 no longer points at the sink, so the next empty read is the end, not a pause.
stop.set()
@@ -601,6 +632,7 @@ def install_worker_stderr_mirror(
sink.close()
return False
os.close(writer_fd)
+ rebound = _rebind_console_stderr()
stop = threading.Event()
relay = _MirrorRelay(inherited, _MIRROR_RELAY_CHUNKS)
pump = threading.Thread(
@@ -610,7 +642,7 @@ def install_worker_stderr_mirror(
daemon = True,
)
pump.start()
- atexit.register(_stop_mirror, inherited, pump, stop, relay)
+ atexit.register(_stop_mirror, inherited, pump, stop, relay, rebound)
return True