[BUG] git/gh subprocess text is locale-dependent; pin the C locale via iris.shell.git_env() - #239
Open
rafaeldearaujop wants to merge 1 commit into
Open
[BUG] git/gh subprocess text is locale-dependent; pin the C locale via iris.shell.git_env()#239rafaeldearaujop wants to merge 1 commit into
rafaeldearaujop wants to merge 1 commit into
Conversation
…git_env() Git localizes its messages; on pt_BR machines the stderr surfaced in RuntimeError read 'Arquivo ou diretório inexistente' and test_git_reader failed while CI passed. Add iris/shell.py::git_env() (a function, so it reflects os.environ at call time) and pass env=git_env() at the 23 subprocess.run sites whose argv starts with git or gh. Structured output was already locale-safe: paired E2E under pt_BR is byte-identical. tests/test_subprocess_locale.py adds the pt_BR regression, an env-isolation check and a static guard. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
[BUG] git/gh subprocess text is locale-dependent; pin the C locale via
iris.shell.git_env()Aberta como PR direta, não como issue: bug reproduzível com fix validado
em mãos; o corpo segue o template
bug.ymlpara rastreabilidade.Referências
arquivo:linhaapontam paramain @ da16235.Summary
O engine repassa o
stderrdo git em mensagens de erro, e o git localizaesse texto conforme
LANG/LC_MESSAGES. Em máquinaspt_BR.UTF-8, amensagem para caminho inexistente é "Arquivo ou diretório inexistente" — e
tests/test_git_reader.py::test_nonexistent_path_raises_with_git_stderr(que espera
"no such file or directory") falha. A CI passa porque roda emlocale inglês. Esta PR fixa o locale C em todos os subprocessos de
gite
ghdo engine, sem alterar o ambiente do usuário.Reproduction steps
LANG=pt_BR.UTF-8 LC_ALL=pt_BR.UTF-8 pytest tests/test_git_reader.py -q→
1 failedemtest_nonexistent_path_raises_with_git_stderr(
tests/test_git_reader.py:66).LC_ALL=C pytest tests/test_git_reader.py -q→passed.git -C /caminho/inexistente log -1→fatal: cannot change to '/caminho/inexistente': Arquivo ou diretório inexistente(com
LANG=C:… No such file or directory).Expected behaviour
Mensagens e parsing de saída do git/gh estáveis por locale: o mesmo
comando, na mesma versão, produz o mesmo texto em qualquer máquina. A suíte
passa localmente em qualquer locale.
Actual behaviour
pt_BR.UTF-8, git 2.43.0).frágil por locale. O parsing estrutural (
--prettycom separadores,--numstat,--porcelain,--json) já era locale-safe; as mensagens deerro que chegam ao usuário e aos testes não eram.
Surface
Engine / CLI (Python)
Versão do CLI
v1.6.1 (
main @ da16235)Repo analisado
Não se aplica — reproduz com caminho inexistente.
Logs / screenshots / trace-id
Correção aplicada
iris/shell.py(novo, 25 linhas):git_env() -> dict[str, str]devolveos.environcomLC_ALL=CeLANG=C. É função, não constante demódulo, para refletir
os.environno momento da chamada (testes fazemmonkeypatch.setenv) em vez de congelar um snapshot na importação.23 call sites em 11 arquivos passam
env=git_env()— exatamente ossubprocess.runcujo argv começa com"git"ou"gh":iris/ingestion/git_reader.pygit log,git rev-parseiris/ingestion/diff_reader.pygit showiris/ingestion/github_reader.pygit remote,gh api graphql,gh pr list,gh pr viewiris/analysis/durability.pygit blameiris/analysis/code_provenance.pygit blameiris/analysis/repo_kind.pygit ls-filesiris/analysis/priming_detector.pygit log --diff-filter=Airis/cli.pygit remote get-url,gh pr view,gh pr comment,git check-ignore,git rev-parseiris/platform/identity.pygh apiiris/platform/config.pygh api user,git configiris/hooks/manager.pygit *args(sonda de configuração)Deliberadamente não tocados, e por quê:
iris/hooks/manager.py:322— executa o arquivo de hook, não o git; oenvali já carrega a testemunha da sonda de alcance.iris/cli.py:1640—curl … | shdo auto-upgrade; não é git/gh.iris/update/auto.py:186—Popendo updater; idem.iris/ingestion/external_reader.py— comandos fornecidos pelo usuáriocom
envpróprio; impor locale seria alterar o comando dele.Guard estático (
tests/test_subprocess_locale.py): varreiris/**/*.pye falha se algum
subprocess.run(cujo argv literal começa comgit/ghnão passa
env=. Limitação conhecida: um call site(
github_reader.py:232) recebeargscomo variável, não literal — foicorrigido à mão, mas o guard não o enxergaria se regredisse. Alternativa
(resolver o nome
argsaté o literal) foi julgada complexidade demais paraum caso; a limitação está na docstring do teste.
Validação (isolada:
main+ só esta mudança)pytest tests/ -qsobLC_ALL=Cpytest tests/ -qsobLC_ALL=pt_BR.UTF-8tests/test_subprocess_locale.pyos.environ· guard)check_analysis_chain.pymetrics.jsonereport.mdbyte-idênticospython -m compileall irisO E2E idêntico é o resultado esperado e importante: a saída estruturada já
era locale-safe, então fixar o locale não pode mudar nenhum número — só
torna as mensagens de erro determinísticas.
Como reproduzir
Análise adversária — toda linha com disposição final
LC_ALL=C.env=+ um módulo de 25 linhas.LC_ALL=Cpode quebrar caminhos não-ASCII na saída do git.core.quotePath) independentemente do locale;repo_kind.pyjá usa-zeerrors="surrogateescape". Não piora. E2E byte-idêntico confirma.CLAUDE.md, Coding Principles: "Favor deterministic outputs".ghnão localiza mensagens; por que incluí-lo?ghrepassa erros do git em alguns caminhos.os.environna importação; testes commonkeypatch.setenve processos longos veriam um ambiente stale.test_git_env_pins_c_locale_and_keeps_the_rest.argscomo variável).env={**os.environ, "LC_ALL": "C", "LANG": "C"}repetidos seria pior para ler e para manter do que uma função de três linhas com o porquê na docstring.subprocess.run.Fora do escopo
external_reader.py).Issues relacionadas (verificado contra as 63 issues do repo, abertas e fechadas — sem duplicata)
stderrreal do git e crioutest_nonexistent_path_raises_with_git_stderr. Repassar o texto foi correto; faltou fixar o locale para que esse texto seja o mesmo em toda máquina. Bug diferente, mesma linha de código.LC_ALL=C sortpara determinismo. Mesmo princípio, aplicado aqui aos subprocessos degit/gh.Referências
iris/shell.py;tests/test_subprocess_locale.py.main @ da16235):iris/ingestion/git_reader.py:71,98,132;iris/ingestion/diff_reader.py:75;iris/ingestion/github_reader.py:37,232,288,390;iris/analysis/durability.py:250;iris/analysis/code_provenance.py:193;iris/analysis/repo_kind.py:143;iris/analysis/priming_detector.py:139;iris/cli.py:243,942,982,1168,1180;iris/platform/identity.py:33,61,89;iris/platform/config.py:66,78;iris/hooks/manager.py:127.iris/hooks/manager.py:322;iris/cli.py:1640;iris/update/auto.py:186;iris/ingestion/external_reader.py.tests/test_git_reader.py:61-66;CLAUDE.md→ Coding Principles ("Favor deterministic outputs").