From e298f3428daa5bfaa728f575c762dac07cf427c7 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Mon, 23 Nov 2026 17:26:01 +0000 Subject: [PATCH 1/3] feat: add opt-in execution plans and backend test coverage --- .github/workflows/bash-oracle.yml | 8 +- .github/workflows/ci.yml | 211 ++-- .github/workflows/coverage.yml | 14 +- .github/workflows/fuzz.yml | 49 +- .github/workflows/js.yml | 144 ++- .github/workflows/nightly.yml | 45 +- .github/workflows/python.yml | 32 +- .github/workflows/windows-nightly.yml | 12 +- README.md | 1 + crates/bashkit-capi/Cargo.toml | 4 + crates/bashkit-cli/Cargo.toml | 2 + crates/bashkit-js/Cargo.toml | 4 + crates/bashkit-python/Cargo.toml | 4 + crates/bashkit-scripted-tool/Cargo.toml | 2 + crates/bashkit-wasm/Cargo.toml | 2 + crates/bashkit/Cargo.toml | 4 + crates/bashkit/docs/compatibility.md | 32 + crates/bashkit/docs/threat-model.md | 1 + crates/bashkit/fuzz/Cargo.toml | 11 + .../fuzz/fuzz_targets/script_plan_fuzz.rs | 49 + crates/bashkit/src/interpreter/arithmetic.rs | 3 + .../src/interpreter/arithmetic/program.rs | 335 ++++++ .../src/interpreter/command_dispatch.rs | 320 ++++++ crates/bashkit/src/interpreter/mod.rs | 355 ++----- crates/bashkit/src/interpreter/script_plan.rs | 974 ++++++++++++++++++ crates/bashkit/src/lib.rs | 15 + crates/bashkit/src/limits.rs | 48 + crates/bashkit/tests/proptest_security.rs | 33 + experiments/script-execution-plan/README.md | 27 + justfile | 12 + scripts/build-c-api.sh | 3 + scripts/fuzz-smoke.py | 52 + scripts/tests/test_execution_plan_ci.py | 87 ++ 33 files changed, 2435 insertions(+), 460 deletions(-) create mode 100644 crates/bashkit/fuzz/fuzz_targets/script_plan_fuzz.rs create mode 100644 crates/bashkit/src/interpreter/arithmetic/program.rs create mode 100644 crates/bashkit/src/interpreter/command_dispatch.rs create mode 100644 crates/bashkit/src/interpreter/script_plan.rs create mode 100644 experiments/script-execution-plan/README.md create mode 100644 scripts/fuzz-smoke.py create mode 100644 scripts/tests/test_execution_plan_ci.py diff --git a/.github/workflows/bash-oracle.yml b/.github/workflows/bash-oracle.yml index 39bac1316..235088425 100644 --- a/.github/workflows/bash-oracle.yml +++ b/.github/workflows/bash-oracle.yml @@ -28,9 +28,13 @@ env: jobs: scoreboard: - name: Bash oracle scoreboard + name: Bash oracle scoreboard (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ubuntu-latest timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -43,7 +47,7 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 - name: Build CLI - run: cargo build -p bashkit-cli + run: cargo build --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit-cli - name: Run scoreboard run: python3 scripts/bash-oracle/run.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c9ff27a28..f0785ff60 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -179,13 +179,17 @@ jobs: # COOP/COEP headers and that sync + async execution both work. See # knowledge/runtimes/browser-package.md. Keep wasm-bindgen-cli in lockstep with the # wasm-bindgen version in Cargo.lock. - name: WASM web package + name: WASM web package (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ubuntu-latest # A hung install step here took `main` red twice by burning the 6-hour job # ceiling (see scripts/install-binaryen.sh). This job's slowest healthy run # is well under 10 minutes, so anything past 30 is stuck, not slow — fail # fast and leave a re-runnable red instead of a cancelled run. timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -205,7 +209,7 @@ jobs: run: sudo ./scripts/install-binaryen.sh - name: Build web bundle - run: bash crates/bashkit-wasm/scripts/build.sh release + run: BASHKIT_WASM_FEATURES="terminal,${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" bash crates/bashkit-wasm/scripts/build.sh release - name: Integration tests (headless Node) run: node --test "crates/bashkit-wasm/__test__/*.test.mjs" @@ -219,7 +223,7 @@ jobs: node crates/bashkit-wasm/scripts/test-streaming-browser.mjs - name: Build optional runtime bundle - run: BASHKIT_WASM_VARIANT=runtimes BASHKIT_WASM_FEATURES=terminal,python,typescript bash crates/bashkit-wasm/scripts/build.sh release + run: BASHKIT_WASM_VARIANT=runtimes BASHKIT_WASM_FEATURES="terminal,python,typescript,${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" bash crates/bashkit-wasm/scripts/build.sh release - name: Embedded runtime callback tests run: BASHKIT_WASM_VARIANT=runtimes node --test crates/bashkit-wasm/__test__/runtime-functions.test.mjs @@ -296,7 +300,7 @@ jobs: run: cargo vet --locked test: - name: Test + name: Test (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) # Pinned, not `ubuntu-latest`: this job's `*_match_gnu` differential tests # need real GNU coreutils as the oracle, and 24.04 is the last image that # ships it as the default. Ubuntu 26.04 installs uutils as `coreutils` @@ -305,6 +309,10 @@ jobs: # GNU oracle is installed explicitly, the way `rg` and `jq` already are; # see "Pinned External Oracles" in knowledge/operations/testing.md. runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -358,12 +366,12 @@ jobs: # Examples have a dedicated job below; skipping them here avoids # duplicated example links that can exhaust runner disk on main. - name: Run tests - run: cargo test --workspace --lib --bins --tests --features http_client,ssh,sqlite + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --workspace --lib --bins --tests --features http_client,ssh,sqlite # The registry's Python/TypeScript surfaces sit behind the crate's own # features, which no workspace member turns on together. - name: Run scripted tool tests (shell, Python, TypeScript surfaces) - run: cargo test -p bashkit-scripted-tool --features python,typescript,jq + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit-scripted-tool --features python,typescript,jq # All three differential gates (bash, sed, grep), not just bash: each is # the only thing checking that its spec expectations still describe the @@ -375,19 +383,19 @@ jobs: # workflow file out of service. - name: Run strict host-tool parity gates (bash, sed, grep) run: | - cargo test -p bashkit --test integration --features http_client,ssh -- spec_tests:: --ignored + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test integration --features http_client,ssh -- spec_tests:: --ignored - name: Run competitor regression corpus - run: cargo test -p bashkit --test integration --features http_client,jq -- competitor_regression_tests + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test integration --features http_client,jq -- competitor_regression_tests - name: Run doc tests - run: cargo test --workspace --doc --features http_client,ssh,sqlite + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --workspace --doc --features http_client,ssh,sqlite # CPython (wasm) python3: unit, integration, capability (diffed against # the runner's python3), security and load tests. Feature-gated, so the # main test step above does not build it into bashkit. - name: Run CPython tests - run: cargo test -p bashkit --features cpython,http_client --lib --test integration -- cpython + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features cpython,http_client --lib --test integration -- cpython # bashkit's own requests/httpx (guest modules) against the upstream # packages: same scenarios, same output. @@ -399,62 +407,75 @@ jobs: # Same suites on the opt-in native-code build (`cpython-native`). - name: Run CPython tests (native code) - run: cargo test -p bashkit --features cpython-native,http_client --lib --test integration -- cpython + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features cpython-native,http_client --lib --test integration -- cpython - name: Run realfs tests - run: cargo test --features realfs -p bashkit --test realfs_tests -p bashkit-cli + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --features realfs -p bashkit --test realfs_tests -p bashkit-cli # The third-party adoption and host-mount suites are `cfg(realfs)`, so # the main "Run tests" step (no realfs) compiles them out entirely. - name: Run realfs integration tests - run: cargo test -p bashkit --test integration --features realfs -- host_mounts_tests thirdparty_adoption_tests + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test integration --features realfs -- host_mounts_tests thirdparty_adoption_tests # In-process terminal + vi builtin are `cfg(terminal)` (off by default), # so the main "Run tests" step compiles them out entirely. - name: Run terminal tests run: | - cargo test -p bashkit --features terminal,git --lib -- terminal:: builtins::vi:: builtins::pager:: builtins::nano:: - cargo test -p bashkit --features terminal --test integration -- terminal_tests l_term_ - cargo test -p bashkit --features terminal --doc terminal + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features terminal,git --lib -- terminal:: builtins::vi:: builtins::pager:: builtins::nano:: + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features terminal --test integration -- terminal_tests l_term_ + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features terminal --doc terminal # markkit/fetchkit builtins are `cfg(markkit|fetchkit)` (off by default), # so the main "Run tests" step compiles them out entirely. - name: Run markkit/fetchkit builtin tests run: | - cargo test -p bashkit --features markkit,fetchkit --lib -- builtins::markkit:: builtins::fetchkit:: - cargo test -p bashkit --features markkit,fetchkit --test integration -- markkit_builtin_tests fetchkit_builtin_tests - cargo test -p bashkit --features markkit --test integration -- markkit_builtin_tests - cargo test -p bashkit --features markkit,fetchkit --doc -- markkit_fetchkit_guide + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features markkit,fetchkit --lib -- builtins::markkit:: builtins::fetchkit:: + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features markkit,fetchkit --test integration -- markkit_builtin_tests fetchkit_builtin_tests + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features markkit --test integration -- markkit_builtin_tests + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features markkit,fetchkit --doc -- markkit_fetchkit_guide # jq must keep working when another crate unifies serde_json's # arbitrary_precision on (issue #2964): non-integers then arrive via # visit_map with the private token instead of visit_f64. - name: Run jq tests with arbitrary_precision unified on - run: "cargo test -p bashkit --lib --features jq,serde_json/arbitrary_precision -- builtins::jq::" + run: "cargo test --features=\"${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}\" -p bashkit --lib --features jq,serde_json/arbitrary_precision -- builtins::jq::" - - name: Run fail-point tests (single-threaded) - run: cargo test --features failpoints --test security_failpoint_tests -- --test-threads=1 + - name: Run failpoint unit and security tests (single-threaded) + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --features failpoints --lib --test security_failpoint_tests -- --test-threads=1 - name: Run property-based security tests (proptest) - run: cargo test --test proptest_security -- --test-threads=1 + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --test proptest_security -- --test-threads=1 env: PROPTEST_CASES: 50 cpython-platforms: # COFF rejects 64 KiB-aligned statics; Mach-O can lose their alignment at # load time. Keep the actual embedding, module load and execution covered. - name: CPython (${{ matrix.os }}, Rust ${{ matrix.rust }}) + name: CPython (${{ matrix.os }}, Rust ${{ matrix.rust }}) (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: include: - - os: ubuntu-latest - rust: "1.100.0" - - os: macos-latest - rust: "1.100.0" - - os: windows-2025 - rust: "1.100.0" + - os: ubuntu-latest + rust: 1.100.0 + execution_plan: false + - os: ubuntu-latest + rust: 1.100.0 + execution_plan: true + - os: macos-latest + rust: 1.100.0 + execution_plan: false + - os: macos-latest + rust: 1.100.0 + execution_plan: true + - os: windows-2025 + rust: 1.100.0 + execution_plan: false + - os: windows-2025 + rust: 1.100.0 + execution_plan: true + steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -474,13 +495,17 @@ jobs: run: cargo test --locked -p bashkit-cpython-wasm --lib - name: Execute CPython through the shell - run: cargo test --locked -p bashkit --features cpython --test integration -- cpython_integration_tests + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --locked -p bashkit --features cpython --test integration -- cpython_integration_tests windows-containment: # THREAT[TM-ESC-033]: Windows path parsing has drive, UNC, device, and # reparse-point semantics that cannot be exercised on a Unix runner. - name: Windows filesystem containment + name: Windows filesystem containment (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: windows-latest + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -494,19 +519,19 @@ jobs: shared-key: windows-containment - name: Test VFS path normalization - run: cargo test -p bashkit --lib --features realfs windows_containment + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --lib --features realfs windows_containment - name: Test RealFS and overlay containment - run: cargo test -p bashkit --test realfs_tests --features realfs windows_containment + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test realfs_tests --features realfs windows_containment - name: Test touch mtime on Windows (issue #2388) - run: cargo test -p bashkit --test realfs_tests --features realfs realfs_touch + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test realfs_tests --features realfs realfs_touch # The C ABI mount-root guard is Windows-conditional, so the Linux # workspace test run compiles it out. Nothing else runs bashkit-capi's # tests on Windows, which left them never executing anywhere. - name: Test C ABI mount-root validation and runtime callbacks - run: cargo test -p bashkit-capi --lib --test runtime_functions + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit-capi --lib --test runtime_functions # The adoption shape this covers — bashkit as an agent's shell, with commands # bridged to host processes — exists to work on Windows without a real bash. @@ -514,8 +539,12 @@ jobs: # semantics (TM-ESC-033), this one pins the embedding contract. Scoped to the # adoption suites rather than the whole workspace. test-windows: - name: Test (Windows adoption shape) + name: Test (Windows adoption shape) (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: windows-latest + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -529,21 +558,21 @@ jobs: shared-key: windows-adoption - name: Run third-party adoption tests - run: cargo test -p bashkit --test integration --features realfs -- thirdparty_adoption_tests + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test integration --features realfs -- thirdparty_adoption_tests - name: Run host mount mapping tests - run: cargo test -p bashkit --test integration --features realfs -- host_mounts_tests + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test integration --features realfs -- host_mounts_tests # The VFS is `/`-separated on every host; host-separator joins only show # up here (#2425, #2933). Reuses the realfs build from the steps above. - name: Run VFS separator and device path tests - run: cargo test -p bashkit --test integration --features realfs -- windows_containment dev_fd_path_tests dev_null_tests + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test integration --features realfs -- windows_containment dev_fd_path_tests dev_null_tests - name: Run command resolver tests - run: cargo test -p bashkit --test integration -- command_resolver_tests + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test integration -- command_resolver_tests examples: - name: Examples + name: Examples (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ubuntu-latest # Secret guard: only expose Doppler/API keys on push to main (trusted # code). PRs — including same-repo branches — execute PR-controlled @@ -551,6 +580,12 @@ jobs: # `github.event_name == 'push'` is the only reliable gate; the old # `head.repo.fork != true` check passes for same-repo PRs and for # workflow_call events where pull_request context is absent. + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] + env: + EXECUTION_PLAN_FEATURE: ${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -562,49 +597,51 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 - name: Build examples - run: cargo build --examples --features "git,http_client,ssh,sqlite" + run: cargo build --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --examples --features "git,http_client,ssh,sqlite" - name: Run C API examples + env: + BASHKIT_CAPI_FEATURES: ${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }} run: ./scripts/run-c-api-examples.sh - name: Run examples run: | - cargo run --example basic - cargo run --example custom_fs - cargo run --example clap_builtin - cargo run --example clap_builtin_subcommands - cargo run -p bashkit-scripted-tool --example scripted_tool_clap_builtin - cargo run --example resource_limits - cargo run --example text_processing - cargo run --example live_mounts - cargo run --example git_workflow --features git - cargo run --example python_external_functions --features python - cargo run --example cpython_scripts --features cpython - cargo run --example typescript_external_functions --features typescript - cargo run --example realfs_readonly --features realfs - cargo run --example realfs_readwrite --features realfs - cargo run --example sqlite_basic --features sqlite - cargo run --example sqlite_workflow --features sqlite - cargo run --example markkit_fetchkit --features markkit,fetchkit - cargo run --example terminal_vi --features terminal - cargo run --example terminal_record --features terminal + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example basic + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example custom_fs + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example clap_builtin + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example clap_builtin_subcommands + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit-scripted-tool --example scripted_tool_clap_builtin + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example resource_limits + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example text_processing + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example live_mounts + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example git_workflow --features git + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example python_external_functions --features python + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example cpython_scripts --features cpython + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example typescript_external_functions --features typescript + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example realfs_readonly --features realfs + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example realfs_readwrite --features realfs + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example sqlite_basic --features sqlite + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example sqlite_workflow --features sqlite + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example markkit_fetchkit --features markkit,fetchkit + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example terminal_vi --features terminal + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example terminal_record --features terminal # SSH tests - name: Run ssh builtin tests (mock handler) - run: cargo test --features ssh -p bashkit --test ssh_builtin_tests + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --features ssh -p bashkit --test ssh_builtin_tests - name: Run ssh supabase.sh example and tests run: | if nc -z -w 5 supabase.sh 22 2>/dev/null; then - cargo run --example ssh_supabase --features ssh - cargo test --features ssh -p bashkit --test ssh_supabase_tests + cargo run --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --example ssh_supabase --features ssh + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --features ssh -p bashkit --test ssh_supabase_tests else echo "::warning::supabase.sh:22 unreachable from this runner — skipping live SSH tests" fi - name: Run realfs bash example run: | - cargo build -p bashkit-cli --features realfs + cargo build --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit-cli --features realfs bash examples/realfs_mount.sh - name: Run ticket CLI example @@ -656,8 +693,8 @@ jobs: - name: Build LLM examples without credentials run: | - cargo build --example agent_tool --features http_client - cargo build -p bashkit-cli --features realfs --quiet + cargo build --features="$EXECUTION_PLAN_FEATURE" --example agent_tool --features http_client + cargo build --features="$EXECUTION_PLAN_FEATURE" -p bashkit-cli --features realfs --quiet # Resolve only the required key; this token-bearing process exits before # repository code runs. Mask the output before crossing the step boundary. @@ -703,8 +740,12 @@ jobs: run: bash examples/harness-openai-joke.sh fuzz-check: - name: Fuzz Compile Check + name: Fuzz build and smoke (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -732,18 +773,34 @@ jobs: env: RUSTUP_TOOLCHAIN: nightly-2026-10-30 with: - tool: cargo-fuzz + tool: cargo-fuzz@0.13.2 locked: true + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + workspaces: crates/bashkit/fuzz -> target + shared-key: fuzz-smoke-${{ matrix.execution_plan }} + cache-on-failure: true + - name: Verify fuzz targets compile working-directory: crates/bashkit run: | - cargo +nightly-2026-10-30 fuzz build - cargo +nightly-2026-10-30 fuzz build --features cpython cpython_fuzz - cargo +nightly-2026-10-30 fuzz build --features cpython cpython_http_fuzz - cargo +nightly-2026-10-30 fuzz build --features python python_fuzz - cargo +nightly-2026-10-30 fuzz build --features python,cpython python_diff_fuzz - cargo +nightly-2026-10-30 fuzz build --features typescript ts_fuzz + cargo +nightly-2026-10-30 fuzz build --codegen-units 16 --features="${{ matrix.execution_plan && 'experimental_execution_plan' || '' }}" + cargo +nightly-2026-10-30 fuzz build --codegen-units 16 --features="cpython${{ matrix.execution_plan && ',experimental_execution_plan' || '' }}" cpython_fuzz + cargo +nightly-2026-10-30 fuzz build --codegen-units 16 --features="cpython${{ matrix.execution_plan && ',experimental_execution_plan' || '' }}" cpython_http_fuzz + cargo +nightly-2026-10-30 fuzz build --codegen-units 16 --features="python${{ matrix.execution_plan && ',experimental_execution_plan' || '' }}" python_fuzz + cargo +nightly-2026-10-30 fuzz build --codegen-units 16 --features="python,cpython${{ matrix.execution_plan && ',experimental_execution_plan' || '' }}" python_diff_fuzz + cargo +nightly-2026-10-30 fuzz build --codegen-units 16 --features="typescript${{ matrix.execution_plan && ',experimental_execution_plan' || '' }}" ts_fuzz + + - name: Smoke every fuzz target (manifest-discovered, bounded) + run: python3 scripts/fuzz-smoke.py ${{ matrix.execution_plan && '--execution-plan' || '' }} + + - name: Upload fuzz failures + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: fuzz-smoke-failures-${{ matrix.execution_plan }} + path: crates/bashkit/fuzz/artifacts # Gate job for branch protection — name must stay "Check" check: diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index d1bf12ea1..f507049a0 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -24,11 +24,15 @@ env: jobs: coverage: - name: Generate Rust Coverage + name: Rust coverage (plan=${{ matrix.execution_plan }}) # Pinned for the GNU coreutils oracle, like ci.yml's `test` job; see the # note there. runs-on: ubuntu-24.04 timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -60,13 +64,13 @@ jobs: # (past --timeout). Its tests still run in the main CI test job. - name: Generate coverage report run: | - cargo tarpaulin --features http_client \ + cargo tarpaulin --features="http_client${{ matrix.execution_plan && ',bashkit/experimental_execution_plan' || '' }}" \ --workspace \ --exclude bashkit-python \ --exclude bashkit-eval \ --out xml \ --out html \ - --output-dir coverage \ + --output-dir coverage/${{ matrix.execution_plan }} \ --exclude-files "crates/bashkit-bench/*" \ --exclude-files "crates/bashkit-cli/*" \ --exclude-files "crates/bashkit-python/*" \ @@ -77,7 +81,7 @@ jobs: - name: Upload coverage artifacts uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - name: rust-coverage-report + name: rust-${{ matrix.execution_plan }}-coverage-report path: coverage/ retention-days: 30 @@ -218,7 +222,7 @@ jobs: uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: token: ${{ secrets.CODECOV_TOKEN }} - files: coverage/cobertura.xml,coverage/python-rust-coverage.json,coverage/node-rust-coverage.json + files: coverage/false/cobertura.xml,coverage/true/cobertura.xml,coverage/python-rust-coverage.json,coverage/node-rust-coverage.json disable_search: true flags: unittests fail_ci_if_error: false diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 2a042ab00..90e9da9ce 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -20,13 +20,24 @@ env: CARGO_TERM_COLOR: always jobs: + targets: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.targets.outputs.matrix }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - id: targets + run: echo "matrix=$(python3 scripts/fuzz-smoke.py --matrix)" >> "$GITHUB_OUTPUT" + fuzz: - name: Fuzz Test + name: Fuzz (${{ matrix.target }}, plan=${{ matrix.execution_plan }}) + needs: targets runs-on: ubuntu-latest strategy: fail-fast: false - matrix: - target: [parser_fuzz, lexer_fuzz, analyze_fuzz, arithmetic_fuzz, glob_fuzz, cpython_fuzz, cpython_http_fuzz, python_fuzz, python_diff_fuzz, ts_fuzz] + matrix: ${{ fromJSON(needs.targets.outputs.matrix) }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -48,20 +59,33 @@ jobs: # On the nightly, not the pinned stable default: an unpinned source # build on a pinned toolchain breaks when upstream raises its MSRV. - name: Install cargo-fuzz - run: cargo +nightly-2026-10-30 install cargo-fuzz --locked + uses: taiki-e/cache-cargo-install-action@9ee83daaa7b96a6fab930949ecf1122bba04a389 # v3 + env: + RUSTUP_TOOLCHAIN: nightly-2026-10-30 + with: + tool: cargo-fuzz@0.13.2 + locked: true + + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + workspaces: crates/bashkit/fuzz -> target + shared-key: fuzz-${{ matrix.features }} + cache-on-failure: true - name: Cache fuzz corpus uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 with: path: crates/bashkit/fuzz/corpus - key: fuzz-corpus-${{ matrix.target }}-${{ github.sha }} + key: fuzz-corpus-${{ matrix.target }}-${{ matrix.execution_plan }}-${{ github.sha }} restore-keys: | - fuzz-corpus-${{ matrix.target }}- + fuzz-corpus-${{ matrix.target }}-${{ matrix.execution_plan }}- - name: Run fuzzer - ${{ matrix.target }} working-directory: crates/bashkit env: DURATION_INPUT: ${{ github.event.inputs.duration || '300' }} + FUZZ_FEATURES: ${{ matrix.features }} + FUZZ_TARGET: ${{ matrix.target }} run: | # Validate duration is a positive integer before use (prevents shell injection # from workflow_dispatch inputs being interpolated directly into the shell). @@ -72,13 +96,10 @@ jobs: exit 1 fi features=() - case "${{ matrix.target }}" in - python_diff_fuzz) features=(--features python,cpython) ;; - cpython_*) features=(--features cpython) ;; - python_*) features=(--features python) ;; - ts_fuzz) features=(--features typescript) ;; - esac - cargo +nightly-2026-10-30 fuzz run "${features[@]}" ${{ matrix.target }} -- \ + if [[ -n "$FUZZ_FEATURES" ]]; then + features=(--features "$FUZZ_FEATURES") + fi + cargo +nightly-2026-10-30 fuzz run --codegen-units 16 "${features[@]}" "$FUZZ_TARGET" -- \ -max_total_time="$DURATION_INPUT" \ -print_final_stats=1 @@ -86,7 +107,7 @@ jobs: if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - name: fuzz-crashes-${{ matrix.target }} + name: fuzz-crashes-${{ matrix.target }}-${{ matrix.execution_plan }} path: | crates/bashkit/fuzz/artifacts/${{ matrix.target }} retention-days: 30 diff --git a/.github/workflows/js.yml b/.github/workflows/js.yml index 4353c0ab1..9c8c1c710 100644 --- a/.github/workflows/js.yml +++ b/.github/workflows/js.yml @@ -71,39 +71,76 @@ jobs: working-directory: crates/bashkit-js build-and-test: - name: ${{ matrix.runtime }} ${{ matrix.version }} + name: ${{ matrix.runtime }} ${{ matrix.version }} (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: include: - # Node.js versions - - runtime: node - version: "20" - run: "node" - - runtime: node - version: "22.23.4" - run: "node" - - runtime: node - version: "24.22.1" - run: "node" - - runtime: node - version: "latest" - run: "node" - # Bun - - runtime: bun - version: "latest" - run: "bun" - - runtime: bun - version: "canary" - run: "bun" - # Deno - - runtime: deno - version: "2.x" - run: "deno run -A" - - runtime: deno - version: "canary" - run: "deno run -A" + - runtime: node + version: '20' + run: node + execution_plan: false + - runtime: node + version: '20' + run: node + execution_plan: true + - runtime: node + version: 22.23.4 + run: node + execution_plan: false + - runtime: node + version: 22.23.4 + run: node + execution_plan: true + - runtime: node + version: 24.22.1 + run: node + execution_plan: false + - runtime: node + version: 24.22.1 + run: node + execution_plan: true + - runtime: node + version: latest + run: node + execution_plan: false + - runtime: node + version: latest + run: node + execution_plan: true + - runtime: bun + version: latest + run: bun + execution_plan: false + - runtime: bun + version: latest + run: bun + execution_plan: true + - runtime: bun + version: canary + run: bun + execution_plan: false + - runtime: bun + version: canary + run: bun + execution_plan: true + - runtime: deno + version: 2.x + run: deno run -A + execution_plan: false + - runtime: deno + version: 2.x + run: deno run -A + execution_plan: true + - runtime: deno + version: canary + run: deno run -A + execution_plan: false + - runtime: deno + version: canary + run: deno run -A + execution_plan: true steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -157,7 +194,10 @@ jobs: working-directory: crates/bashkit-js - name: Build native binding - run: pnpm run build + run: | + pnpm exec napi build --platform --release --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" + pnpm run build:cjs + pnpm run build:ts working-directory: crates/bashkit-js # ava >= 8 requires Node 22.20+, but the package still declares @@ -252,26 +292,35 @@ jobs: ${{ matrix.run }} langchain_agent.mjs callback-platforms: - name: Runtime callbacks (${{ matrix.name }}) + name: Runtime callbacks (${{ matrix.name }}) (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: include: - - name: macos-latest - os: macos-latest - - name: windows-latest - os: windows-latest - # `macos-latest` is arm64, so the shipped x86_64-apple-darwin binding - # only ever runs translated under Rosetta 2, where embedded-runtime - # start-up costs several times native. publish-js.yml was the only - # place that lane ran, so a timing regression on it first surfaced at - # release: v0.20.1 went red here while every native lane was green, - # and `release-js` is gated on these jobs, so npm was never reached. - - name: macos-latest x86_64 (Rosetta) - os: macos-latest - target: x86_64-apple-darwin - architecture: x64 + - name: macos-latest + os: macos-latest + execution_plan: false + - name: macos-latest + os: macos-latest + execution_plan: true + - name: windows-latest + os: windows-latest + execution_plan: false + - name: windows-latest + os: windows-latest + execution_plan: true + - name: macos-latest x86_64 (Rosetta) + os: macos-latest + target: x86_64-apple-darwin + architecture: x64 + execution_plan: false + - name: macos-latest x86_64 (Rosetta) + os: macos-latest + target: x86_64-apple-darwin + architecture: x64 + execution_plan: true + steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -297,7 +346,10 @@ jobs: - run: pnpm install --frozen-lockfile working-directory: crates/bashkit-js - if: ${{ !matrix.target }} - run: pnpm run build + run: | + pnpm exec napi build --platform --release --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" + pnpm run build:cjs + pnpm run build:ts working-directory: crates/bashkit-js - if: ${{ matrix.target }} name: Build ${{ matrix.target }} @@ -318,7 +370,7 @@ jobs: # resumes rather than rebuilds. Only the toolchain crash is retried: # a genuine compile error fails again and still fails the job. for attempt in 1 2 3; do - if pnpm exec napi build --platform --release --target ${{ matrix.target }}; then + if pnpm exec napi build --platform --release --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --target ${{ matrix.target }}; then break fi if [ "$attempt" = 3 ]; then diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index fa8d31db2..56bb6b006 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -18,8 +18,12 @@ env: jobs: miri: - name: Miri + name: Miri (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -42,7 +46,7 @@ jobs: - name: Run Miri on library tests run: | - cargo +nightly-2026-10-30 miri test --lib -p bashkit -- \ + cargo +nightly-2026-10-30 miri test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --lib -p bashkit -- \ --test-threads=1 \ test_parse_simple_command \ test_parse_variable \ @@ -50,6 +54,15 @@ jobs: env: MIRIFLAGS: -Zmiri-disable-isolation + - name: Miri plan admission and storage lifetime + if: matrix.execution_plan + run: | + cargo +nightly-2026-10-30 miri test --lib -p bashkit --features experimental_execution_plan -- \ + --test-threads=1 builder_reservation_outlives_buffer_destruction \ + declined_and_failed_compilation_refund_storage automatic_policy_skips_short_scripts + env: + MIRIFLAGS: -Zmiri-disable-isolation + # CI audits lockfiles on push and PR only, so main goes unscanned for as long # as nobody pushes — and an advisory is published against code that has not # changed. This job re-runs the same scan daily against a fresh copy of the @@ -156,7 +169,7 @@ jobs: retention-days: 30 asan: - name: AddressSanitizer + name: AddressSanitizer (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) # Pinned for the GNU coreutils oracle, like ci.yml's `test` job; see the # note there. runs-on: ubuntu-24.04 @@ -164,6 +177,10 @@ jobs: # differential corpora needs well over the previous 30-minute cap; # the last two nightly runs cancelled mid-suite at exactly 30 min. timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -204,7 +221,7 @@ jobs: RUSTFLAGS: "-Z sanitizer=address" ASAN_OPTIONS: "detect_stack_use_after_return=1:detect_leaks=0" run: | - cargo +nightly-2026-10-30 test -Z build-std --target x86_64-unknown-linux-gnu --lib --tests \ + cargo +nightly-2026-10-30 test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -Z build-std --target x86_64-unknown-linux-gnu --lib --tests \ -- --test-threads=1 # The default-feature run above leaves out embedded python3. The Monty @@ -216,7 +233,7 @@ jobs: RUSTFLAGS: "-Z sanitizer=address" ASAN_OPTIONS: "detect_stack_use_after_return=1:detect_leaks=0" run: | - cargo +nightly-2026-10-30 test -Z build-std --target x86_64-unknown-linux-gnu \ + cargo +nightly-2026-10-30 test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -Z build-std --target x86_64-unknown-linux-gnu \ -p bashkit --features python --lib --test integration -- --test-threads=1 python # The vendored ZapCode VM (crates/bashkit/src/zapcode_vendor) is our @@ -228,18 +245,22 @@ jobs: RUSTFLAGS: "-Z sanitizer=address" ASAN_OPTIONS: "detect_stack_use_after_return=1:detect_leaks=0" run: | - cargo +nightly-2026-10-30 test -Z build-std --target x86_64-unknown-linux-gnu \ + cargo +nightly-2026-10-30 test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -Z build-std --target x86_64-unknown-linux-gnu \ -p bashkit --features typescript --lib --test integration -- --test-threads=1 \ typescript threat_ts ts_tenant_stress zapcode python-stress-soak: - name: Python multi-tenant stress soak + name: Python multi-tenant stress soak (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) # PR CI runs python_tenant_stress_tests at 3 rounds. The soak repeats # them many times in release mode so rare cross-tenant leaks (meter # left on a worker thread, budget not returned after an abandoned call) # show up. Re-sync checklist in knowledge/operations/dependencies.md. runs-on: ubuntu-latest timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -256,16 +277,20 @@ jobs: env: BASHKIT_STRESS_ROUNDS: "300" run: | - cargo test --release -p bashkit --features python --test integration \ + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --release -p bashkit --features python --test integration \ -- python_tenant_stress ts-stress-soak: - name: TypeScript multi-tenant stress soak + name: TypeScript multi-tenant stress soak (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) # PR CI runs ts_tenant_stress_tests at 3 rounds. The soak repeats them in # release mode so rare cross-tenant leaks (meter left on a worker thread, # charge not released after an abandoned call) show up. runs-on: ubuntu-latest timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -282,5 +307,5 @@ jobs: env: BASHKIT_STRESS_ROUNDS: "300" run: | - cargo test --release -p bashkit --features typescript --test integration \ + cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --release -p bashkit --features typescript --test integration \ -- ts_tenant_stress diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index bce1eff59..58e8e291e 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -67,7 +67,7 @@ jobs: # the random-fs fixture — a separate, non-abi3 extension — is still built per # version. Covers 3.9–3.14 (the full abi3 support range). test: - name: Test (Python ${{ matrix.python-version }}) + name: Test (Python ${{ matrix.python-version }}) (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) needs: [build-wheel] # Pinned, not `ubuntu-latest`: Ubuntu 26.04 ships no hosted 3.9 build, and # `setup-python` has no fallback, so the 3.9 leg died the moment @@ -82,6 +82,7 @@ jobs: strategy: fail-fast: false matrix: + execution_plan: [false, true] python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -96,7 +97,7 @@ jobs: # version to prove one wheel runs across the whole 3.9–3.14 range. - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 with: - name: python-wheel + name: python-wheel-${{ matrix.execution_plan }} path: crates/bashkit-python/dist - name: Install Rust toolchain @@ -121,7 +122,7 @@ jobs: # abi3-py39), so it must be built against each interpreter. - name: Build random filesystem fixture run: | - python -m maturin build --release --out /tmp/bashkit-random-fs \ + python -m maturin build --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --release --out /tmp/bashkit-random-fs \ -m crates/bashkit-python/test-fixtures/random-fs/Cargo.toml \ -i python${{ matrix.python-version }} pip install bashkit-random-fs --no-index --find-links /tmp/bashkit-random-fs --force-reinstall @@ -134,11 +135,12 @@ jobs: # Test the native callback bridge on each platform instead of relying only # on the Linux abi3 wheel matrix above. No random-FS fixture is needed here. callback-platforms: - name: Callback loops (${{ matrix.os }}) + name: Callback loops (${{ matrix.os }}) (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: + execution_plan: [false, true] os: [macos-latest, windows-latest] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -152,7 +154,7 @@ jobs: - name: Build and install native wheel run: | python -m pip install "maturin${{ env.MATURIN_VERSION }}" - python -m maturin build -m crates/bashkit-python/Cargo.toml --out dist + python -m maturin build --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -m crates/bashkit-python/Cargo.toml --out dist python -m pip install bashkit --no-index --find-links dist python -m pip install pytest pytest-asyncio pytest-timeout langchain-core deepagents fastapi httpx - name: Install uvloop on Unix @@ -169,8 +171,12 @@ jobs: crates/bashkit-python/tests/test_teardown_determinism.py examples: - name: Examples + name: Examples (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -192,7 +198,7 @@ jobs: - name: Build wheel working-directory: crates/bashkit-python - run: python -m maturin build --release --out dist -i python3.12 + run: python -m maturin build --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --release --out dist -i python3.12 - name: Install local wheel run: | @@ -201,7 +207,7 @@ jobs: - name: Build random filesystem fixture run: | - python -m maturin build --release --out /tmp/bashkit-random-fs \ + python -m maturin build --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --release --out /tmp/bashkit-random-fs \ -m crates/bashkit-python/test-fixtures/random-fs/Cargo.toml \ -i python3.12 pip install bashkit-random-fs --no-index --find-links /tmp/bashkit-random-fs --force-reinstall @@ -225,8 +231,12 @@ jobs: # Verify wheel builds and passes twine check build-wheel: - name: Build wheel + name: Build wheel (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -241,7 +251,7 @@ jobs: - name: Build wheel working-directory: crates/bashkit-python - run: python -m maturin build --release --out dist + run: python -m maturin build --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" --release --out dist - name: Verify wheel metadata run: | @@ -250,7 +260,7 @@ jobs: - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - name: python-wheel + name: python-wheel-${{ matrix.execution_plan }} path: crates/bashkit-python/dist retention-days: 5 diff --git a/.github/workflows/windows-nightly.yml b/.github/workflows/windows-nightly.yml index 2790146ee..d622bada4 100644 --- a/.github/workflows/windows-nightly.yml +++ b/.github/workflows/windows-nightly.yml @@ -33,9 +33,13 @@ env: jobs: windows-tests: - name: Windows full test suite + name: Windows full test suite (${{ matrix.execution_plan && 'execution-plan' || 'interpreter' }}) runs-on: windows-latest timeout-minutes: 120 + strategy: + fail-fast: false + matrix: + execution_plan: [false, true] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -49,10 +53,10 @@ jobs: shared-key: windows-nightly - name: Library tests - run: cargo test -p bashkit --lib --features http_client,realfs + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --lib --features http_client,realfs - name: Integration tests - run: cargo test -p bashkit --test integration --features http_client,realfs + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test integration --features http_client,realfs - name: Property-based security tests - run: cargo test -p bashkit --test proptest_security -- --test-threads=1 + run: cargo test --features="${{ matrix.execution_plan && 'bashkit/experimental_execution_plan' || '' }}" -p bashkit --test proptest_security -- --test-threads=1 diff --git a/README.md b/README.md index 79ce563d3..c367891b1 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Awesomely fast virtual sandbox with bash and file system. Written in Rust. - **Experimental: Git support** - Virtual git operations on the virtual filesystem (`git` feature) - **Experimental: Python support** - Embedded Python interpreter via [Monty](https://github.com/pydantic/monty) (`python` feature), or real CPython 3.14 in a WebAssembly sandbox (`cpython` feature) - **Experimental: TypeScript support** - Embedded TypeScript interpreter via [ZapCode](https://github.com/TheUncharted/zapcode) (`typescript` feature) +- **Experimental: script execution plans** - Opt-in compilation of scalar arithmetic and control flow, with interpreter fallback (`experimental_execution_plan` feature; [details](crates/bashkit/docs/compatibility.md#experimental-execution-plans)) - **Experimental: SQLite support** - Embedded SQLite-compatible engine via [Turso](https://github.com/tursodatabase/turso) (`sqlite` feature) ## Install diff --git a/crates/bashkit-capi/Cargo.toml b/crates/bashkit-capi/Cargo.toml index 5c1d57b22..30ca7e291 100644 --- a/crates/bashkit-capi/Cargo.toml +++ b/crates/bashkit-capi/Cargo.toml @@ -21,3 +21,7 @@ bashkit = { path = "../bashkit", default-features = false, features = ["git", "j serde = { workspace = true } serde_json = { workspace = true } tokio = { workspace = true } + +[features] +# Opt-in script compiler; preserves ordinary Bash syntax and AST fallback. +experimental_execution_plan = ["bashkit/experimental_execution_plan"] diff --git a/crates/bashkit-cli/Cargo.toml b/crates/bashkit-cli/Cargo.toml index 42ccca9b2..01fa48477 100644 --- a/crates/bashkit-cli/Cargo.toml +++ b/crates/bashkit-cli/Cargo.toml @@ -23,6 +23,8 @@ path = "src/main.rs" doc = false # Disable to avoid collision with bashkit library docs [features] +# Opt-in script compiler; preserves ordinary Bash syntax and AST fallback. +experimental_execution_plan = ["bashkit/experimental_execution_plan"] default = ["python", "sqlite", "interactive"] python = ["bashkit/python"] # python/python3 via real CPython 3.14 in a wasm sandbox (replaces Monty) diff --git a/crates/bashkit-js/Cargo.toml b/crates/bashkit-js/Cargo.toml index a5d1aad08..58f1e689b 100644 --- a/crates/bashkit-js/Cargo.toml +++ b/crates/bashkit-js/Cargo.toml @@ -24,3 +24,7 @@ tokio = { version = "1", features = ["sync", "macros", "io-util", "rt", "time"] [build-dependencies] napi-build = { workspace = true } + +[features] +# Opt-in script compiler; preserves ordinary Bash syntax and AST fallback. +experimental_execution_plan = ["bashkit/experimental_execution_plan"] diff --git a/crates/bashkit-python/Cargo.toml b/crates/bashkit-python/Cargo.toml index e2fbf924a..b010478fd 100644 --- a/crates/bashkit-python/Cargo.toml +++ b/crates/bashkit-python/Cargo.toml @@ -53,3 +53,7 @@ pyo3-async-runtimes = { workspace = true } bashkit = { path = "../bashkit", features = ["python", "typescript", "jq", "terminal"] } bashkit-scripted-tool = { path = "../bashkit-scripted-tool", features = ["python", "jq"] } tokio = { workspace = true } + +[features] +# Opt-in script compiler; preserves ordinary Bash syntax and AST fallback. +experimental_execution_plan = ["bashkit/experimental_execution_plan"] diff --git a/crates/bashkit-scripted-tool/Cargo.toml b/crates/bashkit-scripted-tool/Cargo.toml index e22e2766a..8d03bd33d 100644 --- a/crates/bashkit-scripted-tool/Cargo.toml +++ b/crates/bashkit-scripted-tool/Cargo.toml @@ -19,6 +19,8 @@ categories.workspace = true readme = "README.md" [features] +# Opt-in script compiler; preserves ordinary Bash syntax and AST fallback. +experimental_execution_plan = ["bashkit/experimental_execution_plan"] default = [] # Expose registry tools to embedded Python (`python`/`python3` builtins). python = ["bashkit/python"] diff --git a/crates/bashkit-wasm/Cargo.toml b/crates/bashkit-wasm/Cargo.toml index 64ac9eeb9..3bbf4888f 100644 --- a/crates/bashkit-wasm/Cargo.toml +++ b/crates/bashkit-wasm/Cargo.toml @@ -28,6 +28,8 @@ repository.workspace = true publish = false [features] +# Opt-in script compiler; preserves ordinary Bash syntax and AST fallback. +experimental_execution_plan = ["bashkit/experimental_execution_plan"] # Interactive `Terminal` class (keystrokes in, escape-sequence bytes out) for # xterm.js-style renderers. Off by default for crate users, like # `bashkit/terminal`; `scripts/build.sh` turns it on for the npm package because diff --git a/crates/bashkit/Cargo.toml b/crates/bashkit/Cargo.toml index ee2540b1b..77c221fc5 100644 --- a/crates/bashkit/Cargo.toml +++ b/crates/bashkit/Cargo.toml @@ -152,6 +152,10 @@ turso_core = { workspace = true, optional = true } branches = { workspace = true, optional = true } [features] +# Isolated experiment. No production entry point enables this by default. +experimental_execution_plan = [] +# Diagnostic only: compare AST/plan execution in one binary using request data. +experimental_plan_benchmark_control = ["experimental_execution_plan"] default = ["bash_tool", "ring", "tzdata", "iconv_charsets"] # Named IANA timezone support for the `date` builtin's `TZ=` handling, via the # chrono-tz database. On by default. diff --git a/crates/bashkit/docs/compatibility.md b/crates/bashkit/docs/compatibility.md index 8c92492f4..517b81126 100644 --- a/crates/bashkit/docs/compatibility.md +++ b/crates/bashkit/docs/compatibility.md @@ -9,6 +9,38 @@ **Legend:** ✅ Implemented | ⚠️ Partial | ❌ Not implemented | N/A Security exclusion +## Experimental execution plans + +The Cargo feature `experimental_execution_plan` enables an optional compiler +behind the existing `Bash::exec` entry point. It is off by default. Scripts use +ordinary Bash syntax and need no annotations or agent-specific conventions. +Enable this feature on the `bashkit` dependency in a source build; the CLI, +ScriptedTool, C ABI, Python, JavaScript and browser crates forward the same flag. +For example, from a checkout: + +```bash +cargo run -p bashkit-cli --features experimental_execution_plan -- \ + -c 'total=0; for ((i=0;i<1000;i++)); do ((total+=i)); done; echo "$total"' +``` + +Supported scalar arithmetic, numeric assignments, branches and loops can execute +as flat instructions. Small one-shot scripts skip compilation. Unsupported +syntax, tool-containing compound bodies, word expansions, traps, tracing, +`errexit`, `nounset`, arrays and attributed variables use the ordinary +interpreter where required. A mixed script can use both paths. + +Plans belong to one execution and borrow its parsed source. They use the shared +request's work and memory budgets, command/iteration limits, cancellation and +deadline checks. Compilation costs real work and memory, so tight budgets may +reject earlier than the interpreter-only build. There is no shared compiler +cache or persistent hotness state. + +This feature is experimental. Arithmetic-heavy regions improve substantially +in the initial Linux measurements, while substitutions remain about 4% slower +in separate production/feature builds. Measure representative scripts before +opting in. Historical measurements and reproduction instructions are in the +[execution-plan experiment](https://github.com/everruns/bashkit/tree/main/experiments/script-execution-plan). + ## POSIX Shell Compliance Bashkit provides substantial compliance with IEEE Std 1003.1-2024 (POSIX.1-2024) diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index f5979bcd5..cb618c49c 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -141,6 +141,7 @@ stdout capture limit remains downstream of pipelines and redirects. | Child-shell recursion (TM-DOS-125) | Script that re-runs itself via `sh` or `./s.sh` | Child shells count against function depth, max 8 nested | MITIGATED | | Re-entry recursion (TM-DOS-141) | `f(){ eval f; }`, `compgen -C`, `fc`, PROMPT_COMMAND re-entering the interpreter | Each re-entry counts against function depth, max 8 nested | MITIGATED | | Stack exhaustion from combined nesting (TM-DOS-142) | Nested compounds inside recursion inside `eval` overflow a 2 MiB worker stack | Command polls grow the stack on the heap when it runs low (`stacker`); depth caps bound the total | MITIGATED | +| Experimental compiled-region limit bypass (TM-DOS-147) | Optional compilation or execution skips resource checks or retains storage after cancellation | Execution-owned plans admit bounded storage, including vector growth, before allocation; native commands and loops retain shared limits and cancellation/deadline checks. Native fault-injection, reservation-refund and interrupted-execution tests plus differential fuzzing cover the backend | MITIGATED | | Pattern substitution (TM-DOS-127) | `${x//*a*/b}` over a long value | Globs run as a size-capped linear-time regex; extglob search capped at 10,000 attempts | MITIGATED | | Unbounded builtin output (TM-DOS-058) | `seq 1 1000000` produces 1M lines | Add `max_stdout_bytes` limit | **MITIGATED** | | Silent truncation at builtin caps (TM-DOS-109) | `seq 200000`, an awk loop past its cap, or an oversized `sprintf` expression returns incomplete output with exit 0 | Caps report `: limit () exceeded` on stderr and exit non-zero; awk caps and formatting errors are fatal | **MITIGATED** | diff --git a/crates/bashkit/fuzz/Cargo.toml b/crates/bashkit/fuzz/Cargo.toml index ea8c4b236..da46daa41 100644 --- a/crates/bashkit/fuzz/Cargo.toml +++ b/crates/bashkit/fuzz/Cargo.toml @@ -20,6 +20,9 @@ path = ".." features = ["jq"] [features] +# Exercise the shipping feature independently of the diagnostic selector. +experimental_execution_plan = ["bashkit/experimental_execution_plan"] +plan_differential = ["experimental_execution_plan", "bashkit/experimental_plan_benchmark_control"] # CPython (wasm) python3 target; off by default so `cargo fuzz build` stays # light. Run with: cargo +nightly fuzz run cpython_fuzz --features cpython cpython = ["bashkit/cpython"] @@ -37,6 +40,14 @@ members = ["."] [profile.release] debug = 1 +[[bin]] +name = "script_plan_fuzz" +path = "fuzz_targets/script_plan_fuzz.rs" +required-features = ["plan_differential"] +test = false +doc = false +bench = false + [[bin]] name = "parser_fuzz" path = "fuzz_targets/parser_fuzz.rs" diff --git a/crates/bashkit/fuzz/fuzz_targets/script_plan_fuzz.rs b/crates/bashkit/fuzz/fuzz_targets/script_plan_fuzz.rs new file mode 100644 index 000000000..1da698cc3 --- /dev/null +++ b/crates/bashkit/fuzz/fuzz_targets/script_plan_fuzz.rs @@ -0,0 +1,49 @@ +//! Bounded, structured compiler/AST differential fuzzing. All operators and +//! loop/branch forms are in the native subset, so random bytes reach lowering +//! and execution instead of mostly producing shell parse errors. +#![no_main] + +use bashkit::{Bash, ExecOptions, ExecutionExtensions, ExperimentalPlanBenchmarkControl as Mode}; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let mut script = format!( + "a={}; b={}; for ((i=0;i<{};i++)); do if ((i&1)); then\n", + data.first().copied().unwrap_or(0) as i8, + data.get(1).copied().unwrap_or(1) as i8, + data.get(2).copied().unwrap_or(2) % 8 + 1, + ); + // Independent of the loop counter; no input can turn this into an + // unbounded loop. Small decimal operands avoid Bash's octal-variable gap. + for byte in data.iter().take(32).copied().chain(std::iter::once(1)) { + let op = ["+", "-", "*", "^", "|", "&", "<<", ">>"][usize::from(byte & 7)]; + let name = if byte & 8 == 0 { "a" } else { "b" }; + script.push_str(&format!("(({name}={name}{op}{}));\n", (byte >> 4) + 1)); + } + script.push_str("else ((a+=b)); fi; done; printf '%s %s %s %s [%s]\\n' \"$a\" \"$b\" \"$i\" \"$?\" \"${PIPESTATUS[*]}\""); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + rt.block_on(async { + bashkit::testing::fuzz_init(); + let mut results = Vec::new(); + for mode in [Mode::Auto, Mode::InterpreterOnly] { + let mut bash = Bash::new(); + let options = ExecOptions::new().extensions(ExecutionExtensions::new().with(mode)); + let result = bash.exec_with_options(&script, options).await.unwrap(); + bashkit::testing::assert_fuzz_invariants(&result, &script, "script_plan_fuzz", &[]); + results.push(( + result.stdout, + result.stderr, + result.exit_code, + result.control_flow, + )); + // Request-local plans/selectors must not corrupt subsequent use. + let next = bash.exec("printf reusable").await.unwrap(); + assert_eq!(next.stdout, "reusable"); + assert_eq!(next.exit_code, 0); + } + assert_eq!(results[0], results[1], "compiler/AST mismatch: {script}"); + }); +}); diff --git a/crates/bashkit/src/interpreter/arithmetic.rs b/crates/bashkit/src/interpreter/arithmetic.rs index 2c8fdfdec..0177f0a5f 100644 --- a/crates/bashkit/src/interpreter/arithmetic.rs +++ b/crates/bashkit/src/interpreter/arithmetic.rs @@ -23,6 +23,9 @@ use super::*; +#[cfg(feature = "experimental_execution_plan")] +pub(super) mod program; + /// One assignment performed while evaluating: `(name, key, value)`. /// `key` is `None` for scalars, the decimal index for indexed arrays, and the /// key for associative arrays. diff --git a/crates/bashkit/src/interpreter/arithmetic/program.rs b/crates/bashkit/src/interpreter/arithmetic/program.rs new file mode 100644 index 000000000..8ee757c9e --- /dev/null +++ b/crates/bashkit/src/interpreter/arithmetic/program.rs @@ -0,0 +1,335 @@ +//! Experiment: compile safe scalar expressions to stack instructions. Unsupported +//! grammar returns None; the ordinary evaluator remains the semantic fallback. +use super::*; + +#[derive(Debug)] +enum Op { + Number(i64), + Load(String), + Unary(&'static str), + Binary(&'static str), + Store(String), + Update(String, i64, bool), + Drop, +} + +pub(in crate::interpreter) struct Expression<'s> { + pub source: std::borrow::Cow<'s, str>, + ops: Vec, +} + +struct Compiler { + tokens: Vec<(Tok, usize)>, + at: usize, + ops: Vec, +} + +impl Compiler { + fn peek(&self) -> &Tok { + &self.tokens[self.at].0 + } + fn next(&mut self) -> Tok { + let token = std::mem::replace(&mut self.tokens[self.at].0, Tok::Eof); + if self.at + 1 < self.tokens.len() { + self.at += 1; + } + token + } + fn expression(&mut self, min: u8, depth: usize) -> Option<()> { + if depth > 32 { + return None; + } + match self.next() { + Tok::Num(s) => self.ops.push(Op::Number(parse_arith_number(&s).ok()?)), + Tok::Ident(name, None) => { + if let Tok::Op(op @ ("++" | "--")) = self.peek() { + let delta = if *op == "++" { 1 } else { -1 }; + self.next(); + self.ops.push(Op::Update(name, delta, false)); + } else { + self.ops.push(Op::Load(name)); + } + } + Tok::Op(op @ ("!" | "~" | "-" | "+")) => { + self.expression(12, depth + 1)?; + self.ops.push(Op::Unary(op)); + } + Tok::Op(op @ ("++" | "--")) => { + let Tok::Ident(name, None) = self.next() else { + return None; + }; + self.ops + .push(Op::Update(name, if op == "++" { 1 } else { -1 }, true)); + } + Tok::LParen => { + self.expression(0, depth + 1)?; + if self.next() != Tok::RParen { + return None; + } + } + _ => return None, + } + while let Tok::Op(op) = self.peek() { + let op = *op; + let precedence = match op { + "|" => 1, + "^" => 2, + "&" => 3, + "==" | "!=" => 4, + "<" | ">" | "<=" | ">=" => 5, + "<<" | ">>" => 6, + "+" | "-" => 7, + "*" => 8, + _ => break, + }; + if precedence < min { + break; + } + self.next(); + self.expression(precedence + 1, depth + 1)?; + self.ops.push(Op::Binary(op)); + } + Some(()) + } + fn assignment(&mut self) -> Option<()> { + let op = if matches!(self.peek(), Tok::Ident(_, None)) { + match self.tokens.get(self.at + 1) { + Some((Tok::Op(op @ ("=" | "+=" | "-=" | "*=")), _)) => Some(*op), + _ => None, + } + } else { + None + }; + if let Some(op) = op { + let Tok::Ident(name, None) = self.next() else { + unreachable!() + }; + self.next(); + if op != "=" { + self.ops.push(Op::Load(name.clone())); + } + self.expression(0, 0)?; + if op != "=" { + self.ops.push(Op::Binary(match op { + "+=" => "+", + "-=" => "-", + _ => "*", + })); + } + self.ops.push(Op::Store(name)); + } else { + self.expression(0, 0)?; + } + Some(()) + } +} + +impl<'s> Expression<'s> { + // Tokenization can grow before the token-count rejection. Bound geometric + // capacity for one token per source byte, and at most two emitted ops per + // token, plus moved/cloned source text. The caller also admits per-command + // overhead, covering empty-input vectors and fixed container storage. + pub const STORAGE_FACTOR: usize = + 2 * std::mem::size_of::<(Tok, usize)>() + 4 * std::mem::size_of::() + 4; + + pub fn compile(source: impl Into>) -> Option { + let source = source.into(); + if source.len() > 1024 || source.contains(['$', '"', '`']) { + return None; + } + let tokens = tokenize(&source).ok()?; + if tokens.len() > 256 { + return None; + } + let mut c = Compiler { + tokens, + at: 0, + ops: Vec::new(), + }; + if source.trim().is_empty() { + c.ops.push(Op::Number(0)); + } else { + c.assignment()?; + while c.peek() == &Tok::Op(",") { + c.next(); + c.ops.push(Op::Drop); + c.assignment()?; + } + } + if c.peek() != &Tok::Eof { + return None; + } + let mut stack = 0usize; + for op in &c.ops { + match op { + Op::Number(_) | Op::Load(_) | Op::Update(..) => stack += 1, + Op::Binary(_) | Op::Drop => stack = stack.checked_sub(1)?, + _ => {} + } + if stack > 64 { + return None; + } + } + if stack != 1 { + return None; + } + Some(Self { source, ops: c.ops }) + } + pub fn names(&self) -> impl Iterator { + self.ops.iter().filter_map(|op| match op { + Op::Load(n) | Op::Store(n) | Op::Update(n, ..) => Some(n.as_str()), + _ => None, + }) + } +} + +impl Interpreter { + pub(in crate::interpreter) fn evaluate_program_expression( + &mut self, + expr: &Expression<'_>, + writes: bool, + ) -> ArithResult { + let mut budget = ArithmeticBudget::new(); + let mut ev = ArithEval::new(self, &mut budget); + let result: ArithResult = (|| { + ev.enter()?; + ev.budget.charge(&expr.source)?; + let mut stack = [0i64; 64]; + let mut used = 0; + for op in &expr.ops { + match op { + Op::Number(v) => { + stack[used] = *v; + used += 1; + } + Op::Load(n) => { + let target = ev.lvalue(n, None)?; + stack[used] = ev.read_lvalue_int(&target)?; + used += 1; + } + Op::Store(n) => { + let target = ev.lvalue(n, None)?; + ev.store(&target, stack[used - 1]); + } + Op::Update(n, delta, prefix) => { + let target = ev.lvalue(n, None)?; + let old = ev.read_lvalue_int(&target)?; + let new = old.wrapping_add(*delta); + ev.store(&target, new); + stack[used] = if *prefix { new } else { old }; + used += 1; + } + Op::Drop => used -= 1, + Op::Unary(op) => { + let v = &mut stack[used - 1]; + *v = match *op { + "!" => i64::from(*v == 0), + "~" => !*v, + "-" => v.wrapping_neg(), + _ => *v, + }; + } + Op::Binary(op) => { + let r = stack[used - 1]; + let l = stack[used - 2]; + used -= 1; + stack[used - 1] = match *op { + "+" => l.wrapping_add(r), + "-" => l.wrapping_sub(r), + "*" => l.wrapping_mul(r), + "<<" => l.wrapping_shl((r & 63) as u32), + ">>" => l.wrapping_shr((r & 63) as u32), + "&" => l & r, + "|" => l | r, + "^" => l ^ r, + "<" => i64::from(l < r), + ">" => i64::from(l > r), + "<=" => i64::from(l <= r), + ">=" => i64::from(l >= r), + "==" => i64::from(l == r), + "!=" => i64::from(l != r), + _ => unreachable!(), + }; + } + } + } + ev.leave(); + Ok(stack[0]) + })(); + let pending = ev.writes; + if writes { + self.apply_arith_writes(pending); + } + result.map_err(|m| format!("{}: {m}", diag_echo(expr.source.trim()))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn compiler_reservation_covers_tokenizer_capacity_before_decline() { + for source in ["()".repeat(512), format!("{}a", "a+=1,".repeat(63))] { + let tokens = tokenize(&source).unwrap(); + let token_storage = tokens.capacity() * std::mem::size_of::<(Tok, usize)>(); + drop(tokens); + let expression = Expression::compile(source.as_str()); + let op_storage = expression + .as_ref() + .map_or(0, |e| e.ops.capacity() * std::mem::size_of::()); + let reservation = (source.len() + 128) * Expression::STORAGE_FACTOR + 4096; + assert!( + reservation >= token_storage + op_storage, + "compiler buffers need {}, admitted bound {reservation}", + token_storage + op_storage + ); + } + } + + #[test] + fn expressions_match_evaluator_values_and_ordered_writes() { + for value in ["0", "7", "1+2", "9223372036854775807"] { + for source in [ + "x+=3", + "x=x*2+1", + "x++ + x", + "++x", + "x<9", + "x<<65", + "x=3, x+=4, x*2", + "!(x+3)", + "~x & 0xff", + "x=0, x--, x", + ] { + let mut a = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + let mut b = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + a.set_variable("x".into(), value.into()); + b.set_variable("x".into(), value.into()); + let expected = a.try_evaluate_arithmetic_with_assign(source); + let expr = Expression::compile(source).unwrap(); + let actual = b.evaluate_program_expression(&expr, true); + assert_eq!(actual, expected, "{source}, x={value}"); + assert_eq!( + a.lookup_regular_variable("x"), + b.lookup_regular_variable("x") + ); + } + } + } + #[test] + fn unsupported_grammar_uses_fallback() { + for source in [ + "x/0", + "a[0]++", + "x && y++", + "x?y:z", + "$x+1", + "x**2", + "x=(y=3)", + "08", + "x<$(echo 4)", + ] { + assert!(Expression::compile(source).is_none(), "{source}"); + } + } +} diff --git a/crates/bashkit/src/interpreter/command_dispatch.rs b/crates/bashkit/src/interpreter/command_dispatch.rs new file mode 100644 index 000000000..11513e1e0 --- /dev/null +++ b/crates/bashkit/src/interpreter/command_dispatch.rs @@ -0,0 +1,320 @@ +//! Shared command boundaries expanded into separate ordinary/compiled futures. +//! Keeping the AST future free of plan state avoids taxing fallback commands. +use super::*; + +pub(super) type CommandFuture<'a> = + std::pin::Pin> + Send + 'a>>; + +// One boundary definition: guards, accounting, pipes, diagnostics and ERR traps +// stay identical while each async frame contains only its own execution body. +macro_rules! command_future { + ($shell:ident, $command:ident, $body:expr) => { + // THREAT[TM-DOS-142]: every nesting level passes through here, so + // each poll gets enough native stack (see grow_stack.rs). + Box::pin(grow_stack::GrowStack::new(async move { + // Whether ERR may fire after this command: bash decides before + // running it, so a trap the command itself sets (`f` setting + // ERR inside) does not fire for that same command. + if $shell.counters.commands > 0 + && $shell.counters.commands.is_multiple_of(64) + && $shell.execution_output().is_some() + { + crate::execution::yield_once().await; + } + let skip_stage = std::mem::take(&mut $shell.err_trap_skip_stage); + let err_armed = + !skip_stage && $shell.err_trap_armed() && Self::fires_err_trap($command); + let emit_before = $shell.output_emit_count; + $shell.check_cancelled()?; + // Update current line for $LINENO + $shell.set_command_lineno($command); + if let Some(name) = Self::command_name($command) { + $shell.last_command_name = name.to_string(); + } + + // `set -n`: read commands without running them for the rest of + // this exec (bash does the same in scripts; nothing can undo it, + // since `set +n` is not run either). + if $shell.flags.contains(BashFlags::NOEXEC) { + return Ok(ExecResult::ok(String::new())); + } + + // Fail point: inject failures during command execution + #[cfg(feature = "failpoints")] + fail_point!("interp::execute_command", |action| { + match action.as_deref() { + Some("panic") => { + // Test panic recovery + panic!("injected panic in execute_command"); + } + Some("error") => { + return Err(Error::Execution("injected execution error".to_string())); + } + Some("exit_nonzero") => { + // Return non-zero exit code without error + return Ok(ExecResult { + stdout: crate::StreamData::new(), + stderr: "injected failure".into(), + exit_code: 127, + control_flow: ControlFlow::None, + ..Default::default() + }); + } + _ => {} + } + Ok(ExecResult::ok(String::new())) + }); + + $shell.charge_command_execution()?; + + if $shell.pipe_out.is_some() + && let Some(killed) = Box::pin($shell.wait_for_pipe_room()).await + { + return Ok(killed); + } + + let result = $body; + let mut result = result; + $shell.settle_pending_subst_stderr(&mut result); + let mut result = $shell.abort_line_on_error(result); + if err_armed + && let Ok(r) = &mut result + && r.exit_code != 0 + && r.control_flow == ControlFlow::None + && !r.errexit_suppressed + && !$shell.is_in_condition_sequence() + { + // `$LINENO` in the handler is the failing command's line. + $shell.set_command_lineno($command); + Box::pin($shell.run_err_trap_after(r, emit_before)).await; + } + result + })) + }; +} + +// Keep the ordinary list future's original structure. Only prepared lists carry +// a selector; the orchestration itself still has a single definition. +macro_rules! list_command { + (plain,$shell:ident,$command:expr,$index:expr) => { + $shell.execute_command($command) + }; + (prepared,$shell:ident,$command:expr,$index:expr,$commands:ident) => { + $commands.execute($shell, $command, $index) + }; +} +macro_rules! list_body { + ($kind:ident,$shell:ident,$list:ident,$route:ident $(,$commands:ident)?)=> {{ + let mut stdout = crate::StreamData::new(); + let mut stderr = crate::StreamData::new(); + let mut exit_code; + let mut control_flow; + let mut exit_code_from_conditional_context = false; + + // Determine if the first command should run in the background. + // The `&` terminator for first appears as rest[0].op == Background. + let first_is_bg = matches!($list.rest.first(), Some((ListOperator::Background, _))); + + if first_is_bg { + // Boxed: the job path holds a forked Interpreter across an await, + // which would otherwise bloat every recursive execute_list frame. + Box::pin($shell.spawn_in_background(&$list.first, &mut stdout, &mut stderr)).await?; + exit_code = 0; + control_flow = ControlFlow::None; + exit_code_from_conditional_context = false; + } else { + let emit_before = $shell.output_emit_count; + let emitted_before = ( + $shell.output_stream_stdout_bytes, + $shell.output_stream_stderr_bytes, + ); + $shell.sequence_accum = (0, 0); + // A non-final `&&`/`||` element runs with errexit ignored. + let conditional = $list + .rest + .first() + .is_some_and(|(op, _)| matches!(op, ListOperator::And | ListOperator::Or)); + $shell.condition_sequence_depth += usize::from(conditional); + let result = list_command!($kind, $shell, &$list.first, 0 $(, $commands)?).await; + $shell.condition_sequence_depth -= usize::from(conditional); + let mut result = result?; + if $route { + Box::pin($shell.route_exec_output( + &mut result, + emitted_before, + (0, 0), + Self::command_name(&$list.first), + )) + .await?; + } + if $shell.merge_stderr { + Self::merge_stderr_into_stdout(&mut result); + } + $shell.maybe_emit_output(&result.stdout, &result.stderr, emit_before) + .await?; + if $route { + Box::pin($shell.flush_exec_passthrough(&mut result)).await?; + } + if $shell.retain_streamed_output() { + stdout.append(&result.stdout); + stderr.append(&result.stderr); + } + exit_code = result.exit_code; + $shell.last_exit_code = exit_code; + control_flow = result.control_flow; + exit_code_from_conditional_context = result.errexit_suppressed + || $list + .rest + .first() + .is_some_and(|(op, _)| matches!(op, ListOperator::And | ListOperator::Or)); + + // If first command signaled control flow, return immediately + if control_flow != ControlFlow::None { + return Ok(ExecResult { + stdout, + stderr, + exit_code, + control_flow, + ..Default::default() + }); + } + } + + for (i, (op, cmd)) in $list.rest.iter().enumerate() { + // Skip empty sentinel commands (produced by trailing `&`) + if Self::is_empty_sentinel(cmd) { + continue; + } + + // Check if this command is followed by another && / || operator. + // POSIX `errexit` suppression applies to non-final commands in an + // AND-OR list; the final executed command can still abort on failure. + let current_is_conditional = matches!(op, ListOperator::And | ListOperator::Or); + + // Determine if THIS command should be backgrounded. + // A command is backgrounded when the NEXT separator is Background + // (the `&` terminates the current command). + let should_background = + matches!($list.rest.get(i + 1), Some((ListOperator::Background, _))); + + // Check errexit before executing next semicolon-separated command: + // if previous command failed outside conditional context, exit now. + let should_check_errexit = matches!(op, ListOperator::Semicolon) + && $shell.errexit_active() + && exit_code != 0 + && !exit_code_from_conditional_context; + + if should_check_errexit { + return Ok(ExecResult { + stdout, + stderr, + exit_code, + control_flow: ControlFlow::None, + ..Default::default() + }); + } + + let should_execute = match op { + ListOperator::And => exit_code == 0, + ListOperator::Or => exit_code != 0, + ListOperator::Semicolon | ListOperator::Background => true, + }; + + if !should_execute && current_is_conditional { + // Short-circuited && / ||: the carried exit code came from + // a conditional chain, so errexit must not fire on it. + exit_code_from_conditional_context = true; + } + + if should_execute { + if should_background { + Box::pin($shell.spawn_in_background(cmd, &mut stdout, &mut stderr)).await?; + exit_code = 0; + exit_code_from_conditional_context = false; + } else { + let emit_before = $shell.output_emit_count; + let emitted_before = ( + $shell.output_stream_stdout_bytes, + $shell.output_stream_stderr_bytes, + ); + $shell.sequence_accum = (stdout.len(), stderr.len()); + let followed_by_conditional_op = + $list.rest.get(i + 1).is_some_and(|(op, cmd)| { + !Self::is_empty_sentinel(cmd) + && matches!(op, ListOperator::And | ListOperator::Or) + }); + $shell.condition_sequence_depth += usize::from(followed_by_conditional_op); + let result = list_command!($kind, $shell, cmd, i + 1 $(, $commands)?).await; + $shell.condition_sequence_depth -= usize::from(followed_by_conditional_op); + let mut result = result?; + if $route { + Box::pin($shell.route_exec_output( + &mut result, + emitted_before, + (0, 0), + Self::command_name(cmd), + )) + .await?; + } + if $shell.merge_stderr { + Self::merge_stderr_into_stdout(&mut result); + } + $shell.maybe_emit_output(&result.stdout, &result.stderr, emit_before) + .await?; + if $route { + Box::pin($shell.flush_exec_passthrough(&mut result)).await?; + } + if $shell.retain_streamed_output() { + stdout.append(&result.stdout); + stderr.append(&result.stderr); + } + exit_code = result.exit_code; + $shell.last_exit_code = exit_code; + control_flow = result.control_flow; + // Bash suppresses errexit for AND-OR list elements except the + // command following the final &&/|| operator. + exit_code_from_conditional_context = + followed_by_conditional_op || result.errexit_suppressed; + + // If command signaled control flow, return immediately + if control_flow != ControlFlow::None { + return Ok(ExecResult { + stdout, + stderr, + exit_code, + control_flow, + ..Default::default() + }); + } + } + } + } + + // Final errexit check for the last command. A non-zero status only + // remains suppressed when it was carried from a short-circuited or + // non-final AND-OR list element; a failing final &&/|| command exits. + let should_final_errexit_check = $shell.errexit_active() + && exit_code != 0 + && !exit_code_from_conditional_context + && !$shell.is_in_condition_sequence(); + + if should_final_errexit_check { + return Ok(ExecResult { + stdout, + stderr, + exit_code, + control_flow: ControlFlow::None, + ..Default::default() + }); + } + + Ok(ExecResult { + stdout, + stderr, + exit_code, + control_flow: ControlFlow::None, + errexit_suppressed: exit_code_from_conditional_context && exit_code != 0, + ..Default::default() + }) + }}; +} diff --git a/crates/bashkit/src/interpreter/mod.rs b/crates/bashkit/src/interpreter/mod.rs index 649415a85..ccb725dbf 100644 --- a/crates/bashkit/src/interpreter/mod.rs +++ b/crates/bashkit/src/interpreter/mod.rs @@ -42,6 +42,8 @@ // with a diagnostic; handler logic failures never disturb the interrupted // command (TM-DOS-030), while the first resource-limit trip fails the exec. mod arithmetic; +#[macro_use] +mod command_dispatch; mod brace_expansion; mod completion; mod coproc; @@ -57,6 +59,8 @@ mod prompt; mod readline_bind; mod readline_defaults; mod redirection; +#[cfg(feature = "experimental_execution_plan")] +mod script_plan; mod state; mod time_command; mod xtrace; @@ -4288,6 +4292,27 @@ impl Interpreter { run_exit_trap: bool, fire_exit_hook: bool, ) -> Result { + #[cfg(feature = "experimental_execution_plan")] + let plan = { + #[cfg(feature = "experimental_plan_benchmark_control")] + let enabled = self + .current_execution_extensions() + .get::() + .and_then(|mode| { + mode.try_with(|mode| { + matches!(mode, crate::ExperimentalPlanBenchmarkControl::Auto) + }) + .ok() + }) + .unwrap_or(true); + #[cfg(not(feature = "experimental_plan_benchmark_control"))] + let enabled = true; + if enabled { + script_plan::ScriptPlan::compile(script, &self.execution_budget)? + } else { + None + } + }; let mut stdout = crate::StreamData::new(); let mut stderr = crate::StreamData::new(); let mut exit_code = 0; @@ -4344,6 +4369,18 @@ impl Interpreter { ); self.route_top_list = top_level && matches!(command, Command::List(_)); self.top_list_routed = None; + #[cfg(feature = "experimental_execution_plan")] + let result = self + .execute_command_with_program( + command, + if matches!(view, ScriptView::Parsed(_)) { + plan.as_ref().and_then(|p| p.command(index)) + } else { + None + }, + ) + .await; + #[cfg(not(feature = "experimental_execution_plan"))] let result = self.execute_command(command).await; self.route_top_list = false; let list_routed = self.top_list_routed.take(); @@ -4705,71 +4742,9 @@ impl Interpreter { fn execute_command<'a>( &'a mut self, command: &'a Command, - ) -> std::pin::Pin> + Send + 'a>> { - // THREAT[TM-DOS-142]: every nesting level passes through here, so - // each poll gets enough native stack (see grow_stack.rs). - Box::pin(grow_stack::GrowStack::new(async move { - // Whether ERR may fire after this command: bash decides before - // running it, so a trap the command itself sets (`f` setting - // ERR inside) does not fire for that same command. - if self.counters.commands > 0 - && self.counters.commands.is_multiple_of(64) - && self.execution_output().is_some() - { - crate::execution::yield_once().await; - } - let skip_stage = std::mem::take(&mut self.err_trap_skip_stage); - let err_armed = !skip_stage && self.err_trap_armed() && Self::fires_err_trap(command); - let emit_before = self.output_emit_count; - self.check_cancelled()?; - // Update current line for $LINENO - self.set_command_lineno(command); - if let Some(name) = Self::command_name(command) { - self.last_command_name = name.to_string(); - } - - // `set -n`: read commands without running them for the rest of - // this exec (bash does the same in scripts; nothing can undo it, - // since `set +n` is not run either). - if self.flags.contains(BashFlags::NOEXEC) { - return Ok(ExecResult::ok(String::new())); - } - - // Fail point: inject failures during command execution - #[cfg(feature = "failpoints")] - fail_point!("interp::execute_command", |action| { - match action.as_deref() { - Some("panic") => { - // Test panic recovery - panic!("injected panic in execute_command"); - } - Some("error") => { - return Err(Error::Execution("injected execution error".to_string())); - } - Some("exit_nonzero") => { - // Return non-zero exit code without error - return Ok(ExecResult { - stdout: crate::StreamData::new(), - stderr: "injected failure".into(), - exit_code: 127, - control_flow: ControlFlow::None, - ..Default::default() - }); - } - _ => {} - } - Ok(ExecResult::ok(String::new())) - }); - - self.charge_command_execution()?; - - if self.pipe_out.is_some() - && let Some(killed) = Box::pin(self.wait_for_pipe_room()).await - { - return Ok(killed); - } - - let result = match command { + ) -> command_dispatch::CommandFuture<'a> { + command_future!(self, command, { + match command { Command::Simple(simple) => { // One Result local (not `?` + a second ExecResult copy): // this frame repeats per `$(...)` nesting level. @@ -4838,23 +4813,20 @@ impl Interpreter { result } Command::Function(func_def) => Ok(self.define_function(func_def)), - }; - let mut result = result; - self.settle_pending_subst_stderr(&mut result); - let mut result = self.abort_line_on_error(result); - if err_armed - && let Ok(r) = &mut result - && r.exit_code != 0 - && r.control_flow == ControlFlow::None - && !r.errexit_suppressed - && !self.is_in_condition_sequence() - { - // `$LINENO` in the handler is the failing command's line. - self.set_command_lineno(command); - Box::pin(self.run_err_trap_after(r, emit_before)).await; } - result - })) + }) + } + + #[cfg(feature = "experimental_execution_plan")] + fn execute_command_with_program<'a>( + &'a mut self, + command: &'a Command, + program: Option>, + ) -> command_dispatch::CommandFuture<'a> { + let Some(program) = program.filter(|p| p.eligible(self)) else { + return self.execute_command(command); + }; + command_future!(self, command, Box::pin(self.execute_program(program)).await) } /// Queue stderr written inside `$(...)` for the command that expanded it @@ -8495,217 +8467,18 @@ impl Interpreter { /// `route`: this list is a top-level command; route each element's output /// through the `exec` fd table as it finishes (see `route_top_list`). async fn execute_list(&mut self, list: &CommandList, route: bool) -> Result { - let mut stdout = crate::StreamData::new(); - let mut stderr = crate::StreamData::new(); - let mut exit_code; - let mut control_flow; - let mut exit_code_from_conditional_context = false; - - // Determine if the first command should run in the background. - // The `&` terminator for first appears as rest[0].op == Background. - let first_is_bg = matches!(list.rest.first(), Some((ListOperator::Background, _))); - - if first_is_bg { - // Boxed: the job path holds a forked Interpreter across an await, - // which would otherwise bloat every recursive execute_list frame. - Box::pin(self.spawn_in_background(&list.first, &mut stdout, &mut stderr)).await?; - exit_code = 0; - control_flow = ControlFlow::None; - exit_code_from_conditional_context = false; - } else { - let emit_before = self.output_emit_count; - let emitted_before = ( - self.output_stream_stdout_bytes, - self.output_stream_stderr_bytes, - ); - self.sequence_accum = (0, 0); - // A non-final `&&`/`||` element runs with errexit ignored. - let conditional = list - .rest - .first() - .is_some_and(|(op, _)| matches!(op, ListOperator::And | ListOperator::Or)); - self.condition_sequence_depth += usize::from(conditional); - let result = self.execute_command(&list.first).await; - self.condition_sequence_depth -= usize::from(conditional); - let mut result = result?; - if route { - Box::pin(self.route_exec_output( - &mut result, - emitted_before, - (0, 0), - Self::command_name(&list.first), - )) - .await?; - } - if self.merge_stderr { - Self::merge_stderr_into_stdout(&mut result); - } - self.maybe_emit_output(&result.stdout, &result.stderr, emit_before) - .await?; - if route { - Box::pin(self.flush_exec_passthrough(&mut result)).await?; - } - if self.retain_streamed_output() { - stdout.append(&result.stdout); - stderr.append(&result.stderr); - } - exit_code = result.exit_code; - self.last_exit_code = exit_code; - control_flow = result.control_flow; - exit_code_from_conditional_context = result.errexit_suppressed - || list - .rest - .first() - .is_some_and(|(op, _)| matches!(op, ListOperator::And | ListOperator::Or)); - - // If first command signaled control flow, return immediately - if control_flow != ControlFlow::None { - return Ok(ExecResult { - stdout, - stderr, - exit_code, - control_flow, - ..Default::default() - }); - } - } - - for (i, (op, cmd)) in list.rest.iter().enumerate() { - // Skip empty sentinel commands (produced by trailing `&`) - if Self::is_empty_sentinel(cmd) { - continue; - } - - // Check if this command is followed by another && / || operator. - // POSIX `errexit` suppression applies to non-final commands in an - // AND-OR list; the final executed command can still abort on failure. - let current_is_conditional = matches!(op, ListOperator::And | ListOperator::Or); - - // Determine if THIS command should be backgrounded. - // A command is backgrounded when the NEXT separator is Background - // (the `&` terminates the current command). - let should_background = - matches!(list.rest.get(i + 1), Some((ListOperator::Background, _))); - - // Check errexit before executing next semicolon-separated command: - // if previous command failed outside conditional context, exit now. - let should_check_errexit = matches!(op, ListOperator::Semicolon) - && self.errexit_active() - && exit_code != 0 - && !exit_code_from_conditional_context; - - if should_check_errexit { - return Ok(ExecResult { - stdout, - stderr, - exit_code, - control_flow: ControlFlow::None, - ..Default::default() - }); - } - - let should_execute = match op { - ListOperator::And => exit_code == 0, - ListOperator::Or => exit_code != 0, - ListOperator::Semicolon | ListOperator::Background => true, - }; - - if !should_execute && current_is_conditional { - // Short-circuited && / ||: the carried exit code came from - // a conditional chain, so errexit must not fire on it. - exit_code_from_conditional_context = true; - } - - if should_execute { - if should_background { - Box::pin(self.spawn_in_background(cmd, &mut stdout, &mut stderr)).await?; - exit_code = 0; - exit_code_from_conditional_context = false; - } else { - let emit_before = self.output_emit_count; - let emitted_before = ( - self.output_stream_stdout_bytes, - self.output_stream_stderr_bytes, - ); - self.sequence_accum = (stdout.len(), stderr.len()); - let followed_by_conditional_op = - list.rest.get(i + 1).is_some_and(|(op, cmd)| { - !Self::is_empty_sentinel(cmd) - && matches!(op, ListOperator::And | ListOperator::Or) - }); - self.condition_sequence_depth += usize::from(followed_by_conditional_op); - let result = self.execute_command(cmd).await; - self.condition_sequence_depth -= usize::from(followed_by_conditional_op); - let mut result = result?; - if route { - Box::pin(self.route_exec_output( - &mut result, - emitted_before, - (0, 0), - Self::command_name(cmd), - )) - .await?; - } - if self.merge_stderr { - Self::merge_stderr_into_stdout(&mut result); - } - self.maybe_emit_output(&result.stdout, &result.stderr, emit_before) - .await?; - if route { - Box::pin(self.flush_exec_passthrough(&mut result)).await?; - } - if self.retain_streamed_output() { - stdout.append(&result.stdout); - stderr.append(&result.stderr); - } - exit_code = result.exit_code; - self.last_exit_code = exit_code; - control_flow = result.control_flow; - // Bash suppresses errexit for AND-OR list elements except the - // command following the final &&/|| operator. - exit_code_from_conditional_context = - followed_by_conditional_op || result.errexit_suppressed; - - // If command signaled control flow, return immediately - if control_flow != ControlFlow::None { - return Ok(ExecResult { - stdout, - stderr, - exit_code, - control_flow, - ..Default::default() - }); - } - } - } - } - - // Final errexit check for the last command. A non-zero status only - // remains suppressed when it was carried from a short-circuited or - // non-final AND-OR list element; a failing final &&/|| command exits. - let should_final_errexit_check = self.errexit_active() - && exit_code != 0 - && !exit_code_from_conditional_context - && !self.is_in_condition_sequence(); - - if should_final_errexit_check { - return Ok(ExecResult { - stdout, - stderr, - exit_code, - control_flow: ControlFlow::None, - ..Default::default() - }); - } + list_body!(plain, self, list, route) + } - Ok(ExecResult { - stdout, - stderr, - exit_code, - control_flow: ControlFlow::None, - errexit_suppressed: exit_code_from_conditional_context && exit_code != 0, - ..Default::default() - }) + #[cfg(feature = "experimental_execution_plan")] + #[allow(unused_assignments)] + async fn execute_prepared_list( + &mut self, + list: &CommandList, + route: bool, + commands: script_plan::PreparedCommands<'_, '_>, + ) -> Result { + list_body!(prepared, self, list, route, commands) } /// Process variable assignments from a command's prefix (e.g. `VAR=val cmd`). diff --git a/crates/bashkit/src/interpreter/script_plan.rs b/crates/bashkit/src/interpreter/script_plan.rs new file mode 100644 index 000000000..e96d4df19 --- /dev/null +++ b/crates/bashkit/src/interpreter/script_plan.rs @@ -0,0 +1,974 @@ +//! Isolated whole-script execution-plan experiment (off by default). +//! +//! THREAT[TM-DOS-147]: plans borrow one parsed Script, live only for that execution, and reserve +//! storage before lowering. Pure scalar command trees lower to a flat program. +//! Mixed command lists keep the existing shell orchestration with prepared +//! children. Unsupported syntax/state uses the ordinary interpreter. No global +//! cache, pointer-keyed lookup, or new shell syntax is involved. +use super::*; +use arithmetic::program::Expression; + +pub(super) struct ScriptPlan<'s> { + commands: Vec>>, + ops: Vec>, + _storage: crate::limits::ExecutionBudgetLease, +} + +pub(super) enum Program<'s> { + Native(NativeProgram), + List { + list: &'s CommandList, + children: Vec>>, + }, +} + +pub(super) struct NativeProgram { + range: std::ops::Range, +} + +#[derive(Clone, Copy)] +pub(super) struct ProgramRef<'p, 's> { + program: &'p Program<'s>, + ops: &'p [Instruction<'s>], +} + +struct Builder<'b, 's> { + budget: &'b crate::limits::ExecutionBudget, + used: usize, + admitted: usize, + ops: Vec>, + #[cfg(test)] + _after_buffers: Option, + // Rust drops fields in declaration order: release admission only after + // all owning buffers (including partially lowered regions) are destroyed. + storage: crate::limits::ExecutionBudgetLease, +} + +#[cfg(test)] +struct AfterBuffers(Option>); +#[cfg(test)] +impl Drop for AfterBuffers { + fn drop(&mut self) { + if let Some(check) = self.0.take() { + check(); + } + } +} +impl Builder<'_, '_> { + fn reserve(&mut self, bytes: usize) -> Result { + let Some(used) = self.used.checked_add(bytes) else { + return Ok(false); + }; + if used > self.admitted { + let capacity = used.checked_next_power_of_two().unwrap_or(used); + if !self.storage.try_grow_plan_to(capacity)? { + return Ok(false); + } + self.admitted = capacity; + } + self.used = used; + Ok(true) + } +} + +enum Instruction<'s> { + Enter(&'s Command, bool), + Leave(&'s Command), + Assign(&'s SimpleCommand), + Arithmetic(Expression<'s>, Mode), + Status(i32), + Jump(usize), + BranchStatus(usize, bool), + BranchTest(usize), + LoopStart, + Iteration(Option), + Line(usize), + RememberBody, + LoopEnd, +} + +#[derive(Clone, Copy)] +enum Mode { + Command, + Condition, + Clause, +} + +fn numeric(value: &str) -> bool { + if value.len() > 128 { + return false; + } + let value = value.trim(); + if value.is_empty() { + return true; + } + // A chain of signs is an expression (or malformed increment), not a + // literal. Keep recursive variable evaluation outside native admission. + let magnitude = value + .strip_prefix('-') + .or_else(|| value.strip_prefix('+')) + .unwrap_or(value); + magnitude.as_bytes().first().is_some_and(u8::is_ascii_digit) + && arithmetic::parse_arith_number(magnitude).is_ok() +} + +fn assignments(simple: &SimpleCommand) -> bool { + simple.name.parts.iter().all(|p| matches!(p,WordPart::Literal(s) if s.is_empty())) + && simple.args.is_empty() && simple.redirects.is_empty() && !simple.assignments.is_empty() + && simple.assignments.iter().all(|a| { + a.index.is_none() && !a.append && matches!(&a.value, + AssignmentValue::Scalar(w) if matches!(w.parts.as_slice(), [WordPart::Literal(s)] if numeric(s))) + }) +} + +// Bound traversal before reserving any lowering buffers. Parser depth is bounded +// separately; this optional backend declines deeper/larger trees. +fn size(command: &Command, depth: usize) -> Option { + if depth > 64 { + return None; + } + let sequence = |body: &[Command]| { + body.iter() + .try_fold(0usize, |n, c| n.checked_add(size(c, depth + 1)?)) + }; + let extra = match command { + Command::Simple(s) if assignments(s) => { + s.assignments.iter().map(|a| a.name.len() + 64).sum() + } + Command::List(l) => { + size(&l.first, depth + 1)? + + l.rest + .iter() + .try_fold(0usize, |n, (_, c)| Some(n + size(c, depth + 1)?))? + } + Command::Compound(c, r) if r.is_empty() => match c { + CompoundCommand::Arithmetic(e) => e.len(), + CompoundCommand::ArithmeticFor(f) => { + f.init.len() + f.condition.len() + f.step.len() + sequence(&f.body)? + } + CompoundCommand::While(w) => sequence(&w.condition)? + sequence(&w.body)?, + CompoundCommand::Until(w) => sequence(&w.condition)? + sequence(&w.body)?, + CompoundCommand::BraceGroup(b) => sequence(b)?, + CompoundCommand::If(i) => { + sequence(&i.condition)? + + sequence(&i.then_branch)? + + i.elif_branches + .iter() + .try_fold(0usize, |n, (c, b)| Some(n + sequence(c)? + sequence(b)?))? + + i.else_branch.as_ref().map_or(Some(0), |b| sequence(b))? + } + _ => return None, + }, + _ => return None, + }; + let total = extra.checked_add(128)?; + (total <= 32768).then_some(total) +} + +// A small cold statement rarely recovers the cost of lowering it. The cheap +// probe stays inline; full lowering is outlined away from ordinary tool calls. +#[inline] +fn worthwhile(command: &Command, weight: &mut usize, depth: usize) -> bool { + if depth > 64 { + return false; + } + match command { + Command::Simple(s) => { + if assignments(s) { + *weight = weight.saturating_add(1); + } + } + Command::Compound(CompoundCommand::Arithmetic(_), r) if r.is_empty() => { + *weight = weight.saturating_add(1); + } + Command::Compound( + CompoundCommand::ArithmeticFor(_) + | CompoundCommand::While(_) + | CompoundCommand::Until(_), + r, + ) if r.is_empty() => { + return size(command, 0).is_some(); + } + Command::Compound(_, _) => { + if let Some(bytes) = size(command, 0) { + *weight = weight.saturating_add(bytes / 128); + } + } + Command::List(list) => return worthwhile_list(list, weight, depth), + _ => {} + } + *weight >= 8 +} +fn worthwhile_list(list: &CommandList, weight: &mut usize, depth: usize) -> bool { + std::iter::once(list.first.as_ref()) + .chain(list.rest.iter().map(|(_, c)| c)) + .any(|c| worthwhile(c, weight, depth + 1)) +} + +impl<'s> ScriptPlan<'s> { + #[inline] + pub fn compile( + script: &'s Script, + budget: &crate::limits::ExecutionBudget, + ) -> Result>> { + let mut weight = 0; + if !script + .commands + .iter() + .any(|c| worthwhile(c, &mut weight, 0)) + { + return Ok(None); + } + Self::lower_script(script, budget) + } + + #[cold] + fn lower_script( + script: &'s Script, + budget: &crate::limits::ExecutionBudget, + ) -> Result>> { + let capacity = script.commands.len().saturating_mul(4).clamp(8, 256); + let bytes = script + .commands + .len() + .saturating_mul(std::mem::size_of::>>()) + .saturating_add(std::mem::size_of::()) + .saturating_add(capacity.saturating_mul(std::mem::size_of::>())); + let Some(storage) = budget.try_lease_plan(bytes)? else { + return Ok(None); + }; + let mut builder = Builder { + budget, + storage, + used: bytes, + admitted: bytes, + ops: Vec::with_capacity(capacity), + #[cfg(test)] + _after_buffers: None, + }; + // Keep capacity equal to the admitted command storage; collecting a + // fallible iterator may otherwise grow geometrically past its length. + let mut commands = Vec::with_capacity(script.commands.len()); + for command in &script.commands { + commands.push(Program::compile(command, &mut builder, 0)?); + } + if commands.iter().all(Option::is_none) { + return Ok(None); + } + Ok(Some(Box::new(Self { + commands, + ops: builder.ops, + _storage: builder.storage, + }))) + } + pub fn command(&self, index: usize) -> Option> { + self.commands[index].as_ref().map(|program| ProgramRef { + program, + ops: &self.ops, + }) + } +} + +impl<'s> Program<'s> { + fn compile( + command: &'s Command, + builder: &mut Builder<'_, 's>, + depth: usize, + ) -> Result> { + if depth > 64 { + return Ok(None); + } + if let Some(bytes) = size(command, 0) { + builder.budget.consume_work(bytes as u64)?; + let used = builder.used; + let capacity = builder.ops.capacity(); + if !builder.reserve(bytes * Expression::STORAGE_FACTOR + 4096)? { + return Ok(None); + } + let start = builder.ops.len(); + if lower(command, &mut builder.ops, true).is_some() { + return Ok(Some(Self::Native(NativeProgram { + range: start..builder.ops.len(), + }))); + } + builder.ops.truncate(start); + // Failed lowering drops expression buffers, but retains the shared + // vector capacity. Keep those actual retained bytes admitted. + builder.used = used.saturating_add( + (builder.ops.capacity() - capacity) + .saturating_mul(std::mem::size_of::>()), + ); + } + if let Command::List(list) = command { + if !builder.reserve( + (list.rest.len() + 1).saturating_mul(std::mem::size_of::>>()), + )? { + return Ok(None); + } + let mut children = Vec::with_capacity(list.rest.len() + 1); + for command in + std::iter::once(list.first.as_ref()).chain(list.rest.iter().map(|(_, c)| c)) + { + children.push(Self::compile(command, builder, depth + 1)?); + } + if children.iter().all(Option::is_none) { + return Ok(None); + } + return Ok(Some(Self::List { list, children })); + } + Ok(None) + } +} + +impl ProgramRef<'_, '_> { + pub fn eligible(&self, shell: &Interpreter) -> bool { + let Program::Native(program) = self.program else { + return true; + }; + // TODO(experiment): lower these contexts only after their boundary + // semantics have dedicated VM coverage. Fallback is a normal execution. + // Resource failpoints must exercise native fuel checks too. Only the + // command-boundary injector needs AST execution: its early status/error + // actions deliberately replace a whole shell command. This lookup is + // compiled out of production builds. + #[cfg(feature = "failpoints")] + if fail::list() + .iter() + .any(|(name, action)| name == "interp::execute_command" && action != "off") + { + return false; + } + if shell.is_errexit_enabled() + || shell.is_nounset() + || shell.is_xtrace_enabled() + || shell.flags.contains(BashFlags::NOEXEC) + || !shell.scoped.traps.is_empty() + || shell.pipe_out.is_some() + || !shell.subst_stderr.is_empty() + || shell.has_arith_unbound() + { + return false; + } + let plain = |name: &str| { + shell + .var_attrs_get(name) + .difference(VarAttrs::EXPORT) + .is_empty() + && !shell.scoped.arrays.contains_key(name) + && !shell.scoped.assoc_arrays.contains_key(name) + && shell.resolve_nameref(name) == name + && shell.lookup_regular_variable_ref(name).is_none_or(numeric) + }; + self.ops[program.range.clone()].iter().all(|op| match op { + Instruction::Arithmetic(e, _) => e.names().all(plain), + Instruction::Assign(s) => s.assignments.iter().all(|a| plain(&a.name)), + _ => true, + }) + } +} + +fn expression<'s>( + source: std::borrow::Cow<'s, str>, + mode: Mode, + ops: &mut Vec>, +) -> Option<()> { + ops.push(Instruction::Arithmetic(Expression::compile(source)?, mode)); + Some(()) +} +fn sequence<'s>(commands: &'s [Command], ops: &mut Vec>) -> Option<()> { + ops.push(Instruction::Status(0)); + for command in commands { + lower(command, ops, false)?; + } + Some(()) +} +fn patch(ops: &mut [Instruction<'_>], index: usize, target: usize) { + match &mut ops[index] { + Instruction::Jump(n) | Instruction::BranchStatus(n, _) | Instruction::BranchTest(n) => { + *n = target + } + _ => unreachable!(), + } +} +fn lower<'s>(command: &'s Command, ops: &mut Vec>, root: bool) -> Option<()> { + ops.push(Instruction::Enter(command, root)); + match command { + Command::Simple(s) if assignments(s) => ops.push(Instruction::Assign(s)), + Command::List(l) if l.rest.iter().all(|(op, _)| *op == ListOperator::Semicolon) => { + lower(&l.first, ops, false)?; + for (_, c) in &l.rest { + lower(c, ops, false)?; + } + } + Command::Compound(c, r) if r.is_empty() => match c { + CompoundCommand::Arithmetic(e) => { + let source = if e.contains('"') { + std::borrow::Cow::Owned(crate::parser::arith_exec_text(e)) + } else { + std::borrow::Cow::Borrowed(e.trim()) + }; + expression(source, Mode::Command, ops)? + } + CompoundCommand::BraceGroup(b) => sequence(b, ops)?, + CompoundCommand::If(i) => { + let mut ends = Vec::new(); + for (condition, body) in std::iter::once((&i.condition, &i.then_branch)) + .chain(i.elif_branches.iter().map(|(c, b)| (c, b))) + { + sequence(condition, ops)?; + let branch = ops.len(); + ops.push(Instruction::BranchStatus(0, false)); + sequence(body, ops)?; + ends.push(ops.len()); + ops.push(Instruction::Jump(0)); + let next = ops.len(); + patch(ops, branch, next); + } + sequence(i.else_branch.as_deref().unwrap_or(&[]), ops)?; + let end = ops.len(); + for jump in ends { + patch(ops, jump, end); + } + } + CompoundCommand::ArithmeticFor(f) => { + if !f.init.is_empty() { + expression(f.init.as_str().into(), Mode::Clause, ops)?; + } + ops.push(Instruction::LoopStart); + let start = ops.len(); + ops.push(Instruction::Iteration(Some(f.span.line()))); + let mut branch = None; + if !f.condition.is_empty() { + expression(f.condition.as_str().into(), Mode::Condition, ops)?; + branch = Some(ops.len()); + ops.push(Instruction::BranchTest(0)); + } + sequence(&f.body, ops)?; + ops.push(Instruction::RememberBody); + if !f.step.is_empty() { + ops.push(Instruction::Line(f.span.line())); + expression(f.step.as_str().into(), Mode::Clause, ops)?; + } + ops.push(Instruction::Jump(start)); + let end = ops.len(); + if let Some(branch) = branch { + patch(ops, branch, end); + } + ops.push(Instruction::LoopEnd); + } + CompoundCommand::While(_) | CompoundCommand::Until(_) => { + let (condition, body, until) = match c { + CompoundCommand::While(w) => (w.condition.as_slice(), w.body.as_slice(), false), + CompoundCommand::Until(w) => (w.condition.as_slice(), w.body.as_slice(), true), + _ => unreachable!(), + }; + ops.push(Instruction::LoopStart); + let start = ops.len(); + ops.push(Instruction::Iteration(None)); + sequence(condition, ops)?; + let branch = ops.len(); + ops.push(Instruction::BranchStatus(0, until)); + sequence(body, ops)?; + ops.push(Instruction::RememberBody); + ops.push(Instruction::Jump(start)); + let end = ops.len(); + patch(ops, branch, end); + ops.push(Instruction::LoopEnd); + } + _ => return None, + }, + _ => return None, + } + ops.push(Instruction::Leave(command)); + Some(()) +} + +impl Interpreter { + pub(super) async fn execute_program( + &mut self, + program: ProgramRef<'_, '_>, + ) -> Result { + let Program::Native(native) = program.program else { + let Program::List { list, children } = program.program else { + unreachable!() + }; + let route = std::mem::take(&mut self.route_top_list); + let result = self + .execute_prepared_list( + list, + route, + PreparedCommands { + children, + ops: program.ops, + }, + ) + .await; + if route && let Ok(r) = &result { + self.top_list_routed = Some((r.stdout.len(), r.stderr.len())); + } + return result; + }; + // Loop stack is bounded by the admitted compiler depth, and restored on + // every error. No interpreter scope survives this borrowed plan. + let mut loops = [0i32; 128]; + let mut loop_count = 0; + let result = async { + let mut pc = native.range.start; + let mut status = 0; + let mut test = false; + while pc < native.range.end { + let op = &program.ops[pc]; + self.check_cancelled()?; + pc += 1; + match op { + Instruction::Enter(command, root) => { + if !root { + if self.counters.commands > 0 + && self.counters.commands.is_multiple_of(64) + { + crate::execution::yield_once().await; + } + self.set_command_lineno(command); + if let Some(name) = Self::command_name(command) { + self.last_command_name = name.to_string(); + } + self.charge_command_execution()?; + } + } + Instruction::Leave(command) => { + if matches!( + command, + Command::Simple(_) + | Command::Compound(CompoundCommand::Arithmetic(_), _) + ) { + self.set_simple_pipestatus(status); + } + let result = self.abort_line_on_error(Ok(ExecResult { + exit_code: status, + ..Default::default() + }))?; + if result.control_flow != ControlFlow::None { + return Ok(result); + } + self.last_exit_code = status; + } + Instruction::Assign(simple) => { + let result = self.execute_simple_command(simple, None).await?; + if !result.stdout.is_empty() + || !result.stderr.is_empty() + || result.control_flow != ControlFlow::None + { + return Ok(result); + } + status = result.exit_code; + } + Instruction::Arithmetic(e, mode) => { + match self.evaluate_program_expression(e, !matches!(mode, Mode::Condition)) + { + Ok(value) => match mode { + Mode::Command => status = i32::from(value == 0), + Mode::Condition => test = value != 0, + Mode::Clause => {} + }, + Err(message) => { + if matches!(mode, Mode::Command) { + return Ok(ExecResult::err( + self.arith_diag("((: ", &message), + 1, + )); + } + self.record_arith_error(message); + test = false; + } + } + } + Instruction::Status(value) => status = *value, + Instruction::Jump(target) => pc = *target, + Instruction::BranchStatus(target, success) => { + if (status == 0) == *success { + pc = *target; + } + } + Instruction::BranchTest(target) => { + if !test { + pc = *target; + } + } + Instruction::LoopStart => { + self.counters.enter_loop(); + self.loop_depth += 1; + loops[loop_count] = 0; + loop_count += 1; + } + Instruction::Iteration(line) => { + self.counters.tick_loop(&self.limits)?; + if let Some(line) = line { + self.current_line = self.line_at(*line); + } + } + Instruction::Line(line) => self.current_line = self.line_at(*line), + Instruction::RememberBody => loops[loop_count - 1] = status, + Instruction::LoopEnd => { + loop_count -= 1; + status = loops[loop_count]; + self.counters.exit_loop(); + self.loop_depth -= 1; + } + } + } + Ok(ExecResult { + exit_code: status, + ..Default::default() + }) + } + .await; + for _ in 0..loop_count { + self.counters.exit_loop(); + self.loop_depth -= 1; + } + result + } +} + +// A borrowed selector exists only in prepared lists. Ordinary list futures use +// the original direct command calls and carry no selector or plan reference. +pub(super) struct PreparedCommands<'p, 's> { + children: &'p [Option>], + ops: &'p [Instruction<'s>], +} +impl PreparedCommands<'_, '_> { + pub(super) fn execute<'a>( + &'a self, + shell: &'a mut Interpreter, + command: &'a Command, + index: usize, + ) -> command_dispatch::CommandFuture<'a> { + shell.execute_command_with_program( + command, + self.children[index].as_ref().map(|program| ProgramRef { + program, + ops: self.ops, + }), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numeric_admission_requires_a_literal_instead_of_unary_expressions() { + for value in ["++1", "--1", "-+2", "+-2", "+ 2"] { + assert!( + !numeric(value), + "expression-valued variable must fall back: {value}" + ); + } + for value in ["", "-2", "+2", " -2 ", "010", "16#ff"] { + assert!( + numeric(value), + "numeric literal should remain eligible: {value}" + ); + } + } + + #[test] + fn differential_fuzz_operator_templates_reach_native_execution() { + let interp = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + for operator in ["+", "-", "*", "^", "|", "&", "<<", ">>"] { + let source = format!( + "for ((i=0;i<8;i++)); do if ((i&1)); then ((a=a{operator}16)); else ((a+=b)); fi; done" + ); + let ast = Parser::new(&source).parse().unwrap(); + let plan = ScriptPlan::compile(&ast, &interp.execution_budget) + .unwrap() + .unwrap(); + let program = plan.command(0).unwrap(); + assert!(matches!(program.program, Program::Native(_)), "{operator}"); + assert!(program.eligible(&interp), "{operator}"); + } + } + + #[tokio::test] + async fn abandoned_native_execution_releases_plan_and_session_is_reusable() { + let mut bash = crate::Bash::new(); + let mut future = Box::pin(bash.exec("for ((i=0;i<10000;i++)); do ((a+=i)); done")); + let mut context = std::task::Context::from_waker(std::task::Waker::noop()); + assert!(std::future::Future::poll(future.as_mut(), &mut context).is_pending()); + drop(future); + assert!( + bash.interpreter + .lookup_regular_variable("i") + .unwrap() + .parse::() + .unwrap() + > 0 + ); + assert_eq!(bash.interpreter.execution_budget.live_bytes_for_test(), 0); + let next = bash + .exec("a=0; for ((i=0;i<3;i++)); do ((a+=1)); done; printf '%s' \"$a\"") + .await + .unwrap(); + assert_eq!(next.stdout, "3"); + assert_eq!(next.exit_code, 0); + assert_eq!(bash.interpreter.loop_depth, 0); + } + + #[test] + fn declined_and_failed_compilation_refund_storage() { + let ast = Parser::new("for ((i=0;i<3;i++)); do ((a+=i)); done") + .parse() + .unwrap(); + for (limits, work_error) in [ + (ExecutionLimits::new().max_live_intermediate_bytes(1), false), + (ExecutionLimits::new().max_work_units(1), true), + ] { + let budget = + crate::limits::ExecutionBudget::new(&limits, Arc::new(AtomicBool::new(false))); + let result = ScriptPlan::compile(&ast, &budget); + if work_error { + assert!(result.is_err()); + } else { + assert!(result.unwrap().is_none()); + } + assert_eq!(budget.live_bytes_for_test(), 0); + } + } + + #[cfg(feature = "failpoints")] + #[tokio::test] + async fn native_loop_fault_injection_keeps_command_budget_enforced() { + let _scenario = fail::FailScenario::setup(); + fail::cfg("limits::tick_loop", "return(reset_counter)").unwrap(); + let ast = Parser::new("for ((i=0;1;i++)); do ((a+=i)); done") + .parse() + .unwrap(); + let mut interp = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + interp.limits = ExecutionLimits::new() + .max_commands(12) + .max_loop_iterations(2); + let plan = ScriptPlan::compile(&ast, &interp.execution_budget) + .unwrap() + .unwrap(); + let program = plan.command(0).unwrap(); + assert!( + program.eligible(&interp), + "resource fault injection must reach the VM" + ); + let result = interp + .execute_command_with_program(&ast.commands[0], Some(program)) + .await; + assert!(matches!( + result, + Err(crate::Error::ResourceLimit( + crate::limits::LimitExceeded::MaxCommands(12) + )) + )); + assert_eq!(interp.loop_depth, 0); + fail::cfg("interp::execute_command", "return(error)").unwrap(); + assert!( + !program.eligible(&interp), + "command injection must retain AST boundaries" + ); + } + + #[test] + fn builder_reservation_outlives_buffer_destruction() { + let budget = crate::limits::ExecutionBudget::new( + &ExecutionLimits::new(), + Arc::new(AtomicBool::new(false)), + ); + let observed = Arc::new(std::sync::atomic::AtomicU64::new(u64::MAX)); + let observer = observed.clone(); + let shared = budget.clone(); + let builder = Builder { + budget: &budget, + storage: budget.try_lease_plan(1024).unwrap().unwrap(), + used: 1024, + admitted: 1024, + ops: Vec::with_capacity(8), + _after_buffers: Some(AfterBuffers(Some(Box::new(move || { + observer.store(shared.live_bytes_for_test(), Ordering::Relaxed); + })))), + }; + drop(builder); + assert!( + observed.load(Ordering::Relaxed) > 0, + "buffers must be released before their admission lease" + ); + assert_eq!(budget.live_bytes_for_test(), 0); + } + + #[test] + fn automatic_policy_skips_short_scripts_and_keeps_general_regions() { + let budget = crate::limits::ExecutionBudget::new( + &ExecutionLimits::new(), + Arc::new(AtomicBool::new(false)), + ); + for source in ["printf hello", "a=2; ((a+=3)); printf '%s' \"$a\""] { + let ast = Parser::new(source).parse().unwrap(); + assert!(ScriptPlan::compile(&ast, &budget).unwrap().is_none()); + } + for source in [ + "a=0; while ((a<4)); do ((a++)); done".to_string(), + format!("a=0\n{}", "((a+=1))\n".repeat(16)), + ] { + let ast = Parser::new(&source).parse().unwrap(); + assert!(ScriptPlan::compile(&ast, &budget).unwrap().is_some()); + } + } + + #[tokio::test] + async fn arena_offsets_and_failed_regions_preserve_later_branches() { + let source = "a=1\nif ((a<3)); then ((a+=2)); else a=9; fi\n((a/0))\nfor ((i=0;i<3;i++)); do ((a+=i)); done\n((a+=4))"; + let ast = Parser::new(source).parse().unwrap(); + let mut before = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + let mut after = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + let plan = ScriptPlan::lower_script(&ast, &after.execution_budget) + .unwrap() + .unwrap(); + assert!(plan.command(2).is_none(), "division must use AST fallback"); + let mut end = 0; + for (index, command) in ast.commands.iter().enumerate() { + if let Some(program) = plan.command(index) { + let Program::Native(native) = program.program else { + panic!("expected native region") + }; + assert!(native.range.start >= end); + end = native.range.end; + } + let expected = before.execute_command(command).await.unwrap(); + let actual = after + .execute_command_with_program(command, plan.command(index)) + .await + .unwrap(); + assert_eq!( + ( + expected.stdout, + expected.stderr, + expected.exit_code, + expected.control_flow + ), + ( + actual.stdout, + actual.stderr, + actual.exit_code, + actual.control_flow + ) + ); + } + for name in ["a", "i"] { + assert_eq!( + before.lookup_regular_variable(name), + after.lookup_regular_variable(name) + ); + } + assert_eq!(before.counters.commands, after.counters.commands); + } + + #[tokio::test] + async fn native_regions_match_ast_execution_and_command_charges() { + for source in [ + "a=2; ((a+=3)); if ((a<10)); then ((a*=2)); else a=0; fi", + "a=0; while ((a<8)); do ((a++)); done", + "a=0; until ((a==8)); do ((a++)); done", + "total=0; for ((i=0;i<20;i++)); do ((total+=i)); done", + "total=0; for ((i=0;i<5;i++)); do for ((j=0;j<3;j++)); do ((total+=i+j)); done; done", + "a=0; if ((a)); then a=2; elif ((1)); then a=3; else a=4; fi", + "if ((0)); then a=1; fi", + "for ((i=0;i<0;i++)); do ((i++)); done", + "a=0; { ((a++)); ((a+=7)); }", + ] { + let ast = Parser::new(source).parse().unwrap(); + let mut expected = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + let mut actual = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + let plan = ScriptPlan::lower_script(&ast, &actual.execution_budget) + .unwrap() + .unwrap(); + for (index, command) in ast.commands.iter().enumerate() { + let program = plan.command(index).expect("test must compile"); + assert!( + matches!(program.program, Program::Native(_)), + "must exercise flat instructions: {source}" + ); + assert!(program.eligible(&actual), "must exercise VM: {source}"); + let before = expected.execute_command(command).await.unwrap(); + let after = actual + .execute_command_with_program(command, Some(program)) + .await + .unwrap(); + assert_eq!( + ( + before.stdout, + before.stderr, + before.exit_code, + before.control_flow + ), + ( + after.stdout, + after.stderr, + after.exit_code, + after.control_flow + ), + "{source}" + ); + } + for name in ["a", "i", "j", "total"] { + assert_eq!( + expected.lookup_regular_variable(name), + actual.lookup_regular_variable(name), + "{source}: {name}" + ); + } + assert_eq!( + expected.counters.commands, actual.counters.commands, + "{source}" + ); + assert_eq!( + expected.scoped.arrays.get("PIPESTATUS"), + actual.scoped.arrays.get("PIPESTATUS"), + "{source}" + ); + assert_eq!(actual.loop_depth, 0); + } + } + + #[tokio::test] + async fn budget_errors_restore_native_loop_scopes() { + let ast = Parser::new("for ((i=0;i<100;i++)); do ((a+=i)); done") + .parse() + .unwrap(); + for limits in [ + ExecutionLimits::new().max_commands(5), + ExecutionLimits::new().max_loop_iterations(5), + ] { + let mut interp = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + interp.limits = limits; + let plan = ScriptPlan::lower_script(&ast, &interp.execution_budget) + .unwrap() + .unwrap(); + let result = interp + .execute_command_with_program(&ast.commands[0], plan.command(0)) + .await; + assert!(result.is_err()); + assert_eq!(interp.loop_depth, 0); + } + } + + #[test] + fn dynamic_and_instrumented_contexts_decline_native_execution() { + let ast = Parser::new("((a+=1))").parse().unwrap(); + let mut interp = Interpreter::new(Arc::new(crate::InMemoryFs::new())); + let plan = ScriptPlan::lower_script(&ast, &interp.execution_budget) + .unwrap() + .unwrap(); + let program = plan.command(0).unwrap(); + assert!(program.eligible(&interp)); + interp.set_variable("a".into(), "1+2".into()); + assert!(!program.eligible(&interp)); + interp.set_variable("a".into(), "2".into()); + interp.flags.insert(BashFlags::NOUNSET); + assert!(!program.eligible(&interp)); + } +} diff --git a/crates/bashkit/src/lib.rs b/crates/bashkit/src/lib.rs index 4b54d7664..c7756af6d 100644 --- a/crates/bashkit/src/lib.rs +++ b/crates/bashkit/src/lib.rs @@ -516,6 +516,21 @@ pub use error::{Error, Result}; pub use execution_capability::{ CapabilityCleanupReport, ExecutionCapability, ExecutionCapabilityError, ExecutionExtensions, }; + +/// Diagnostic execution selector for benchmarks and differential fuzzing, +/// passed through [`ExecOptions::extensions`]. +/// +/// Both modes must attach this same type for a matched, same-binary comparison. +/// It adds no lookup to ordinary builds of the execution-plan experiment. +#[cfg(feature = "experimental_plan_benchmark_control")] +#[doc(hidden)] +#[derive(Clone, Copy)] +pub enum ExperimentalPlanBenchmarkControl { + /// Apply the experiment's ordinary admission policy. + Auto, + /// Use the AST executor, skipping optional plan construction. + InterpreterOnly, +} pub use fs::{ DirEntry, DirListing, FileSystem, FileSystemExt, FileType, FsBackend, FsLimitExceeded, FsLimits, FsUsage, InMemoryFs, LazyLoader, Metadata, MountableFs, NamespaceAccess, NamespaceFs, diff --git a/crates/bashkit/src/limits.rs b/crates/bashkit/src/limits.rs index a8f2e4939..8b4363383 100644 --- a/crates/bashkit/src/limits.rs +++ b/crates/bashkit/src/limits.rs @@ -993,6 +993,23 @@ impl ExecutionBudget { }) } + /// Optional experiment storage may decline without poisoning the request. + #[cfg(feature = "experimental_execution_plan")] + pub(crate) fn try_lease_plan( + &self, + bytes: usize, + ) -> Result, LimitExceeded> { + self.check()?; + let bytes = u64::try_from(bytes).unwrap_or(u64::MAX); + if self.reserve_live_bytes(bytes).is_err() { + return Ok(None); + } + Ok(Some(ExecutionBudgetLease { + budget: self.clone(), + bytes, + })) + } + fn reserve_live_bytes(&self, bytes: u64) -> Result<(), u64> { reserve_atomic(&self.inner.live_bytes, bytes, self.inner.max_live_bytes).map(|_| ()) } @@ -1065,6 +1082,22 @@ impl Drop for ExecutionBudgetCompletionGuard { } impl ExecutionBudgetLease { + /// Grow an optional plan reservation without poisoning the request when + /// compilation should decline and fall back to ordinary execution. + #[cfg(feature = "experimental_execution_plan")] + pub(crate) fn try_grow_plan_to(&mut self, bytes: usize) -> Result { + self.budget.check()?; + let bytes = u64::try_from(bytes).unwrap_or(u64::MAX); + if bytes <= self.bytes { + return Ok(true); + } + if self.budget.reserve_live_bytes(bytes - self.bytes).is_err() { + return Ok(false); + } + self.bytes = bytes; + Ok(true) + } + fn try_grow_to(&mut self, bytes: u64) -> Result<(), LimitExceeded> { self.budget.check()?; if bytes <= self.bytes { @@ -2085,6 +2118,21 @@ mod tests { assert_eq!(budget.function_count, 1); } + #[test] + #[cfg(feature = "experimental_execution_plan")] + fn optional_plan_growth_declines_without_poisoning_or_leaking_bytes() { + let limits = ExecutionLimits::new().max_live_intermediate_bytes(32); + let budget = ExecutionBudget::new(&limits, Arc::new(AtomicBool::new(false))); + let mut storage = budget.try_lease_plan(8).unwrap().unwrap(); + assert!(storage.try_grow_plan_to(16).unwrap()); + assert_eq!(budget.live_bytes_for_test(), 16); + assert!(!storage.try_grow_plan_to(64).unwrap()); + assert_eq!(budget.live_bytes_for_test(), 16); + assert!(budget.check().is_ok()); + drop(storage); + assert_eq!(budget.live_bytes_for_test(), 0); + } + #[test] fn execution_budget_live_leases_release_but_exhaustion_poisons() { let limits = ExecutionLimits::new().max_live_intermediate_bytes(4); diff --git a/crates/bashkit/tests/proptest_security.rs b/crates/bashkit/tests/proptest_security.rs index e4981db3d..2bfa3195a 100644 --- a/crates/bashkit/tests/proptest_security.rs +++ b/crates/bashkit/tests/proptest_security.rs @@ -766,3 +766,36 @@ proptest! { ); } } + +// Unlike arbitrary shell text, these bounded scalar programs reliably reach +// the execution-plan backend when enabled. Keep the real Bash oracle as well +// as the in-process compiler/AST libFuzzer oracle. +#[cfg(unix)] +proptest! { + #[test] + fn scalar_loops_match_real_bash( + seed in -100i64..100, + trips in 0usize..16, + body in prop::collection::vec((0usize..3, -9i64..10), 1..16), + ) { + let mut script = format!("a={seed}; for ((i=0;i<{trips};i++)); do\n"); + for (op, value) in body { + let op = ["+=", "-=", "*="][op]; + script.push_str(&format!("((a{op}({value})));\n")); + } + script.push_str("done; printf '%s %s\\n' \"$a\" \"$i\""); + let expected = std::process::Command::new("bash") + .env_clear() + .arg("--noprofile").arg("--norc").arg("-c").arg(&script) + .output().expect("Bash oracle is required on Unix"); + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + let actual = rt.block_on(async { + fuzz_init(); + Bash::new().exec(&script).await.unwrap() + }); + assert_fuzz_invariants(&actual, &script, "scalar_loop_property", &[]); + prop_assert_eq!(actual.stdout.as_bytes(), expected.stdout.as_slice(), "{}", script); + prop_assert_eq!(actual.stderr.as_bytes(), expected.stderr.as_slice(), "{}", script); + prop_assert_eq!(Some(actual.exit_code), expected.status.code(), "{}", script); + } +} diff --git a/experiments/script-execution-plan/README.md b/experiments/script-execution-plan/README.md new file mode 100644 index 000000000..2d738e6be --- /dev/null +++ b/experiments/script-execution-plan/README.md @@ -0,0 +1,27 @@ +# Experimental script execution plans + +The `experimental_execution_plan` Cargo feature is disabled by default. +It compiles supported scalar arithmetic, assignments, branches and loops to +execution-owned instructions, with normal interpreter fallback. Scripts keep +ordinary Bash syntax; see the [activation and limits](../../crates/bashkit/docs/compatibility.md#experimental-execution-plans). + +The full benchmark harness, matched lockfile, raw samples, allocation profiles, +validation records and reproduction instructions are preserved in the +[experiment archive](https://github.com/everruns/bashkit/tree/41591e58/experiments/script-execution-plan). +Those are historical Linux measurements against baseline `782a4c55`, rather +than measurements of every later shipping revision. + +| Historical workload | Time change | +|---|---:| +| Short scripts | Previous 8% penalty eliminated | +| Straight arithmetic | 12% less | +| Supported loops | 26–63% less | +| Pipelines | Approximately flat | +| Substitutions | 4% more | + +The substitution regression remains a gate for enabling the feature by default. +Same-binary controls did not reproduce that penalty, so its build-dependent +cause remains unresolved. Full source, samples and methodology are linked above. + +Continuous feature-on/off coverage, security and fuzzing commands are described +in the [testing strategy](../../knowledge/operations/testing.md#experimental-execution-plan-coverage). diff --git a/justfile b/justfile index b72017ce7..059ca422d 100644 --- a/justfile +++ b/justfile @@ -29,6 +29,18 @@ test: cargo test --features http_client cargo test --features failpoints --test security_failpoint_tests -- --test-threads=1 +# Full workspace/doc suites plus serialized native/security fault injection. +# Uses the same broad feature slice as CI; optional runtime slices remain in CI. +test-execution-plan: + cargo test --workspace --lib --bins --tests --features http_client,ssh,sqlite,bashkit/experimental_execution_plan + cargo test --workspace --doc --features http_client,ssh,sqlite,bashkit/experimental_execution_plan + cargo test -p bashkit --features failpoints,experimental_execution_plan --lib --test security_failpoint_tests -- --test-threads=1 + +# Discover and smoke every fuzz target with the optional compiler enabled. +# Requires the pinned nightly and cargo-fuzz (see scripts/fuzz-smoke.py). +fuzz-execution-plan: + python3 scripts/fuzz-smoke.py --execution-plan + # Run fail-point tests only (single-threaded, requires failpoints feature) test-failpoints: cargo test --features failpoints --test security_failpoint_tests -- --test-threads=1 diff --git a/scripts/build-c-api.sh b/scripts/build-c-api.sh index b91f2d954..0b65cc8f9 100755 --- a/scripts/build-c-api.sh +++ b/scripts/build-c-api.sh @@ -6,6 +6,9 @@ set -euo pipefail repo_root=$(cd "$(dirname "$0")/.." && pwd) profile=debug cargo_args=(-p bashkit-capi) +if [[ -n "${BASHKIT_CAPI_FEATURES:-}" ]]; then + cargo_args+=(--features "$BASHKIT_CAPI_FEATURES") +fi if [[ "${1:-}" == "--release" ]]; then profile=release diff --git a/scripts/fuzz-smoke.py b/scripts/fuzz-smoke.py new file mode 100644 index 000000000..1732dc336 --- /dev/null +++ b/scripts/fuzz-smoke.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Discover every fuzz target from Cargo.toml and run bounded PR smoke coverage.""" +from __future__ import annotations +import argparse +import json +from pathlib import Path +import subprocess +import tomllib + +ROOT = Path(__file__).resolve().parents[1] +NIGHTLY = 'nightly-2026-10-30' + + +def matrix() -> list[dict]: + manifest = tomllib.loads((ROOT / 'crates/bashkit/fuzz/Cargo.toml').read_text()) + rows = [] + for target in manifest['bin']: + required = target.get('required-features', []) + for enabled in (False, True): + if 'plan_differential' in required and not enabled: + continue + features = required + (['experimental_execution_plan'] if enabled else []) + rows.append({'target': target['name'], 'execution_plan': enabled, 'features': ','.join(features)}) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--matrix', action='store_true') + parser.add_argument('--execution-plan', action='store_true') + parser.add_argument('--target', help='Run one discovered target (default: all)') + args = parser.parse_args() + rows = matrix() + if args.matrix: + print(json.dumps({'include': rows})) + return + selected = [r for r in rows if r['execution_plan'] == args.execution_plan + and (args.target is None or args.target == r['target'])] + if not selected: + parser.error('no targets selected') + for row in selected: + command = ['cargo', '+' + NIGHTLY, 'fuzz', 'run', '--codegen-units', '16'] + if row['features']: + command += ['--features', row['features']] + command += [row['target'], '--', '-runs=256', '-max_total_time=15', + '-max_len=512', '-timeout=10', '-print_final_stats=1'] + print(' '.join(command), flush=True) + subprocess.run(command, cwd=ROOT / 'crates/bashkit', check=True) + + +if __name__ == '__main__': + main() diff --git a/scripts/tests/test_execution_plan_ci.py b/scripts/tests/test_execution_plan_ci.py new file mode 100644 index 000000000..7faca7f60 --- /dev/null +++ b/scripts/tests/test_execution_plan_ci.py @@ -0,0 +1,87 @@ +"""Guard against feature-on CI that merely compiles or omits security paths.""" +from pathlib import Path +import importlib.util +import tomllib +import unittest +import yaml + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('fuzz_smoke', ROOT / 'scripts/fuzz-smoke.py') +fuzz = importlib.util.module_from_spec(spec) +spec.loader.exec_module(fuzz) + + +def modes(job): + matrix = job.get('strategy', {}).get('matrix', {}) + return set(matrix.get('execution_plan', [])) | { + row['execution_plan'] for row in matrix.get('include', []) if 'execution_plan' in row + } + + +class UniqueKeys(yaml.SafeLoader): + def construct_mapping(self, node, deep=False): + keys = [key.value for key, _ in node.value] + if len(keys) != len(set(keys)): + raise ValueError('duplicate YAML key: ' + str(keys)) + return super().construct_mapping(node, deep=deep) + + +class ExecutionPlanCI(unittest.TestCase): + def test_workflow_mappings_do_not_shadow_env_or_other_keys(self): + for workflow in (ROOT / '.github/workflows').glob('*.yml'): + with self.subTest(workflow=workflow.name): + yaml.load(workflow.read_text(), Loader=UniqueKeys) + + def test_full_core_and_security_suites_keep_both_engines(self): + jobs = yaml.safe_load((ROOT / '.github/workflows/ci.yml').read_text())['jobs'] + self.assertEqual(modes(jobs['test']), {False, True}) + commands = '\n'.join(str(step.get('run', '')) for step in jobs['test']['steps']) + for line in commands.splitlines(): + if 'cargo test ' in line: + self.assertIn('experimental_execution_plan', line) + for suite in ['--workspace --lib --bins --tests', '--doc', 'security_failpoint_tests', + 'proptest_security', '--lib --test security_failpoint_tests']: + self.assertIn(suite, commands) + self.assertEqual(modes(jobs['fuzz-check']), {False, True}) + self.assertTrue(any('scripts/fuzz-smoke.py' in str(s.get('run', '')) + for s in jobs['fuzz-check']['steps'])) + self.assertIn('test', jobs['check']['needs']) + self.assertIn('fuzz-check', jobs['check']['needs']) + + def test_cargo_fuzz_features_use_one_comma_separated_option(self): + workflow = (ROOT / '.github/workflows/ci.yml').read_text() + for line in workflow.splitlines(): + if ' fuzz build ' in line: + self.assertEqual(line.count('--features'), 1, line) + self.assertIn('--codegen-units 16', line) + + def test_each_fuzzer_runs_in_each_supported_mode_with_required_features(self): + manifest = tomllib.loads((ROOT / 'crates/bashkit/fuzz/Cargo.toml').read_text()) + rows = fuzz.matrix() + for target in manifest['bin']: + selected = [r for r in rows if r['target'] == target['name']] + required = set(target.get('required-features', [])) + expected = {True} if 'plan_differential' in required else {False, True} + self.assertEqual({r['execution_plan'] for r in selected}, expected) + for row in selected: + features = set(filter(None, row['features'].split(','))) + self.assertLessEqual(required, features) + self.assertEqual('experimental_execution_plan' in features, row['execution_plan']) + self.assertIn('bashkit/experimental_execution_plan', manifest['features']['experimental_execution_plan']) + + def test_binding_artifacts_and_sanitizers_cover_both_modes(self): + for workflow, names in { + 'ci.yml': ['wasm-web', 'windows-containment', 'test-windows', 'cpython-platforms'], + 'python.yml': ['test', 'build-wheel', 'callback-platforms'], + 'js.yml': ['build-and-test', 'callback-platforms'], + 'coverage.yml': ['coverage'], + 'nightly.yml': ['asan', 'miri', 'python-stress-soak', 'ts-stress-soak'], + 'windows-nightly.yml': ['windows-tests'], + 'bash-oracle.yml': ['scoreboard'], + }.items(): + jobs = yaml.safe_load((ROOT / '.github/workflows' / workflow).read_text())['jobs'] + for name in names: + with self.subTest(workflow=workflow, job=name): + self.assertEqual(modes(jobs[name]), {False, True}) + python = (ROOT / '.github/workflows/python.yml').read_text() + self.assertEqual(python.count('name: python-wheel-${{ matrix.execution_plan }}'), 2) From 5786368f095081bbaa9612f43c70b02eeb0dd9f4 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Mon, 23 Nov 2026 17:26:01 +0000 Subject: [PATCH 2/3] chore: document execution-plan resource and testing contracts --- knowledge/foundations/index.md | 1 + .../foundations/script-execution-plan.md | 135 ++++++++++++++++++ knowledge/operations/limitations.md | 7 + knowledge/operations/testing.md | 27 +++- knowledge/security/security-testing.md | 12 ++ knowledge/security/threat-model.md | 1 + 6 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 knowledge/foundations/script-execution-plan.md diff --git a/knowledge/foundations/index.md b/knowledge/foundations/index.md index 558d4e734..5ea467d81 100644 --- a/knowledge/foundations/index.md +++ b/knowledge/foundations/index.md @@ -1,6 +1,7 @@ # Foundations * [Bashkit Architecture](architecture.md) - Core interpreter architecture, module boundaries, execution flow, and design principles. +* [Script Execution Plan Experiment](script-execution-plan.md) - Execution-owned compilation of supported Bash command trees with interpreter fallback. * [Parser](parser.md) - Bash syntax parser and lexer architecture and compatibility decisions. * [Virtual Filesystem](vfs.md) - Filesystem abstraction, path safety, implementations, and sandbox invariants. * [Builtin Commands](builtins.md) - Builtin command trait, execution planning, registration, and implementation conventions. diff --git a/knowledge/foundations/script-execution-plan.md b/knowledge/foundations/script-execution-plan.md new file mode 100644 index 000000000..46080c37d --- /dev/null +++ b/knowledge/foundations/script-execution-plan.md @@ -0,0 +1,135 @@ +--- +type: Experimental Design +title: Script Execution Plan Experiment +description: Execution-owned compilation of supported Bash command trees with interpreter fallback. +tags: + - bashkit + - interpreter + - performance + - experiment +--- + +# Script Execution Plan Experiment + +## Status + +Experimental opt-in compiler, shipped behind the disabled-by-default +`experimental_execution_plan` Cargo feature. All embedding crates forward the +flag; the existing public execution APIs and Bash syntax stay the same. + +## Decision + +Compile a parsed script into an execution-owned plan before running its first +command. The ordinary script runner still handles alias/extglob reparsing, +source lines, output routing, hooks, trailing syntax errors, and shell recovery. +An allocation-free eligibility probe skips lowering for small one-shot regions; +supported loops and larger straight-line regions still compile. This is a +conservative local cost policy, not profiling or persistent hotness state. +Reparsed script views use ordinary execution. Nested `eval`/`source` scripts +build their own local plans through the same entry point. + +Supported scalar command trees lower to a flat instruction vector with explicit +branches, jumps, arithmetic operations, and loop boundaries. Numeric literal +assignments use the existing assignment executor. The instruction evaluator +uses the existing arithmetic variable resolver and ordered write overlay; +variable values are read during execution. + +All native regions share one instruction arena; each stores a range into it. +Arithmetic tokens borrow source text where possible and transfer owned names +instead of cloning them. The boxed plan keeps its storage out of the ordinary +script future. Ordinary and compiled command/list dispatch use separate futures, +with shared macros preserving identical command boundaries and orchestration. +A fallback command immediately enters the ordinary dispatcher and does not +carry a prepared-program selector through its nested execution. + +Mixed command lists retain the existing list orchestration with prepared child +commands. This preserves conditional execution, builtin/tool calls, redirects, +and background-job handling around compiled regions. A compound containing an +unsupported body falls back as a whole. Functions, pipelines, word expansions +(including `$((...))`), and general tool-containing loop bodies are not lowered +in this first version. + +## Eligibility and fallback + +Native regions support arithmetic commands, numeric scalar assignments, brace +groups, `if`/`elif`/`else`, arithmetic `for`, `while`, and `until`. Arithmetic +supports safe scalar operators, assignment, increments, and comma sequences. +Unsupported operators and grammar use the ordinary evaluator. + +Runtime admission declines native regions with tracing, traps, `errexit`, +`nounset`, no-exec, active output pipes, pending substitution errors, variable +attributes beyond export, arrays, namerefs, or expression-valued variables. +These are conservative backend limits, not changes to accepted Bash syntax. +Admission runs when the region executes, so a preceding fallback command can +change shell options or variable attributes safely. Resource failpoints remain active in native execution. When the +`interp::execute_command` injector is configured, admission declines so its +whole-command error and early-status actions retain their AST boundary. + +## Resources and lifetime + +Plans borrow their parsed script and are dropped on every exit path, including +future cancellation. They introduce no interpreter fields, process-global +cache, or pointer-keyed state. Optional storage reservations may decline and +fall back without exhausting the request. Compilation charges work before +tokenization/lowering; storage is conservatively admitted before allocations. +Compiler traversal, expression length, token count, and instruction-stack depth +are bounded. + +One growable optional-storage lease covers the instruction arena. Token and +expression-op admission includes geometric vector growth and source text, using +their actual Rust type layouts. Command/child vectors allocate their admitted +capacity explicitly; a 1 KiB tokenizer-boundary regression checks transient +storage even when compilation ultimately declines. Capacity grows +geometrically, and rejected lowering rolls back instructions while retaining +the reservation for allocated capacity. Buffers drop before the lease releases +their accounting, including failed compilation; a drop-order regression test +checks this invariant. + +The VM charges every executable command node and loop iteration, checks shared +cancellation/deadline/memory state between instructions, yields periodically, +and restores active loop counters when execution returns an error. Arithmetic +uses the normal recursion/fuel budget and variable-write checks. Compilation +has real work/live-memory costs, so tight budgets can stop execution earlier +than the ordinary interpreter. + +## Validation and performance gates + +PR CI runs the full workspace and optional-runtime test slices with the feature +both disabled and enabled, including CLI/C ABI, binding suites, browser tests, +realfs, strict host-tool oracles, failpoints and security properties. Nightly +ASan, Miri admission/lifetime checks, tenant soaks and Windows suites also cover +both modes. Manifest-discovered fuzz targets run bounded PR smoke cases in both +modes and longer scheduled campaigns. The dedicated `script_plan_fuzz` target +uses finite supported loops/branches and an execution-local interpreter selector +to compare output, status, writes and subsequent session use. Structured +proptest scripts also compare with real Bash. Native-specific unit tests prove +backend eligibility, resource fault injection, compilation admission refunds, +and abandoned-future cleanup instead of accepting silent AST fallback. + + +Unit tests require native regions to be selected and compare results, variable +writes, PIPESTATUS, command counts, and scope cleanup with ordinary AST +execution. Public-API differential probes cover mixed scripts and fallback +contexts. Baseline/candidate binaries must use identical dependency lockfiles +and compiler/profile settings. + +The additional `experimental_plan_benchmark_control` feature is diagnostic only +and is also off by default. A typed execution extension selects automatic plan +admission or interpreter-only execution in one binary. Both benchmark modes +attach the same extension type; no shared switch or cache is introduced. Normal +experimental builds contain no selector lookup. Same-binary controls complement, +and do not replace, comparisons with a production baseline build. + +Measure parsing, compilation, and execution together on fresh Bash instances. +Report short/one-shot scripts and fallback workloads alongside supported hot +regions. A supported-loop speedup alone is insufficient to enable the feature +by default. Before production, broaden differential/resource coverage, reduce +compilation overhead, and audit native command-boundary equivalence. + +## See also + +- [Architecture](architecture.md) +- [Parser](parser.md) +- [Security Testing](../security/security-testing.md) +- [Performance Results](../operations/performance-results.md) +- [Experiment results and remaining gates](../../experiments/script-execution-plan/README.md) diff --git a/knowledge/operations/limitations.md b/knowledge/operations/limitations.md index b2c5ea5ef..5fd03ee78 100644 --- a/knowledge/operations/limitations.md +++ b/knowledge/operations/limitations.md @@ -15,6 +15,13 @@ Living document (updated as limitations are added/lifted) ## Summary +The optional execution-plan compiler is experimental and disabled by default. +It accelerates a conservative scalar subset and falls back for other syntax; +this does not expand or restrict the accepted Bash language. Compilation consumes +request budgets and can reject tighter limits earlier. The remaining substitution +performance regression is tracked in [Execution Plans](../foundations/script-execution-plan.md). + + The negative spec: what Bashkit deliberately does NOT do (and why), plus known partial implementations. Absences can't be recovered from code, so they're recorded here; everything positive is generated or tested instead: diff --git a/knowledge/operations/testing.md b/knowledge/operations/testing.md index 7aa43476a..dd115e3e3 100644 --- a/knowledge/operations/testing.md +++ b/knowledge/operations/testing.md @@ -86,6 +86,30 @@ intermediate-artifact layout; scripts must not depend on internal build/deps paths. The consumer's own lockfile is used after fresh resolution, so this check catches dependency-floor drift hidden by the workspace's locked graph. +## Experimental execution-plan coverage + +The normal CI test job has interpreter and execution-plan matrix rows. The latter +adds `bashkit/experimental_execution_plan` to every existing feature slice; +required `Check` waits for both rows. Binding wheels/binaries use separate matrix +artifacts, so a feature-on test cannot accidentally load the default build. +Windows, browser, host-Bash oracle and nightly sanitizer/soak suites retain both +rows as well. `scripts/tests/test_execution_plan_ci.py` guards the critical gates. + +Run `just test-execution-plan` for the broad workspace/doc and serialized +fault-injection slices, or add `--features experimental_execution_plan` to +individual commands above. `just fuzz-execution-plan` runs all fuzz smoke targets. For native failpoint proof, run: + +```bash +cargo test -p bashkit --features experimental_execution_plan,failpoints --lib script_plan::tests -- --test-threads=1 +python3 scripts/fuzz-smoke.py --execution-plan +``` + +The smoke runner discovers targets and required runtime features from the fuzz +manifest; it runs 256 inputs or 15 seconds per target. Scheduled fuzzing uses the +same discovered matrix with a longer duration. The compiler/AST differential +target additionally enables the diagnostic selector, without shared switch +state. See [Execution Plans](../foundations/script-execution-plan.md). + ## Spec Test Framework ### Test File Format @@ -292,7 +316,8 @@ them is scoped proof, not a claim that the unchanged full/coverage suites ran. ## Coverage -Uploaded to Codecov from three sources: Rust unit/integration coverage via +Rust coverage is collected in both execution-plan modes, with distinct XML +paths/artifacts merged by the token-isolated upload job. Uploaded to Codecov from three sources: Rust unit/integration coverage via `cargo tarpaulin`; Rust coverage exercised through Python and Node binding tests via `cargo llvm-cov`. diff --git a/knowledge/security/security-testing.md b/knowledge/security/security-testing.md index e96482f0e..39d3ab078 100644 --- a/knowledge/security/security-testing.md +++ b/knowledge/security/security-testing.md @@ -23,6 +23,18 @@ Fail points are disabled by default, zero runtime overhead when disabled. cargo test --features failpoints security_ -- --test-threads=1 ``` +## Execution-plan coverage + +Security suites run with the experimental compiler enabled as well as disabled. +Resource failpoints are honored inside native regions. Only an active +`interp::execute_command` injector forces AST admission, preserving its +whole-command early-error semantics. Native unit tests assert admission before +injecting a loop-counter reset and verify that the command budget still stops +the loop. Separate tests cover dropped futures, reuse, optional-memory decline, +work-budget failure and reservation refunds. `script_plan_fuzz` compares bounded +native arithmetic/branch loops with the AST executor; structured proptest cases +also compare with real Bash. See [Execution Plans](../foundations/script-execution-plan.md). + ## Available Fail Points ### Resource Limits (`limits.rs`) diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index fa65368ca..9d2ae6082 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -318,6 +318,7 @@ on default 2 MiB test threads (TM-DOS-044). | TM-DOS-141 | Re-entry recursion via eval/compgen/fc | `f(){ eval f; }`, `compgen -C f`, `fc` re-exec, or PROMPT_COMMAND re-enter the interpreter without a function frame, so recursion was bounded only by the native stack and aborted the shared process | Each re-entry counts against `max_function_depth` and a separate `MAX_REENTRY_DEPTH` (8); over the cap the command fails `maximum nesting depth exceeded` (exit 2). Regressions: `recursive_eval_is_bounded`, `recursive_compgen_command_is_bounded` | **MITIGATED** | | TM-DOS-142 | Product of nesting caps overflows worker stack | Each nesting kind has its own cap, but their product (compound nesting x functions x eval x child shells) can exceed a 2 MiB tokio worker stack in release builds | `execute_command` polls through `interpreter/grow_stack.rs`, which uses `stacker::maybe_grow` (512 KiB red zone, 4 MiB segments) so deep but capped nesting extends the stack on the heap instead of aborting. Not on wasm32 (single-threaded, host stack). Regression: `nested_compounds_inside_recursion_do_not_overflow` | **MITIGATED** | | TM-DOS-144 | Root real mount drops FsLimits | `mount_real_readonly(dir)` / `mount_real_readwrite(dir)` at `/` wrapped the host dir in `OverlayFs::new`, whose upper layer used default limits, so a tenant could write past the configured `filesystem_limits` | The root overlay is built with `OverlayFs::with_limits` and the base filesystem's limits. Regression: `root_real_mount_keeps_filesystem_limits` | **MITIGATED** | +| TM-DOS-147 | Experimental compiled regions bypass request limits | Optional lowering or flat execution could allocate outside admission, skip command/loop fuel, or retain reservations after an error or dropped future | Compilation admits bounded storage before allocation and charges work before lowering; every VM command/iteration/instruction uses the shared fuel/cancellation/deadline checks. Buffers precede reservation release. Native admission, fault-injected counter, refund and abandoned-future tests plus structured differential fuzzing cover the backend directly | **MITIGATED** | **TM-DOS-051** is historical. The custom parser was deleted with the `yaml` helper; the replacement `yq` parser/evaluator boundary is tracked by TM-DOS-101. From 74cc32de3481ce521fee32aa1a0044f0e6b3fc00 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Mon, 23 Nov 2026 17:38:20 +0000 Subject: [PATCH 3/3] chore: fix execution-plan knowledge formatting --- knowledge/foundations/script-execution-plan.md | 3 +-- knowledge/operations/limitations.md | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/knowledge/foundations/script-execution-plan.md b/knowledge/foundations/script-execution-plan.md index 46080c37d..ee8522f0d 100644 --- a/knowledge/foundations/script-execution-plan.md +++ b/knowledge/foundations/script-execution-plan.md @@ -22,7 +22,7 @@ flag; the existing public execution APIs and Bash syntax stay the same. Compile a parsed script into an execution-owned plan before running its first command. The ordinary script runner still handles alias/extglob reparsing, source lines, output routing, hooks, trailing syntax errors, and shell recovery. -An allocation-free eligibility probe skips lowering for small one-shot regions; +An inexpensive eligibility probe skips lowering for small one-shot regions; supported loops and larger straight-line regions still compile. This is a conservative local cost policy, not profiling or persistent hotness state. Reparsed script views use ordinary execution. Nested `eval`/`source` scripts @@ -106,7 +106,6 @@ proptest scripts also compare with real Bash. Native-specific unit tests prove backend eligibility, resource fault injection, compilation admission refunds, and abandoned-future cleanup instead of accepting silent AST fallback. - Unit tests require native regions to be selected and compare results, variable writes, PIPESTATUS, command counts, and scope cleanup with ordinary AST execution. Public-API differential probes cover mixed scripts and fallback diff --git a/knowledge/operations/limitations.md b/knowledge/operations/limitations.md index 5fd03ee78..68676fce6 100644 --- a/knowledge/operations/limitations.md +++ b/knowledge/operations/limitations.md @@ -21,7 +21,6 @@ this does not expand or restrict the accepted Bash language. Compilation consume request budgets and can reject tighter limits earlier. The remaining substitution performance regression is tracked in [Execution Plans](../foundations/script-execution-plan.md). - The negative spec: what Bashkit deliberately does NOT do (and why), plus known partial implementations. Absences can't be recovered from code, so they're recorded here; everything positive is generated or tested instead: