Skip to content

fix(parameter_errors): judge the scalar form bound by element 0 (#638) - #640

Merged
caomengxuan666 merged 2 commits into
masterfrom
fix/issue618-nounset-array-boundness
Oct 16, 2026
Merged

caomengxuan666 merged 2 commits into
masterfrom
fix/issue618-nounset-array-boundness

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Fixes #638.

The problem

Under set -u, the scalar form of an array or associative array
(${a} / ${m}) was judged wrong in both directions:

declare -A m=([k]=v); unset "m[k]"; set -u; printf 'x[%s]\n' "$m"
  master: x[]                 (status 0 — a silent data difference)
  GNU   : m: unbound variable (status 127)

set -u; declare -A m; m[0]=v; echo "[${m}]"
  master: m: unbound variable (status 127 — GNU runs fine)
  GNU   : [v]                 (status 0)

declare -p, ${#m[@]} and ${m[@]} were all correct in the same probes,
so the divergence was specific to this one test.

What GNU does

The scalar form resolves through element/key 0, not through "does this
array have any element":

/* subst.c:7787-7790 parameter_brace_expand_word() */
else if (assoc_p (var))
    temp = assoc_reference (assoc_cell (var), "0");
else if (array_p (var))
    temp = array_reference (array_cell (var), 0);

array.c:657 array_reference() and assoc.c:120 assoc_reference() return
NULL when that element is absent, and subst.c:10162-10169 parameter_brace_expand() then raises err_unboundvar (error.c:448) — with
all_element_arrayref exempting the @/* forms, which is why an array
holding only element 3 is unbound for ${a} yet bound for ${a[@]}.

Two defects behind it

  1. The rule. nounset_variable_bound tested !entries.is_empty() —
    "has any element" — for IndexedArray and AssociativeArray alike, and
    in the mirror fallback too.

  2. The assoc typed cell is never kept in step. It is created only by
    declare/typeset (builtins/declare.rs:105, :193) and
    printf -v m[k] (builtins/printf.rs:365). Every later mirror write —
    m[k]=v, unset "m[k]", m=(...), m+=(...), ${!name[k]},
    wait-bound assoc variables, export/readonly — updates only the
    mirror string in env_vars. The indexed side has a sync family for
    exactly this (arrays/storage.rs:390 sync_typed_indexed_storage, :321 sync_typed_indexed_element); there is no assoc counterpart. So
    declare -A m left an empty cell behind that outlived m[0]=v, and
    unset "m[k]" left a cell still holding k.

    The value read comes from the mirror
    (variable_state.rs:462-470 scalar_parameter_value →
    assoc_value_at(storage,"0") / array_value_at(storage,0)), so the stale
    cell let boundness disagree with the very value it was guarding.

The fix

Change the invariant at the reader rather than wiring a drop into every one of
the ~12 writers — a writer list can never be proven complete, and its next
omission would silently reintroduce the class. The mirror decides, through
those same two helpers, so boundness and value agree by construction and a
future writer cannot break the pair. The rule itself becomes
contains_key(0) / contains_key("0") in every half.

The typed cell stays authoritative for scalars, where it is complete by
construction, and is still consulted for unmarked arrays. Both parses are
content-addressed memos (arrays/storage.rs:64, assignment_helpers.rs:491)
and the value read performs the same one, so this costs a cache hit rather
than a re-parse — the indexed set -u path keeps its O(1) shape.

Verification

  • 40-case GNU differential: 39 byte-identical on stdout, stderr and
    status. The single remaining difference is set -u: an arithmetic array subscript is expanded without the nounset check #639 — an arithmetic subscript
    never runs the nounset check, so GNU fails during the assignment instead.
  • tests/issue638_nounset_array_boundness.rs 20/20, covering both
    directions across declare/bare/compound/+=/unset/printf -v writers,
    plus the controls that must not move: ${a[@]}, ${a[i]}, an empty-string
    element 0 (existence, not truthiness), x='()' as a scalar (rubash#311),
    declare -A scalar→assoc conversion, ${#m[@]}, declare -p, and the
    unmarked m[k]=v → indexed dispatch.
  • cargo test --lib 584/584; cargo fmt --check clean.
  • Serial failure-set ratchet vs 12da0b5 (~/bench_niu/ratchet.sh):
    cli_tests 1=1 with NEW=0; executor_tests 1173=1173 with 1 NEW /
    1 DISAPPEARED, both in the known-nondeterministic command_chaining::part_080
    coproc family — all pass in isolation on both sides, so host timing.
  • Serial full-suite gate (cargo test --no-fail-fast -- --test-threads=1,
    one cargo at a time, both trees, failure-set diff — never counts):
    branch 246 ok / 26 failing targets, master 245 ok / 26 failing targets, and
    the failing-target sets are identical (NEW=0, DISAPPEARED=0). All 26
    shared failing targets even match per-target (executor_tests 1172=1172,
    issue555_file_builtin_family_regressions 11=11, regression 8=8, …) and
    are pre-existing Android-host environment reds ([test][platform:linux] 24 cli_tests red on Android unmasked by #613 (fail-fast hid them behind the lib failures): 13 missing bashdb fixture, 6 Windows-hardcoded expectations, 3 host-tool assumptions, 2 to triage #615). Branch has exactly one
    more ok target — the new issue638_nounset_array_boundness. At the test
    level the only NEW rows (2) and DISAPPEARED rows (2) are all in
    command_chaining::part_080, and all four pass in isolation on both
    trees
    , so host scheduling, not a regression.
  • Nounset/array-focused targets: issue311_nounset_pattern_regressions 9/9,
    issue535_redirect_nounset_regressions 12/12, array_store_parity 2/2,
    array_compound_quote_regressions 13/13,
    arrdefault_quoted_array_default_regressions 10/10,
    issue148_glob_in_compound_array_assignment 15/15.
  • issue298_299_array_fieldsplit_regressions (1) and parameter_transform_tests
    (4) fail identically on master — same failure names, verified as a set
    diff rather than by count — so they are pre-existing and out of scope here.

Attribution for #618

Found while surveying the assoc typed-cell invariant for #618. The same
harness re-measured the assoc write path on 12da0b5: m[k$((i%100))]=$i at
N=200000 is 18.3x GNU (16.830s vs 0.921s, min-of-3 with the shell order
rotated per round), and scaling the key count shows the mechanism — the
per-write cost tracks the number of keys because every write re-renders the
whole mirror (assignment_helpers.rs:345 format_assoc_storage):

keys K GNU rubash ratio
10 0.007s 0.008s 1.1x
100 0.007s 0.013s 1.9x
1000 0.011s 0.242s 22x
5000 0.025s 5.574s 223x

That O(keys)-per-write structure is what #618's perf phase has to remove; this
PR only makes the correctness half hold, and does not touch the write path.
The indexed side shows the same shape far more sharply (908x at K=5000), which
is #616's next phase.

Caveat: local bash is 5.3.20 while the repository oracle is WSL bash 5.3.0;
every rule above is taken from the vendored 5.3 C source cited, not from a
version's observed output.

The durable write-up is in docs/perf-issue-616-array-store.md.

Under `set -u` the scalar form of an array or associative array was judged
wrong in BOTH directions:

    declare -A m=([k]=v); unset "m[k]"; set -u; printf 'x[%s]\n' "$m"
      master: x[]                     (status 0 — a silent difference)
      GNU   : m: unbound variable     (status 127)

    set -u; declare -A m; m[0]=v; echo "[${m}]"
      master: m: unbound variable     (status 127 — GNU runs fine)
      GNU   : [v]                     (status 0)

GNU resolves the scalar form through element/key "0":

    /* subst.c:7787-7790 parameter_brace_expand_word() */
    else if (assoc_p (var))
        temp = assoc_reference (assoc_cell (var), "0");
    else if (array_p (var))
        temp = array_reference (array_cell (var), 0);

`array.c:657 array_reference()` and `assoc.c:120 assoc_reference()` return NULL
when that element is absent, and `subst.c:10162-10169 parameter_brace_expand()`
then raises `err_unboundvar` (`error.c:448`) — with `all_element_arrayref`
exempting `${a[@]}`, which is why an array holding only element 3 is unbound
for `${a}` yet bound for `${a[@]}`.

rubash's rule was `!entries.is_empty()`: "the cell holds any element". That is
wrong for `ShellValue::IndexedArray` and `ShellValue::AssociativeArray` alike
(`a=([3]=x)`, `a=(x y)` after `unset "a[0]"`, `m=([k]=v)`), and for the mirror
fallback too.

Behind it sat a second defect. The assoc typed cell is created only by
`declare`/`typeset` (`builtins/declare.rs:105`, `:193`) and `printf -v m[k]`
(`builtins/printf.rs:365`); every later mirror write — `m[k]=v`,
`unset "m[k]"`, `m=(...)`, `m+=(...)`, `${!name[k]}`, `wait`-bound assoc
variables, `export`/`readonly` — updates only the mirror string in `env_vars`.
The indexed side has a sync family for exactly that
(`arrays/storage.rs:390 sync_typed_indexed_storage`, `:321
sync_typed_indexed_element`); there is no assoc counterpart. So `declare -A m`
left an EMPTY cell behind that outlived `m[0]=v`, and `unset "m[k]"` left a
cell still holding `k`. Because the *value* read comes from the mirror
(`variable_state.rs:462-470 scalar_parameter_value` →
`assoc_value_at(storage, "0")` / `array_value_at(storage, 0)`), the stale cell
let boundness disagree with the very value it was guarding.

Rather than wiring a drop into every one of the ~12 writers — which can never
be proven complete, and whose next omission would silently reintroduce the
class — this fixes the invariant at the reader: the MIRROR decides, through
those same two helpers, so boundness and value agree by construction. The
typed cell stays authoritative for scalars (where it is complete by
construction) and is still consulted for unmarked arrays; the rule itself
becomes `contains_key(0)` / `contains_key("0")` in every half. Both parses are
content-addressed memos (`arrays/storage.rs:64`, `assignment_helpers.rs:491`)
and the value read performs the same one, so this costs a cache hit rather
than a re-parse and the indexed `set -u` path keeps its O(1) shape.

Verification: 40-case GNU differential — 39 byte-identical (stdout, stderr and
status); the single remaining difference is #639, where an arithmetic
*subscript* never runs the nounset check at all and GNU fails during the
assignment instead. Previously-green probes unchanged: `${a[@]}`, `${a[i]}`,
an empty-string element 0 (existence, not truthiness), `x='()'` as a scalar
(rubash#311), `declare -A` scalar→assoc conversion, `${#m[@]}`, `declare -p`,
and the unmarked `m[k]=v` → indexed dispatch.
`tests/issue638_nounset_array_boundness.rs` 20/20; `cargo test --lib` 584/584;
serial failure-set ratchet vs `12da0b5` clean.
…ess fix

`errors5.sub` sets `array[1]`/`array[2]`, then `set -u`, then runs
`( echo ${array} )`. Under the old `!entries.is_empty()` rule that scalar
form was judged bound because the array was non-empty, so rubash printed a
blank line where GNU prints `array: unbound variable` — the silent data
difference #638 was filed for.

`fix(parameter_errors): judge the scalar form bound by element 0 (#638)`
makes that line take the unbound path, so the blank line leaves stdout and
`errors5.sub:7` now matches GNU. Only `errors.snap` moves; the other 12
snapshots are byte-identical (verified against the CI-recorded
`regression-snapshots` artifact, which this bytes set is taken from per the
re-record protocol in the tests/regression.rs module header).

GNU reference (vendored third_party/bash): subst.c:7787-7790
parameter_brace_expand_word resolves the scalar form through element/key 0;
array.c:657 array_reference returns NULL when it is absent.
@caomengxuan666
caomengxuan666 merged commit ce471a2 into master Oct 16, 2026
6 checks passed
@caomengxuan666
caomengxuan666 deleted the fix/issue618-nounset-array-boundness branch October 16, 2026 00:46
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.

set -u: the scalar form of an array/assoc is bound by element 0, not by "any element"

1 participant