Skip to content

perf(executor): hot-path residue — test marks gate, word materialization once, assignment scan admission (rubash#242) - #501

Merged
caomengxuan666 merged 5 commits into
masterfrom
perf/executor-hotpath
Oct 10, 2026
Merged

caomengxuan666 merged 5 commits into
masterfrom
perf/executor-hotpath

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Closes #242 (executor hot-path residue; see honesty note below for what this PR deliberately does NOT claim).

Method (per the #437 playbook: measure first, then fix)

No LD_PRELOAD on Windows, so attribution ran through the existing RUBASH_EXEC_PROFILE drill-down (temporary fine-grained phase timers over the release build, removed before landing), plus synthetic decomposition probes to separate the per-command floor from per-construct add-ons. Every fix is a separate commit with its own attribution. Timings: best-of-5, perf_counter_ns, interleaved A/B (base and new alternate each round on the same host, release builds of 7be6a799 vs this branch) so host-load spikes hit both sides equally.

Attribution findings (release build, per 5-10k commands, inflated phase sums):

hot spot where the time went
sync_fd_terminal_marks rebuilt the __RUBASH_FD_TERMINAL_<fd> env mirror (full env_vars.retain + fd-table walk + console probes) on every test/[ call; the marks have exactly one consumer: the -t arm
expand_command_words tail one dead materialization per word per command (overwritten by the glob loop) + 2 extra allocations per plain word
assignment RHS strip two chained str::replace per assignment even with zero carrier bytes present
${...} walker tail raw std::env::var_os debug switches on every parameter expansion and assignment (the exact pattern #437 fixed in trace_stdio_write), and a provably-inert =/:= fragment scan per word

Fixes (one commit each, all output-identical by construction)

  1. cb241bc8 — test/[ refreshes fd-terminal marks only when a -t operand is present. The refresh is idempotent and runs before dispatch in the same call, so every real -t evaluation still sees fresh marks; a -t in a string-comparison position merely triggers a harmless refresh.
  2. 2d83fad7 — test/[ operand strip borrows instead of cloning argv (Vec<&str> + side table for the rare -v rewrite; zero String allocations for the common [ $i -lt N ]).
  3. 158f7ad3 — expand_command_words materializes each word once at its consumer: the pre-glob collect fed only the test/[ branch (the general branch overwrote it), and a word with no carrier bytes and no comsub payload prefix materializes to itself (same identity argument as materialize_expanded_command_word's own fast path) — moved, not copied twice more.
  4. e795c23a — apply_parameter_assignment_expansions_in_word admits on a single = probe: both applied arms split the ${...} body on =/:= (the only arms), so a word with no = anywhere can never fire one (rubash#117 whitelist discipline; a false negative is impossible because the operators require the byte).
  5. fd70638a — assignment RHS IFS-carrier strip goes through cow_replace (borrows when absent, byte-identical contract), and the process-lifetime debug switches (RUBASH_TRACE_APPAE x3, RUBASH_DBG_AAV x5, RUBASH_DBG_TRAP x2) are cached in OnceLocks exactly like trace_stdio_write after [perf] 数组追加与算术循环是脚本执行的热点(micro-benchmark 报告) #437.

Before/after (release, same host, interleaved best-of-5; GNU column kept from the ISSUE for scale only — different host/build, debug-vs-release, not comparable directly)

probe (ISSUE lane) ISSUE debug ratio master release (ms) this PR (ms) delta
15-expansion-x5000 (76x lane) 76x 445.2 359.7 1.24x
06-strconcat-x5000 (77x lane) 77x 192.9 167.2 1.15x
07-fncall-noop-x5000 (94x lane) 94x 235.3 203.8 1.15x
04-loop-true-builtin-x2000 (52x lane) 52x 81.3 74.5 1.09x
13-readloop-gen-x2000 (106x lane) 106x 140.1 136.3 1.03x
12-pipe-echo-read-x2000 5.7x 972.8 948.0 1.03x
11-pipeline-yes-head 28x 42.8 41.8 1.02x
08-cmdsub-true-x1000 1.2x 66.0 64.9 1.02x
05-arith-x5000 (50x lane) 50x 66.8 70.7 ~noise (untouched)
01/02-startup (13x lane) 13x 10.9/11.7 11.2/11.6 ~noise (untouched)
10-pathmiss-x100 / 14-glob 11x / — — — ~noise (untouched)

Context on the ISSUE ratios: the table's rubash numbers were debug builds; on release builds those multipliers are already single-digit before this PR (e.g. 15-expansion is ~7.7x against the ISSUE's WSL GNU column even on master). This PR therefore reports same-host release-vs-release deltas and does not claim a halving of the ISSUE table's debug-vs-GNU multipliers.

Honesty note: what is NOT fixed, and why

  • 05-arith lane: attribution shows arithcmd is only ~17.5ms of ~90ms phase time — the loop's cost is the same per-command floor as everywhere else; no single dominant item to cut safely. Untouched.
  • 13-readloop: dominated by pipeline machinery (chain phase ~134ms of the probe), i.e. a separate token/pipeline-architecture lane (same conclusion as perf(lexer): opener-state checkpoint - fold passes resume from the bare { (rubash#281) #486's nvm note). The +3% here is the shared floor, not the read builtin.
  • apply_shell_assignment store (~2us per store in probe 15): nameref/array/readonly attribute machinery; needs a structured-variable-store lane, not a spot patch.
  • Function-call preamble (~6us self per call in probe 07 beyond the body's floor): positional/BASH_* stack save-restore and tempenv bookkeeping — a grind with semantic risk (BASH_LINENO/SOURCE/ARGV0 stacks are observable); deferred.
  • Considered and rejected: memoizing the set_current_command render keyed on (parse generation, node address) — pipeline stages and other materialized temporary nodes can reuse a freed node's address within one generation, so a stale hit could publish the wrong BASH_COMMAND text. The render memo was worth at most ~5%; rejected on correctness.

Verification

  • Full cargo test --no-fail-fast on this branch vs a fresh origin/master build: failure sets byte-identical, bidirectional diff empty (45 named failures on both sides; the known host-env families: bashdb, tilde/HOME, examples, heredoc-fd, pwd logical-mode, path virtual-system-root). Pass/fail counts per suite identical.
  • Targeted suites green: issue343_345_trap_regressions (9/9), issue440_broken_pipe_shell_survival (3/3), perf(lexer): opener-state checkpoint - fold passes resume from the bare { (rubash#281) #486 lanes perf10_token_reuse (10/10), lexer:: (93/93), script_driver (19/19).
  • 22 purpose-built semantics probes over every touched surface (test operators incl. -t/-v/arrayref operands and -t-as-data, literal/quoted/glob/ANSI-C/comsub-payload words, assignment operators incl. readonly/:=/+=, IFS-guarded $'...' values, $_/DEBUG-trap command text, function call semantics, arith loops, pipeline read) — stdout+stderr+rc byte-identical between master and this branch.
  • Debug switches verified live: RUBASH_TRACE_APPAE=1 and RUBASH_DBG_AAV=1 still emit their traces with the OnceLock caching.
  • cargo fmt clean.

…nd is present

sync_fd_terminal_marks rebuilt the __RUBASH_FD_TERMINAL_<fd> env mirror
with a full env_vars retain + fd-table walk + per-endpoint console probes
on EVERY test/[ invocation. The marks have exactly one consumer: the -t
operator arm in builtins/test.rs. Gate the refresh on the operand list
containing -t; a -t in a string-comparison position merely triggers a
harmless idempotent refresh, and every real -t evaluation still sees
freshly synced marks (the sync runs in the same call, before dispatch).

Profiled attribution (RUBASH_EXEC_PROFILE drill-down, release, while [
...] loop): latebuiltin self-time for 4000 true/[ calls dropped from
~11ms to the testcore+bufout core. benchmarks/04 88.0 -> 69.1 ms,
benchmarks/06 200.1 -> 163.2 ms (best-of-5, same session).
execute_test_words cloned every operand into a fresh Vec<String> on
every invocation only so the -v subscript rewrite could mutate one
element in place. Strip the in-band ARRAYREF_FLAG by borrow (GNU copies
word->flags, it does not touch the text) and keep the rare -v rewrites
in a side table resolved at use - zero String allocations for the
common "[ $i -lt N ]" shape.

cargo test --lib: 637 passed / 2 failed = the pre-existing host-env
failure set (pwd logical-mode, path virtual-system-root), identical to
master.
…ts consumer

Two dead copies per word per command in every loop:

1. The pre-glob collect into variable_expanded.words fed only the
   test/[ branch; the general branch re-derived every word in its own
   NoMatch/suppress_glob pass and overwrote the collect. Gate the
   collect on the test branch.
2. For a word with no carrier-family byte and no comsub payload prefix,
   materialize_expanded_command_word is the identity (its own fast path)
   and the DATA_SQUOTE restore scans nothing - so move the expanded
   word instead of copying it twice more. Literal words (true, -lt,
   2000, echo payloads) take this on every iteration.

expwords attribution (RUBASH_EXEC_PROFILE): 15.7ms of 88ms in
benchmarks/04, 58.3ms of 230ms in benchmarks/07, 49.7ms of 453ms in
benchmarks/15.
… probe

apply_parameter_assignment_expansions_in_word walked every command word
and every assignment RHS on every expansion, scanning for ${ fragments
and walking per-fragment quote state before concluding there was nothing
to apply. Both applied arms split their ${...} body on '=' / ':=' (the
only arms), so a word carrying no '=' anywhere can never fire one -
whitelist admission (rubash#117 discipline), not a blacklist: a
false-negative is impossible because the operators require the byte.
"${a#alpha}" / "${a%%:*}" / "payload line" / "-lt" skip straight out.
…-iteration scans

Three per-iteration costs on the assignment/parameter hot path, each
provably output-identical:

1. expand_assignment_value stripped the IFS_GLUE / ANSI_C_IFS_GUARD
   carriers with two chained str::replace calls - two full scans and
   two fresh Strings per assignment RHS even when no carrier byte was
   present (the common case: every plain a=x, b=$other, b=${a#p} in a
   loop). markers::cow_replace borrows when the needle is absent, so
   the marker-free RHS pays one scan and one final allocation
   (the helper's contract: byte-identical output either way).

2. The RUBASH_TRACE_APPAE switch was re-read with a raw
   std::env::var_os at EVERY ${...} walker tail (parameter_words.rs
   x3) - the std::env lock plus an environment scan per parameter
   expansion (measured 122ns/call missing, 1.2us present on Windows;
   the trace_stdio_write fix in rubash#437 was the same pattern).
   Same for RUBASH_DBG_AAV on the assignment paths (x5) and
   RUBASH_DBG_TRAP in the comsub trap paths (x2). All three switches
   are process-lifetime debug knobs: cache each in a OnceLock, exactly
   like trace_stdio_write's cached switch.
@caomengxuan666
caomengxuan666 merged commit a800dc5 into master Oct 10, 2026
8 checks passed
@caomengxuan666
caomengxuan666 deleted the perf/executor-hotpath branch October 10, 2026 09:55
caomengxuan666 added a commit that referenced this pull request Oct 12, 2026
…lent wrong-file read (#552)

The file-operand loop ran each operand through expand_word AFTER the
simple-command executor had already expanded the argv once
(execute_cmd.c execute_disk_command -> expand_words). A single-quoted
or escaped operand like '$FIX/c' arrives at that loop with its quotes
removed and a live-looking dollar, so the second pass re-scanned the
literal text and silently opened zz/c where GNU reports
'cat: $FIX/c: No such file or directory' (status 1) - a silent
wrong-file read (issue #511, P0 data-corruption class).

Use the argv as-is, the same rule external_sed adopted in rubash#177.
parse_cat_argv already classifies options from the same final argv
(getopt sees post-expansion text, exactly like the real cat.exe), and
pathname expansion happened once in expand_command_words before
dispatch, so dropping the second pass restores single-expansion
semantics without touching option parsing, /dev/fd operands, '-' stdin
handling, or the inline pipeline stage arm (which operates on raw
pre-expansion words and keeps its own first-pass expansion).

Bisect (2026-10-12, real rubash.exe probes): every commit of
41de831..origin/master reproduces, back through 41de831 to the
initial import 896ef0d (chore: init) - the double expansion predates
the #501 hot-path rework the issue suspected; no introducing commit
exists in history. Tests: tests/issue511_cat_quoted_operand_regressions
(9 cases; 6 fail on unfixed master, 9 pass with this change).
caomengxuan666 added a commit that referenced this pull request Oct 13, 2026
…601)

40 commits (PRs #496-#600) folded into [1.4.0] by theme instead of
per-commit listing:
- GNU semantics waves 1-4b with their issue families
- argv re-expansion P0 pair (#511/#555), PWD POSIX persona (#537)
- -s on-demand stdin driver as the canonical library reader (#586)
- CLI entry-shape semantics (#589-#591) and the GNU usage contract (#585)
- diagnostic message fidelity (#551) and parser diagnostic tokens
- Windows path contract (#568/#592)
- lexer/executor performance rounds (#554/#562/#501)
- docs: boundary invariants, platform gap, baselines, debugger M0

Commit message deliberately carries no release/version claim.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant