`IO.Process.spawn` flushes the parent's stdout only when `stdin` (not `stdout`) is `.inherit`, so output comes out of order

Abierto Apto para principiantes
#16,809 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
78/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo

Línea de trabajo

Lee lean_io_process_spawn en src/runtime/uv/process.cpp, especialmente la comprobación del modo stdio alrededor de las líneas 338–340; el issue identifica el campo stdout como índice 1. Reproduce el problema con el programa Lean proporcionado y stdout redirigido; después, comprueba el orden de salida con stdout heredado y null stdin. Se considera terminado cuando, en ese caso, la salida almacenada en búfer del proceso padre aparece antes que la del proceso hijo y se mantiene el comportamiento interactivo existente de stdin.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug
Prerequisites
  • Check that your issue is not already filed:
    https://github.com/leanprover/lean4/issues
  • Reduce the issue to a minimal, self-contained, reproducible test case.
    Avoid dependencies to Mathlib or Batteries.
  • Test your test case against the latest nightly release, for example on
    https://live.lean-lang.org/#project=lean-nightly
    (You can also use the settings there to switch to “Lean nightly”)
  • When reporting a perceived soundness bug: Does it affect lake check --paranoid?
    If in doubt, please reach out on [email protected] for responsible disclosure.
    (Not a soundness bug.)
Description

Before spawning, std::cout is flushed only when the child inherits stdin (src/runtime/uv/process.cpp:338-340). With stdout := .inherit and stdin := .null or .piped, output the parent has buffered (stdout is a pipe) can appear after the child's output. Keying on stdin is old and probably deliberate: it makes an interactive prompt visible before a child reads the terminal. Nothing documents that inherited stdout is ordered, so this is a missing case rather than a broken contract. Flushing when stdout (field 1) is inherited as well would fix it.

    if (static_cast<stdio_mode>(cnstr_get_uint8(stdio_cfg.raw(), 0)) == stdio_mode::inherit) {
        std::cout.flush();
    }

The program writes "parent1 " to standard output (a pipe, so the parent's stdio buffer keeps it), then calls IO.Process.spawn { cmd := "echo", args := #["child"], stdout := .inherit, stdin := .null }, waits for the child and writes "parent2 0". Its standard output is "child\nparent1 parent2 0\n": the child's line, written straight to the inherited descriptor 1, comes before the output the parent had already written. The parent's pending output should have been flushed before the child could write to the same stream, as the spawn code itself intends: it calls std::cout.flush() before spawning, but it guards that flush with the stdin mode (cnstr_get_uint8(stdio_cfg.raw(), 0)) instead of the stdout mode (field 1), so with stdout := .inherit, stdin := .null no flush happens. The same program with only stdin := .inherit prints "parent1 child\nparent2 0\n", i.e. the parent's earlier output first. So a field that has nothing to do with standard output — the child's standard input mode — changes the program's standard output; the flush decision belongs to the stdout field, which is .inherit in both programs.

Context
  • Affected function: lean_io_process_spawn (src/runtime/uv/process.cpp)
  • Upstream: no existing issue found; the cited code is unchanged in nightly-2026-11-26. The stdin-keyed flush already existed in the pre-libuv src/runtime/process.cpp (v4.20.0, line 558).
Steps to Reproduce
  1. Save the following as input.lean:
import Std

def main : IO Unit := do
  IO.print "parent1 "
  let child ← IO.Process.spawn { cmd := "echo", args := #["child"], stdout := .inherit, stdin := .null }
  let c ← child.wait
  IO.println s!"parent2 {c}"
  1. Compile: lean -c input.c input.lean && leanc -o prog input.c
  2. Run with stdout redirected to a pipe or file: ./prog | cat (or ./prog > out.txt; cat out.txt)

For comparison, the same program with stdin := .inherit (nothing else changed) prints the lines in the right order.

Expected behavior:

parent1 child
parent2 0

Actual behavior:

child
parent1 parent2 0

(With stdin := .inherit the output is parent1 child\nparent2 0\n, as expected.)

Versions

Lean (version 4.38.0-nightly-2026-11-26, arm64-apple-darwin24.6.0, commit e1228b8b45918ece1a00d68e5fc5e6a685ca59ee, Release)
macOS 26.6.2 (arm64)

Additional Information

Root cause analysis. lean_io_process_spawn receives an ordinary configuration { cmd := "echo", args := #["child"], stdout := .inherit, stdin := .null }. Before spawning, it flushes the parent's pending standard output only when cnstr_get_uint8(stdio_cfg.raw(), 0) — the standard input mode — equals inherit; with stdin := .null it skips the flush although the stdout mode (field 1) is inherit, so the child's child\n reaches the shared descriptor before the parent's buffered parent1 . The modes are not produced by a callee: stdio_cfg is the toStdioConfig field of the argument object the caller passed, and the only callee that sees the modes, setup_stdio, just mirrors each mode into the libuv container and returns; the wrong index is selected in lean_io_process_spawn itself at src/runtime/uv/process.cpp:338.

Suggested fix: also flush when the stdout field (index 1, cnstr_get_uint8(stdio_cfg.raw(), 1)) is inherit (keeping the existing stdin case, which makes a prompt visible before an interactive child reads the terminal); consider the same for stderr (index 2) if std::cerr is ever buffered. With the decision made on the stdout field, both variants print parent1 child\nparent2 0\n.

Impact

Programs that print to a pipe or file and then spawn a child with inherited stdout but non-inherited stdin (CI logs, scripted runs) can get output out of order.

Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.

Lenguaje dominante
Lean
Estrellas
10.3k
Forks
1.1k
Merge medio
18 h 27 min
PR fusionados (30 d)
390

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de leanprover/lean4

Todos los issues de leanprover/lean4

Issues similares

Más issues de Operating Systems

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.