Skip to content

Use UTF-8 for Python code-execution subprocess I/O (#6489 class) - #6548

Merged
danielhanchen merged 11 commits into
unslothai:mainfrom
GodlyDonuts:fix-exec-utf8-windows
Jun 22, 2026
Merged

danielhanchen merged 11 commits into
unslothai:mainfrom
GodlyDonuts:fix-exec-utf8-windows

Conversation

@GodlyDonuts

@GodlyDonuts GodlyDonuts commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Studio's Python code-execution tool (_python_exec) crashes on Windows when model-written code — or its output — contains non-ASCII (arrows, em-dashes, CJK, emoji), which is extremely common in LLM output. Same class of bug as #6489.

Root cause

The path already tells the child to emit UTF-8 (_build_safe_env sets PYTHONIOENCODING=utf-8 and LANG=C.UTF-8), but the rest of the I/O uses the OS default codec:

  • the temp .py script is written with os.fdopen(fd, "w") (no encoding);
  • the subprocess pipe is read with text=True (no encoding);
  • _build_bypass_env doesn't set PYTHONIOENCODING at all.

On Windows the default codec is cp1252, so a character it can't represent (→, 数, 😀, …) raises UnicodeEncodeError / UnicodeDecodeError.

Fix (core/inference/tools.py)

  • write the temp script with encoding="utf-8";
  • decode _python_exec stdout with encoding="utf-8", errors="replace";
  • set PYTHONIOENCODING=utf-8 in _build_bypass_env too.

The child is python with PYTHONIOENCODING=utf-8, so it emits UTF-8 regardless of the console code page — the UTF-8 decode is always correct. On a UTF-8 host (Linux/macOS CI) the changes are no-ops.

Scope

Deliberately limited to _python_exec. The shell tool (_bash_exec) runs cmd /c on Windows, whose output uses the console code page rather than UTF-8; making that correct (e.g. chcp 65001) needs Windows validation and is better as its own change. See the review thread for details.

Tests

studio/backend/tests/test_exec_utf8.py: _python_exec round-trips "café — 数字 → ✓ 😀" (sandboxed and bypass paths). Passes on a UTF-8 host and guards against a regression to the OS default codec. The 247 existing sandbox/bypass tests still pass.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request ensures that Python and shell executions handle non-ASCII characters correctly by enforcing UTF-8 encoding during file writes, subprocess execution, and environment setup. It also introduces a test suite to verify that non-ASCII output round-trips successfully. The review feedback suggests ensuring that Windows cmd.exe outputs UTF-8 by changing the active code page to 65001, and refactoring the bash execution test to use a portable Python command instead of skipping it on Windows.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread studio/backend/core/inference/tools.py Resolved
Comment thread studio/backend/tests/test_exec_utf8.py Resolved
@GodlyDonuts
GodlyDonuts force-pushed the fix-exec-utf8-windows branch from 8120281 to 7fbde55 Compare June 22, 2026 04:26
Studio's code-execution tool already tells the child to emit UTF-8
(PYTHONIOENCODING=utf-8 in _build_safe_env), but _python_exec writes the
temp script and decodes the subprocess pipe with the OS default codec.
On Windows (cp1252), non-ASCII in model-written code or its output --
arrows, CJK, emoji -- raises UnicodeEncodeError / UnicodeDecodeError and
breaks execution.

Complete the UTF-8 wiring in core/inference/tools.py:
- write the temp script with encoding="utf-8"
- decode _python_exec stdout as utf-8, errors="replace"
- set PYTHONIOENCODING=utf-8 in _build_bypass_env too (matches
  _build_safe_env, so the bypass path's child also emits utf-8)

The child is python with PYTHONIOENCODING=utf-8, so it emits UTF-8
regardless of the console code page and the decode is always correct.
Shell execution via cmd.exe has a separate console-code-page story and
is left to a follow-up.

Refs unslothai#6489
@GodlyDonuts
GodlyDonuts force-pushed the fix-exec-utf8-windows branch from 7fbde55 to cbcd5c9 Compare June 22, 2026 04:27
@GodlyDonuts GodlyDonuts changed the title UTF-8 for code/shell execution subprocess I/O (Windows non-ASCII crash, #6489 class) Use UTF-8 for Python code-execution subprocess I/O (#6489 class) Jun 22, 2026
@GodlyDonuts

GodlyDonuts commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor Author

I Went through both points:

1. _bash_exec UTF-8 decode (cmd.exe code page). Correct: _get_shell_cmd runs ["cmd", "/c", command] on Windows, and cmd.exe emits the console/OEM code page, not UTF-8, so forcing a UTF-8 decode there would garble native shell output. The suggested chcp 65001 is the usual remedy, but it's unreliable in this exact context — these subprocesses spawn with CREATE_NO_WINDOW and a redirected PIPE, where the console code page isn't dependably honored — and I can't validate it without a Windows runner.

So rather than ship an unverifiable partial fix, I've scoped this PR to _python_exec, whose child is python with PYTHONIOENCODING=utf-8 (set in _build_safe_env / now also _build_bypass_env). That deterministically emits UTF-8 regardless of the console code page, so the UTF-8 decode is always correct. Shell/cmd UTF-8 is a separate concern worth its own change with Windows verification.

2. Cross-platform bash test. Removed along with the _bash_exec change. For the record, the suggested f"{sys.executable} -c \"...\"" wouldn't be robust on Windows either — sys.executable is unquoted (breaks under paths with spaces like Program Files), and the nested double-quotes don't survive cmd /c.

Net diff is now 3 lines in tools.py (script write + stdout decode + bypass-env PYTHONIOENCODING) plus a _python_exec round-trip test.

@Imagineer99 Imagineer99 self-assigned this Jun 22, 2026
@Imagineer99

Copy link
Copy Markdown
Member

Tested on windows and this is a valid issue, the fix works as expected. Thank you for the PR.
image

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jun 22, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 925c17b28d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

def test_bash_bypass_uses_bypass_preexec(captured_popen):
_bash_exec("echo hi", None, 5, "t", disable_sandbox = True)
assert captured_popen["kwargs"]["preexec_fn"] is tools._bypass_preexec
assert "PYTHONIOENCODING" not in captured_popen["kwargs"]["env"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 Badge Control PYTHONIOENCODING in bash bypass test

When the test runner itself has PYTHONIOENCODING set, _build_bypass_env() intentionally preserves benign host variables for bypassed bash execution, so this new assertion fails even though _bash_exec did not add the variable. Please clear or explicitly set this env var in the test before asserting the bash-specific behavior.

Useful? React with 👍 / 👎.

…slothai#6548

Bypass mode preserves benign host env vars, so a host-set PYTHONIOENCODING was
inherited into the bash bypass env and tripped the new assertion even though
_bash_exec never adds it. Clear it in the test so the assertion checks _bash_exec,
not the runner environment.
@danielhanchen
danielhanchen merged commit 7ecbf5a into unslothai:main Jun 22, 2026
32 of 34 checks passed
Imagineer99 added a commit to Imagineer99/unsloth that referenced this pull request Jun 23, 2026
Extracted and narrowed from unslothai#6543 by @TheJagStudio.

This keeps the startup/banner and text file encoding hardening separate from the already-merged Python code-exec UTF-8 fix in unslothai#6548.

Co-authored-by: Jagrat Patel <[email protected]>
Imagineer99 added a commit that referenced this pull request Jul 1, 2026
Extracted and narrowed from #6543 by @TheJagStudio.

This keeps the startup/banner and text file encoding hardening separate from the already-merged Python code-exec UTF-8 fix in #6548.

Co-authored-by: Jagrat Patel <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants