codex icon indicating copy to clipboard operation
codex copied to clipboard

Windows: Python pipe encoding corrupts Unicode shell output despite UTF-8 PowerShell prefix

Open zzzhang1127 opened this issue 1 month ago • 3 comments

Problem

Python's redirected standard streams on Windows CP936 can corrupt Chinese shell-tool output even in PowerShell 7 and even when the source file was explicitly read as UTF-8. If an agent uses the corrupted shell output to update an automation prompt, the corrupted text becomes persistent. This is a reproducible shell-output boundary issue, not evidence of a scheduler serialization defect.

Environment

  • Codex CLI bundled with the affected desktop installation: 0.162.0-alpha.17.2
  • Windows, ANSI code page 936; Python 3.12.12 with redirected stdout encoding gbk
  • Reproduced with PowerShell 7.6.5 and Windows PowerShell 5.1
  • Proposed fix tested against official main ce0323f2f2d3b25e82806cd555237da3db4e1897

Minimal reproduction

Run the following through the Codex shell tool / redirected process output, rather than a Python interactive console:

Remove-Item Env:PYTHONIOENCODING -ErrorAction SilentlyContinue
$env:PYTHONUTF8 = '0'
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
python -c 'import json; print(json.dumps(chr(0x7ee7)+chr(0x7eed),ensure_ascii=False))'

Expected: JSON containing the original Chinese characters. Actual: replacement characters. The PowerShell console prefix is insufficient because Python uses the ANSI code page for redirected pipes independently of Console.OutputEncoding.

Changing only the child-process encoding fixes it:

$env:PYTHONIOENCODING = 'utf-8'
python -c 'import json; print(json.dumps(chr(0x7ee7)+chr(0x7eed),ensure_ascii=False))'

Other caller-side workarounds are python -X utf8 or ASCII-escaped JSON. Explicit file decoding alone does not solve the output boundary.

Why it persisted in an automation

The file was decoded correctly in Python, printed using json.dumps(..., ensure_ascii=False) to a GBK pipe, and received as UTF-8 with replacement characters. JSON punctuation survived, so parsing still succeeded. An agent then reused the damaged string in an automation update. An unchecked missing section marker in that agent's read/modify/write code additionally retained corrupted old content instead of replacing it. Those agent-side errors amplified the shell encoding problem; this report does not blame the scheduler for independently damaging valid input.

Concrete fix and regression tests

Proposed commit with tests / diff against upstream.

In codex-rs/shell-command/src/powershell.rs, extend the existing UTF-8 prefix with:

if (-not $env:PYTHONIOENCODING) { $env:PYTHONIOENCODING='utf-8' }

This preserves nonempty explicit encodings and changes Python's standard streams, not default file decoding. Added Windows tests verify Chinese stdout/stderr and preservation of an explicit cp936:strict setting. Existing prefix idempotence coverage remains.

Validation on Windows:

  • cargo test -p codex-shell-command powershell::tests --lib: 11 passed.
  • cargo test -p codex-shell-command --lib: 175 passed.
  • Independent real-child-process matrix for PowerShell 7 and 5.1: original-prefix corruption reproduced, fixed stdout/stderr preserved, explicit encoding preserved (6 checks).
  • rustfmt --edition 2024 --check and git diff --check: passed.

Local mitigation sets shell_environment_policy.set.PYTHONIOENCODING = "utf-8". An already-running process may not reload the setting, so explicit UTF-8 is still used for current commands. The damaged task prompt was rewritten from clean text through a structured Unicode argument and checked after saving.

Related #23044 concerns PowerShell 5.1 Get-Content's file-decoding default; this is a different boundary and reproduces in PowerShell 7. #31219 describes handoff corruption without this minimal pipe reproduction.

The affected user requested an upstream PR. I read the current contribution policy; GitHub rejected upstream PR creation with CreatePullRequest permission denial. This issue follows the policy's supported route for a root-cause report and concrete fix proposal. No real automation prompts, private logs, credentials, or personal paths are included.

zzzhang1127 avatar Oct 17 '26 10:10 zzzhang1127

Another observed instance on Codex Desktop for Windows (app package 26.1029.7803.0, Windows 11 build 26340, zh-CN locale).

An active recurring heartbeat showed garbled Chinese both in its task name and in the messages sent to the chat. Inspecting its automation.toml as UTF-8 showed that the corruption was already persisted: the name contained 14 U+FFFD replacement characters, and the 1,613-character prompt contained 817. The file itself was valid UTF-8. The UI was therefore displaying damaged stored text, not merely rendering intact Chinese incorrectly.

The recorded update read the previous task using Python tomllib with read_text(encoding='utf-8'), printed a JSON object with ensure_ascii=False, parsed the shell output in JavaScript, and passed the resulting name and prompt into automation_update. This matches the pipe-output-to-automation-update failure path described above. The original update input and business-specific content are omitted here. I have not independently traced the internal encoding boundary for this particular run, so this is corroborating evidence rather than a separate root-cause proof.

The task remained active after the corrupted update, so subsequent scheduled messages repeated the damaged instructions. It would be useful for a fix or regression test to cover both preserving Unicode through the shell boundary and avoiding silent persistence of corrupted automation text.

Water-Run avatar Nov 05 '26 01:11 Water-Run

Same corruption also happens through shell: "bash", where there is no PowerShell UTF-8 prefix at all — worth covering in the fix so the POSIX path is fixed too.

Reproduced today on Codex Desktop 26.1117.3838.0 / bundled codex-cli 0.171.0-alpha.13, Windows 11 x64, ANSI code page 936.

t.py (saved as UTF-8):

print('中文测试')

Ask the agent to run python t.py with shell: "bash" (Git Bash):

{"type":"item.completed","item":{"id":"item_3","type":"command_execution",
 "command":"\"...\\Git\\bin\\bash.exe\" -lc 'python t.py'",
 "aggregated_output":"���IJ���\r\n","exit_code":0,"status":"completed"}}

Running the same command in a terminal prints 中文测试, so the script and the shell are fine; Python writes stdout using the process ANSI code page (cp936) when redirected, and Codex decodes those bytes as UTF-8 → U+FFFD.

Because the PowerShell prefix never runs for shell: "bash" (and for any other non-PowerShell shell), extending only the PowerShell prefix leaves this path broken. Setting the default on the child-process spawn side — e.g. PYTHONIOENCODING=utf-8 via shell_environment_policy.set, or falling back to GetACP() / GetConsoleOutputCP() when decoding — would cover both shells. Local mitigation with shell_environment_policy.set.PYTHONIOENCODING = "utf-8" does work for the bash path as well.

IndexEeve avatar Nov 21 '26 15:11 IndexEeve

I encountered a closely related Windows Unicode failure while generating Persian Realtime audio from a PowerShell-driven Python diagnostic.

Environment / evidence:

  • Windows PowerShell reported OEM code page 437.
  • An earlier diagnostic manifest recorded the Persian input/transcript as literal ???? after the script had been passed through a PowerShell pipeline.
  • I rewrote the diagnostic as a UTF-8 .py file and executed the file directly with python -X utf8 (rather than piping source or Persian text through PowerShell).
  • The new run preserved a 172-codepoint Persian input, returned a transcript exactly equal to that input, and generated a normal 14-second Cedar WAV. The previous malformed-input run had produced an implausibly long 160-second sample.

This is not a full reproduction of the Codex shell bug and I cannot attribute the original corruption to one specific layer with certainty, but it is a practical confirmation that the PowerShell/Python pipe boundary can invalidate Unicode payloads and downstream model/audio results.

Workaround adopted in our Windows project:

$env:PYTHONUTF8 = '1'
$env:PYTHONIOENCODING = 'utf-8'
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
python -X utf8 path\to\script.py

We now keep Python source and Persian payloads in UTF-8 files, avoid piping source/Unicode strings through the shell, and assert that round-tripped text contains the expected Persian marker and no unexpected ? or U+FFFD.

Thanks for documenting the issue and the child-process encoding workaround.

ImanCognitiveArch avatar Dec 04 '26 10:12 ImanCognitiveArch