Skip to content

perf(array): O(1) ${#a[@]} via the typed indexed cell, zero behaviour change (#616 Phase 1a) - #627

Merged
caomengxuan666 merged 5 commits into
masterfrom
perf/array-structured-store
Oct 15, 2026
Merged

caomengxuan666 merged 5 commits into
masterfrom
perf/array-structured-store

Conversation

@caomengxuan666

@caomengxuan666 caomengxuan666 commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Phase 1a of the #616 array-subsystem plan: give the indexed array a maintained
count so ${#a[@]} is O(1), with zero behavioural change.

Durable write-up: docs/perf-issue-616-array-store.md.

GNU ownership

  • gnu:array.h:121 array_num_elements — length is a maintained field, O(1).
  • gnu:array.c:516 array_insert — append is an O(1) list splice
    (array.c:533-629 maintain max_index/num_elements).
  • Sparse indices legal (a[100]=x → ${#a[@]} == 1).

Rubash renders arrays to a string in ShellState.env_vars, so every length read
had to split the whole render.

Design

The review draft proposed a new side table; recon showed the typed owner already
exists (shell/state.rs:32-40: variables: VariableStore and env_vars;
shell/variables.rs:10-14: ShellValue::IndexedArray(BTreeMap<i64,String>)).
Adding a side table would have made a third truth, so Phase 1a rides the
existing typed store — the IndexedArray cell is the O(1) count
(BTreeMap::len(); no separate num_elements field needed, unlike GNU's
linked list). env_vars stays the projection all storage readers see.

Invariant: a structured cell is either a complete mirror of the same
indexed_array_entries parse the render uses, or absent.
Writes always sync
or drop; only reads consult the gate. A refused (readonly) typed write drops
the cell instead of shadowing the mirror. RUBASH_ARRAY_STORE=0 disables the
structured reads as a global escape hatch. Assoc is out of scope.

Commits

Measurements

Termux/Android aarch64, release (opt-level 3, LTO), 6 cores.

Method correction. The harness used to always run bash, master, branch,
and this host throttles: the same binary measures 1.14x slower merely
for being invoked later in a round, so "branch last" carried a phantom ~10–15%
penalty. It made 19_arrcopy read 0.8x branch slower here and 1.1x branch faster elsewhere, for code that is 1.0x. The harness now rotates the
shell order per round; the numbers below are order-rotated best-of-5 minima on a
non-idle host, so they are a ratchet, not a clean-room median.

Workload bash master branch master/branch
scalar ${#s} control (200k) 659 1848 1886 1.0x
build10k compound + ${#a[@]} 39 79 79 1.0x
sparse + 200k ${#a[@]} 669 2244 1906 1.2x
15_arrbuild n=2000 33 2104 2130 1.0x
15b_arrbuild n=10000 55 57448 57984 1.0x
15c_arrbuild_compound n=2000 34 2318 2319 1.0x
16_arriter n=2000 47 2319 2349 1.0x
19_arrcopy n=2000 6810 26592 27746 1.0x
comboundedit (write+len) 53 27210 11702 2.3x

No row regresses. comboundedit's 2.3x is this PR's own win (it is dominated by
2000 ${#a[@]} reads that stop parsing the render).

The marquee construct — the fixed cost being removed (measured with the earlier
non-rotated protocol; an NA cannot be flattered by ordering):

Workload bash master branch
10k array + 200k ${#a[@]} 594 NA (>300 s) 2274 (3.86x GNU)
1k array + 200k ${#a[@]} 583 NA (>90 s) 1685 (2.89x GNU)

The branch is the only build that completes.

15_arrbuild is still ~64x GNU because the per-element render is quadratic, and
the write path is deliberately untouched here — Phase 1b (stacked on this
branch) takes it.

Gates

  • lib 581/581;
  • tests/array_store_parity.rs (38 GNU-verified cases) green with the store
    on and off;
  • cli_tests red set name-identical to master in the same tree (1
    pre-existing failure);
  • executor_tests failure set identical to master (1229, set-compared);
  • 2500-script differential fuzz: branch == master for all 2500; both differ from
    GNU on the same 677 scripts (pre-existing, not introduced).

Three real defects found and fixed by this discipline: unset 'a[1]' stale cell;
((a[i]=v)) downgrade + printf -v incomplete rebuild; readonly read -a
stale cell. Two self-inflicted regressions were found the same way (element write
rebuilding the cell; compound append rebuilding it) and removed before this PR.

Oracle caveat: reference is GNU Bash 5.3.20 (this host), not the repo's
designated WSL 5.3.0. These Termux/Android numbers are not Windows or Linux
x86_64 validation.

Refs #616.

…e mirror (#616)

`${#name[@]}` fell back to rendering `env_vars` storage and re-parsing it
on every read (`parameter_array_storage` + `array_values`). GNU keeps an
ARRAY object with a maintained `num_elements` count field
(subst.c:7533 `array_num_elements`, array.h:121) and reads it directly.

`ShellState.variables` already carries a typed store mid-migration, so
instead of adding a new side table, ride the existing
`ShellValue::IndexedArray(BTreeMap<i64, String>)` cell as the O(1) length
truth and keep the rendered `env_vars` string as the projection every
storage reader still sees.

Invariant: the structured cell is either a COMPLETE mirror of the same
`indexed_array_entries` parse the render uses, or absent. Every mirror
write site now syncs through `sync_typed_indexed_array` /
`sync_typed_indexed_storage`, or drops a stale indexed cell
(`drop_typed_indexed_array`); a refused typed write (readonly cell while
the mirror write still lands) drops the cell instead of shadowing the
mirror. Writes always sync; only reads consult `RUBASH_ARRAY_STORE=0`.

Adds `VariableStore::replace_indexed_array_entries` (key-preserving, for
sparse arrays — the dense `replace_indexed_array` enumerates positions).

Gates: lib 581/581; cli red-set name-identical; executor_tests failure
set identical to master; new tests/array_store_parity.rs (34 GNU-verified
cases, run with the gate on and off).
…es (#616)

The Phase 1a structured store kept `${#a[@]}` O(1), but every element write
rebuilt the whole `BTreeMap` from the mirror parse, so the element-write
battery regressed 6-12% vs the pre-#616 baseline (15_arrbuild 1943->2168ms,
16_arriter 1950->2181ms, 19_arrcopy 22588->23880ms).

GNU keeps an ARRAY object and appends a node: array.c:516 array_insert() is
O(1) on the array's element list, and array.h:121 reads num_elements. Mirror
that: when the structured cell is already a complete `IndexedArray`, insert
the one changed key (O(log n)) instead of rebuilding; otherwise fall back to
the full structured sync, which is also what drops a refused (readonly) cell.

The in-place path is only taken when the resulting size equals the caller's
own post-write parse size, so a cell that is not a complete mirror of the
render is never extended -- the "complete or absent" invariant is checked,
not trusted.

Measured (release, best-of-7 interleaved): 15_arrbuild 1.0x, 16_arriter 1.0x,
19_arrcopy 1.1x (branch faster), comboundedit 2.0x, len@sparse 1.2x, and the
10k/1k length-read cases are only reachable on this branch (master times out).

Gates: lib 581/581; cli red-set identical to master@6daf8e1 (1 pre-existing
item); executor_tests failure-set identical (1229); tests/array_store_parity
34 GNU-verified cases green; 2500-script differential fuzz branch==master
(bash-diff 677==677).
Durable interpretation for the array structured store: GNU ownership
(array.h:121 num_elements, array.c:516 array_insert), the deviation from the
side-table draft to the existing typed store, the "complete or absent"
invariant, the write-sync/read-gate rules, the 90 s-timeout A/B table, the
preserved intermediate regression, and what Phase 1a explicitly does not fix
(the quadratic per-element render).
@caomengxuan666

Copy link
Copy Markdown
Member Author

Coordinator review: not merging on CI alone. Before merge please make BENCH evidence traceable to exact baseline and candidate SHAs, build flags, runnable scripts and raw samples (prefer median/all samples rather than only best-of-7). The document baseline 6daf8e1 differs from current PR base 14fe757; explain or rerun against current base. Small arrbuild/arriter changes cannot support an absolute no-regression claim. The stated Android GNU 5.3.20 caveat is appreciated; designated GNU 5.3.0 behavior verification remains required by repository rules.

An independent static audit of complete-or-absent typed-cell synchronization is in progress, particularly failed readonly writes, temporary assignment restoration, unset, arithmetic, read/mapfile and printf. Keep #616 open: O(1) length is only phase 1a, not the outstanding quadratic write path.

@caomengxuan666

Copy link
Copy Markdown
Member Author

Independent static review of head 6b752f4 found a likely merge-blocking synchronization omission (not yet dynamically reproduced):

  1. src/executor/unset_arrays.rs around line 721: default-compat unset a[@] / unset a[*] clears the rendered mirror then returns without dropping/synchronizing the typed cell. The length fast path in arrays/executor.rs can retain the previous count. Please reproduce with a three-element array followed by each unset form and a length query, with structured reads on/off, and add regressions.

  2. declare.rs around lines 102/161 drops sparse keys via into_values/dense replacement. A sparse mirror with keys 2,5 can have typed keys 0,1; the same-length extension gate in shell/variables.rs does not establish the documented complete-or-absent invariant. Please preserve sparse keys or invalidate the cell, with direct invariant tests.

Readonly failure tests should assert status, values/indices and attributes, not only single-element lengths. No code or branch was changed by this review. Findings apply to the stated head SHA; please address before merge.

@caomengxuan666

Copy link
Copy Markdown
Member Author

Dynamically confirmed against exact PR head 6b752f4 in a separate detached worktree, cargo build --locked --bin rubash (debug). A script file initializes three elements, unsets a[@], queries length, then repeats with a[*].

  • RUBASH_ARRAY_STORE=1: stdout 3 then 3; rc=0, empty stderr.
  • RUBASH_ARRAY_STORE=0: stdout 0 then 0; rc=0, empty stderr.
  • Designated WSL GNU Bash 5.3.0: stdout 0 then 0; rc=0, empty stderr.

This confirms the unset flush path is a real behavior regression, not just a theoretical invariant concern. PR must remain unmerged until fixed and regression-tested. Local reproducible artifacts: target/issue359/pr627-probe.sh and pr627-repro.json in the Niubash coordinator workspace. No production code or task branch changed.

…tes (#616)

Phase 1a kept the structured indexed cell in lockstep with the `PREFIX(...)`
mirror on every write, but the sync re-parsed the render and rebuilt the
whole cell. The compound-append path (`a+=(...)` in a loop) therefore copied
every element once per iteration -- work the pre-#616 baseline never did --
and the compound battery regressed to 0.84x at n=2000 and 0.73x at n=4000.

GNU never re-serialises on append: array.c:516 array_insert() appends to the
ARRAY's element list and array.h:121 counts it. Mirror that: when the parsed
map is an extension of the current cell, copy only the appended tail
(`extend_indexed_array_from_parsed`, O(tail log n)) and skip the rebuild.

The retained prefix is verified key-by-key before the fast path is taken, so
the cell is still exactly the parsed render -- a cache refresh, never a
second source of truth. Any other shape (shrink, mid-array edit, absent
cell, readonly) returns false and takes the unchanged full path, which is
also what drops a refused cell.

Also reuse the memoised parse directly (`indexed_array_entries_cached`, one
Arc copy) instead of `indexed_array_entries` followed by a second deep copy
inside `sync_typed_indexed_array`.

Measured (order-rotated best-of-9, release, same working tree, local bash
5.3.20): cmp2000 2002->2015ms (0.99x), cmp4000 8108->8132ms (1.00x),
cmp_literal2000 2030->2012ms (1.01x), elem2000_ctl 2049->59ms (34.7x).

The harness now rotates the shell order per round: the device throttles and
the same binary measured 1.14x slower simply for running later in the round,
which an always-last branch reports as a phantom regression.

Gates: lib 581/581; array_store_parity green with the store on and off;
cli_tests red-set and executor_tests failure-set identical to master
(6daf8e1); 2500-seed differential fuzz branch==master 0/2500.
The harness always ran bash, master, branch in that order. This host
throttles, and the same binary measures 1.14x slower merely for being invoked
later in a round (measured directly, same binary in positions 1 and 3), so
"branch last" carried a phantom ~10-15% penalty. The harness now rotates the
shell order per round and takes each shell's best from comparable positions.

The visible casualty was 19_arrcopy, which read "1.1x branch faster" under one
ordering and "0.8x branch slower" under another; it is 1.0x. The table is
replaced with the current nine-case battery measured order-rotated
best-of-5 on this branch, plus the master-unreachable length-read construct,
which an ordering bias cannot flatter.

The corrected rows also record the two regressions this branch introduced and
removed within itself -- the element write rebuilding the structured cell, and
the compound append rebuilding it -- since both were found by refusing to
report a number until every write path had been measured.
@caomengxuan666

Copy link
Copy Markdown
Member Author

Follow-up after syncing current master 12da0b5 (Niubash6295367): the previously reported PR627 unset-all regression is STILL reproducible in the latest product build.

Using the original script file target/issue359/pr627-probe.sh: initialize three indexed elements; unset a[@]; print length; repeat with a[*].

RUBASH_ARRAY_STORE=1: stdout 3 then 3, rc0, empty stderr.
RUBASH_ARRAY_STORE=0: stdout 0 then 0, rc0, empty stderr.
Designated GNU5.3.0 had already returned 0 then 0 for this same script in the original review. Current unset_arrays.rs flush branch still updates env_vars and returns without synchronizing the typed cell.

The existing array_store_parity (2 harness tests) and issue631 regression (9 tests) both pass, so those suites do not cover this omission. This is an outstanding correctness blocker, not an integration/text conflict; please do not treat phase1a/1b/1c merges or their benchmarks as proving all write routes correct.

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