Skip to content

fix: let regular builtins see their prefix assignments - #353

Open
ferdingler wants to merge 3 commits into
strands-agents:mainfrom
ferdingler:fix/308-prefix-assign-builtins
Open

ferdingler wants to merge 3 commits into
strands-agents:mainfrom
ferdingler:fix/308-prefix-assign-builtins

Conversation

@ferdingler

Copy link
Copy Markdown
Collaborator

Description

A prefix assignment in front of a builtin was ignored, so IFS=, read x y still split on whitespace and gave [a,b][] instead of bash's [a][b]. It also went the other way: v=tmp read v left the read value behind, where bash puts the old v back.

Now a regular builtin sees its prefix assignments, exported, for that one command, and the previous values (and export state) come back when it finishes. Special builtins like export, eval and : are left alone on purpose; they behave differently and need their own fix.

I added a differential case for the split, the restore, and a later read using the default IFS again. On main it failed on those lines, and with the change it passes along with the full test suite. An older IFS== read case that was marked as a known difference now matches bash, so I dropped its marker. A fix for #343 is changing read itself; this one only touches where builtins are dispatched, so they shouldn't conflict.

Related Issues

Fixes #308

Documentation PR

N/A

Type of Change

Bug fix

Testing

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

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

Approve. The fix does what #308 asks and matches bash 5.2.15 on the common idioms (IFS=, read x y, while IFS=: read -r k v, HOME=/x cd). Two 🟡 inline, both regressions on rare inputs, so neither blocks; a follow-up is fine.

Pass Result
Correctness 🟡 a builtin's own write to a prefix variable is undone or leaks (local, getopts, cd, builtin unset)
Adversarial (bash / base / head) 🟡 dropping Shell::run() mid-builtin leaves the prefix set and exported
Tests cargo test --workspace --all-targets at a11b2bf: 2733 passed, 0 failed. The new case fails on dbb6189 and passes on head
API not run: no public surface change (is_exported is pub(crate))
What I verified, test gaps, appendix

Verified (head a11b2bf, base dbb6189, Debian 12 aarch64, debug builds, every script also run through bash 5.2.15)

  • Both #308 repros: base [a,b][] / [a][b], head and bash [a][b] / [a b][].
  • prefix_assignment_regular_builtin.expected equals what bash prints under the README's recording environment. Removing the known-difference marker from read_ifs_fields.sh is right: base prints k1=v1 -> , head and bash k1 -> v1.
  • Restore holds for: IFS previously unset, set or exported; x=1 x=2 true; a failed redirect (x=1 read v < /nonexistent); a failing builtin; set -e; an EXIT trap; x=1 true &; the shell's own timeout (cooperative, so the restore runs).
  • Export state is put back in both directions. x=1 command sh -c 'echo $x' sees the value once.
  • Also fixed by this PR: readonly r=1; r=2 true now reports r: readonly variable as bash does, and x=1 xargs sh -c … passes x to the child.
  • Pipeline stages (x=1 printf … | cat) are unchanged from base.
  • Not run: pytest tests/python, npm test (bindings untouched; CI is green on both), cargo fmt, cargo clippy.

Test gaps (non-blocking): the new case covers read and true only. Nothing covers a builtin that writes its own prefix variable (the first inline finding), the export flag after restore, or the redirect-failure return at src/exec.rs:3974.

Appendix: pre-existing, same on base

  • VAR=x func ignores the prefix when the command is a shell function. Filed #361.
  • x=1 eval …, x=1 . file and x=1 source file don't see the prefix. The PR description already calls out special builtins; not filed.
  • A function named like a builtin (cd() { … }) is ignored and the builtin runs. Unrelated to this change; not filed.

Comment thread src/exec.rs Outdated
// A regular builtin sees its prefix assignments, exported, for this command
// only; the previous values come back when it ends.
let mut saved_env = Vec::new();
if !is_special(&name) {

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.

🟡 A builtin's own write to a prefix variable is undone, or leaks out of a function

The restore puts the old value back even when the builtin itself wrote that variable. For read that matches bash (v=tmp read v). For local, getopts, cd and builtin unset, bash keeps the write, and so did the base commit, since it ignored the prefix.

local is the worst case: x=g; f() { x=1 local x=2; echo "in:$x"; }; f; echo "after:$x" prints in:g after:1 here, and in:2 after:g in bash and on base. declare_local (src/os.rs:1036) records the temporary 1 as the outer value, so when f returns the global x becomes 1 and stays that way for the rest of the session.

All of these need a prefix naming a variable the builtin writes, which is rare, so this is non-blocking.

Suggestion: keep these on the old path. Skip the prefix for local and for builtin <special builtin>, and leave out of saved_env the names cd (PWD, OLDPWD) and getopts (OPTIND, OPTARG, its name argument) write. I haven't run that change. Restoring only when the value is unchanged would break the read case.

Reproduction details

Head a11b2bf, base dbb6189 (cargo build, debug), bash 5.2.15, Debian 12 aarch64. Each script run as <shell> -c '<script>' in an empty directory; all exit 0.

Script bash and base head
x=g; f() { x=1 local x=2; echo "in:$x"; }; f; echo "after:$x" in:2 after:g in:g after:1
f() { IFS=, local IFS; }; f; echo "IFS exported: $(env | grep -c "^IFS=")" 0 1
set -- -a -b x; OPTIND=1 getopts ab: o; echo $o; getopts ab: o; echo $o a b a a
cd /; cd /usr; PWD=/usr OLDPWD=/etc cd /tmp; echo "PWD=$PWD OLDPWD=$OLDPWD" PWD=/tmp OLDPWD=/usr PWD=/usr OLDPWD=/
x=0; x=1 builtin unset x; echo "x=${x-unset}" x=unset x=0

Controls that match bash on head: local OPTIND=1 o; while getopts ab o "$@"; … inside a function, v=tmp read v, HOME=/usr cd.

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 the local case in 114b758: local keeps the old path and no longer takes the prefix, so x=1 local x=2 inside a function prints in:2 after:g again. A new differential case covers it; it fails without the guard and passes with it. I left getopts, cd and builtin unset alone. Deciding which builtins keep their own writes to a prefix variable is a behavior call, so that goes to Fernando as a follow-up.

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.

local is fixed at 114b758: the three local repros match bash and base again, and prefix_assignment_local fails on a11b2bf and passes here.

Still reproducing at 114b758, so I'm leaving this open for the follow-up decision: the getopts, cd and builtin unset rows above, plus one way around the new guard. x=g; f() { x=1 builtin local x=2; echo "in:$x"; }; f; echo "after:$x" prints in:g after:1 (bash and base: in:2 after:g), because the guard compares the name builtin, not the builtin it runs. x=1 command local x=2 is fine.

Comment thread src/exec.rs
}),
)
.await;
restore_env(shell_proc, saved_env);

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.

🟡 A cancelled run() leaves the prefix assignment set and exported for the rest of the session

This restore only runs if the builtin's future completes. A Rust caller that drops Shell::run() while a prefixed builtin is still running in the top-level shell keeps the temporary value: after tokio::time::timeout(100ms, shell.run("LC_ALL=C xargs sleep < /tmp/n")) expires, the next run() sees LC_ALL=C, exported. On base it is unset. The repo already treats a dropped run() followed by another call as supported (cancelling_wait_stops_a_background_pipeline, and the errexit_ignored reset at src/shell.rs:421).

Reach is narrow: read inside a pipeline stage runs in a fork and doesn't leak, and the shell's own timeout is cooperative and restores. The Node binding runs each job to completion; I didn't test Python-side interruption.

Suggestion: keep the saved values on Process and undo them at the top of Shell::run / execute, next to the errexit_ignored reset, or restore from a drop guard. I haven't run either.

Reproduction details

Head a11b2bf and base dbb6189, Debian 12 aarch64, Rust 1.100.0. Temporary file tests/zz_cancel353.rs in each tree, run with cargo test --test zz_cancel353 -- --nocapture, then deleted.

use strands_shell::Shell;

#[test]
fn cancelled_prefix_builtin() {
    for script in [
        "echo 1 > /tmp/n353; LC_ALL=C xargs sleep < /tmp/n353",
        "sleep 1 & IFS=, wait",
        "f() { IFS=, read x y; }; sleep 1 | f",
    ] {
        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        let local = tokio::task::LocalSet::new();
        rt.block_on(local.run_until(async {
            let mut shell = Shell::builder().build().unwrap();
            let cancelled =
                tokio::time::timeout(std::time::Duration::from_millis(100), shell.run(script)).await;
            let after = shell
                .run("echo \"IFS=[${IFS-unset}] LC_ALL=[${LC_ALL-unset}] exported=$(env | grep -c -e ^IFS= -e ^LC_ALL=)\"; v='a b'; set -- $v; echo \"fields=$#\"")
                .await;
            println!("{script:?} cancelled={} -> {:?}", cancelled.is_err(), after.stdout);
        }));
    }
}
Script (cancelled at 100 ms) base, next call head, next call
LC_ALL=C xargs sleep < /tmp/n353 LC_ALL=[unset] exported=0 LC_ALL=[C] exported=1
sleep 1 & IFS=, wait IFS=[unset] exported=0, fields=2 IFS=[,] exported=1, fields=1
f() { IFS=, read x y; }; sleep 1 | f (control) IFS=[unset] exported=0 IFS=[unset] exported=0

The test passed (it only prints) in both trees; all three calls were cancelled.

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.

Leaving this one for Fernando. Fixing it means deciding where the temporary values live (on the process and undone at the next run, or a drop guard), and that is a design call beyond this fix. No code change here.

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

Still approve, now at 114b758. The new commit fixes the local leak and nothing else changed.

Earlier finding Status
🟡 Builtin's own write to a prefix variable is undone or leaks local fixed and verified. getopts, cd and builtin unset still reproduce (deferred by the author), and the leak is still reachable as x=1 builtin local x=2. Details in the thread.
🟡 Cancelled run() leaves the prefix set Open, deferred by the author. No change.

Neither blocks. The deferred items have no tracking issue yet.

What I verified
  • Head 114b758, previous head a11b2bf, base dbb6189, bash 5.2.15, Debian 12 aarch64, debug builds.
  • x=g; f() { x=1 local x=2; echo "in:$x"; }; f; echo "after:$x": in:2 after:g on 114b758, base and bash; in:g after:1 on a11b2bf.
  • f() { IFS=, local IFS; }; f: IFS is no longer exported or set afterwards. f(){ x=1 local x; }; f no longer leaves x=1 behind.
  • prefix_assignment_local.expected equals what bash prints. The case fails on a11b2bf and passes on 114b758.
  • The #308 repros and v=tmp read v still match bash.
  • cargo test --workspace --all-targets at 114b758: 2733 passed, 0 failed. Differential: 110 cases passed, 16 known differences.
  • CI: macOS and Windows Rust jobs, one Windows Python job and the security audit were still running when I looked. The red rollup came from two superseded, cancelled 2 Approvers for Bots runs.
  • Not run: pytest tests/python, npm test, cargo fmt, cargo clippy.

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

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] IFS=… read ignores the prefix assignment (builtins don't see VAR=x builtin env)

2 participants