Skip to content

fix(host): closed stdout pipe terminates niu — one diagnostic, status 1 (#245) - #256

Merged
caomengxuan666 merged 5 commits into
masterfrom
fix/host-broken-pipe
Oct 12, 2026
Merged

caomengxuan666 merged 5 commits into
masterfrom
fix/host-broken-pipe

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Issue

Closes #245 — tests/host_contract.rs::closed_stdout_pipe_does_not_print_broken_pipe_error failed deterministically on clean master: after the downstream reader closed niu's stdout pipe, niu never exited and spammed niu: line 1: Broken pipe to stderr forever. External repro shape: niu -c 'yes' | head -c 1.

Relationship to rubash#455

rubash#455 (issue #440) already landed in the engine and is active here via the local [patch] — a closed-output write is now an ordinary command failure (report, status 1, the list continues). That is GNU-correct for pipeline members and finite scripts, but it does NOT terminate niu when the shell's OWN stdout is the pipe whose reader went away: on Windows there is no SIGPIPE to kill the producer, so every later write fails again and an unbounded builtin loop (while true; do echo; done, yes) earns one diagnostic per iteration forever. This PR is the niu product-layer complement to #455, not a re-fix of it: the engine's script-continues semantics are preserved and pinned by the new inner_pipeline_broken_pipe_keeps_gnu_shape test.

Root cause

The engine's per-command error arm keeps the list running (correctly); nothing in the niu layer observes that the process's own stdout died. With panic="abort" launcher writers exit-0 on 232 (#125/#140), but the loop runs inside execute_ast, where the launcher has no hook.

Fix

New src/piped_stdout.rs: for non-interactive executions with a PIPE on stdout, niu interposes a kernel pipe + pump thread between the process's stdout writers (engine builtins, external children — everything targeting STD_OUTPUT_HANDLE) and the real downstream:

writers -> wrapper pipe (SetStdHandle) -> pump thread -> real stdout
  • while the reader lives the pump is transparent: same bytes, same order (single FIFO), backpressure through the pipe buffer;
  • when the downstream write fails (109/232), niu enforces the [bug][console] 原生 Win32 控制台 TUI 白屏 + 按键无响应(devin setup 最小复现) #455 contract at the process level: ONE diagnostic on stderr (niu: stdout: write error: pipe closed by downstream reader), exit status 1 — no spam, no unbounded loop;
  • finish() drains before process exit (closes niu's write handle, joins the pump); every post-execution exit funnel routes through it, so normal runs never lose output; a live-but-slow reader holds the exit exactly like the pre-change niu blocked in write (GNU bash does the same).

Never installed for: the interactive REPL (console stdout cannot break), launcher word paths (--version/--help keep their own closed-pipe exit-0 policy — tests/closed_pipe.rs stays green untouched), --internal-* pipeline components (their quiet exit IS the GNU child-SIGPIPE shape), niu -i, or when stdout is not a pipe. Non-Windows targets are unchanged (build checked for x86_64-unknown-linux-gnu).

Verification (target/debug/niu.exe, Windows)

  • cargo test --test host_contract closed_stdout_pipe → passes unmodified (0.84s; previously hung to the 3s deadline with a wall of Broken pipe)
  • New black-box suite tests/broken_stdout_pipe.rs (all deadline-bounded, 5/5):
    • while true; do echo; done and yes producers: reader closes → exit 1, exactly one diagnostic, no raw OS spam strings
    • live reader: 50 002-line output delivered in order through the drain (truncation guard)
    • inner yes | head -c 3; echo done-$?: quiet, rc 0, script continues — rubash#455 parity
    • echo hi; exit 3: output survives the nonzero exit
  • Related suites green: closed_pipe (3), smoke/smoke_1_3_0, defaults_floor, startup_files, completion_probe, repl_command, issue 117/149/153/156/160/162/176/191/195/200/201/204/365/59, plugin/skill/theme suites, unit tests (22 bin + 435 runtime)
  • Engine-side parity re-run on the local rubash worktree: issue440_broken_pipe_shell_survival 5/5 green
  • Two failures seen during the run — host_contract::history_and_fc_use_the_host_history_provider and issue182_bashit_history_interlock — reproduce identically on the unmodified master worktree (verified in a detached baseline worktree); pre-existing on this machine, unrelated to stdout plumbing.

… 1 (#245)

rubash#455 gave the engine GNU's parent-shell semantics for closed-output
writes (report, status 1, the list continues). Correct for pipeline members
and finite scripts — but when the shell's OWN stdout is the pipe whose
reader went away, 'continues' degenerates on Windows: there is no SIGPIPE
to kill the producer, every later write fails again (ERROR_BROKEN_PIPE 109
/ ERROR_NO_DATA 232), so an unbounded builtin loop printed one diagnostic
per iteration forever and niu never exited
(host_contract::closed_stdout_pipe; manual repro: niu -c 'yes' | head -c 1).

Fix (src/piped_stdout.rs): for non-interactive executions with a PIPE on
stdout, niu interposes a kernel pipe + pump thread between the process's
stdout writers (engine builtins, external children — everything targeting
STD_OUTPUT_HANDLE) and the real downstream:

    writers -> wrapper pipe (SetStdHandle) -> pump -> real stdout

- while the reader lives the pump is transparent: same bytes, same order
  (single FIFO), backpressure through the pipe buffer;
- when the downstream write fails, niu enforces the #455 contract at the
  process level: ONE diagnostic on stderr, exit status 1 — no spam, no
  unbounded loop;
- finish() drains before process exit (closes niu's write handle, joins
  the pump), and every post-execution exit funnel routes through it, so
  normal runs never lose output (verified with a 50k-line drain test);
  a live-but-slow reader holds the exit exactly like the pre-change niu
  blocked in write (GNU bash does the same).

The wrapper is never installed for the interactive REPL (console stdout
cannot break), the launcher word paths (--version/--help keep their own
closed-pipe exit-0 policy, pinned by tests/closed_pipe.rs), --internal-*
pipeline components (their quiet exit IS the GNU child-SIGPIPE shape),
niu -i, or when stdout is not a pipe. Non-Windows targets are unchanged.

Tests: new black-box suite tests/broken_stdout_pipe.rs (deadline-bounded):
while-true/yes producers exit once with status 1 and exactly one
diagnostic; live-reader drain keeps full output; inner 'yes | head -c 3'
keeps the rubash#455 GNU SIGPIPE shape (quiet, rc 0, script continues);
'echo hi; exit 3' still delivers output through the nonzero exit.
host_contract::closed_stdout_pipe now passes unmodified; closed_pipe and
the engine-side issue440/issue382 suites stay green. The history_and_fc
and issue182 host-contract failures seen on this machine reproduce
identically on the unmodified master worktree (pre-existing, unrelated).
…e red-lock window

CI runs with RUSTFLAGS=-D warnings; while the lockfile kept every run
red (rubash 1.4.0 bump), merged code was never lint-checked and carried
these through:

- plugins/assets.rs: the adapter_for(...).map closure uses only the
  Option as a gate; the binding is now _adapter.
- setup_wizard.rs probe_tools: the wpm insert is cfg(windows)-only, so
  the mut binding moves into a cfg(windows) shadow instead of firing
  unused_mut on unix.
- shell.rs native_command_not_found_hint_lines_with_policy: the closure
  parameter is only called on the windows path; allow(unused_mut) under
  cfg_attr(not(windows)).
- shell.rs ShellChannel::Stdout: reserved half of the GNU stream-shape
  contract (#190); no constructor exists yet by design, the channel
  capture tests assert the stderr-only shape against the two-variant
  enum. allow(dead_code) with the contract comment.

Verified: RUSTFLAGS=-D warnings cargo check -p niubash-runtime --locked
clean on both x86_64-pc-windows-msvc and x86_64-unknown-linux-gnu.
…est targets

Second batch behind the previous -D warnings commit, found by
compiling --workspace --all-targets on both windows-msvc and
x86_64-unknown-linux-gnu:

- piped_stdout.rs: BROKEN_STDOUT_EXIT_CODE/BROKEN_STDOUT_DIAGNOSTIC are
  consumed only by the cfg(windows) pump imp; gate them the same way so
  unix targets stop seeing dead constants.
- tests/interactive/driver.rs: the pty harness is compiled into every
  interactive test binary, each consuming a subset of the surface;
  allow(dead_code) on the module with the rationale.
- issue200_esc_quote_strip.rs: two expected vectors are never mutated.
- shell.rs test: print_command_not_found_hints takes &self.
- issue149/issue162 boundary tests: helpers and imports follow the
  tests' own windows gate instead of dangling unused on unix.

Verified: RUSTFLAGS=-D warnings cargo check --workspace --all-targets
--locked clean on both targets.
@caomengxuan666
caomengxuan666 merged commit 11c1612 into master Oct 12, 2026
6 of 7 checks passed
caomengxuan666 added a commit that referenced this pull request Oct 12, 2026
…ords, 675 assets, evidence-based reclassification (#263)

Static analysis + WSL GNU bash comparison + current rubash -n (noexec).
No untrusted asset executed locally; the dead 2026-10-10 replay channel
(closed-stdout-pipe artifact, fixed by #256) is superseded.

Headlines:
- SR bucket (54 records / 39 unique): 20 GNU-parity (extglob parse-time
  dependency; bash -n rejects standalone on BOTH shells), 11 fixed since
  the snapshot (ble.sh x6 arithmetic grammar, jb-cli #463, odsel parse
  timeout, zZsh/mirkop/.shortcut #460), 6 zsh-dialect (never attributed
  to rubash), 2 corpus pollution (README.md, fenced essay), 1 genuinely
  broken; exactly ONE live defect remains: sheldritch args.sh line 1307
  - multi-line bracket-expression inside a function body with a
  pipe-pipe continuation line (rubash#505, minimal repro included).
- HANG bucket (101 / 80): 9 map to closed-fixed rubash#451 class A
  (ConPTY 0x15 injection) and class B (post-source continuation), 3 are
  snapshot-era mid-source parse errors now parsing clean, 45+ are
  interactive stdin-consumer artifacts (GNU completes with stdin closed),
  rest env-dependent / network / prompt-stream artifacts; 6 honest
  residuals flagged for a spot live replay on a post-#256 build.
- Snapshot verdict instability documented: 275 assets carry conflicting
  verdicts across the three in-snapshot runs (binary drift).
- GAF/SLOW/EXITED/ERROR-STORM reclassified with per-record evidence.

Machine-readable: reclassified-records-20261012.jsonl (747 rows),
classified-uniques.json (675 rows with full evidence).
caomengxuan666 added a commit that referenced this pull request Oct 12, 2026
…ion end - the missing exit half of #250's -c semantics (#265)

The only red in #256's fourth-round CI, tests/host_contract.rs
history_and_fc_use_the_host_history_provider, panicked at its final
assertion: after a one-shot `niu -c "history -c"` the host history
file still held the pre-clear lines, not the empty file the host
contract pins.

#250 (niubash#182) moved the provider's `history -c` to the GNU
semantics the bash-it interlock needs: clear the in-memory list only
(builtins/history.def:185), snapshot-and-restore the file bytes so the
theme's per-prompt `-c && -r` cycle can reload them. The host
contract's "file is empty after -c" outcome was the old
truncate-on-clear behavior (the assertion predates #250; blame
5ad24ec). Both halves are right about their own side; what niu was
missing is bash's OTHER half of `-c`: the exit write. bashhist.c's
exit_shell() writes the final history list to $HISTFILE when a session
that remembers history ends (overwrite unless histappend), so a list
that `-c` emptied truncates the file at exit - the `-c` builtin itself
never touches the file in bash either.

Fix (crates/niubash-runtime/src/history.rs only): the provider now
performs that session-end write when it drops - every rc-0 session end
tears down normally, the same path the pre-existing drop-time sync
already relies on:

- final list empty -> truncate the backing file (the host contract's
  empty file); a session without history still creates nothing;
- final list non-empty -> one reedline sync of its unwritten buffer,
  which after the staleness refresh is exactly the set the file lacks
  (the -a dedupe). A blind overwrite would roll back lines another
  concurrent shell appended, and the bash-it `-a && -c && -r` cycle
  must stay a fixed point.

The append deliberately routes through reedline's own sync instead of a
raw file append: reedline's FileBackedHistory syncs its unwritten buffer
again on Drop, so a raw append leaves that accounting stale and the
drop-time sync re-appends the same lines.

Failures warn once via log::warn and never reach stderr, like every
history-file write. Sessions that terminate through std::process::exit
(nonzero -c statuses, the exit-jump path) skip Drop and keep the
pre-clear file, the same as the pre-existing drop-time sync.

Proven: host_contract 43/43 green including the fixed test; runtime lib
15/15 history unit tests green; four new unit tests pin the cleared-list
truncate, the concurrent-shell no-rollback, the dedupe re-append after a
transient (read-only) sync failure, and the degraded memory-only no-op.
@caomengxuan666
caomengxuan666 deleted the fix/host-broken-pipe branch October 13, 2026 02:06
caomengxuan666 added a commit that referenced this pull request Oct 13, 2026
…ve execution shape (closes #286) (#289)

* test(host): pin the closed-stdout contract across every non-interactive execution shape (closes #286)

The #286 failure (host_contract::closed_stdout_pipe... red on 0830c78:
niu never exits after the stdout reader leaves and spams 'niu: line 1:
Broken pipe' per failed write) is already fixed on master by the
piped-stdout pump (#245/#256): one diagnostic, status 1, prompt exit.
Reproduced locally for the record - the pin file below is RED on
0830c78 (3 of 4 shapes hang past the deadline) and GREEN on master.

What was still unpinned after #256 were the execution shapes #286's
report implies but nothing guarded: a script FILE producer loop, a
stdin-script producer loop, an EXTERNAL child as the unbounded
producer (the inherited-handle path), and stderr being gone too when
the pump reports. All four now carry the deadline-bounded contract:
exit by itself, rubash#455-shaped status 1, no raw OS broken-pipe
text, exactly one diagnostic.

GNU oracle (WSL bash): the same producer under 'bash | head -c 16'
dies promptly via SIGPIPE with zero stderr bytes; niu's vendored
adaptation keeps the prompt termination and the errno silence,
spending one descriptive diagnostic plus status 1 instead of signal
death - deliberate, per the rubash#455 semantics ownership note in
tests/broken_stdout_pipe.rs.

* test(host): drop the unused Path import pinning the -D warnings lane
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.

[bug] stdout 管道关闭后 niu 不退出且刷 Broken pipe(host_contract::closed_stdout_pipe 测试失败)

1 participant