Skip to content

WIP: 多 session 止血 (G-02 cwd / G-03 env / G-01 lock) — ms-stopbleed - #1778

Merged
caomengxuan666 merged 10 commits into
masterfrom
fix150/ms-stopbleed
Oct 26, 2026
Merged

caomengxuan666 merged 10 commits into
masterfrom
fix150/ms-stopbleed

Conversation

@caomengxuan666

@caomengxuan666 caomengxuan666 commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

多 session 止血(1.5.0 线,ms-stopbleed 簇)。第二轮验收通过,保持 draft 待主会话处置。

多 Session 并发互改会让另一个 session 死掉/串话,本 PR 做三条止血,三个实现 commit、验收 harness 与一轮修复 commit 均已落地:

  • G-02 进程 cwd = 会话 cwd(501a6d82):cwd 入 ShellState,cd 家族只改会话字段;全部 spawn 点传 current_dir(会话 cwd)。
  • G-03 env 镜像回滚(082bfd14):Executor Drop 不再按出生快照全量还原进程 env;改为按本 lineage 的写入 journal 条件还原。
  • G-01 EXECUTION_LOCK 粒度收窄(a837b95b):锁从 execute_ast 全程持有收窄到进程全局状态触碰点。
  • 验收 harness(6f05794b):tests/multi_session_isolation.rs + tests/session_threading_contract.rs。
  • 验收修复轮(01d1876f / 34a6e30b / 6a02984f / c30da804):三类真分歧逐类根因修复 + 回归钉 tests/ms_stopbleed_regressions.rs。

首轮验收发现的三类真分歧与修复

  1. G-02 残余(harness ×42):spawn 盖戳有效,但相对重定向的数据路径未锚——缓冲内建输出的实际落点 OutputTarget::Path 臂以原始相对词 append 打开(进程 cwd),加同形状 30 余处(append 打开点、条件绑定 FileFd::open_write、模拟命令 cat/touch/cp/rm/rmdir 的操作数、输入侧相对读)。进程内模拟的 cat 相对读因此读到各会话累积进进程 cwd 的共享文件。修复:逐处包 Executor::session_path(...)(G-02 既定锚定收口,绝对路径透传)。
  2. G-03 子进程 env 可见性(×1):apply_child_environment env_clear 后只按会话 exported 表重建,从不读进程 env 镜像(其余 spawn 面均以镜像为跨进程传输)。修复:覆盖前先投影镜像集(shell_assignment_needs_process_env 门控;TMPDIR、__RUBASH_TRAP* 沿既有排除规则),会话值随后逐名覆盖。
  3. lib 新增 6 条失败:定版根因是 G-03 journal 漏口——宿主 API set_env 未像 remove_env 那样 push journal guard,run 外写入的 __RUBASH_IS_C/__RUBASH_INTERACTIVE 镜像标记零记录、Drop 不还原、被后续 Executor 出生导入污染分类(serial 单线程亦确定性复现,污染者→受害者同进程直证;基线靠旧 Drop 全量还原兜住、与锁收窄无关)。修复:set_env 持 journal guard 后再写,未回扩 EXECUTION_LOCK。

第二轮验收实测(2026-10-26 晚,单槽一次获取内三段串行,净化 env,JOBS=1,--skip login_posix_env)

  • 基线 lib(pristine 160e792):771 passed / 1 failed / 1 ignored,失败集仅 ownership_unary_operators_check_existing_file(已知基线)。
  • 工作树 lib:771 passed / 1 failed / 1 ignored —— 失败集与基线全等,首轮 6 条新增失败全部消失。
  • harness:PASSED —— 0 mismatching files / 0 deviations(540 个比较实例)。逐步与整脚本两模式 N=2/N=4 全 0;G-03 三探针全对且子进程 env 文件比较通过;反饿死决定性通过(A 纯计算 1016.5s 期间 B 命令 2.85ms);吞吐三档 tp 全 agree,sessions=2 本轮 41.81s → 31.34s 过 0.85 门(首轮判环境噪声的那格本轮亦达标)。threading contract 通过。
  • 回归钉 tests/ms_stopbleed_regressions.rs:1 passed(三类各一确定性钉)。

结论:第二轮验收通过。 详细根因、证据链与口径见簇 REPORT.md(修复轮一节)。本 PR 保持 draft,不合并。

Multi-session isolation (1.5.0 ms-stopbleed): the process cwd WAS the
session cwd — builtins/cd.rs chdir'd the whole process, so one
session's cd silently moved every other session's relative paths,
external /bin/pwd output, and redirect landings (isolation harness
stepwise items (b)(c)(d) cross-talked deterministically).

- ShellState gains a cwd: PathBuf field (physical native form);
  $PWD remains its logical display twin, written by the cd family
  exactly as before.
- cd/pushd/popd move only the field, via a canonicalize probe in
  place of chdir. GNU: builtins/cd.def cd_builtin chdirs the shell
  process itself and the process cwd is the session state every
  later command inherits; here the field plays that role per
  session. The move stands even when the readonly $PWD bind fails,
  mirroring chdir preceding bindpwd (builtins/cd.def:136-175).
- Every child spawn stamps current_dir(session cwd): external
  commands, pipeline stages, background/coproc, procsub readers,
  command substitution, the exec builtin, and the whitelisted-fd
  spawn (the fd layer gains a cwd field, passed as CreateProcessW
  lpCurrentDirectory on Windows instead of NULL).
- Process-cwd save/restore brackets (command substitution,
  pipeline stages, procsub, subshell restore) collapse into the
  ShellState swap: cwd now rides the state clone with fork
  semantics (GNU subst.c:7143 command_substitute forks;
  execute_cmd.c:1576 subshell inherits the process cwd).
- Session-cwd semantic reads re-anchored: pwd builtin, external
  /bin/pwd (via the spawn stamp), the $(pwd -P) fast path,
  child-shell env PWD, fresh-shell cwd, test(1) relative operands,
  source lookup, glob physical anchor, redirect target opens,
  external relative file operands, command-lookup cache
  invalidation on cd.
- pushd's Dir/Index/Swap branches now move the session cwd too:
  they never chdir'd in the old code (GNU builtins/pushd.def
  change_to_temp chdirs) — a latent divergence the field model
  removes rather than preserves.

Regression: tests/multi_session_isolation.rs stepwise (b)(c)(d)
land with the harness commit of this PR.
Multi-session isolation (1.5.0 ms-stopbleed): assignments mirror
into the process env, and Executor::drop restored the whole birth
snapshot — the first session to exit rolled back every surviving
session's variables.

- Mirror writes funnel through local_helpers::set_process_env /
  unset_process_env / mirror_env_set / mirror_env_remove, which
  journal (key -> final written state) into the running executor's
  EnvWriteJournal (thread-local stack). Child executors built
  under a parent's run journal into the parent's lineage, so
  command-substitution children keep the rubash#182 process-env
  discipline instead of leaking their writes on their own Drop.
- Direct-write bypasses routed through the funnel: scoped env
  restores (restore_shell_env, function frame pops), init-time
  __RUBASH_* clears, the shopt checkhash marker.
- Drop now restores per journaled key: when the process value no
  longer equals this lineage's final write, a surviving owner
  stands and the key is skipped; otherwise the birth-snapshot
  state is restored. TMPDIR keeps its existing carve-out.
- The fresh-shell full env swap in external_finish stays
  unjournaled on purpose: it is a self-restoring bracket with
  net-zero writes, and journaling it would record the whole
  environment per script child for no coverage gain.
- Known residual (簇 REPORT.md): same-key interleavings across
  lineages whose write orders nest adversely can restore a stale
  value; the journal bounds the blast radius to keys this lineage
  actually wrote.

Regression: env-rollback scenario in
tests/multi_session_isolation.rs (harness commit of this PR).
Multi-session isolation (1.5.0 ms-stopbleed): EXECUTION_LOCK was
held for whole execute_ast / call_function_owned runs, so one
session's long command starved every other session — multi-session
in name only.

The lock is now taken, through local_helpers::acquire_process_state
(reentrant per thread), only where execution touches process-global
mutable state:

- env mirror writes: the funnel (set/unset_process_env,
  mirror_env_set/remove) makes the mutation + G-03 journal record
  one critical section;
- Executor Drop: the compare-and-restore sequence is one section;
- Executor birth snapshots (new_inner, command-substitution fork);
- trap disposition reconcile slow path (builtins/kill.rs) — its
  fast path reads only the disposition atomics and stays lock-free;
- the fresh-shell env swap bracket in external_finish (swap + run
  + restore): while the process env shows the child's env, sibling
  sessions must not read it as their fallback env or land mirror
  writes the restore would wipe. The child's own funnel writes
  pass through reentrantly on the same thread.

Newly routed into the funnel/journal by the audit: the unset
builtin's array/nameref removal paths, completion-state cleanup,
the host remove_env API, and init-time clears (already covered in
G-03). The locale LC_*/LANG process-env sync and the driver
LINES/COLUMNS winsize sync are point-locked but deliberately not
journaled (process-wide by C-library/host nature; per-session
locale isolation is WP-3).

Everything else was audited and proven NOT to need the lock:
kill.rs disposition tables are atomics, SELF/KERNEL signal queues
and the command-lookup cache carry their own Mutexes, job tables
and fd tables are per-Executor, waits are pid-specific (no
any-child waitpid), and after G-02 no production code calls
set_current_dir at all. EXECUTION_LOCK_DEPTH remains as the
run-nesting marker gating the reader-level latch resets.

Residuals (ms-stopbleed REPORT.md): umask stays process-global,
setlocale/strcoll can race a sibling's locale sync, the
self-signal queue's first-poller-wins arbitration is G-04/WP-3.

Regression: anti-starvation scenario + throughput assertions in
tests/multi_session_isolation.rs (harness commit of this PR).
…r owner

Acceptance round 1 left six lib failures (dollar_flags x2,
interactive discard x3, noninteractive FORCE_EOF x1): all passed
isolated, all failed deterministically when run together, and the
working tree failed even single-threaded while the baseline passed
the same filter 54/54. Root cause is a journal gap, not the lock
narrowing itself: Executor::set_env called set_process_env bare,
while remove_env wraps the same funnel in push_env_journal. A test
(or the niubash host) that sets a __RUBASH_* protocol marker through
the host API outside any run therefore wrote the process env with no
journal record, the owner's Drop never restored it, and every later
Executor in the process imported the stale marker at construction
(__RUBASH_IS_C flips error classification to FORCE_EOF/127;
__RUBASH_INTERACTIVE adds the i flag to $-). Proven on the
pre-repair binary: running c_context_stays_fatal first in one
process makes interactive_nounset_is_discard_not_exit fail.

Fix: set_env holds push_env_journal(&self.env_write_journal) across
the mirror write, exactly like remove_env. The write joins the
owner's lineage, Drop compare-and-restores it, and nothing else
changes (in-run calls already run under the owner's journal; the
guard no-ops when the same journal is stack-top).
The harness G-03 section showed a session's own mirrored assignment
(__RUBASH_MS_PROBE) invisible to its spawned /usr/bin/env both
before and after a sibling's Drop: apply_child_environment
env_clear()s and rebuilt the child env only from the session's
EXPORTED_VARS table plus the LOCAL_EXPORT_ENV stash, never reading
the process-env mirror that assignments write through to. Every
other spawn surface honors the mirror as the cross-process
transport (respawn/comsub env_map bases start from
std::env::vars()); this builder was the odd one out.

Fix: right after env_clear, project the mirror set from the process
env (shell_assignment_needs_process_env: PATH/HOME family, locale
family, all __RUBASH_*), keeping the established exclusions —
TMPDIR is never mirrored, __RUBASH_TRAP* keys stay stripped except
the merged TRAP_ORIG_IGNORES, which the existing
transport_inherited_ignores arm re-adds in child form. The session
overlays run afterwards, so session values win name-by-name and an
unexported non-mirror variable still never reaches the child.
Round-1 acceptance: spawn current_dir stamps were correct, but
every session's relative redirect appends accumulated into the
test process cwd's rel.txt (session files stayed empty) and the
emulated cat read the shared file back. The setup opens were
anchored via create_redirect_output, but the buffered-output data
path was not: OutputFdState::write_to_fd's OutputTarget::Path arm
(the append-open that builtin output bytes actually land through)
plus 14 sibling open_redirect_append sites, the conditional-bind
FileFd::open_write pair, an input-redirect validation probe, the
in-process emulated file commands' operands (cat/touch/cp/rm/
rmdir), and nine input-side operand/target reads all converted
with shell_path_to_windows and opened relative to the process cwd.

Fix: wrap each conversion in Executor::session_path, the same
anchor the G-02 commit established (create_redirect_output,
open_input_redirect) — absolute paths pass through unchanged, so
fd-table and procsub-carried absolute paths are unaffected.
One sequential #[test] (the scenarios mutate process-global state
by design): relative >> appends and a relative emulated-cat read
stay inside the session cwd and never touch the process cwd; a
mirrored __RUBASH_* assignment is visible to a spawned
/usr/bin/env while an unexported non-mirror variable is not, and
the mirror write is rolled back at Drop; __RUBASH_IS_C /
__RUBASH_INTERACTIVE set through the host set_env API are gone
from the process env after Drop and are not imported by a fresh
Executor.
…tegration

1. ast_exec.rs: master's new fg_sigint_unwind block (rubash#1639) called
   restore_flat_subshell(saved_state, subshell_cwd.take()) — the pre-G-02
   two-arg form whose saved_cwd only fed env::set_current_dir at restore.
   Under G-02 the process-cwd save/restore brackets are collapsed into the
   ShellState swap (the one-arg definition already in this branch), so the
   call now matches the branch's other six call sites; the block's 130 /
   SigintUnwind semantics are unchanged.

2. glob.rs: master's new follow-symlink enumeration site (rubash#1672)
   called shell_directory_entries(&logical_path, env_vars), which is not
   in this branch's import set; every other site here reads via
   shell_directory_entries_in(physical). The entry's physical_path is
   already computed directly above, so the site now reads the identical
   directory through the physical form, consistent with the G-02 glob
   anchoring chain.
@caomengxuan666

Copy link
Copy Markdown
Member Author

集成收尾(主会话集成线):已合入当前 master db5ff08b(merge b57f9548,不改写历史),新增 fixup 2bccff17 解两处自动合并的语义冲突——(1) path.rs:保留 master 的 path_scan_scaffold 结构、把本线 G-02 的 anchor_at_session_cwd 移进 scaffold 的 dirs 计算;(2) ast_exec.rs #1639 新块的二参 restore_flat_subshell 改回 G-02 一参形(saved_cwd 仅喂 set_current_dir,已塌陷进 ShellState 交换);(3) glob.rs #1672 新枚举点改走 shell_directory_entries_in(&physical_path)。

三段验收在合并树重跑(run-accept.sh 同口径、单槽):Stage 1 基线 lib 771/1/1 失败集={ownership 基线项};Stage 2 harness 0 mismatch / 540 实例 / 0 deviation、G-03 三探针全对、反饿死通过、吞吐三档 agree;Stage 3 工作树 lib 771/1/1、失败集与基线逐条全等。集成轮验收通过,细节在簇 REPORT.md「集成轮」节。PR 现 MERGEABLE(clean),保持 draft 待主会话合并。

@caomengxuan666
caomengxuan666 marked this pull request as ready for review October 26, 2026 23:11
@caomengxuan666
caomengxuan666 merged commit 6290f08 into master Oct 26, 2026
8 of 9 checks passed
@caomengxuan666
caomengxuan666 deleted the fix150/ms-stopbleed branch October 30, 2026 01:41
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