Repository navigation
fix(install): decode Git output as UTF-8 regardless of Windows locale - #3626
Conversation
On hosts whose locale codec is not UTF-8 (cp936/GBK on Simplified Chinese Windows), subprocess text mode decoded Git output with the locale codec and crashed `apm install` inside the Windows reader thread (#3056). Add run_git_text() to the Git child-process owner (utils/git_env.py): it decodes UTF-8 with surrogateescape so decoding never fails mid-stream, then raises GitOutputDecodeError if a successful command's stdout is not valid UTF-8, and renders stderr / failed-command output with visible backslash escapes so existing failure handling is unchanged. Route the install-path Git text-mode calls through it, decode the progress clone stream as UTF-8, and add the transport-platform-git-output-decoding architecture guard. Fixes #3056 Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Malformed Git output raises GitOutputDecodeError without triggering cleanup, leaving populated staging trees behind; cleanup handling and regression coverage are needed for checkout and bare-repository paths.
1 open issue
What changed in this PR
This PR addresses #3056 by making install-path Git output decoding independent of the Windows locale, using a shared UTF-8 helper.
Changes:
- Rejects malformed successful stdout while visibly escaping undecodable diagnostic bytes.
- Migrates Git text calls to the shared helper and explicitly configures progress-stream decoding.
- Adds Windows regression tests and an architecture guard against locale-dependent decoding.
| File | Description |
|---|---|
tests/unit/utils/test_git_output_decoding.py |
Adds real-process locale and malformed-output regressions. |
tests/integration/test_architecture_owner_rule_mutations.py |
Adds a mutation case for the decoding guard. |
src/apm_cli/utils/git_sparse.py |
Routes sparse-checkout text output through the helper. |
src/apm_cli/utils/git_env.py |
Owns UTF-8 decoding, decode errors, and diagnostic escaping. |
src/apm_cli/marketplace/ref_resolver.py |
Migrates commit-existence probes to the helper. |
src/apm_cli/deps/tiered_ref_resolver.py |
Migrates cached ref resolution to the helper. |
src/apm_cli/deps/github_downloader.py |
Migrates sparse download and checkout commands. |
src/apm_cli/deps/github_downloader_validation.py |
Migrates tree-path validation output. |
src/apm_cli/deps/git_file_transport.py |
Uses shared decoding for file-transport Git commands. |
src/apm_cli/deps/bare_cache.py |
Migrates bare-cache resolution and materialization commands. |
src/apm_cli/cache/git_cache.py |
Migrates persistent-cache clone, fetch, and checkout commands. |
scripts/architecture_linter/checks/transport_auth_platform.py |
Enforces shared decoding in install-path consumers. |
CHANGELOG.md |
Documents the Windows decoding fix. |
.apm/architecture/owners/transport-auth-platform.json |
Registers the decoding guard under the Git process owner. |
Review effort: Balanced
Resolve conflicts with the link-text checkout rewrite (#3599/#3602) in git_cache.py, bare_cache.py, git_env.py and git_sparse.py by taking main's version and re-applying this PR's mechanical text=True -> run_git_text rewrite to the remaining Git text-mode calls. main's new bytes-mode ls-tree/cat-file path in git_sparse stays as is. The sparse regression test now drives main's public apply_sparse_cone, sparse_checkout_active and materialize_tracked_symlinks instead of the removed _tracked_symlinks helper. Co-authored-by: Copilot App <[email protected]>
GitOutputDecodeError subclasses subprocess.SubprocessError, not CalledProcessError or TimeoutExpired, so a rejected checkout or bare clone output escaped _create_checkout() and _ensure_bare_repo() (and its partial-clone fallback) without removing the .inc.* staging tree. Catch SubprocessError in those three handlers so the stage is removed and the failure is still raised as the existing RuntimeError, chained to the named decode error. Regression tests prove no stage or shard remains; each handler was mutation-broken to confirm its test fails without it. Addresses Copilot inline on src/apm_cli/cache/git_cache.py:834. Co-authored-by: Copilot App <[email protected]>
APM Review Panel:
|
| Persona | B | R | N | Takeaway |
|---|---|---|---|---|
| Python Architect | 0 | 0 | 2 | Locale-independent Git decoding centralized in git_env.py with sound exception hierarchy, two-pass decode, and dual guardrail; no architectural faults. |
| Test Coverage Expert | 0 | 1 | 0 | 10 regression tests with mutation-break evidence cover all four scope scenarios; recommend one unit test for _git_command_label URL/path-stripping promise. |
| Performance Expert | 0 | 0 | 1 | Encode+decode round-trip adds ~0.2ms total to a 50-dep install (~400 git calls); ship. |
| Doc Writer | 0 | 1 | 2 | The CHANGELOG entry is accurate, ASCII-only and follows repo conventions. No docs page needs a change. Two wording/placement fixes are optional. |
| Auth Expert | 0 | 0 | 0 | Mechanical subprocess-to-run_git_text migration preserves credential flow; _git_command_label prevents URL/token echo in decode errors; exception widening is safe. |
| Supply Chain Security Expert | 0 | 0 | 0 | Locale-independent UTF-8 decoding is fail-closed on corrupt machine output, staging-tree cleanup covers the new error type, and no check=False path parses escaped stdout as identity data; ship. |
B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.
Top 5 follow-ups
- [Test Coverage Expert] Add a parametrized unit test for
_git_command_labelasserting URL-bearing and path-bearing git argv never leak into GitOutputDecodeError diagnostics. -- Missing guardrail on a secure-by-default surface. - [Doc Writer] Sharpen the CHANGELOG entry to describe what users observe (an error naming the Git command and the offending byte) instead of "reports a named error". -- Users never see the class name.
- [Doc Writer] Qualify the CHANGELOG scope beyond
apm installto the marketplace and update commands that also run Git throughrun_git_text. -- The entry understates the fix surface. - [Python Architect] Add
typing.overloadpairs so_escaped_git_text/_strict_git_textreturnstrinstead ofobject. -- Keeps CompletedProcess[str] assignments type-safe. - [Performance Expert] Empty-string fast path in the two helpers to skip codec calls on empty stdout. -- Free one-liner, no correctness implication.
Architecture
classDiagram
direction LR
class git_env_module {
<<CanonicalOwner>>
+GIT_OUTPUT_ENCODING str
+run_git_text(command, kw) CompletedProcess
-_strict_git_text(command, value) object
-_escaped_git_text(value) object
-_git_command_label(command) str
}
class SubprocessError {
<<stdlib>>
}
class CalledProcessError {
<<stdlib>>
}
class TimeoutExpired {
<<stdlib>>
}
class GitOutputDecodeError {
<<DomainException>>
+cmd list
}
class GitCache {
+_ensure_bare_repo()
+_create_checkout()
}
class bare_cache_module {
<<Module>>
+materialize_from_bare()
}
class git_sparse_module {
<<Module>>
+apply_sparse_cone()
+sparse_checkout_active()
}
class install_path_consumers {
<<Module>>
+github_downloader
+git_file_transport
+tiered_ref_resolver
+marketplace_ref_resolver
}
SubprocessError <|-- CalledProcessError
SubprocessError <|-- TimeoutExpired
SubprocessError <|-- GitOutputDecodeError
GitCache ..> git_env_module : run_git_text
bare_cache_module ..> git_env_module : run_git_text
git_sparse_module ..> git_env_module : run_git_text
install_path_consumers ..> git_env_module : run_git_text
class git_env_module:::touched
class GitOutputDecodeError:::touched
class GitCache:::touched
classDef touched fill:#fff3b0,stroke:#d47600
flowchart TD
A["Install-path call site"] -->|"run_git_text(argv, kw)"| B["subprocess.run text, utf-8, surrogateescape"]
B -->|"CalledProcessError / TimeoutExpired"| C["escape output+stderr as \\xNN, re-raise same type"]
B -->|"CompletedProcess"| E["stderr escaped as \\xNN"]
E --> F{"returncode == 0?"}
F -->|"yes"| G["strict UTF-8 check on stdout"]
G -->|"valid"| H["return CompletedProcess"]
G -->|"invalid"| I["raise GitOutputDecodeError naming git subcommand, byte, offset"]
I --> J["GitCache handlers: remove staged tree, raise RuntimeError chained"]
F -->|"no"| N["stdout escaped as \\xNN"]
N --> H
Recommendation
Ship after folding the _git_command_label unit test and the CHANGELOG wording fixes. The merge-worker folds all five follow-ups into this PR (fold-by-default) and re-runs the panel in delta mode on the resulting head.
Full per-persona findings
Python Architect
- [nit] _escaped_git_text and _strict_git_text return object instead of str or None at
src/apm_cli/utils/git_env.py
At every call site they receive str/bytes/None and return str/None; object-typed returns weaken type checking.
Suggested: Add typing.overload pairs (str)->str, (bytes)->str, (None)->None. - [nit] Design patterns assessment for the architectural record
Canonical Owner: git_env.py owns all Git text output decoding; 30+ consumers delegate via run_git_text. Domain Exception: GitOutputDecodeError extends SubprocessError so widened cleanup handlers catch it. No further pattern warranted at this scope.
Test Coverage Expert
- [recommended] _git_command_label strips URLs and paths from GitOutputDecodeError diagnostics but has no direct test. at
tests/unit/utils/test_git_output_decoding.py
No test exercises the stripping with URL-bearing git argv; a missed option in _GIT_OPTIONS_WITH_VALUE could leak a URL into diagnostics.
Proof (missing at):tests/unit/utils/test_git_output_decoding.py::test_git_command_label_strips_urls_and_paths-- proves: Error diagnostics from Git decode failures never echo auth-bearing URLs or filesystem paths. [secure-by-default]
Performance Expert
- [nit] Empty-string fast-path in _strict_git_text and _escaped_git_text would skip two codec calls per empty-stdout success. at
src/apm_cli/utils/git_env.py
Saves ~50-80us per 50-dep install; free, no correctness implication.
Doc Writer
- [recommended] CHANGELOG says 'reports a named error'; users actually see a message naming the Git command, byte and offset at
CHANGELOG.md
Suggested: 'stops with an error naming the Git command and the offending byte instead of using Git output that is not valid UTF-8'. - [nit] The new Fixed entry sits between the two fix(git): pin core.symlinks=true so package hashes match across platforms #3545 symlink entries; move it below them at
CHANGELOG.md - [nit] The entry mentions only apm install, but the fix also covers marketplace and update Git calls at
CHANGELOG.md
Auth Expert
No findings.
Supply Chain Security Expert
No findings.
This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.
Generated by autopilot-pr-merge-worker. This comment is AI-generated and may contain errors.
Add a parametrized regression proving GitOutputDecodeError names only 'git <subcommand>' and never echoes URLs, tokens, paths or option values; mutation-broken by dropping the option-value skip (5 of 6 cases fail). Treat --config-env as a value-taking global option, which Git accepts in the separated form. Type _escaped_git_text and _strict_git_text with overloads so CompletedProcess[str] assignments stay typed, and skip the codec round-trip for empty output. Addresses panel follow-ups from test-coverage-expert (FU-1), python-architect (FU-4) and performance-expert (FU-5). Co-authored-by: Copilot App <[email protected]>
Name what users observe (an error naming the Git command and offending byte), cover apm update and other Git-running commands, and keep the entry next to, not between, the related #3545 symlink entries. Addresses panel follow-ups from doc-writer (FU-2, FU-3). Co-authored-by: Copilot App <[email protected]>
Resolve the git_cache.py conflict with #3602 (incomplete promisor checkout retry): keep main's `checkout =` result binding and route it through run_git_text, and route main's new ls-files probe and sparse completeness pin through run_git_text as well. Co-authored-by: Copilot App <[email protected]>
The #3071 sparse completeness probe documents that probe failures count as incomplete so the shard is rebuilt, but it caught only CalledProcessError and TimeoutExpired, so a GitOutputDecodeError from non-UTF-8 ls-files output escaped the cache-hit path. Catch SubprocessError there and in the best-effort pin write, matching the other cache handlers in this PR. Regression test mutation-broken. Co-authored-by: Copilot App <[email protected]>
On Linux the shard lock leaves a <variant>.lock file next to the checkout; assert that no stage or published shard remains, as the bare clone regression already does. Fixes the Build & Test Shard 2 failure. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Resolve git_cache.py, bare_cache.py and git_sparse.py by taking main's line-ending pin rewrite (#3599) and re-applying this PR's mechanical text=True -> run_git_text rewrite plus the SubprocessError cleanup and probe handlers, so GitOutputDecodeError still removes staged trees and counts as an incomplete sparse probe. Co-authored-by: Copilot App <[email protected]>
APM Review Panel:
|
| Persona | B | R | N | Takeaway |
|---|---|---|---|---|
| Python Architect | 0 | 0 | 0 | Prior nits resolved; run_git_text migration and SubprocessError widening are consistent with the single-owner rule. |
| Test Coverage Expert | 0 | 0 | 0 | Prior FU-1 resolved by a mutation-broken label test; the sparse probe widening has a direct regression test. |
| Performance Expert | 0 | 0 | 0 | Empty-string fast path folded; centralized calls add negligible overhead. |
| Doc Writer | 0 | 0 | 0 | Reworded CHANGELOG entry is accurate, ASCII, convention-compliant and correctly placed. |
| Auth Expert | 0 | 0 | 0 | Delta is auth-safe; the credential-retry classification of checkout stderr still works. |
| Supply Chain Security Expert | 0 | 0 | 0 | The sparse probe now rebuilds on decode errors (fail-closed), and ls-files parsing only runs after strict UTF-8 succeeds. |
B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.
Recommendation
All five prior follow-ups are folded and checked, and the delta panel returned zero findings. CI is green at 86466bf1 (26 checks pass), the Copilot thread is resolved, and there are no open follow-ups.
Full per-persona findings
Python Architect
No findings.
Test Coverage Expert
No findings.
Performance Expert
No findings.
Doc Writer
No findings.
Auth Expert
No findings.
Supply Chain Security Expert
No findings.
This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.
Generated by autopilot-pr-merge-worker. This comment is AI-generated and may contain errors.
Bring in #3626, #3419 and #3641. Move this PR's CODEX_HOME CHANGELOG bullet off the Fixed section tail, where new entries land, to avoid repeat append conflicts. Co-authored-by: Copilot App <[email protected]>

Description
TL;DR
On Windows hosts whose locale codec is not UTF-8 (cp936/GBK on Simplified Chinese Windows),
apm installcrashed withUnicodeDecodeError: 'gbk' codec can't decode bytebecause Git child output was decoded with the locale codec. This PR routes install-path Git text output through one owner helper,run_git_text()inutils/git_env.py. The helper always decodes UTF-8. If a successful command's stdout is not valid UTF-8, it raises a named error. Bytes it cannot decode in error output are shown as visible\xNNescapes, so existing failure handling stays the same.Note
Local preflight skipped by maintainer instruction (2026-11-12); CI is the gate.
Problem (WHY)
subprocess.run(..., text=True)withoutencodinguseslocale.getencoding(), so the same Git bytes decode differently per host. On Windows the decode runs insubprocess._readerthread. A decode error there is printed as a thread traceback and the output is lost, which matches the reporter's stack trace.mainwith the real owner function and the default codec forced to GBK:git_remote_refs()against a repo with a UTF-8 branch name raisedUnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 166: illegal multibyte sequence.errors="replace"would hide malformed machine output (ref lists,ls-tree -zpaths, SHAs). The approved scope rules that out: "Blanket silent replacement or dropping of malformed machine output, unrelated encoding rewrites, or masking subprocess failures" (scope record).Approach (WHAT)
run_git_text()decodes withencoding="utf-8", errors="surrogateescape", so decoding never fails mid-stream, including in Windows reader threads.GitOutputDecodeError(subprocess.SubprocessError)naminggit <subcommand>and the bad byte and offset.CalledProcessError/TimeoutExpiredpayloads show undecodable bytes as\xNNescapes. Return codes and raised exceptions are unchanged.Popenplus GitPython pump) decodes UTF-8 withbackslashreplace. That stream is diagnostic only.transport-platform-git-output-decodingblocks rawtext=Truein the 8 install-path Git modules.Implementation (HOW)
src/apm_cli/utils/git_env.py: addsGIT_OUTPUT_ENCODING,GitOutputDecodeError, andrun_git_text()to the registered owner of Git child processes.git_remote_refs,clone_git_worktree,checkout_git_worktree,git_resolve_commitandgit_current_branchuse it.init_git_remote_worktreealready pinnedencoding="utf-8"and takes an injected runner, so it is unchanged.cache/git_cache.py,deps/bare_cache.py,deps/github_downloader.py,deps/github_downloader_validation.py,deps/tiered_ref_resolver.py,deps/git_file_transport.py,marketplace/ref_resolver.py,utils/git_sparse.py: 30 call sites change fromsubprocess.run(..., text=True[, encoding="utf-8"])torun_git_text(...). This was a mechanical AST-guided rewrite. Bytes-mode calls are untouched.scripts/architecture_linter/checks/transport_auth_platform.pyand.apm/architecture/owners/transport-auth-platform.json: register the new guard under thegit-child-repository-isolationowner.tests/integration/test_architecture_owner_rule_mutations.py: adds its mutation case.tests/unit/utils/test_git_output_decoding.py(new,windows_compat): 7 regressions with real child processes and the default codec forced to GBK.Diagram
How one install-path Git call decodes output before and after this PR.
sequenceDiagram participant C as Install call site participant H as run_git_text (git_env.py) participant G as git child C->>H: argv, check, env H->>G: subprocess.run(text, utf-8, surrogateescape) G-->>H: raw bytes (any locale) Note over H: decode never raises mid-stream alt exit 0 H->>H: stdout strict UTF-8 check H-->>C: CompletedProcess or GitOutputDecodeError else non-zero exit H->>H: escape undecodable bytes as \xNN H-->>C: CalledProcessError or result (unchanged semantics) endTrade-offs
surrogateescapeplus a post-run check instead of bytes mode plus manual decode. This keepstext=Truesemantics (universal newlines,strresults), so the ~2,600 related unit tests that mocksubprocess.runwithstroutput pass unchanged.text=Truecalls (runtime managers, policy, version) are left alone, as the record excludes "unrelated encoding rewrites".core.eolpin): both PRs touchgit_cache.py,bare_cache.py,git_env.pyand the owners JSON. I kept the owner description untouched to limit conflicts. Any remaining conflicts should be small textual ones.Benefits
git <subcommand>, byte and offset, instead of a reader-thread traceback and lost output.CalledProcessError, symlink-capability detection, credential redaction) is unchanged.Issue and approved scope
Issue: Fixes #3056
Human scope-approval comment: #3056 (comment) (canonical
apm-scope:v1record; review contact Daniel Meppiel (@danielmeppiel)). The Wave 2 map (2026-11-12) re-confirmed this issue as a bounded accept.Does this PR complete the issue? Yes. Done-when coverage: the regression covers the reported Windows/locale failure, valid output decodes deterministically, malformed machine output is surfaced, and command failure behavior is unchanged. Credit to Andrew Barnes (@Bortlesboat) for the earlier analysis and fix plan on the issue, which this implementation follows.
Type of change
Testing
Scenario evidence
apm installresolves refs on a cp936 Windows hosttest_remote_refs_decode_utf8_under_cp936_localetest_sparse_ls_tree_paths_decode_utf8_under_cp936_localetest_progress_clone_decodes_utf8_paths_under_cp936_localetest_malformed_stdout_is_surfaced_not_silently_corruptedtest_command_failure_is_preserved_with_malformed_stderr,test_unchecked_failure_returns_visible_escapesValidation output
How to test
uv run --extra dev pytest tests/unit/utils/test_git_output_decoding.py -p no:xdist. Expect 7 passed. These also run in the PR-time Windows Compatibility Gate (windows_compat).chcp 936), runapm installfor a dependency whose refs or paths contain non-ASCII characters. Expect noUnicodeDecodeErrortraceback.errors="surrogateescape"inrun_git_textand rerun step 1. Expect failures.Spec conformance (OpenAPM v0.1)
CONFORMANCE.{md,json}regeneratedCo-authored-by: Copilot [email protected]