Skip to content

fix(pipeline): keep merged-stream order in pipeline stages - #3399

Merged
caomengxuan666 merged 5 commits into
unixwin:masterfrom
Uarz:fix/issue-3324
Nov 12, 2026
Merged

caomengxuan666 merged 5 commits into
unixwin:masterfrom
Uarz:fix/issue-3324

Conversation

@Uarz

@Uarz Uarz commented Nov 11, 2026

Copy link
Copy Markdown
Member

Fixes #3324

What was fixed

Pipeline stages lost cross-stream order when their stdout and stderr merged into one sink (trap -p lists vs diagnostics, printf output vs its diagnostics): GNU's execute_pipeline forks each element and the element's own redirections run in the child (execute_cmd.c:2620, do_redirections redir.c:237), so writes to the same descriptor are naturally ordered, and bash line-buffers stdout (shell.c:1921-1922 sh_setlinebuf). Rubash had three instances of the same disease, all in the merge layer rather than in any builtin:

  1. A sub-shell stage's chunk routing fell through to pair-block writes (all of stdout, then all of stderr) whenever apply_ordered_output_redirects found nothing to do — but the stage's clone had already had its fd 1/2 entries stripped, so the walk legitimately had nothing to do while the fd table already held a merged binding ([A2-02] command <external> as a pipeline stage drops the command's own redirections #2689). Now it falls through to the chunk walk only when redirect_failed and first_open_error are both empty.
  2. The inline Trap/Printf arms collected their ordered writes into two separate Vecs and returned a (stdout, stderr) tuple with the interleave already lost — both arms now go through OrderedOutputLog ([A3-R58A] Multi-argument builtin stdout/stderr interleaving lost in the shared buffered-output path #2699), recorded in the new Executor::pipeline_stage_ordered_chunks field (cleared at execute_pipeline_stage_inner entry; initialized in init.rs and command_substitution.rs), and the driver rebuilds the merged stream from the log through one shared sink when both streams resolve to the same sink (2>&1, 1>&2, >f 2>&1, including the ProcessStderr≡Stderr 1>&2 variant), keeping the order-dependence of 2>&1 >f.
  3. printf's [bug] printf invalid-number diagnostic comes after the output value in a merged 2>&1 stream #1134 error model was wrong: render() collected all output into one String and diagnostics separately, with consumers writing all diagnostics first, on the claim that GNU's stdio fully buffers stdout — the oracle (printf '%d\n' 5 bad 7 2>&1 | cat and the direct form both give 5, diagnostic, 0, 7) shows bash line-buffers stdout, so RenderedPrintf is now a production-ordered sequence of PrintfSegment::{Text, Error} (with %n counts summed over Text segments and -v still joining Text), execute_printf goes through the log + chunk routing, and the now-dead write_buffered_builtin_output_stderr_first plus the two stderr_first parameters were removed with four comments corrected. [bug] printf invalid-number diagnostic comes after the output value in a merged 2>&1 stream #1134's single-parameter test still passes (its diagnostic precedes its own converted value, which the interleave model also satisfies).

What was deleted

write_buffered_builtin_output_stderr_first and the stderr_first parameters of route_builtin_buffered_output_ordered / write_buffered_builtin_output_ordered (dead after the interleave model replaced the stderr-first model), plus four comments stating the old fully-buffered model. No files, features, or tests were removed.

Verification (all run, per-item counts)

Owed

  1. declare -p mixed form still reversed (newly found here, needs a separate issue): v=1; declare -p BADNAME v 2>&1 | cat — GNU: diagnostic first, listing after; rubash: listing first, diagnostic after. Different mechanism from this fix: declare's diagnostics go through Diag::pending, rendered only after the handler returns via flush_with, and the funnel uses the pair route. Fixing it needs declare's funnel (execute_declare and 2 other sites) to go through the log + flush each Diag in the print loop — a big declare-family change, not folded into this fix.
  2. Builtin stage leaks the parent EXIT trap (pre-existing, noted in the pin file's header comment): trap "echo bye" EXIT; type ls | cat prints bye once when the stage exits and again at script end; GNU prints it once. execute_builtin_pipeline_stage (pipeline_stages.rs:927) lacks reset_for_subshell_child. The pin's type cases deliberately avoid installing an EXIT trap.
  3. Merged-to-Closed diagnostic count: when both streams point at Closed, the merged stream reports write error: Bad file descriptor once (before the fix, each stream reported once; GNU loses the diagnostic entirely because fd 2 is closed, so it is unobservable). Closer to GNU; no separate issue filed.
  4. printf fast paths inside command substitution (command_substitution.rs:1042, command_substitution_pipelines.rs:930) take only stdout and already drop diagnostics — the captured value contains stdout only, so cross-stream order is unobservable there; untouched.

Pipeline stages lost cross-stream order when their stdout and stderr merged into one sink (trap -p lists vs diagnostics, printf output vs its diagnostics): GNU's execute_pipeline forks each element and the element's own redirections run in the child (execute_cmd.c:2620, do_redirections redir.c:237), so writes to the same descriptor are naturally ordered, and bash line-buffers stdout (shell.c:1921-1922 sh_setlinebuf). Rubash had three instances of the same disease, all in the merge layer rather than in any builtin: (1) a sub-shell stage's chunk routing fell through to pair-block writes (all of stdout, then all of stderr) whenever apply_ordered_output_redirects found nothing to do — but the stage's clone had already had its fd 1/2 entries stripped, so the walk legitimately had nothing to do while the fd table already held a merged binding (unixwin#2689); now it falls through to the chunk walk only when redirect_failed and first_open_error are both empty; (2) the inline Trap/Printf arms collected their ordered writes into two separate Vecs and returned a (stdout, stderr) tuple with the interleave already lost — both arms now go through OrderedOutputLog (unixwin#2699), recorded in the new Executor::pipeline_stage_ordered_chunks field (cleared at execute_pipeline_stage_inner entry; initialized in init.rs and command_substitution.rs), and the driver rebuilds the merged stream from the log through one shared sink when both streams resolve to the same sink (2>&1, 1>&2, >f 2>&1, including the ProcessStderr==Stderr 1>&2 variant), keeping the order-dependence of 2>&1 >f; (3) printf's unixwin#1134 error model was wrong: render() collected all output into one String and diagnostics separately, with consumers writing all diagnostics first, on the claim that GNU's stdio fully buffers stdout — the oracle (printf '%d\n' 5 bad 7 2>&1 | cat and the direct form both give 5, diagnostic, 0, 7) shows bash line-buffers stdout, so RenderedPrintf is now a production-ordered sequence of PrintfSegment::{Text, Error} (with %n counts summed over Text segments and -v still joining Text), execute_printf goes through the log + chunk routing, and the now-dead write_buffered_builtin_output_stderr_first plus the two stderr_first parameters were removed with four comments corrected. unixwin#1134's single-parameter test still passes (its diagnostic precedes its own converted value, which the interleave model also satisfies).

Refs unixwin#3324

Regression pin tests/issue3324_pipeline_stage_merged_order.rs (18 tests; fail-first 7 passed / 11 failed on the unpatched tree, 18/18 pass after; supervisor verified both rounds with the patch method). Adjacent: printf/trap/type/help/pipeline/echo/declare families 149 targets, 976 pass / 10 fail — the 10 failures are pre-existing, verified by the supervisor on the unpatched tree with identical counts (issue1100_printf_option_parsing 4/5 and issue3046_exec_pipeline_chardev_stdin 10/5 on both trees; unixwin#1100 expects a bash: prefix where the worktree binary reports its own path, unixwin#3046 is an exec + char-device stdin pipeline read-count issue). lib printf unit tests 56/56; unixwin#1134 1/1, unixwin#2699 7/7 (supervisor re-ran both; the agent's report said 8/8 for unixwin#2699, the supervisor's own count is 7/7, all green). cargo fmt clean.
@caomengxuan666 caomengxuan666 self-assigned this Nov 11, 2026
@caomengxuan666 caomengxuan666 added bug Something isn't working gnu-baseline Tracked by the GNU Bash 5.3.0 true-baseline ledger P3-low 低:优化、文档、远期规划,有机会再做 area:fd redirection, fd table, /dev/* emulation, dup/close ordering labels Nov 11, 2026
@caomengxuan666

Copy link
Copy Markdown
Member

Thanks, @Uarz — received. This is queued for captain review (per the owner's rule, external PRs are reviewed by the captain first); no merge or change request from intake.

First pass on the diff: the change matches the body — the three merge-layer defects are addressed where claimed: the subshell-stage chunk routing now falls through to the chunk walk only when redirect_failed and first_open_error are both empty; the inline Trap/Printf arms go through OrderedOutputLog into the new Executor::pipeline_stage_ordered_chunks field, with the driver rebuilding the merged stream through one shared sink when both streams resolve to the same sink; and RenderedPrintf is now a production-ordered PrintfSegment::{Text, Error} sequence, with the dead write_buffered_builtin_output_stderr_first helper and its stderr_first parameters removed. The new pin tests/issue3324_pipeline_stage_merged_order.rs covers 18 forms with fail-first 7 passed / 11 failed on the unpatched tree as claimed.

CI is fully green here (10 checks passed + 1 skipping).

One thing flagged for the captain's review, from your Owed §1: the newly found declare -p mixed form (v=1; declare -p BADNAME v 2>&1 | cat — GNU prints the diagnostic first, rubash the listing first) still needs a separate issue; whether it gets filed now or folded into review is the captain's call. No action needed from you unless the review asks for it.

@caomengxuan666

Copy link
Copy Markdown
Member

Captain review — PASS

Reviewed at head c2b44abb80479f5e8fdb07c0de0cd22981c153ed; true fork point
f5f65d35 (git merge-base). All legs ran on the Simular box in a clean-fd
context. Full dossier: ~/workspace/review-3399/CAPTAIN-VERIFY.md.

Measured

  • Pin issue3324_pipeline_stage_merged_order: 18/18 on the head; on the
    fork base with only the pin topped up, 7 passed / 11 failed, the failures
    exactly the merged-order shapes (printf direct, printf pipeline mixed,
    trap -p diag-first/sandwich/multi-stage/file-merge/|&, type diag-first).
    Clean fail-first.
  • Adjacent stems unchanged bilaterally: issue1100_printf_option_parsing
    4/5 and issue3046_exec_pipeline_chardev_stdin 10/5 on both trees with
    identical failure name sets — both pre-existing, as the PR body declares.
    issue1134 1/1 and issue2699 7/7 stay green.
  • lib: 1245 passed / 0 failed / 4 ignored on both trees, failure name sets
    identical (empty). fmt, marker-literal and UTF-8 boundary hygiene legs clean.
  • Warnings: scoped -D warnings check (lib + bins + this pin) rc=0. The
    full-target --keep-going enumeration on the head yields exactly 16 error
    points, all intra-file lints in pre-existing test files (dead fields,
    unused imports/variables, needless mut, one unused function and method) —
    none in src/, none in this PR's pin. Every one of those files is
    byte-identical between the fork base and this head (git diff -- tests/
    adds only the pin), so the set is point-identical to the fork-base set;
    master has been clearing this exact class since the fork (the
    issue2722:32 point via test(executor): correct pwd expectation formula and clear -D warnings dead code #3369 9994ad97, the sibling issue3182 point
    via test(issue3182): drop never-read Outcome.stdout field from diagnostic faces pin #3418).
  • Head CI: 15 check-runs finished, 10 success + 5 skipped, zero failure.
  • Three-way probes (32 shapes; GNU bash 5.3.20 oracle, fork base, this head,
    current master): the head matches GNU byte-for-byte, modulo script path, on
    every in-scope shape.

Delimitations attached to this review

  • Owed §3 is closed by measurement. Across 15 Closed-sink shapes the
    head's observable write error count equals GNU's everywhere (zero where
    GNU's report dies with the closed fd, exactly one where GNU reports once),
    and the fork base shows the same counts — the pre-fix "reported twice"
    behaviour does not reproduce on the true fork base. Nothing to fold in,
    nothing to file for §3 as written.
  • Two neighbouring Closed-fd divergences surfaced instead; both are
    base ≡ head (pre-existing, untouched by this PR) and are recommended as
    one separate small issue, not a condition here: (A) printf pass-granular
    abort — GNU suppresses later-pass conversion diagnostics once a pass fails
    to write (builtins/printf.def:819 ferror gate); rubash prints them.
    (B) a pipeline stage whose own redirections close both fds — GNU loses
    every diagnostic; rubash resurrects the write error once via the driver's
    captured stream.
  • [bug] declare -p mixed diagnostic/output still reversed on a merged stream (follow-up to #3324) #3408 and [bug] EXIT trap fires inside a pipeline element (type ls | cat prints the trap output twice) #3409 cross-checked on the fork base, this head, and current
    master
    : both reproduce identically on all three trees and are not covered
    or altered by this PR (declare's own diagnostic funnel; the stage
    executor's missing subshell trap reset). They stay Refs-only in the merge
    body, exactly as filed.

Merge conditions

Update-branch first (the PR's 9 files intersect master's interval since the
fork in 6 files, unchanged against both f6e8c674 and dcc2c220), then on
the merged head: pin 18/18, lib failure set ∅, adjacent stems unchanged,
full-target -D warnings with no point in src/ or this PR's files and the
set within the 16-point fork-base set, merged-shape spot checks, final-head
CI finished green.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:fd redirection, fd table, /dev/* emulation, dup/close ordering bug Something isn't working gnu-baseline Tracked by the GNU Bash 5.3.0 true-baseline ledger P3-low 低:优化、文档、远期规划,有机会再做

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pipeline stage 输出跨流失序:trap -p 列表与诊断合流顺序与 GNU 不符

2 participants