Skip to content

fix7 coproc-life: coproc lifecycle & grammar fixes (12 issues) - #1712

Closed
caomengxuan666 wants to merge 17 commits into
masterfrom
fix7/slice-coproc-life
Closed

caomengxuan666 wants to merge 17 commits into
masterfrom
fix7/slice-coproc-life

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

fix7/coproc-life 集成片:coproc 生命周期与语法面 12 条修复(簇分支 fix7/coproc-life 16 commit cherry-pick 至当前 master,外加 1 笔集成 fmt 修正——仅本片自家改动行的折行,cargo fmt --check 漂移文件数与基线同为 46,改动文件零新增漂移)。

Fixes #1623
Fixes #1624
Fixes #1625
Fixes #1632
Fixes #1638
Fixes #1644
Fixes #1645
Fixes #1651
Fixes #1652
Fixes #1653
Fixes #1655
Fixes #1659

Refs #1646(引擎侧裁定不复现数据丢失——{var}/exec 持久形态在本引擎构建上逐一实测均送达;残余嫌疑在 niubash 宿主退出路径未调 finish_shell / close_all_persistent_output_process_substitutions,待 niu 侧核查,本片无代码改动)

簇侧门(基线 d15a02d 的簇树)

  • cargo test --locked --test cli_tests issue16:28 passed / 0 failed
  • cargo test --locked --test parser_coproc_tests:31 passed / 0 failed(含按 GNU oracle 改写的 5 条 time 存量测试)
  • cargo test --locked --lib -- --skip login_posix_env:771 passed / 1 failed / 1 ignored,唯一失败 ownership_unary_operators_check_existing_file(基线允许项)
  • 改动文件 CR 全部 0

内容摘要

与协作者单条 PR 的比对(a-rookie-of-C-language,簇 REPORT 比对节)

集成树验证(定向 cli/parser_coproc、lib 同集、diffcorpus 306)在本 PR 评论区回填后合并。

…rubash#1623)

The -u call site recomputed read_eof_no_delimiter from the trimmed
line — whose delimiter had already been stripped — so every
successful read from a coproc fd was marked EOF and returned 1.
read_coproc_stdout already adjudicates the flag from the raw record
bytes, which is where GNU puts it (builtins/read.def: EOF only when
the record ends with no delimiter). Drop the caller-side recompute.

Regression: issue1623_read_u_coproc_read_status_matches_gnu.
… (rubash#1624)

retire_completed_coproc decided "is a coproc" by scanning the fd
endpoint table, but by reap time the read endpoint is routinely
already closed (EOF consumed it), so named coprocs kept their NAME,
NAME_PID and fd entries forever. GNU decides from the coproc
registry itself (execute_cmd.c coproc_reap -> coproc_unsetvars).
Use shell_state.coproc_names as the authority, keeping the endpoint
scan as a fallback.

Regression: issue1624_coproc_vars_unset_after_eof_and_reap.
…nd returns (rubash#1638)

GNU forks the >(body) consumer at expansion time (subst.c
process_substitute), so an append consumer's output is on disk as
fast as the consumer runs. Rubash's deferred-carrier model left
append-form data undelivered at the next command
(`echo x >> >(cat >f)` could still have no file). The tree's
standing specs pin opposite edges: the truncate form must never
block the next command (rubash#1220), while append-form consumers
are expected drained when the owning command returns
(executor_command_chaining part_080). Mark the append forms
(>>, &>>, 2>>, and the shared pairs involving them) with
drain_synchronously and wait for the consumer at finish; its status
still lands in completed_statuses, so `wait $!` observes it exactly
as for the detached form. wait_for_background_pid and its outcome
type become crate-visible for this.

Regression: issue1638_append_procsub_redirect_drains_before_next_command;
the part_080 append pair in executor_tests turns green, and the
rubash#1220 async pin still passes.
…rubash#1632, #1644, #1655, #1651)

execute_coproc_command wired the child's stdio from the coproc
pipes and then let apply_coproc_redirects handle only file/close
targets: fd-dup redirects were silently skipped and a redirected
stdout left the read end facing a writer-less pipe (instant EOF,
data lost). GNU's order is pipes first, the command's own
redirections applied on top in the child (execute_cmd.c
execute_coproc; redir.c). Rework the spawn to that order:

- prepare duplicate handles of the child's pipe ends up front;
- apply_coproc_redirects' dup arms now dup2 the prepared handles
  (`>&2` sends the child's stdout to the shell's stderr — rubash
  #1644; `2>&1` joins stderr into the read pipe — the issue text's
  "already agrees" note was wrong for the pipe-capture shape) and
  report displacement;
- a displaced stdout keeps a retained writer duplicate in the
  parent (new Executor map, released at close_coproc_endpoints), so
  the read end sees EOF at reap instead of at spawn (rubash#1632);
  the named-group form of the >&2 loss is rubash#1655, same
  mechanism;
- the stderr forwarder thread runs only when stderr was not
  displaced.

The same spawn rewiring also gives the child its fd-0
heredoc/herestring instead of the coproc stdin pipe (rubash#1651):
the coproc path never passes preexpand_command_stdin, so wire the
winning fd-0 body through a temp carrier — expanding the raw
here-string word with the simple-command walker and restoring the
heredoc body's final line terminator, which the stored form drops.
The #1644/#1655/#1651 regression pins land in their own commits.

Regression: issue1632_coproc_redirected_stdout_read_end_blocks_until_exit.
The fix rides the execute_coproc_command rewiring in the rubash
#1632 commit: >&2 (either spelling) now dup2s the shell's stderr
into the child instead of being skipped (output used to be
misdelivered into the coproc read pipe), and 2>&1 dup2s the pipe
writer so stderr joins the read end. These three tests pin both
directions against GNU.
… (rubash#1655)

Follow-up to rubash#1644: the named brace-group form lost its
output entirely with a trailing >&2. Same root point (dup redirects
skipped by apply_coproc_redirects), same fix in the rubash#1632
commit; this pins the group form against GNU, including that the
read end blocks (142) rather than reporting EOF while the child
still runs.
The wiring rides the execute_coproc_command rewiring in the
rubash#1632 commit. Root cause in three parts: the coproc dispatch
ignored fd0_stdin_redirect_winner entirely (the child blocked on
the coproc stdin pipe); the here-string word reached the fallback
unexpanded, delivering its quote characters as data; and the stored
heredoc body drops the final line's terminator, so the child's last
record arrived unterminated and the parent's read reported EOF
(rc 1) on a full line. The pins assert content, read status 0, and
that the child consumed its stdin and exited, all per GNU.
…nctions (rubash#1625)

`{ coproc FC2 { cat; }; echo ok; }` was a syntax error: the brace
fold (run_skip_brace) stopped the OUTER group at the coproc body's
`}`. After the word `coproc`, completing the NAME word resets
prev_accepts_close (a plain word is not close-acceptable), so the
body's `{` never counted as a standalone opener — while its `}`
still counted as a closer. GNU's grammar takes the body as a
shell_command at command position (parse.y coproc productions:
COPROC WORD shell_command), independent of
reserved_word_acceptable. Mirror the existing function_chain: a
coproc_chain (0/1/2) on SkipBraceScan and its resume snapshot,
advanced as `coproc` then the NAME word complete, admitted by the
`{` arm alongside function_chain == 2. The two chains must not
reset each other at the whitespace-completion point — the NAME
word's completion is exactly where the function chain's else used
to zero the coproc chain before its advance could read it.

Regressions: the four issue1625_* tests (group, function body,
preceded-by-command, then-clause), each also exercising the coproc.
…bash#1645)

coproc_command_source_text always rendered the name (or the
default COPROC) ahead of the body text, so `jobs` showed
"COPROC" as argv[0] for `coproc sleep 5 &`. GNU shows the name
only where one was written or implied by the form: an unnamed
simple coproc displays just its command words, while group forms
display COPROC (or the given name). Insert the name only when the
coproc has a body.

Regression: issue1645_jobs_omits_implicit_name_for_simple_coproc.
…position (rubash#1652)

`coproc ! echo hi` silently dropped the negation and ran the
coproc; GNU exits 2 (syntax error near unexpected token `!') —
the coproc productions (parse.y: COPROC simple_command / COPROC
WORD shell_command) have no slot for the pipeline-level BANG.
Measured GNU position model: `!` errors as the operand, directly
after a name candidate (`coproc NC ! ...`), and directly after
the command name (`coproc echo ! hi`, also trailing); it is an
ordinary word once an assignment prefix or a second word
intervenes (`coproc x=1 ! echo hi`, `coproc echo a ! hi` are
legal). Return the parse-error marker node at the operand check
and at the one-collected-non-assignment-word point of the word
collection loop.

The collection loop also carries the rubash#1653 raw pin for a
leading `time` keyword (the two edits share one diff hunk and
cannot be staged apart); the pin is inert until the #1653 commit
removes the time arm that routes around this loop.

Regressions: issue1652_coproc_bang_prefix_is_a_syntax_error,
issue1652_named_coproc_bang_is_a_syntax_error.
… (rubash#1653)

parse_coproc_compound_body had a `time` arm that routed
`coproc time CMD | CAT` into the time-prefixed productions,
swallowing the pipeline into the coproc body so COPROC_PID bound
in the parent. After `coproc`, GNU's grammar admits only a
shell_command or simple_command — `time` there is the first word
of the simple command (parse.y coproc productions; `time` is a
prefix only at pipeline level), so the pipeline binds the coproc
in its stage subshell and the parent never sees COPROC_PID. Drop
the arm (the collected word's raw pin to the quoted form
'\''time'\'', which keeps the respawned child's re-parse from
regaining keyword status for it, landed with the rubash#1652
commit — the two edits share one diff hunk).

Regressions: issue1653_coproc_time_word_binds_in_pipeline_stage_only,
issue1653_coproc_time_word_is_a_simple_command.
…(rubash#1659)

`mapfile arr <&${COPROC[0]}` returned instantly with zero lines:
mapfile_input_for_command's fd-0 branch went through the generic
stdin snapshot, whose virtual-fd machinery only serves
materialized bytes, while the same fd read fine through read/cat
(fd_table.read_all_text drains a CoprocStdout endpoint). When the
winning fd-0 redirect is a DuplicateInput whose source endpoint
is a coproc read end, drain that endpoint directly — blocking
until EOF like GNU, so a late producer's lines are collected too.

Regressions: issue1659_mapfile_reads_coproc_fd_via_redirect,
issue1659_mapfile_blocks_for_late_coproc_producer.
…at exit

Follow-up to the #1632 fix found by comparison with the
collaborator's single PR #1695: retaining the displaced-stdout
writer duplicate in the PARENT deferred EOF to reap time, and a
blocking reader makes the reap unreachable — `coproc { echo hi; }
>file; cat <&${COPROC[0]}` hung forever (timeout 124) where GNU
returns instantly. GNU's coproc child itself holds a writer on the
read pipe for its whole life (execute_cmd.c coproc pipe setup:
the oracle's fd dump shows the write end at the child's fd 10), so
EOF tracks the child's exit.

On Unix the duplicate is now pinned into the child at fd 10 via
pre_exec dup2 (pin_coproc_writer_in_child; the dev_fd operand pin
is the in-tree precedent). The parent map remains only for
platforms without pre_exec, where EOF still tracks the reap.

Verified against GNU bash 5.3.20: plain displaced shape drains
with instant EOF and the data lands in the file; `2>&1 >file`
drains stderr-then-EOF; the #1632 seed shape still times out a
`read -t` (142) while the child lives. Regression tests: the two
new issue1632_* cli tests (an untimed drain is the pin — on the
parent-retention code they hang).

Refs: rubash#1632
Co-authored-by: 曹梦轩 <[email protected]>
Follow-up to the #1651 fix, found by comparison with the
collaborator's single PR #1694: when fd 0 carried both a file
redirect and a here-string, the winner was decided correctly
(fd0_stdin_redirect_winner) but the body file was bound to the
child BEFORE apply_coproc_redirects ran, so the pass's fd-0 file
arm clobbered it — `coproc cat < file <<< "FROMHS"` read the
file. GNU applies redirections left to right (redir.c
do_redirections), so the later redirect supplies the bytes.

The body file is now bound after the redirect pass; the pipe
read end is still dropped up front when the body wins.
Regression: issue1651_coproc_mixed_fd0_redirects_last_one_wins
pins both orders against the oracle.

Refs: rubash#1651
Co-authored-by: 曹梦轩 <[email protected]>
…d `!`

Follow-up to the #1652 fix, found by comparison with the
collaborator's single PR #1693: when a compound body followed,
the name-consumption branch stole the operand-position `!` as
the coproc NAME, so the bang check never fired and the line
failed later with ``!': not a valid identifier` (exit 1). GNU
reports the syntax error (exit 2): parse.y has no production
that puts BANG at a coproc's operand position. `!` is now
excluded from name consumption (a quoted "!" is a word token
and unaffected).

Regression: issue1652_coproc_bang_before_brace_body_is_a_syntax_error;
the parser-level pin rides the #1653 follow-up commit, whose
test rewrite covers the one-word bang rule.

Refs: rubash#1652
Co-authored-by: 曹梦轩 <[email protected]>
…prefix

Follow-up to the #1653 fix, found by comparison with the
collaborator's single PR #1698: is_coproc_shell_command_start
still admitted two time-prefix predicates, so in
`coproc time { ...; }` the `time` was not seen as the WORD of
the `COPROC WORD shell_command` production (parse.y:1125-1173)
— the coproc bound anonymously instead of as `time`, and
`coproc time for ...` failed with a syntax error. Both
predicates are gone (with the now-unused parse_loop imports),
so the name logic sees `time` like any other word in front of a
compound body.

Also rewrites the five stale tests in parser_coproc_tests.rs
that pinned the old timed-coproc model. Their replacements pin
the oracle's actual shapes (verified against GNU bash 5.3.20):
`coproc MYC time echo hi` is the UNNAMED coproc whose simple
command starts with the word MYC; the `for` line errors at
`do`; and the #1652 one-word bang rule (with the legal two-word
form). New cli pins: time-as-name for brace and for bodies, and
the combination residual `coproc time ! echo hi` — one collected
word (`time`), so the `!` errors per #1652; neither side's
original fix covered it alone.

Refs: rubash#1653, rubash#1652
Co-authored-by: 曹梦轩 <[email protected]>
@caomengxuan666

Copy link
Copy Markdown
Member Author

集成树验证回填(构建经 build-slot、纯化环境):

  • cli_tests issue16 定向:27 passed / 1 failed 🔴
  • parser_coproc_tests:31/31 ✅;lib 全量(--skip login_posix_env):771/1/1,唯一失败 ownership_unary_operators_check_existing_file(同集)✅;diffcorpus 306:305 PASS、失败集 {ms10} ✅;CR 0、fmt 零新增漂移 ✅

红点:issue1651_coproc_mixed_fd0_redirects_last_one_wins 时序脆弱——file_last 方向读到 FROMHS(GNU 期望 FROMFILE)。隔离采样:集成树 1 过/5 挂,簇树自身二进制 0 过/5 挂,即与本次集成无关,是 follow-up 602f3d3 绑定机制与重定向 pass 接线的竞速,簇终验窗口下恰全过、当前时序下几乎恒输。

按红门纪律本 PR 暂不合并,12 条 issue 与 6 个协作者单条 PR 均保持原状,待主会话裁定(修竞速后复跑,或摘出 #1651 一例先行其余 11 条)。详见集成报告 SLICE-COPROC-LIFE-REPORT.md。

@caomengxuan666

Copy link
Copy Markdown
Member Author

关闭为 superseded——逐条对账证据见裁定报告(~/workspace/coproc-adjudication/REPORT.md §二/§五),结论如下:

分支保留不删。本 PR 的多日冻结源于外部先行规矩的裁定流程,裁定与执行记录在案。

SpookyWaste pushed a commit to SpookyWaste/rubash that referenced this pull request Oct 29, 2026
…44, unixwin#1655)

Transplant of PR unixwin#1695 (a-rookie-of-C-language, commit 1bcffe8,
2026-10-26 05:06 +0800) onto current master, per the coproc-line
adjudication: unixwin#1695's ordered state machine is the widest of the
two competing fixes (unixwin#1712's own body concedes this), passes 7/7
on its own base, and discriminates cleanly on master (all five
dup-semantics pins red, both control pins green).

GNU redir.c do_redirections runs in the forked coproc child after
the coproc pipes are dup'd, so a trailing '>&2' rebinds the child's
stdout to the shell's stderr. Rubash's spawn path only handled the
single-field file redirects and dropped every dup: a simple
command's output landed in the coproc pipe instead of the shell's
stderr (unixwin#1644), and a named group's output sat in the pipe unread
— lost entirely (unixwin#1655).

The fix applies the coproc command's output redirects to the child
in list order (GNU's left-to-right semantics, so '>file 2>&1' and
'2>&1 >file' differ as they should), replacing the field blocks —
which additionally misread '>file 2>&1' (the '2>&1' arrived as a
bogus Append field). A cloneable spec per fd makes dups copy the
current binding: '>&2' dups the shell's current fd-2 endpoint (the
unixwin#1882 direct plan's resolved endpoint, or the stderr forwarder's
target), '>&word'/'1>&word' is r_err_and_out (one open for both
fds, redir.c:832-838), '2>&word' is an ambiguous redirect
(diagnostic once, no coproc created, status 1 per the unixwin#846
coproc-failure convention), and move forms ('>&2-') close the
source in the child after the dup (self-moves excepted,
rubash#1236).

Transplant deltas vs 1bcffe8 (master moved under the PR):
- apply_coproc_redirects keeps master's rubash#1651 stdin-body /
  redirect_in head verbatim and gains the caller's stderr_forward
  target; the return becomes CoprocRedirectOutcome — Proceed
  carries the rubash#1632 displaced pipe writer, Declined is the
  ambiguous arm — so the unixwin#1632 save-slot hand-back and the unixwin#1882
  stderr plan keep their exact semantics: replacing the fd-1 spec
  hands the pipe writer back instead of dropping it, and the fd-2
  dup seed resolves from the same fd-2 endpoint the plan used.
- The append arm keeps master's session_path conversion.
- A self-dup ('1>&1', including the move spelling) is skipped as
  the no-op GNU makes it, instead of round-tripping through a
  spec clone, so the pipe writer is never displaced by a redirect
  that changes nothing.

Known limitation kept from unixwin#1695: a dup whose source is fd >= 3
is left unchanged (the spawn model inherits no extra fds).

Regression tests: tests/issue1644_1655_coproc_dup_stderr_regressions.rs
— PR unixwin#1695's seven pins taken verbatim, plus the '1>&2'
explicit-spelling pin absorbed from PR unixwin#1712 (commit 331c743).

Implementation by a-rookie-of-C-language (PR unixwin#1695), transplanted
onto current master.

Co-authored-by: a-rookie-of-C-language <[email protected]>
caomengxuan666 added a commit that referenced this pull request Oct 29, 2026
…ection (rubash#1983)

GNU's lexer returns an assignment-shaped first word as
ASSIGNMENT_WORD, and parse.y:5899 reserved_word_acceptable has no
ASSIGNMENT_WORD in its accept set, so a `!` after `coproc X=1`
never becomes BANG — it lexes as a plain WORD and lands as the
child command's name (GNU bash 5.3.20: the child reports
`!: command not found`, script rc 0). The #1693 implementation of
the #1652 rejection fired for every one-word collection, so the
GNU-legal spaced shape `coproc X=1 ! echo hi` was rejected rc 2.

Exempt assignment-shaped first words (name / name[subscript],
optional `+`, then `=`), judged on the raw spelling — a quoted
name is not an assignment word in GNU either. Non-name shapes
(`9a=1`, `a-b=1`) stay WORDs and keep the rc-2 rejection. The
word_metadata Vec gets an explicit element type: the exemption
reads [0].raw before the first push, which leaves the element
type ambiguous to inference (E0282). Judgment shape first
measured in the #1712 line's 537e177.

Regression pins: tests/issue1983_coproc_assignment_bang_regressions.rs
(X=1 / a+=1 / _a9= spaced forms, a[1]=x subscript form, 9a=1 /
a-b=1 negative controls, glued X=1! control). The pins assert the
parse-admission face only; the coproc wait status after the
output fd drains is a separate, pre-existing reap-face race
(GNU deterministically reports 0 there) and is deliberately not
pinned here.
@caomengxuan666
caomengxuan666 deleted the fix7/slice-coproc-life branch October 30, 2026 01:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment