Skip to content

fix(executor): restore fd N after group redirect (Refs #3706) - #3723

Merged
caomengxuan666 merged 3 commits into
masterfrom
fix/3706-group-redirect-fd-restore
Nov 16, 2026
Merged

caomengxuan666 merged 3 commits into
masterfrom
fix/3706-group-redirect-fd-restore

Conversation

@caomengxuan666

@caomengxuan666 caomengxuan666 commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

fix(executor): restore fd N after group redirect (Refs #3706)

Root cause

After { ...; } N<redir, fd N was not restored to its pre-group target — it landed on fd 0's target (for N</dev/null) or fd 1's target (for N<&-), for fds 3/8/9, both redirect forms, in the current shell. The next read <&N then failed read: 0: read error: Bad file descriptor (isolation: #2902 round-3 REPORT §4).

The defect is in the group-redirect save/restore: the scope save only cloned the userspace FdEntry (entries.get(&fd).cloned()). The bind then called the retiring table methods (open_input/open_output/close_input → retire_read_arm/retire_write_arm, rubash#3213), whose retire_file closes the kernel descriptor when no other table entry shares the Rc — and the scope's saved clone is not in the table, so it does not count. The restore re-inserted a retired FileFd, and the next external spawn's pin pass (ambient_fd_pins_with_redirects) dup2'd whatever kernel descriptor had recycled that number onto fd N. Confirmed by strace: the ls child's pre-exec did fcntl(4, F_DUPFD_CLOEXEC, 9) = 10; dup2(10, 8) — fd 8 came from kernel fd 10, the #2615 save-slot range, holding the recycled /home/hatch directory handle.

Fix (by mechanism — the undo save IS a kernel dup)

GNU's undoable redirect saves the displaced descriptor before the redirect binds, with fcntl (fd, F_DUPFD, SHELL_FD_BASE) (redir.c:965 for input, :1082 for duplicating, :1144 for move; SHELL_FD_BASE is 10, redir.c:86), recorded by add_undo_redirect so undo_redirections can dup it back. Compound groups run do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) (execute_cmd.c:854).

This makes the scope save the same kernel dup:

  • FileFd::duplicate() (src/executor/fd_table.rs) — duplicates the kernel handle into a fresh FileFd on the same open file description (shared offset), with the table's close-on-exec discipline (unix F_DUPFD_CLOEXEC, like crate::fd::dup_adopted_fd; Windows duplicate_handle is already non-inheritable).
  • FdEntry::dup_file_endpoints() — the undo-save form of an entry: every File-backed endpoint (File, CoprocStdout/CoprocStdin) is duplicated; text/directory/marker/channel endpoints clone exactly. A <> pair's two arms share one Rc (open_readwrite_pair); the save preserves that sharing (the write arm reuses the read arm's duplicate) so closing one direction still retires the shared descriptor, as GNU's close(2) closes the whole descriptor.
  • FdTable::saved_entry(fd) — the snapshot helper used by every save site.

Applied at every group-redirect save site: the numbered-input save (save_compound_numbered_input_fd), the numbered-output save (save_compound_output_fd), the dynamic-close snapshots (save_dynamic_close_snapshot), the fd-0 guard (bind_command_fd0_input, 6 branches), the numbered-heredoc bind (bind_numbered_heredoc_redirects), and both materialized undo-save passes (the scoped walk and the output pass). The save functions are now fallible: a dup failure fails the redirect (ExecuteError::IoError, GNU REDIRECTION_ERROR on a failed F_DUPFD save) and unwinds the partial walk like an apply failure (GNU undo_partial_redirects, execute_cmd.c:855); the heredoc bind unwinds its own already-bound entries.

No descriptor-count change per scope: the save's dup replaces the handle the bind retires (one in, one out); a dropped saved entry closes its dup via Drop.

Regression pin

tests/issue3706_group_redirect_fd_restore.rs — 12 cells, the REPORT §4 repros byte-shaped: §4.2 single group (fd 8, two sequential reads), §4.1 LOOP form (3 iterations), fd 3, fd 9 (+ fd 8 untouched), the N<&- close form, the N<file bind form, nested groups, fd 0, the external-child /proc/self/fd/8 face (Linux-only), the <> pair's write arm, the <>-close sharing guard, and the plain-group control. All except the control and the sharing guard are fail-first on the unfixed base.

本 PR 删除了什么

No product code, no files, no tests, no public API are deleted. Net diff is +467/−39 (5 files): the three new helpers in fd_table.rs, the fallible save signatures + saved_entry call sites in command_input_scope.rs, the fallible heredoc bind in compound_exec.rs, and the one-line ? at its execute_direct_shell_script call site in external_finish.rs. No behavior changes outside group-redirect save/restore (the retire machinery itself is untouched).

UNVERIFIED-BY-CAPTAIN

No build slot was available when this lane ran (Simular box hibernated with an empty wallet, X299 unreachable via the box, local builds forbidden by the write wall / sub-1.5G memory gate), so nothing in this PR has been compiled or run yet — the pin's fail-first run on the base, its green run on this head, the neighbor fd/redirect/group stems, the full lib head-vs-base counts, RUSTFLAGS="-D warnings" cargo check, and the hygiene scripts are all owed legs, listed in the lane REPORT. cargo fmt --check is clean on all five touched files. Do not merge until the legs land.

Base: master e81a1af1 (tip at lane start). The tip moved during the lane: 04495715 (user-merged #3708, BASH_ARGV0 materialization: set.rs, declare_local.rs, dynamic_arrays.rs, unset_arrays.rs — zero file intersection with this PR), then to 05870284 by PR open (10 user merges, all niubash#993 faces + #3708/#3709); the interval touches exactly one of this PR's files, src/executor/compound_exec.rs, one hunk at @@ -5288 (#3709, coproc NAME) ~390 lines from this PR's hunks, different function — update-branch at merge time is trivial.

Group-redirect save/restore replayed a dead entry: the scope save
only cloned the userspace FdEntry, so the bind-time retire
(retire_read_arm/retire_write_arm, rubash#3213) closed the very
descriptor the restore was about to replay, and the next spawn's
pin pass dup2'd whatever kernel descriptor had recycled that
number (fd N landed on fd 0's target for N</dev/null, fd 1's
target for N<&-).

GNU's undoable redirect saves the displaced descriptor BEFORE
the redirect binds, with fcntl (fd, F_DUPFD, SHELL_FD_BASE)
(redir.c:965/1082/1144; SHELL_FD_BASE is 10, redir.c:86),
recorded by add_undo_redirect for undo_redirections (compound
groups: execute_cmd.c:854 RX_ACTIVE|RX_UNDOABLE). This makes
the scope save the same kernel dup: FdTable::saved_entry
duplicates every File-backed endpoint (FileFd::duplicate,
F_DUPFD_CLOEXEC on unix, non-inheritable duplicate on
Windows), applied at every group-redirect save site — the
numbered input/output saves, the dynamic-close snapshots, the
fd-0 guard, the numbered-heredoc bind, and both materialized
undo-save passes. A <> pair's two arms share one Rc; the save
preserves that sharing so closing one direction still retires
the shared descriptor, as GNU's close(2) closes the whole
descriptor. A dup failure fails the redirect (GNU
REDIRECTION_ERROR), unwinding the partial walk like an apply
failure.

Regression pin: tests/issue3706_group_redirect_fd_restore.rs
(12 cells: REPORT §4.2 single group, §4.1 LOOP, fd 3/9,
close form, N<file form, nested, fd 0, external-child /proc
face, <> write arm + close-sharing guard, plain-group control).

UNVERIFIED-BY-CAPTAIN: no build slot was available (Simular
box hibernated, X299 unreachable, local builds forbidden), so
the pin's fail-first run and the verification legs are owed;
see the PR body.
@caomengxuan666

Copy link
Copy Markdown
Member Author

队长复核:FAIL——编译未过,机制与钉本轮未判。

CI run 43742845650 全部 8 个 job 皆在构建步失败,同一根因,两处 error[E0308](mismatched types):

  • src/executor/command_input_scope.rs:510——return Err(error);,error 为 std::io::Error,函数返回 Result<_, ExecuteError>;
  • src/executor/compound_exec.rs:4889——同形。

显式 return Err(error) 不走 From<std::io::Error> 转换(? 才会),须包成 ExecuteError::IoError(error)(rustc 的 help 建议即此)。canary run 43742845785 只红 ledger 漂移(MISSING Session::cwd,待 #3704/niu #1021 合入),与本 PR 无关;API ledger tripwire 已过。

请在同一分支修后重推,勿另开 PR;编译通过后腿(钉 fail-first + 全绿、邻居、lib 双边、-D warnings、卫生脚本)由复核方跑。REPORT §7 的欠账表依然有效。

…efs #3706)

CI run 43742845650 failed all 8 jobs at build: error[E0308] at
command_input_scope.rs:510 and compound_exec.rs:4889 — an explicit
return Err(error) does not use the From<std::io::Error> conversion
(only ? does), and the functions return Result<_, ExecuteError>.
Wrap the std::io::Error in ExecuteError::IoError, as rustc suggests
and as the surrounding code already does.

UNVERIFIED-BY-CAPTAIN
@caomengxuan666

Copy link
Copy Markdown
Member Author

队长跟进:返工已核。两处 E0308 已修(新头 4bca3a31,仅两行包 IoError),CI run 43744826604 已按名——编译通过(5 job 绿:CLI、交叉×2、功能、Windows 编译),3 个红 job 皆只红已知基线格 issue2875_input_procsub_child_runs_as_rubash_shell,无新 E0308;canary run 43744826349 只红 ledger 漂移(MISSING Session::cwd,待 #3704/niu #1021),tripwire 过。编译 FAIL 已解除;机制与钉的腿(钉 fail-first + 全绿、邻居、lib 双边、-D warnings、卫生脚本)按 REPORT §7 由复核方跑,合入前仍需 update-branch + 重核守卫表。

caomengxuan666 added a commit that referenced this pull request Nov 15, 2026
…3727)

Root cause: function_call_stdin saved the displaced fd-0 entry with a
bare Rc clone at seven sites (function_calls.rs :1599 text/heredoc,
:1663 fd-alias dup, :1703 /dev/tcp, :1764 <> device, :1778 < device,
:1811 <> file, :1825 < file). The bind that follows retires the
displaced descriptor (retire_read_arm / retire_write_arm, #3213), so
the restore (restore_function_call_fd0 via FunctionCallStdinBinding)
re-inserted a retired entry and the next read off fd 0 failed EBADF.
Same hazard as #3706 (group redirects), on the function-call stdin
face.

Fix: snapshot fd 0 with FdTable::saved_entry (kernel dup,
FdEntry::dup_file_endpoints) at all seven sites, never a bare clone.
GNU: a function's redirections are undoable (execute_cmd.c:854
do_redirections RX_ACTIVE|RX_UNDOABLE, applied by execute_function)
and the undo save IS a kernel duplicate (fcntl (fd, F_DUPFD,
SHELL_FD_BASE), redir.c:965/1082/1144, SHELL_FD_BASE 10 at redir.c:86).
A dup failure fails the call as ExecuteError::IoError, as GNU fails
the whole redirect (redir.c REDIRECTION_ERROR on a failed F_DUPFD
save).

Note: FdTable::saved_entry / FdEntry::dup_file_endpoints /
FileFd::duplicate are ported verbatim from draft PR #3723 (the #3706
fix, unmerged at this base); the added lines are byte-identical, so
whichever PR lands first, the other rebases to a no-op on fd_table.rs.

Tests: tests/issue3727_function_call_stdin_fd_restore.rs, 12 cells
(one per bind face, plus loop / nested / no-redirect control), each
fail-first on the unfixed base.

UNVERIFIED-BY-CAPTAIN: all build/test legs OWED — no cargo build route
is live this round (see REPORT ~/workspace/fix-3727/REPORT.md).
caomengxuan666 added a commit that referenced this pull request Nov 15, 2026
…etires them (Refs #3732)

The in-process output-procsub consumer runs under the compound's
prefix redirects as its spawn plan (with_procsub_spawn_plan,
rubash#3491). The plan bind saved the displaced entry with a bare Rc
clone and then retired the displaced descriptor on every arm —
FdTable::close (Closed), set_fd_input_file (File read /
CarrierRead), open_output (File write / TruncatedFile /
CarrierWrite / CaptureWrite / StreamWrite) — so the restore
re-inserted a retired entry and the next read/write (or the next
spawn's pin pass) hit a dead descriptor.

GNU's undo save IS a kernel dup (fcntl (fd, F_DUPFD, SHELL_FD_BASE),
redir.c:965/1082/1144; SHELL_FD_BASE is 10, redir.c:86; compound
groups run do_redirections (..., RX_ACTIVE|RX_UNDOABLE),
execute_cmd.c:854). This makes the plan-bind save the same kernel
dup: FdTable::saved_entry duplicates every File-backed endpoint
(FileFd::duplicate, F_DUPFD_CLOEXEC on unix, non-inheritable
duplicate on Windows), applied at the single save point that covers
all bind arms. A <> pair's two arms share one Rc; the save preserves
that sharing so closing one direction still retires the shared
descriptor, as GNU's close(2) closes the whole descriptor. A dup
failure fails the consumer run (GNU REDIRECTION_ERROR) before it
starts, unwinding the bindings already made; with_procsub_spawn_plan
now returns Result<T, ExecuteError> and its single caller surfaces
the bind error exactly like the consumer's own error.

Note: the three fd_table.rs helpers are the same code as PR #3723
(Refs #3706), which is still an open draft on the same base — #3723
adds them for the group-redirect save sites, this PR for the
spawn-plan save site. Whichever merges second drops its copy of
the helper hunk; the product hunks do not overlap (#3723 touches
command_input_scope.rs / compound_exec.rs / external_finish.rs,
this PR touches external_setup.rs / pipeline_exec.rs).

Regression pin: tests/issue3732_procsub_spawn_plan_fd_restore.rs
(11 cells: File-read fd 8/3, Closed, TruncatedFile, append-File,
ReadWrite <>, CarrierRead, CarrierWrite, no-displacement control,
external-child /proc face, <>-close sharing guard).

UNVERIFIED-BY-CAPTAIN: no build slot was available (Simular box
hibernated, X299 unreachable, old server unreachable, local builds
forbidden), so the pin's fail-first run and the verification legs
are owed; see the PR body.

本 PR 删除了什么:未删除任何内容(纯增量修复;仅将
with_procsub_spawn_plan 的返回由 T 改为 Result<T, ExecuteError>,
唯一调用点同步适配;无删除的功能、文件或公开面)。
caomengxuan666 added a commit that referenced this pull request Nov 16, 2026
…3727) (#3739)

Root cause: function_call_stdin saved the displaced fd-0 entry with a
bare Rc clone at seven sites (function_calls.rs :1599 text/heredoc,
:1663 fd-alias dup, :1703 /dev/tcp, :1764 <> device, :1778 < device,
:1811 <> file, :1825 < file). The bind that follows retires the
displaced descriptor (retire_read_arm / retire_write_arm, #3213), so
the restore (restore_function_call_fd0 via FunctionCallStdinBinding)
re-inserted a retired entry and the next read off fd 0 failed EBADF.
Same hazard as #3706 (group redirects), on the function-call stdin
face.

Fix: snapshot fd 0 with FdTable::saved_entry (kernel dup,
FdEntry::dup_file_endpoints) at all seven sites, never a bare clone.
GNU: a function's redirections are undoable (execute_cmd.c:854
do_redirections RX_ACTIVE|RX_UNDOABLE, applied by execute_function)
and the undo save IS a kernel duplicate (fcntl (fd, F_DUPFD,
SHELL_FD_BASE), redir.c:965/1082/1144, SHELL_FD_BASE 10 at redir.c:86).
A dup failure fails the call as ExecuteError::IoError, as GNU fails
the whole redirect (redir.c REDIRECTION_ERROR on a failed F_DUPFD
save).

Note: FdTable::saved_entry / FdEntry::dup_file_endpoints /
FileFd::duplicate are ported verbatim from draft PR #3723 (the #3706
fix, unmerged at this base); the added lines are byte-identical, so
whichever PR lands first, the other rebases to a no-op on fd_table.rs.

Tests: tests/issue3727_function_call_stdin_fd_restore.rs, 12 cells
(one per bind face, plus loop / nested / no-redirect control), each
fail-first on the unfixed base.

UNVERIFIED-BY-CAPTAIN: all build/test legs OWED — no cargo build route
is live this round (see REPORT ~/workspace/fix-3727/REPORT.md).

Co-authored-by: 曹梦轩 <[email protected]>
caomengxuan666 added a commit that referenced this pull request Nov 16, 2026
…binds it (Refs #3728) (#3738)

* fix(executor): snapshot displaced fd 0 with a kernel dup before read binds it (Refs #3728)

`read` from /dev/tcp restored a retired fd 0 entry — the same hazard
#3706 isolated for group redirects. The transient fd-0 binds saved
only an Rc clone of the userspace entry, the bind retired the
displaced descriptor (retire_read_arm/retire_write_arm, rubash#3213),
and the restore re-inserted the retired entry, so the next read from
the restored fd failed (EBADF) or read whatever recycled the number.

GNU's undo save IS a kernel duplicate of the displaced descriptor
(`fcntl (fd, F_DUPFD, SHELL_FD_BASE)`, redir.c:965/1082/1144;
compound groups run `do_redirections (..., RX_ACTIVE|RX_UNDOABLE)`,
execute_cmd.c:854). This makes every transient fd-0 save the same
kernel dup: `FdTable::saved_entry` duplicates every File-backed
endpoint (`FdEntry::dup_file_endpoints`, `FileFd::duplicate`,
F_DUPFD_CLOEXEC on unix, non-inheritable duplicate on Windows),
applied at all three read_io.rs sites (the /dev/tcp arm, the
Windows-only winuxcmd-fifo arm, the non-regular/device arm) — and at
the simple-command funnel's `bind_net_input_fd`, which is the live
path for a plain `read x < /dev/tcp/...`: every in-process builtin
dispatch binds its net inputs there before the body runs, and the
read builtin then serves the already-bound endpoint. A `<>` pair's
two arms share one Rc; the save preserves that sharing so closing
one direction still retires the shared descriptor, as GNU's close(2)
closes the whole descriptor. A dup failure fails the redirect (GNU
REDIRECTION_ERROR), unwinding the partial bind like a connect
failure in the funnel and failing the read in read_io.rs.

The three helpers are the same mechanism #3723 (PR, unmerged)
introduces for #3706, ported here so this PR is self-contained on
master; if #3723 lands first, its fd_table.rs hunks supersede these.

Regression pin: tests/issue3728_read_tcp_fd_restore.rs (4 cells:
plain /dev/tcp fd-0 restore, `exec 0<>file` sharing face, numbered
`read -u 3 ... 3</dev/tcp/...`, `read x < /dev/null` device arm).
Expected outputs verified byte-for-byte against GNU bash 5.3
(vendored build) with a loopback listener; the Windows-only fifo
arm has no Linux pin and is fixed by the identical mechanism.

本 PR 删除了什么:无。只改保存/恢复路径,不删任何行为、测试或公开面。

UNVERIFIED-BY-CAPTAIN: no build slot was available (Simular box
hibernated, X299 unreachable, local builds forbidden), so the pin's
fail-first run and the verification legs are owed; see the PR body.

* fix(tests): clone tag before the move closure in issue3728 pin (E0382)

The run_driver helper moved `tag` (String) into the spawned thread's
move closure and then borrowed it again in the recv_timeout panic,
so cargo check --tests failed with E0382 on the cross-target legs.
Keep a clone for the timeout message; no assertion or product change.

---------

Co-authored-by: 曹梦轩 <[email protected]>
@caomengxuan666

Copy link
Copy Markdown
Member Author

【WIN-AGENT-AUDIT-u3】PR #3723 第3轮 — 续作开工
head: 4bca3a3(gh 实时,与队长返工核验时一致)
状态:draft / CONFLICTING → 本轮做机械解冲突 + 全腿审计。

计划:

  1. merge origin/master(5d253cf6)进本分支。预检:冲突仅 src/executor/fd_table.rs 一处 doc-comment 叠加(master 经 fix(executor): dup-save function-call fd 0 before stdin binds (Refs #3727) #3739 已落地同名 saved_entry/dup_file_endpoints/FileFd::duplicate 帮助函数,本 PR 的 fd_table.rs 增量与 master 逐字节相同,合并后该文件对 master 零 diff——本 PR 的有效增量收敛为 command_input_scope/compound_exec/external_finish 的 saved_entry 调用点转换 + 12 枚钉)。
  2. 解冲突后跑全腿:钉自跑(issue3706_group_redirect_fd_restore)+ fail-first(merge-base e81a1af)+ lib 双边 + -D warnings + fmt/卫生 + CI 按名核查 + GNU 对照。
  3. 判词按第 6 节模板给出;不合入、不关单。

@caomengxuan666

Copy link
Copy Markdown
Member Author

【WIN-AGENT-AUDIT】PR #3723 第1轮 — 建议:PASS
head: 4075d34(= 本轮 merge commit;原 head 4bca3a3 + origin/master 5d253cf)base(merge-base): e81a1af 文件: 4 个 +360/-39
关联 issue: #3706(open,核于本地 2026-11-17)

机制核查:

  • bind_numbered_heredoc_redirects 改用 FdTable::saved_entry(dup 保存被顶替的描述符)+ 失败时 undo_partial_redirects 式回卷,对应 GNU execute_cmd.c:855 与 general.c dup 语义;fd_table.rs 的 +107 行设施与 master e1e3d7b(fix(executor): dup-save function-call fd 0 before stdin binds (Refs #3727) #3739,function-call fd0)同型,merge 后与 master 侧实现合流,无重复定义。
  • diff 无顺手改无关面;无桥接/翻译层。

腿:

  • 钉自跑:issue3706_group_redirect_fd_restore — Windows head 11/11 通过;Linux(WSL rustup 1.99.0 原生构建)head 12/12 通过(多 1 个 unix-only 格 external_child_sees_restored_fd8)。
  • fail-first:Linux merge-base e81a1af 上 4 passed / 8 failed,红名 = {close_form_restores_fd8, external_child_sees_restored_fd8, group_redirect_to_file_restores_fd8, loop_form_reads_three_iterations, nested_groups_restore_fd8, single_group_dev_null_restores_fd3, single_group_dev_null_restores_fd8, single_group_dev_null_restores_fd9_and_leaves_fd8},与修复面一致(Windows 上 base/head 双绿是仿真 fd table 的平台假象,Linux 才是判据)。
  • lib 双边(Windows cargo test --lib):head 失败名集 {api::consumer_tests::issue2084_session_end_restores_host_process_state} / base(5d253cf) 同集 / 差集 ∅(head 运行期另有 3 个 executor::path/glob 瞬时红,串行复跑全绿=负载抖动,非本 PR)。
  • -D warnings:cargo check --locked 四 worktree 全过,0 警告。
  • 卫生:rustfmt --edition 2021 --check 涉及 4 文件全 CLEAN;marker-lint OK(118 consts/268 sites);utf8 卫生脚本全仓 76 处历史违规,本 PR 文件 0 新增。
  • CI(head 4075d34):红 = GNU regression goldens and canaries(issue_753::case_9_declare_indexed_operand_binds_nothing + upstream_suite_slice_snapshots,与 master run 43910187524 同名同计数=基线)、Regression pin stem census(84 FAIL vs master 基线 89;差集仅 issue371_assoc_assignment_transform 5 格,本地串行复跑 9/9 绿=基线抖动簇;且本 PR 使 master 基线里的 issue2614_scope_restore_undo 7 格转绿,方向正确)。余皆 pass/pending。
  • GNU 对照:WSL GNU bash 5.3.20(1)-release (x86_64-pc-linux-gnu),脚本 target/u3-audit/probe-3706.sh + probe-3706-shared.sh(共享 open file description 变体)。T1-T10 + shared-desc 共 11 形状 head 输出与 GNU 逐字节一致(含 8<&- 后原 fd 仍可读、<> 对 close-input 双侧失效 Bad file descriptor rc=1)。

F 点:无。

续作记录:

  • 4075d34 Merge remote-tracking branch 'origin/master' into fix/3706-group-redirect-fd-restore(fd_table.rs 冲突保留 master open_input 文档+本 PR 实现);新 head: 4075d34

未跑/VOID 的腿:Windows 侧 fd 仿真无法复现 Linux fd 语义,fd 类结论均以 WSL Linux 原生构建为准;census 全量 1524 stem 未在本地重跑(CI 已覆盖)。

@caomengxuan666
caomengxuan666 marked this pull request as ready for review November 16, 2026 17:36
@caomengxuan666
caomengxuan666 merged commit b7e9e94 into master Nov 16, 2026
9 of 12 checks passed
caomengxuan666 added a commit that referenced this pull request Nov 16, 2026
execute_simple_loop saved the displaced fd with a bare Rc clone, then open_input retired the descriptor the clone shared, so the post-loop restore re-inserted a retired entry (the #3706 hazard, loop-heredoc face). Save via FdTable::saved_entry — a kernel dup of the displaced descriptor, the same undo-save #3723 introduced for group redirects — and unwind already-bound heredocs if the dup fails (GNU undo_partial_redirects, execute_cmd.c:855).

GNU: loop redirections are undoable (execute_cmd.c:854 do_redirections RX_ACTIVE|RX_UNDOABLE); the undo save is fcntl(fd, F_DUPFD, SHELL_FD_BASE) (redir.c:965/1082/1144). New pins: tests/issue3725_loop_heredoc_fd_restore.rs (6 cells). UNVERIFIED-BY-CAPTAIN: all cargo legs owed, routes down.

Co-authored-by: 曹梦轩 <[email protected]>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
caomengxuan666 added a commit that referenced this pull request Nov 16, 2026
… (Refs #3731)

Refs #3731.

## 根因

`execute_persistent_output_process_substitution`(src/executor/trap_exec.rs:7357,base f56716b;修后位于 7360)以裸 Rc clone 保存 fd 0:`let old_fd0 = self.fd_table.entries.get(&0).cloned();`。随后的 `set_fd_input_text(0, ...)` 经 `open_input` retire 被顶掉的 File 描述符(retire_read_arm / retire_write_arm,#3213;`#[cfg(unix)]`),restore 又把已 retire 的 entry 插回去——下一次从 fd 0 读便失败 EBADF。与 #3706(组重定向)、#3727(函数调用 stdin)同 hazard,落在 procsub 体解析面。唯一调用方是 `close_persistent_output_fd`(:7174);体在 fd 关闭时运行,不在命令结束时运行——钉须显式 `exec 3>&-` 触发,否则读在体前、空过。

## GNU 锚点

- redir.c:965/1082/1144:undo save 是 kernel dup(`fcntl (fd, F_DUPFD, SHELL_FD_BASE)`)。
- execute_cmd.c:854:`do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE)`。
- Oracle(本地 bash 5.3.20):primitive 驱动 `r1=0 l1=[o1] r2=0 l2=[o2] r3=0 l3=[o3]` rc=0;body-reads / cat / readwrite / loop 均与 GNU 一致。

## 修法

一行(+3 行注释),沿 #3723 同款:`let old_fd0 = self.fd_table.saved_entry(0)?;`(`FdEntry::dup_file_endpoints`,#3739 已带入 master;unix 下 `fcntl(handle, F_DUPFD_CLOEXEC, 0)`)。dup 失败时 `?` 返回 `ExecuteError::IoError`,体不运行、fd 0 不动;无裸 clone 回退。restore 保持直接 insert 不变(同 `restore_command_fd0_input` 的形态)。

## 本 PR 删除了什么

无删除:不删除任何行为或公开面,仅把 1 行裸 clone 保存换成 kernel-dup 快照,并新增回归钉文件 1 个(tests/issue3731_procsub_body_fd0_restore.rs,11 组)。不碰 `docs/api-ledger.md`、`src/lexer/continuation.rs`。

## 验证(实测)

钉:11 组(primitive、body-reads、cat、compound、twice、readwrite、loop、nested、devnull、control、implicit-doc)。compound 用 `>(echo a; echo b)`;`>({ ... })` 群组体是另一 parser 缺口(见下)。

- **Linux fail-first(新服务器,base f56716b + 钉 v3)**:pin 2 passed / 9 failed(PIN_RC=101)。9 红皆 EBADF:`driver.sh: line 7: read: 0: read error: Bad file descriptor`。lib 1260 passed / 0 failed / 4 ignored(LIB_RC=0)。日志 `~/leg-3731-linux-base.log`(服务器)。
- **Linux fixed(新服务器,fix + 钉 v4)**:pin 11/11(PIN_RC=0),lib 1260 passed / 0 failed / 4 ignored(LIB_RC=0),`RUSTFLAGS="-D warnings" cargo check` rc=0。日志 `~/leg-3731-linux-fixed.log`(服务器)。lib 双边与 base 完全一致。
- **X299 fixed(Windows,fix + 钉 v4)**:pin 11/11(PIN_RC=0),lib 1362 passed / 1 failed / 4 ignored——唯一红与 base 相同(`api::consumer_tests::issue2084_session_end_restores_host_process_state`,既存基线),`RUSTFLAGS="-D warnings" cargo check` rc=0。日志 `C:\Users\WWW\leg-3731-fixed-launch.log`。注:retire 是 `#[cfg(unix)]`,Windows 上钉在 base 即按构造通过,本腿仅作无回归验证。
- **X299 base 旧钉(已废弃)**:pin v1 8/2(触发空洞:读在体前)、v2 10/1(compound 一格为驱动语法错,非 hazard)——均已被 Linux fail-first 取代。
- **rustfmt**:`rustfmt --edition 2021 --check`,trap_exec.rs(61a80f15)rc=0,钉 v4 rc=0。

队长复核(2026-11-17 02:0x CST):CI run 43922615482:goldens 恰 2 基线格(issue_753::case_9_declare_indexed_operand_binds_nothing、upstream_suite_slice_snapshots),census 79 格、issue3731 钉全绿,macOS/darwin 全绿,其余 7 项作业全绿、1 项跳过;4 格 head-only(assoc_member_and_bare_at_a_forms_stay_one_word、assoc_star_at_a_quoted_prints_full_assignment_body、elf_operand_is_refused_not_run_as_script、issue3575_posix_cd_out_after_failure_restores_pwd)为 census 抖动——assoc/at 族已知同树翻动(86→93),issue3575 同现于 #3807 printf 头,fd0 保存修法不可达该面;另 15 格父集红格在头上翻绿(含组重定向 fd 恢复面);漂移 f56716b...fcc1de5 与本单两文件零交集 → 按零交集例外合入。

## 残差

- `>({ echo a; echo b; })` 群组体:GNU 合法(实测,rc=0),rubash 报 `ambiguous redirect`——独立 parser 缺口,不属本单,已记 REPORT §4,待队长立案。
caomengxuan666 added a commit that referenced this pull request Nov 16, 2026
#3729)

## Summary

Fixes the stdio-marker reinstate hazard in `close_persistent_output_fd` (rubash#3729): the face took a bare `Rc` clone of the fd's entry, then `open_output(fd, Stdout/Stderr marker)` retired the displaced descriptor (`retire_read_arm`, rubash#3213), and the restore re-inserted the retired entry — the same hazard as #3706. The snapshot is now a kernel duplicate via `FdTable::saved_entry` (the #3723/#3739 pattern), exactly like GNU's `fcntl (fd, F_DUPFD, SHELL_FD_BASE)` save (redir.c:965/1082/1144). A dup failure propagates (GNU fails the redirect the same way).

## 本 PR 删除了什么

无删除。仅将一行裸 clone 改为内核 dup 快照,并新增回归钉文件 `tests/issue3729_stdio_marker_fd_restore.rs`(7 格)。

## Reachability note (read before reviewing the pin)

The face needs a File-backed read arm AND the output-procsub registration to coexist on fd 1/2 at close/flush time. They cannot: every input bind calls `clear_output_fd_mirrors` (rubash#3655) and drops the registration, and every output bind retires any read arm. A full trigger battery against GNU bash 5.3.20 and the base binary (f56716b) confirms it — `exec 2> >(...)` + `exec 2<input.txt` + close/rebind/dup-to-closed/failed-rebind, group variants, and the `{var}`-close form all agree with GNU on the read result. So there is NO shell-level fail-first cell for the face itself: the 7 pin cells are GUARDS on the face's code path (stdio-marker reinstate + fd state after close/rebind), written so a future change that makes the face reachable cannot silently reintroduce the hazard. All 7 pass on the base and on the fixed head. Full battery + evidence in REPORT.md (workdir `~/workspace/fix-3729/REPORT.md`).

A separate real divergence in the same area — the deferred procsub body is dropped after an input rebind (GNU runs it at close, rubash does not) — is documented as a residual in the REPORT for the captain to file as its own issue; it is deliberately NOT pinned here (it fails on the fixed head too).

## Legs (队长复核)

- X299 base pin stem (`issue3729_stdio_marker_fd_restore`): **7 passed / 0 failed** (base build RC=0, 45.10s).
- X299 head pin stem: **7 passed / 0 failed** (head build RC=0, 14.02s).
- X299 lib bilateral: head **1362 passed / 1 failed** vs base **1362 passed / 1 failed** — sole fail on both sides is the known `api::consumer_tests::issue2084_session_end_restores_host_process_state` (no new red).
- `RUSTFLAGS="-D warnings" cargo check --locked --all-targets`: **RC=0**, zero diagnostics (39.83s).
- `rustfmt --edition 2021 --check` on the 2 changed files: **RC=0**.
- marker-lint: **OK** (118 registry consts, 268 allowlisted sites).
- CI(更新头 6fd24c2,run 43926778677,已 update-branch 到尖 52ffeba):goldens 恰 2 基线格(issue_753::case_9_declare_indexed_operand_binds_nothing、upstream_suite_slice_snapshots);census 78 格、issue3729 钉全绿;其余 8 项作业全绿、1 项跳过。3 格 head-only(elf_operand_is_refused_not_run_as_script、issue1902_stdout_stderr_names_follow_their_bindings、issue3575_posix_cd_out_after_failure_restores_pwd)皆为已备案 census 抖动格(issue1902 为 #3799 复核裁定的抖动格;elf/issue3575 同现于 #3801/#3807 头;修法面已证不可达,钉为 guard 钉)。旧头 census 重跑已证同头两次跑 4 格翻动。

队长复核(2026-11-17 02:2x CST):diff 已读——trap_exec.rs 1 行裸 clone 改 kernel-dup 快照 + 7 格 guard 钉;reachability §3.2 要点已亲核(clear_output_fd_mirrors 删双键、三处 set_fd_input_* 尾调用、open_output 替换双臂);X299 腿钉 7/7 双边、lib 双边同名同数、-D warnings rc=0、fmt 干净、marker-lint OK。
caomengxuan666 added a commit that referenced this pull request Nov 17, 2026
fd_table.rs helpers already landed via #3739; take master's version.
Picks up #3723's saved_entry conversion of the compound numbered-input
save, removing the stale-FileFd producer that turned this PR's
saved_entry dup into an EBADF command failure on Linux.
caomengxuan666 added a commit that referenced this pull request Nov 17, 2026
The [[ ]] stdio save only cloned the userspace FdEntry, so the
bind-time retire (retire_write_arm, rubash#3213) closed the very
descriptor the restore was about to replay, and the next write or
spawn's pin pass used whatever kernel descriptor had recycled that
number (fd 1 lands on the [[ ]] redirect's target file, or the
write is lost with EBADF).

GNU's undoable redirect saves the displaced descriptor BEFORE the
redirect binds, with fcntl (fd, F_DUPFD, SHELL_FD_BASE)
(redir.c:965/1082/1144; SHELL_FD_BASE is 10, redir.c:86),
recorded by add_undo_redirect for undo_redirections (the
conditional stamps its line only once its redirections have
bound, execute_cmd.c:4138 SET_LINE_NUMBER). This makes the scope
save the same kernel dup: FdTable::saved_entry duplicates every
File-backed endpoint (FileFd::duplicate, F_DUPFD_CLOEXEC on unix,
non-inheritable duplicate on Windows), applied at the [[ ]]
stdio save site — the same helper #3723 adds for the group
redirect face (rubash#3706), ported here because that PR is still
unmerged. A <> pair's two arms share one Rc; the save preserves
that sharing so closing one direction still retires the shared
descriptor, as GNU's close(2) closes the whole descriptor. A dup
failure fails the command (GNU REDIRECTION_ERROR) via ?.

The hazard needs fd 1/2 File-backed (at birth they are the
symbolic Stdout/Stderr markers, which no retire touches), so the
pin first runs exec 1>file / exec 2>file.

Regression pin: tests/issue3730_cond_stdio_fd_restore.rs
(10 cells: fd 1 output redirect, fd 2 stderr redirect, close
form, LOOP form, 2>&1 dup form, both-slots form, offset-sharing
guard, && list form, plain-conditional control, Linux-only
external-child /proc face).

UNVERIFIED-BY-CAPTAIN: no build slot was available (Simular
box hibernated, X299 unreachable, local builds forbidden), so
the pin's fail-first run and the verification legs are owed;
see the PR body.

Co-authored-by: 曹梦轩 <[email protected]>
caomengxuan666 added a commit that referenced this pull request Nov 17, 2026
…etires them (Refs #3732) (#3741)

* fix(executor): dup-save procsub spawn-plan fds before the plan bind retires them (Refs #3732)

The in-process output-procsub consumer runs under the compound's
prefix redirects as its spawn plan (with_procsub_spawn_plan,
rubash#3491). The plan bind saved the displaced entry with a bare Rc
clone and then retired the displaced descriptor on every arm —
FdTable::close (Closed), set_fd_input_file (File read /
CarrierRead), open_output (File write / TruncatedFile /
CarrierWrite / CaptureWrite / StreamWrite) — so the restore
re-inserted a retired entry and the next read/write (or the next
spawn's pin pass) hit a dead descriptor.

GNU's undo save IS a kernel dup (fcntl (fd, F_DUPFD, SHELL_FD_BASE),
redir.c:965/1082/1144; SHELL_FD_BASE is 10, redir.c:86; compound
groups run do_redirections (..., RX_ACTIVE|RX_UNDOABLE),
execute_cmd.c:854). This makes the plan-bind save the same kernel
dup: FdTable::saved_entry duplicates every File-backed endpoint
(FileFd::duplicate, F_DUPFD_CLOEXEC on unix, non-inheritable
duplicate on Windows), applied at the single save point that covers
all bind arms. A <> pair's two arms share one Rc; the save preserves
that sharing so closing one direction still retires the shared
descriptor, as GNU's close(2) closes the whole descriptor. A dup
failure fails the consumer run (GNU REDIRECTION_ERROR) before it
starts, unwinding the bindings already made; with_procsub_spawn_plan
now returns Result<T, ExecuteError> and its single caller surfaces
the bind error exactly like the consumer's own error.

Note: the three fd_table.rs helpers are the same code as PR #3723
(Refs #3706), which is still an open draft on the same base — #3723
adds them for the group-redirect save sites, this PR for the
spawn-plan save site. Whichever merges second drops its copy of
the helper hunk; the product hunks do not overlap (#3723 touches
command_input_scope.rs / compound_exec.rs / external_finish.rs,
this PR touches external_setup.rs / pipeline_exec.rs).

Regression pin: tests/issue3732_procsub_spawn_plan_fd_restore.rs
(11 cells: File-read fd 8/3, Closed, TruncatedFile, append-File,
ReadWrite <>, CarrierRead, CarrierWrite, no-displacement control,
external-child /proc face, <>-close sharing guard).

UNVERIFIED-BY-CAPTAIN: no build slot was available (Simular box
hibernated, X299 unreachable, old server unreachable, local builds
forbidden), so the pin's fail-first run and the verification legs
are owed; see the PR body.

本 PR 删除了什么:未删除任何内容(纯增量修复;仅将
with_procsub_spawn_plan 的返回由 T 改为 Result<T, ExecuteError>,
唯一调用点同步适配;无删除的功能、文件或公开面)。

* test(3732): gate carrier_read cell to unix — <(...) input procsub write end undelivered on Windows (Refs #3732)

---------

Co-authored-by: 曹梦轩 <[email protected]>
caomengxuan666 added a commit that referenced this pull request Nov 17, 2026
#3740)

* fix(executor): net bind saves displaced fd via kernel dup (Refs #3726)

bind_simple_command_net_inputs' in-process net bind saved the
displaced fd-table entry as a bare Rc clone; the bind's open_input /
open_output retired that descriptor (retire_read_arm /
retire_write_arm, rubash#3213), so restore_simple_command_net_inputs
re-inserted a retired entry and the next read saw EBADF (same hazard
as #3706, on the network-redirect face). The undo save is now a
kernel dup via FdTable::saved_entry / FdEntry::dup_file_endpoints
(GNU redir.c:965/1082/1144 fcntl (fd, F_DUPFD, SHELL_FD_BASE);
execute_cmd.c:854 RX_UNDOABLE); a dup failure fails the whole
redirect list like a refused connect (diagnostic + status 1, body
never runs; binds already made are unwound, execute_cmd.c:855).

NOTE: the fd_table.rs hunk (FileFd::duplicate /
FdEntry::dup_file_endpoints / FdTable::saved_entry) is byte-identical
to draft PR #3723's; whichever merges second drops the duplicate.

UNVERIFIED-BY-CAPTAIN: no build slot existed in this lane (see
REPORT); pin fail-first / head-green / lib / -D warnings legs OWED.

* test(3726): drop out-of-scope <> connection-count asserts from fd-restore pin (Refs #3726)

---------

Co-authored-by: 曹梦轩 <[email protected]>
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.

1 participant