Repository navigation
feat: add $RANDOM - #275
ferdingler wants to merge 2 commits into
Conversation
Each expansion of $RANDOM gives a value from 0 to 32767, and assigning to it seeds the generator. The generator follows bash's, so a seeded script prints the same sequence it prints under bash. Subshells reseed so they don't repeat the parent's values. Part of strands-agents#207
|
@strandly-the-agent Please review this PR |
strandly-the-agent
left a comment
There was a problem hiding this comment.
Verdict: approve. Nothing blocks this; there are two 🟡 notes where seeded output stops matching bash. @ferdingler
The generator is right. A sweep of all 2³² seeds against bash's intrand32 found no mismatches. Seeding, $(…)/( … )/& reseeding, functions, groups and loops with redirects, eval, ., set -u and $((RANDOM % n)) all match bash 5.2.15. Tests, fmt and clippy are clean (the clippy warnings are pre-existing and outside the diff).
- 🟡
${RANDOM-word}and${RANDOM:-word}draw two values. This one has a 4-line fix (inline). - 🟡 In a pipeline, a simple-command stage's
$RANDOMcomes from the parent's generator, not a fresh one (inline). It's out of scope to fix, but worth aknown-differencecase.
✅ What I verified
- SHA
882bd0b.cargo test --workspace --all-targets: 2573 passed, 0 failed.cargo fmt --checkis clean.cargo clippy: 19 warnings, none on lines this PR touches. - I compared about 75 one-liners between this PR's
strands-shelland bash 5.2.15 (probes). Every difference other than the two 🟡s is either already listed in the PR body or a feature that's missing onmaintoo (let,((,declare,[[,<<<,${x:0:2},${!r}). - I ran a C sweep of every u32 seed, comparing bash's int32
intrand32with the i64 version here: 0 mismatches. The u32 truncation matches bash for i64::MIN, -1, 2³¹±1, 2³², and i64::MAX. bash 5.2'ssbrandalso resetslast_random_value, so resettinglast: 0on reseed is correct. next_randomdoes a Relaxed load then a store, which isn't one atomic step. That's safe here:Processonly runs behind&muton a LocalSet, and there's no.awaitbetween the load and the store.- I wasn't able to build wasm32-wasip2.
RandomStateandSystemTimeare both available on that target.
Appendix: non-blocking (5)
- ⚪
RANDOM=42; RANDOM+=1seeds with 1 (PR prints 16807, bash 1798).assignment()reads the old value withproc.env.get(src/exec.rs:609), butRANDOMis never stored inenv. You could add this to the list of omissions in the PR body. - ⚪ A here-doc on a builtin expands in a freshly seeded fork.
RANDOM=42; read x <<EOFwith$RANDOMas the body gives a random value and leaves the parent's sequence where it was. bash gives17772and moves the sequence on. Cause:apply_redirectsruns onio_proc = proc.fork()(src/exec.rs:1697,:2921). - ⚪
local RANDOM=5reseeds the global generator. bash makes a plain local variable instead (prints5). - ⚪ Seeds outside the i64 range seed 0. bash wraps them (
RANDOM=18446744073709551615gives 16807 in bash, 20814 here). Rare. - ⚪ Nothing tests the
set -uexemption atsrc/exec.rs:1392. Addingset -uat the top ofrandom_range.shwould cover it, and the expected output staysdone.
Reading order
src/os.rs RandomGen, then set_env/seed_random/fork, then src/exec.rs resolve_var, then the tests.
| "$" => Some(proc.pid.to_string()), | ||
| "!" => proc.last_bg_pid.map(|p| p.to_string()), | ||
| "#" => Some(proc.args.len().to_string()), | ||
| "RANDOM" => Some(proc.next_random().to_string()), |
There was a problem hiding this comment.
🟡 ${RANDOM-word} and ${RANDOM:-word} use up two values, so seeded output stops matching bash.
RANDOM=42; echo ${RANDOM:-z}; echo $RANDOM
bash: 17772 26794
PR: 26794 1435
In expand_part_split, uses_alternate_word calls resolve_var (src/exec.rs:598), and then line 568 calls it again for the value. That was harmless before, but now every lookup advances the generator. ${RANDOM+x} is fine because it only looks once.
Suggestion: look the variable up once and pass the value in. With this patch both forms match bash, and shell_integration and differential still pass (1967 tests).
patch
- if uses_alternate_word(proc, name, op, *colon) {
+ let val = resolve_var(proc, name);
+ if uses_alternate_word(val.as_deref(), op, *colon) {
...
} else if op == "-"
- && let Some(v) = resolve_var(proc, name)
+ && let Some(v) = val
...
-fn uses_alternate_word(proc: &Process, name: &str, op: &str, colon: bool) -> bool {
- let is_unset_or_null = match resolve_var(proc, name) {
+fn uses_alternate_word(val: Option<&str>, op: &str, colon: bool) -> bool {
+ let is_unset_or_null = match val {There was a problem hiding this comment.
Fixed in 20ca036 with your suggestion: the variable is looked up once. The seeded differential case now covers ${RANDOM:-z} and "${RANDOM-z}" and matches bash.
| host_writes: self.host_writes.clone(), | ||
| background_owner: self.background_owner.clone(), | ||
| in_background_job: self.in_background_job, | ||
| // A subshell draws its own values, as in bash, rather than repeating its parent's. |
There was a problem hiding this comment.
🟡 In a pipeline, a simple-command stage takes $RANDOM from the parent's generator, not a fresh one.
RANDOM=42; echo $RANDOM | cat; echo $RANDOM
bash: <random> 17772
PR: 17772 26794
run_pipeline expands each stage's arguments on shell_proc before it forks the stages (src/exec.rs:3372), so the reseed here never applies to them. f | cat and { …; } | cat are fine. This contradicts the claim that a seeded script prints the same numbers as bash, for any seeded script that pipes $RANDOM.
Fixing it would mean expanding each stage's arguments in its own fork, which is out of scope here. Suggestion: narrow the claim in the PR body, and add a case marked # known-difference: pipeline stages expand in the parent (see tests/differential/README.md:24) so the gap is tracked.
There was a problem hiding this comment.
Agreed, leaving the fix out of this PR. I added random_pipeline_stage as a known-difference case (it pipes $RANDOM to cat >/dev/null so the bash output stays deterministic) and narrowed the claim in the description.
Also track the pipeline-stage difference from bash as a known-difference case, and cover the set -u exemption. Part of strands-agents#207
|
Thanks. On the appendix: I added |
Description
$RANDOMexpanded to nothing, so scripts that use it for retry jitter, temp names or sampling quietly got an empty string.Now each expansion gives a number from 0 to 32767, and assigning to
RANDOMseeds it. It follows bash's generator, so a seeded script mostly prints the same numbers it does under bash. Subshells pick a fresh seed like bash does, so$(echo $RANDOM)doesn't repeat the parent's next value. It only uses the standard library, so it works the same on wasm.I compared it with bash 5.2 for a handful of seeds, including 0, negative numbers and values past 32 bits, and they matched. I added a differential case for seeded output and one that checks the range, plus tests for the seed surviving between runs and subshells getting their own values. The full Rust check passes. I couldn't build the wasm module locally since I don't have wasi-sdk here.
A few bash corners I left out:
$RANDOMin a simple command that's a pipeline stage comes from the parent's sequence instead of a fresh one, because those words are expanded before the stages start. A here-doc on a builtin has the opposite problem. I added a known-difference case for the pipeline one.unset RANDOMandlocal RANDOMdon't turn it into a normal variable, andRANDOM+=1doesn't add to the current value.envafterexport RANDOM.Related Issues
Part of #207
Documentation PR
None
Type of Change
New feature
Testing
How have you tested the change? Verify that the changes do not break functionality or introduce new warnings.
cargo test --workspace --all-targets,pytest tests/python,npm test)cargo fmtandcargo clippyChecklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.