Skip to content

feat: add $RANDOM - #275

Open
ferdingler wants to merge 2 commits into
strands-agents:mainfrom
ferdingler:feat/random-variable
Open

ferdingler wants to merge 2 commits into
strands-agents:mainfrom
ferdingler:feat/random-variable

Conversation

@ferdingler

@ferdingler ferdingler commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Description

$RANDOM expanded 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 RANDOM seeds 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:

  • $RANDOM in 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 RANDOM and local RANDOM don't turn it into a normal variable, and RANDOM+=1 doesn't add to the current value.
  • The seed is read as a plain integer rather than an arithmetic expression, so seeds past the 64-bit range seed 0.
  • It doesn't show up in env after export 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.

  • I ran the relevant test suites for the bindings I touched (cargo test --workspace --all-targets, pytest tests/python, npm test)
  • If I touched Rust, I ran cargo fmt and cargo clippy

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

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
@ferdingler
ferdingler requested a review from a team as a code owner November 13, 2026 05:12
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent Please review this PR

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 $RANDOM comes from the parent's generator, not a fresh one (inline). It's out of scope to fix, but worth a known-difference case.
✅ What I verified
  • SHA 882bd0b. cargo test --workspace --all-targets: 2573 passed, 0 failed. cargo fmt --check is clean. cargo clippy: 19 warnings, none on lines this PR touches.
  • I compared about 75 one-liners between this PR's strands-shell and 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 on main too (let, ((, declare, [[, <<<, ${x:0:2}, ${!r}).
  • I ran a C sweep of every u32 seed, comparing bash's int32 intrand32 with the i64 version here: 0 mismatches. The u32 truncation matches bash for i64::MIN, -1, 2³¹±1, 2³², and i64::MAX. bash 5.2's sbrand also resets last_random_value, so resetting last: 0 on reseed is correct.
  • next_random does a Relaxed load then a store, which isn't one atomic step. That's safe here: Process only runs behind &mut on a LocalSet, and there's no .await between the load and the store.
  • I wasn't able to build wasm32-wasip2. RandomState and SystemTime are both available on that target.
Appendix: non-blocking (5)
  • ⚪ RANDOM=42; RANDOM+=1 seeds with 1 (PR prints 16807, bash 1798). assignment() reads the old value with proc.env.get (src/exec.rs:609), but RANDOM is never stored in env. 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 <<EOF with $RANDOM as the body gives a random value and leaves the parent's sequence where it was. bash gives 17772 and moves the sequence on. Cause: apply_redirects runs on io_proc = proc.fork() (src/exec.rs:1697, :2921).
  • ⚪ local RANDOM=5 reseeds the global generator. bash makes a plain local variable instead (prints 5).
  • ⚪ Seeds outside the i64 range seed 0. bash wraps them (RANDOM=18446744073709551615 gives 16807 in bash, 20814 here). Rare.
  • ⚪ Nothing tests the set -u exemption at src/exec.rs:1392. Adding set -u at the top of random_range.sh would cover it, and the expected output stays done.
Reading order

src/os.rs RandomGen, then set_env/seed_random/fork, then src/exec.rs resolve_var, then the tests.

Comment thread src/exec.rs
"$" => 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()),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 ${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 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/os.rs
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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@ferdingler

Copy link
Copy Markdown
Collaborator Author

Thanks. On the appendix: I added set -u to random_range.sh to cover the exemption. RANDOM+=1, local RANDOM, the here-doc case and seeds past the 64-bit range are now listed as omissions in the description rather than fixed here.

This branch has not been deployed

No deployments
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.

2 participants