Repository navigation
perf(array): O(1) ${#a[@]} via the typed indexed cell, zero behaviour change (#616 Phase 1a) - #627
Conversation
…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).
|
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. |
|
Independent static review of head 6b752f4 found a likely merge-blocking synchronization omission (not yet dynamically reproduced):
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. |
|
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[*].
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.
|
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. 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. |
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-629maintainmax_index/num_elements).a[100]=x→${#a[@]} == 1).Rubash renders arrays to a string in
ShellState.env_vars, so every length readhad 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: VariableStoreandenv_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
IndexedArraycell is the O(1) count(
BTreeMap::len(); no separatenum_elementsfield needed, unlike GNU'slinked list).
env_varsstays the projection all storage readers see.Invariant: a structured cell is either a complete mirror of the same
indexed_array_entriesparse the render uses, or absent. Writes always syncor drop; only reads consult the gate. A refused (readonly) typed write drops
the cell instead of shadowing the mirror.
RUBASH_ARRAY_STORE=0disables thestructured reads as a global escape hatch. Assoc is out of scope.
Commits
87bcc51,a907d09— the cell, plus the in-place single-key elementextension (the first revision rebuilt the whole
BTreeMapper element write).1b2c248— incremental cell refresh. The sync rebuilt the whole cell onevery write, so the compound append (
a+=(...)in a loop) copied the wholearray per iteration — work pre-[perf][P1] Array mutation is O(n²) and ${#arr[@]} is O(n): a[i]= / a+=() 39-666× slower, length query ~230× — dual-store capture-replay replays per element write #616 never did. Now, when the parsed map is a
verified extension of the current cell, only the appended tail is copied
(
extend_indexed_array_from_parsed), so it stays exactly the parsed render.GNU does the same:
array_insertappends to theARRAYobject and neverre-serialises.
6b752f4,0d82f3a— the durable write-up, then the measurement correction.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_arrcopyread0.8x branch slowerhere and1.1x branch fasterelsewhere, for code that is 1.0x. The harness now rotates theshell 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.
${#s}control (200k)build10kcompound +${#a[@]}${#a[@]}15_arrbuildn=200015b_arrbuildn=1000015c_arrbuild_compoundn=200016_arritern=200019_arrcopyn=2000comboundedit(write+len)No row regresses.
comboundedit's 2.3x is this PR's own win (it is dominated by2000
${#a[@]}reads that stop parsing the render).The marquee construct — the fixed cost being removed (measured with the earlier
non-rotated protocol; an
NAcannot be flattered by ordering):${#a[@]}${#a[@]}The branch is the only build that completes.
15_arrbuildis still ~64x GNU because the per-element render is quadratic, andthe write path is deliberately untouched here — Phase 1b (stacked on this
branch) takes it.
Gates
tests/array_store_parity.rs(38 GNU-verified cases) green with the storeon and off;
cli_testsred set name-identical to master in the same tree (1pre-existing failure);
executor_testsfailure set identical to master (1229, set-compared);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 -vincomplete rebuild; readonlyread -astale 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.