Skip to content

[perf][P1] Scalar assignment path 2.72x slower: unconditional xtrace-only memo insert, dual BTreeMap+HashMap stores with replay log, nameref pre-allocation #609

Closed

Description

@caomengxuan666

Evidence

Android/Termux aarch64 (6-core tablet), niubash 1.4.0 Android build (embeds rubash e785c3c8f610) vs GNU bash 5.3.20-1 aarch64. Interleaved, best-of-3.

Pure assignment microbenchmark (30k iterations):

S=abcdefghijklmnopqrstuvwxyz
for ((i=0; i<30000; i++)); do t=$S; done

bash 0.086s vs niu 0.234s → 2.72x. The empty-loop baseline for the same shell pair extrapolates to ~0.086s (bash) / ~0.203s (niu), i.e. bash's assignment here rounds to noise while niu adds ~0.031s (~1 µs/assignment) of pure assignment machinery. The x=$((x*3+7)) arm of the arithmetic-for benchmark (2.26x, see that issue) pays this same path on top of the evaluator costs.

Root cause (all citations verified against this checkout)

1. Every scalar assignment inserts into assignment_expansion_memo, which is only ever read under xtrace

src/executor/temporary_assignments.rs:29-32:

let expanded_value = self.expand_assignment_value_with_raw(name, value, raw);
self.assignment_expansion_memo
    .borrow_mut()
    .insert((name.clone(), value.clone()), expanded_value.clone());  // 3 String clones + hash insert

This runs unconditionally on every assignment. The memo's only reader is xtrace_assignment_text (src/executor/prompt_expansion.rs:961, sole caller xtrace_command_lines at prompt_expansion.rs:838, which is itself gated by if self.xtrace_enabled() at command_dispatch.rs:112 / command_prepare.rs:2952). The memo exists for rubash#254 (args=$(echo hi) echo x ran the RHS twice when tracing) — correct behavior, but the write is paid by 100% of assignments to serve the ~0% that have set -x on, and it is thrown away one command later anyway (command_execute.rs:35 clears it per command).

Fix shape: populate lazily from the xtrace path (the expansion it needs is recomputable there), or keep the memo only while xtrace_enabled() — a runtime flag gate, not a symptom blacklist.

2. Every scalar assignment writes two stores, with clones on both sides

src/executor/temporary_assignments.rs:1233-1245 (typed store) and :1265-1272 (env mirror):

if let Some(variable) = self.shell_state.variables.get_mut(base_name) {      // BTreeMap lookup
    if let ShellValue::Scalar(current) = &mut variable.value { *current = value.clone(); }
} else {
    let _ = self.shell_state.variables.set_scalar(base_name, value.clone()); // alloc + insert
}
...
self.shell_state.env_vars.insert(base_name.to_string(), value.clone());      // alloc + insert
if crate::builtins::set::shell_option_enabled(&self.shell_state.env_vars, "allexport") { ... }  // option lookup
sync_shell_assignment_process_env(&self.shell_state.env_vars, base_name, value);                // setenv path
  • The two stores are structural: shell_state.variables: BTreeMap<String, Variable> (src/shell/variables.rs:43) — lookups are O(log n) string comparisons over ~170 entries — plus env_vars: HashMap<String, String> as the export/attribute mirror.
  • The same split is what forces the evaluator-side replay log (record_arith_write → sync_arith_writes_to_shell_state, src/executor/arithmetic/mod.rs:55-59, :82-100 — see the arithmetic-for issue §1/§4): every variable mutation in the engine is written twice and diff-synced once. The rubash#404 comment at mod.rs:66-77 documents the invariant that makes this necessary today: the evaluator writes env_vars while parameter lookup prefers the typed store.
  • Per assignment: ≥2 value clones + 1 key clone + 1 BTreeMap op + 1 HashMap op + 1 option lookup + the process-env sync.

GNU's model (variables.c): one bind_variable into a single hash table, value moved once, exported flag carried on the cell — no mirror, no replay, no diff.

3. Nameref pre-resolution allocates before checking whether the variable is a nameref

src/executor/variable_state.rs:108-124:

pub(in crate::executor) fn nameref_resolution(&self, name: &str) -> NamerefResolution {
    let mut current = name.to_string();          // heap String per call
    for level in 1..=9 {
        if !is_marked_var(&self.shell_state.env_vars, NAMEREF_VARS, &current) {
            return if current == name { NotNameref } else { Target(current) };

Callers include the general assignment path (temporary_assignments.rs:649, :179), array assignment, loop variable resolution (loop_select.rs:197) and more — every one pays a String allocation for the overwhelmingly common verdict NotNameref (first is_marked_var check false, current == name). The name is already a &str for the entire non-hopping case.

Fix directions

  1. §1 — gate the memo insert on xtrace_enabled() (one option-table read already cached elsewhere) or move population to the xtrace read site. Removes 3 allocations + 1 hash insert per assignment; zero behavioral surface when tracing is off (the memo is cleared unread anyway).
  2. §2 (structural, the real fix) — converge on one authoritative store like GNU: either make env_vars the export mirror derived lazily at child-spawn/export time (it already serializes via export_environment), or make the typed store a view over env_vars with attribute side-tables. This deletes the per-assignment double write, the evaluator replay log, and the sync boundary from every hot path at once — matches AGENTS.md "fix a wrong invariant / converge to the real mechanism" rather than caching around it. If a staged approach is preferred: move variables from BTreeMap to HashMap (check declare -p / ${!x} ordering consumers first) and skip set_scalar when the cell already holds the identical value (the sync layer already computes this comparison elsewhere).
  3. §3 — check the NAMEREF mark on the borrowed &str first; only allocate the working String when a hop actually happens (same shape as the arithmetic lvalue fix in the arithmetic-for issue §2).

Impact

  • ~1 µs per scalar assignment of avoidable work; assignment-only loops measure 2.72x vs bash, and every x=... in every script — including the x=$((...)) arm of the arithmetic benchmark and the t= chains of the parameter-expansion benchmark — pays §1-§3.
  • §2 is shared infrastructure: fixing the two-store split also removes the evaluator's per-evaluation diff-sync, which is on the critical path of the arithmetic-for-loop gap (cross-ref).

Verification plan

  • Local cargo build --release + bench_niu/micro.sh (assign op) + the arithmetic-for benchmark; target: assign-op within 1.2x of bash, measurable knock-on improvement in both other issues' numbers.
  • Semantics risk is concentrated in §2 (export visibility, allexport, readonly/nameref attribute handling, [[ -eq ]] sync — the rubash#404 class). Stage 1 (§1, §3) is allocation-only and safe behind the standard true-baseline slice; stage 2 (§2) needs the full 83-suite ledger per AGENTS.md, with export/declare/nameref/readonly suites called out.

Related

  • unixwin/niubash#352 — umbrella benchmark matrix for this device (environment, methodology, full results)
  • unixwin/niubash#351 — startup cost is wrapper-side; local rubash -c true measures at bash parity, so none of the numbers above include a startup penalty from the engine

Activity

  1. added
    P1-high
    performance
    on Oct 14, 2026
  2. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    已认领并完成初步 triage。当前 checkout 含他人未跟踪文件,按协作规则暂不直接编辑 rubash 工作树;标量赋值优化涉及 export/readonly/nameref 语义,需在干净 worktree 按 issue 验证计划实施。

  3. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    已落地与 #607 共享的低风险 nameref lazy-allocation 优化:普通变量先返回 NotNameref,避免无意义 String 分配;未改双存储架构。相关检查通过。

  4. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    Reopen: PR#611 fixed only the third root cause (nameref pre-allocation, +8%); the unconditional memo insert and the dual BTreeMap+HashMap stores — the two main costs — remain

    Measured on-device after rebuilding from master 334afab (engine-only rubash, best-of-3 wall, vs archived 1.4.0 engine at e785c3c and GNU bash 5.3.20):

    workload e785 (1.4.0) 334afab (new) GNU bash old→new new vs bash
    assign loop ×200k 1 426 ms 1 320 ms 611 ms 1.08× 2.2× slower

    src/executor/variable_state.rs (nameref deferral) changed — that's the 8%. The two dominant root causes have zero lines changed in #611:

    • the unconditional xtrace-only memo insert per assignment (temporary_assignments.rs:29-32; sole reader prompt_expansion.rs:961 is gated by xtrace_enabled() — the memo can be gated the same way);
    • the dual BTreeMap+HashMap stores with the diff-sync replay (temporary_assignments.rs:1233-1245,1265-1272, variables.rs:43).

    Allocator evidence (LD_PRELOAD interposer, unixwin/niubash#352 appendix): the assign loop still performs 1.27× bash's malloc count / 1.13× its bytes (8.40M / 151.3 MB vs 6.60M / 134.8 MB), i.e. the measurable allocation tail of the memo/dual-store path persists.

    Reopening to request a follow-up PR gating the memo on xtrace and collapsing the dual stores, with the row above as the acceptance benchmark (target: within ~1.2× of bash, currently 2.2×). The allocator counters are deterministic and can gate the fix in CI.

  5. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    Profiling evidence: scalar-assign loop allocates 1.27× the calls / 1.13× the bytes of GNU bash

    LD_PRELOAD allocator interposer (methodology: unixwin/niubash#352 profiling appendix), workload for ((i=0;i<200000;i++)); do v=$i; done:

    shell malloc realloc bytes requested
    bash 5.3 6 600 687 1 134.8 MB
    niu 1.4.0 8 402 393 172 151.3 MB

    +1.8M allocations (+27%) and +16 MB (+13%) for the same loop — consistent with the unconditional per-assignment memo insert + dual-store write + nameref pre-allocation diagnosed in this issue. The multiplier is smaller than the 2.72× wall-time gap, i.e. roughly half the wall-time cost sits in the CPU-side state work (option lookups, diff-sync bookkeeping) rather than the allocation calls themselves — matching the issue's fix direction (make the memo xtrace-gated, collapse the dual stores).

  6. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    Measurement correction: quiet re-measure — posted 2.2× corrects to 2.03×; conclusion unchanged

    (Reopen table ran under background load; bash's wall column was inflated ~1.8×. Old→new columns were load-immune.) Quiet best-of-3:

    workload rubash e785 rubash 334afab niu product GNU bash
    assign ×200k 1 184 ms 1 110 ms 1 551 ms 548 ms

    Demand unchanged: gate the xtrace-only memo insert on xtrace_enabled() + collapse the dual BTreeMap/HashMap stores; acceptance row above, target ≤1.2× vs bash (alloc counters in the appendix are load-immune).

  7. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    重新认领后已完成 GNU subst.c:3576 do_assignment_internal 的 trace gate 核对,并在独立 worktree 实现 xtrace-only memo gating(permanent + temporary 两路径);Linux 两项新单元测试与现有 xtrace CLI 回归通过。release baseline / after 已分别构建,下一步提交实际交错 benchmark。该补丁不声称解决 dual-store 全部开销,未达 ≤1.2× GNU 的指标前不会关闭本 issue。

  8. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    重要实测纠正:固定 scalar workload for ((i=0;i<200000;i++)); do v=$i; done 在当前 334afab 走 command_prepare 的 standalone assignment 路径,并不经过 apply_permanent_assignments 的 memo insert。Linux 2 warmup+9 rotating interleaved: baseline median1298.94ms / memo-gate1292.00ms / GNU350.94ms,变化仅0.5%且有离群样本;glibc分配计数约6.801M前后不变。因此不能把memo gating声称为这个scalar workload的性能修复。本 issue 保持开放,继续调查真正的state/store成本;bench脚本与完整样本将进后续PR。

  9. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    后续 PR #620 已提交并通过全部必需 CI。实测 scalar allocation calls 6.802M -> 6.202M(-8.82%),但 wall median1323.35 ->1322.74ms基本持平;prefix453.56 ->448.76ms约-1.1%,GNU对应353.01/109.74ms。这是有bench证据的部分分配优化,不是完整性能验收;#609保持OPEN。完整命令、commits、9轮样本、输出一致性和未达标说明在 PR/docs。

  10. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    First slice up as PR #672 (branch perf/issue609-scalar): whitelist fast RHS for literal/``/"" (one borrowed read; binding path untouched). 100k `t=` 1096ms->927ms (1.18x); battery 30/30. Gate running. Remainder (dual-store write, bind clones) is later slices.

  11. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Slice 1 landed as #672 (squash-merged e5f7c7a). 100k t=$S 1096ms->927ms; battery 30/30; gates identical (niu 49=49). Issue stays open for slice 2 (dual-store write, bind clones).

  12. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Slice 2 up as PR #678 (branch perf/issue609-slice2): marks-free bind via one attr probe, in-place dual write, identical-rebind skip (readonly still diagnoses). Net assign 2.03us->1.33us (-35%), GNU 1.25us; battery 30/30. Gate running.

  13. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Slice 2 landed as #678 (squash-merged 952ee84). Net assign 2.03us->1.33us (-35%), GNU 1.25us; battery 30/30; gates identical (niu 49=49).

  14. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Fixed by slices 1+2 (#672, #678). Net assign cost 2.03us->1.33us vs GNU 1.25us (1.06x, inside the 1.2x target); battery 30/30. Raw-loop remainder is loop machinery, tracked in #607.

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

Metadata

Metadata

Labels

P1-highperformance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions