Skip to content

Fix the red parity gate: run_pwsh has to set the writing end of the pipe too - #10484

Merged
danielhanchen merged 2 commits into
mainfrom
pwsh-runner-utf8
Sep 8, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
pwsh-runner-utf8

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

parity (windows-latest) has been red on main for days, on both shells, on the same two cases:

tests/python/test_windows_python_venv_hardening.py::test_a_non_ascii_marker_survives_the_rollback[powershell]
tests/python/test_windows_python_venv_hardening.py::test_a_non_ascii_marker_survives_the_rollback[pwsh]

Runs 34092822926, 34109277955, 34116989434 and 34117845683 all fail this way, and it is not the installer. The marker file the test checks is written correctly. The corruption is in how the test reads the shell's stdout.

What was wrong

Nobody was setting the writing end of the pipe.

Windows PowerShell 5.1 writes a redirected pipe in the OEM code page, pwsh 7 writes UTF-8, and text = True decodes with the ANSI code page. So a non-ASCII character survived only where those two happened to agree, and they agree nowhere we run: on the GitHub runner both shells come back as mojibake, and on a cp437 box 5.1 comes back as U+FFFD.

_run_powershell in that test already names encoding = "utf-8", and that is the half-fix which made this hard to spot. It corrects pwsh 7 and makes 5.1 strictly worse. 0x84 is not valid UTF-8, so the decode raises inside subprocess's reader thread, where the exception is swallowed and the attribute is left as None:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 72: invalid start byte
rc 0 OUT None ERR ''

The caller gets returncode == 0 and stdout is None, which reads as a script that printed nothing rather than as a pipe nobody agreed on. Locally that surfaces as AttributeError: 'NoneType' object has no attribute 'strip', several frames away from the cause.

The fix

run_pwsh now sets both halves, always together:

  • a one-line prologue on the -Command script pinning [Console]::OutputEncoding to BOM-less UTF-8, so the shell writes UTF-8 whatever the console is set to
  • encoding = "utf-8" on the decode

The pair is exact for every code point on both shells, and a no-op on ASCII, which is what all but a handful of the 57 call sites emit. UTF8Encoding($false), not [Text.Encoding]::UTF8: the latter emits a preamble that would land in stdout as a BOM and break the first assertion of whatever reads it.

Four branches leave a caller alone:

caller what happens why
bytes mode untouched they asked for bytes, and a prologue would change them
named some other encoding untouched they chose
named UTF-8 gets the prologue it was missing this is the half-fix above
-File decode half only there is no script string to prepend to

The call site's own argv list is never written to, so a caller that reuses it, or reports it on failure, sees exactly what it built.

Tests

tests/python/test_pwsh_runner_encoding.py. The behavioural ones run a real shell and compare the string that comes back with the string that went in, over four samples chosen for different widths: a Latin-1 character that is one byte in cp437 and two in UTF-8, CJK that has no code-page representation at all, an astral emoji that is a surrogate pair in PowerShell's UTF-16 strings, and a mixture. The strings are built from code points inside PowerShell so the script itself stays ASCII, since a script carrying the character would be testing how the -Command argument is encoded, which is a different pipe. The rest pin the branches that must not interfere with a caller.

Measurement

All 20 files that use run_pwsh, this host, --dist loadfile:

  • before: 220 failures
  • after: 215 failures
  • diff of the two failure sets: 5 tests fixed, 0 newly broken

The remaining 215 are pre-existing and unrelated to this change.

The two cases in the title go from failing to passing here:

tests/python/test_windows_python_venv_hardening.py -k non_ascii
before: 2 failed, 85 deselected
after:  2 passed, 85 deselected

Split out of #10282, which is where the encoding mismatch turned up. It is not a Windows-on-ARM issue and it is red on main today, so it belongs on its own.

parity (windows-latest) has been failing on main for days, both shells, on
tests/python/test_windows_python_venv_hardening.py::
test_a_non_ascii_marker_survives_the_rollback. The marker file it checks is
written correctly; the corruption is in how the test reads the shell's stdout.

Nobody set the writing end. Windows PowerShell 5.1 writes a redirected pipe in
the OEM code page, pwsh 7 writes UTF-8, and `text = True` decodes with the ANSI
code page, so a non-ASCII character survived only where those happened to agree.
It does not agree anywhere we run: on the runner both shells return mojibake, and
on a cp437 box 5.1 returns U+FFFD.

That test already names `encoding = "utf-8"` at the call site, which is the half
that made this hard to see. It corrects pwsh 7 and makes 5.1 strictly worse: 0x84
is not valid UTF-8, so the decode raises in subprocess's reader thread, where the
exception is swallowed and the attribute is left as None. The caller then sees
returncode 0 with stdout None, which reads as a script that printed nothing
rather than as a pipe nobody agreed on. Reproduced here:

    UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 72
    rc 0 OUT None ERR ''

So run_pwsh now sets both halves together: a one-line prologue on the -Command
script fixing [Console]::OutputEncoding to BOM-less UTF-8, and utf-8 on the
decode. The pair is exact for every code point on both shells and a no-op on
ASCII, which is what all but a handful of the 57 call sites emit. A caller that
named some other encoding is left alone; one that named UTF-8 gets the prologue
it was missing; byte-mode callers are untouched, since a prologue would change
the bytes they asked for. `-File` has no script string to prepend to and gets the
decode half only. The call site's own argv list is never written to.

tests/python/test_pwsh_runner_encoding.py runs a real shell and round-trips four
strings chosen for different widths (a Latin-1 character that is one byte in
cp437 and two in UTF-8, CJK that has no code-page form, an astral emoji that is a
surrogate pair in PowerShell, and a mixture), and pins the branches that must not
interfere with a caller.

Measured on this host over all 20 files that use run_pwsh: 220 failures before,
215 after, and the diff of the two failure sets is five tests fixed and nothing
newly broken. The rest are pre-existing and unrelated.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-08T07:26:25.510176Z 5b54d48 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Every PowerShell test in that job shells out through
tests/_shared/unsloth_pwsh_runner.py, and it was in no path filter, so a change
to it triggered nothing. That is how the half-fix it replaces went unmeasured.

Adds the new file to the pytest selection so the gate this PR fixes is the gate
that proves it.

@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: 5b54d48307

ℹ️ 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".

named = kwargs.get("encoding")
if named is not None and named.lower().replace("_", "-") not in _UTF8_ALIASES:
return argv
kwargs["encoding"] = "utf-8"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid forcing UTF-8 decoding for unwrapped -File runs

When run_pwsh invokes Windows PowerShell 5.1 with -File, this assignment forces Python to decode stdout as UTF-8 even though no prologue is added and the shell still writes using its OEM code page. A script that prints non-ASCII output can therefore produce a decode failure/stdout is None—the exact half-fix failure described above. Either leave the decoder unchanged for -File or invoke the file through a wrapper that sets the writing encoding first.

Useful? React with 👍 / 👎.

return argv
if script >= len(argv) or not isinstance(argv[script], str):
return argv
return argv[:script] + [_UTF8_PROLOGUE + argv[script]] + argv[script + 1 :]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve leading PowerShell declarations

For a -Command script whose first construct is a script-level param(...) block or a using statement, prepending this executable assignment changes the script's grammar: param must remain the leading script declaration, and using directives must precede ordinary statements. Such otherwise-valid commands will fail to parse or execute after passing through run_pwsh; inject the encoding setup without placing a statement before these declarations.

Useful? React with 👍 / 👎.

Comment on lines +181 to +182
if not (kwargs.get("text") or kwargs.get("universal_newlines")):
return argv

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recognize encoding and errors as text mode

subprocess.Popen enables text mode when either encoding or errors is supplied, even if text and universal_newlines are omitted or false, but this guard treats those calls as byte mode. Consequently, a normal call such as run_pwsh(..., encoding="utf-8") returns decoded strings while skipping the writing-side prologue, so Windows PowerShell 5.1 still emits OEM bytes and reproduces the decode failure this change is intended to prevent. Include encoding and errors when determining whether the subprocess is in text mode.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

CI has now run the gate this fixes, on the runner, and it is green:

parity (windows-latest) -> success
parity (ubuntu-latest)  -> success

Both test_a_non_ascii_marker_survives_the_rollback cases pass, powershell and pwsh, where they have been failing on main.

One thing worth keeping from this beyond the fix itself: tests/_shared/unsloth_pwsh_runner.py was in no path filter, although every PowerShell test in that job shells out through it. A change to the shared runner triggered nothing, which is how the half-fix it replaces went unmeasured. It is in the filter now, along with the new test file, so the gate that proves this is the gate this fixes.

@danielhanchen
danielhanchen merged commit 266cd48 into main Sep 8, 2026
18 checks passed
@danielhanchen
danielhanchen deleted the pwsh-runner-utf8 branch September 8, 2026 12:02
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.

1 participant