From a19ae17117696055219a7fd8b419c8ac1a1afe28 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Tue, 13 Oct 2026 10:58:17 -0700 Subject: [PATCH 1/3] test: write test executables out of process #13056 avoided executables that a concurrently forked child kept busy in five ways: shell functions, a symlinked /bin/cat, /bin/sh symlinked as python3, scripts run through /bin/sh, and a retry loop. A child process now writes each test executable, so this process never holds it open for writing and no fork can inherit that descriptor. The SSH collector, recipe, vLLM launch, and SDK postcondition tests go back to plain scripts, and the scripted OpenTofu no longer needs its warm-up retry. The staged provider in nemoclaw-test-fixtures still runs through /bin/sh: the code under test writes that file, not the test. --- crates/nemoclaw-provider/src/hardware/ssh.rs | 57 ++++++++----------- crates/nemoclaw-provider/src/lib.rs | 3 + crates/nemoclaw-runtime/src/lib.rs | 3 + .../src/vllm/runtime/inline_recipe.rs | 14 +---- .../src/vllm/runtime/process.rs | 17 ++---- crates/nemoclaw-sdk/src/lib.rs | 3 + crates/nemoclaw-sdk/src/process.rs | 14 ++--- crates/nemoclaw-sdk/tests/main.rs | 3 + .../tests/support/scripted_tofu.rs | 27 +-------- crates/test-support/executable.rs | 39 +++++++++++++ 10 files changed, 90 insertions(+), 90 deletions(-) create mode 100644 crates/test-support/executable.rs diff --git a/crates/nemoclaw-provider/src/hardware/ssh.rs b/crates/nemoclaw-provider/src/hardware/ssh.rs index c781961527d..de3536b30aa 100644 --- a/crates/nemoclaw-provider/src/hardware/ssh.rs +++ b/crates/nemoclaw-provider/src/hardware/ssh.rs @@ -325,51 +325,40 @@ mod tests { } } - /// Run the shipped script with fake `docker` and `nvidia-smi` shell commands, and + /// Run the shipped script with fake `docker` and `nvidia-smi` on PATH, and /// the real `uname`, `stat`, and `/proc/meminfo` of this Linux host. #[cfg(target_os = "linux")] #[test] fn collector_script_queries_compute_and_memory_and_parses_on_linux() { use std::{fs, process::Command}; let root = tempfile::tempdir().unwrap(); + let bin = root.path().join("bin"); let docker_root = root.path().join("docker-root"); let calls = root.path().join("calls"); + fs::create_dir(&bin).unwrap(); fs::create_dir(&docker_root).unwrap(); let info = json!({"ID": "fixture", "OSType": "linux", "Architecture": std::env::consts::ARCH, "DockerRootDir": docker_root}); - // Shell functions preserve the collector's command arguments without - // executing newly written files that another spawn could hold writable. - let fakes = r#"docker() { - printf '%s\n' "docker $*" >> "$TEST_COLLECT_CALLS" - case "$1 $2" in - 'context inspect') printf '%s\n' unix:///var/run/docker.sock ;; - 'info --format') - case "$3" in - '{{json .}}') printf '%s\n' "$TEST_COLLECT_INFO" ;; - '{{.DockerRootDir}}') printf '%s\n' "$TEST_COLLECT_ROOT" ;; - *) return 2 ;; - esac ;; - *) return 2 ;; - esac -} -nemoclaw_nvidia_smi() { - printf '%s\n' "nvidia-smi $*" >> "$TEST_COLLECT_CALLS" - [ "$2" = --format=csv,noheader,nounits ] || return 2 - case "$1" in - --query-gpu=name,driver_version) printf '%s\n' 'NVIDIA GB10, 580.0' ;; - --query-gpu=compute_cap) printf '%s\n' 12.1 ;; - --query-gpu=memory.total,memory.free) printf '%s\n' '[N/A], [N/A]' ;; - --query-compute-apps=pid) ;; - *) return 2 ;; - esac -} -alias nvidia-smi=nemoclaw_nvidia_smi -"#; - let result = Command::new("/bin/sh") - .args(["-c", &format!("{fakes}\n{COLLECT}")]) - .env("TEST_COLLECT_CALLS", &calls) - .env("TEST_COLLECT_INFO", info.to_string()) - .env("TEST_COLLECT_ROOT", &docker_root) + let fakes = [ + ("docker", format!( + "case \"$1 $2\" in\n'context inspect') echo unix:///var/run/docker.sock ;;\n'info --format') if [ \"$3\" = '{{{{json .}}}}' ]; then echo '{info}'; else echo '{root}'; fi ;;\n*) exit 2 ;;\nesac\n", + root = docker_root.display() + )), + ("nvidia-smi", "[ \"$2\" = --format=csv,noheader,nounits ] || exit 2\ncase \"$1\" in\n--query-gpu=name,driver_version) echo 'NVIDIA GB10, 580.0' ;;\n--query-gpu=compute_cap) echo 12.1 ;;\n--query-gpu=memory.total,memory.free) echo '[N/A], [N/A]' ;;\n--query-compute-apps=pid) ;;\n*) exit 2 ;;\nesac\n".into()), + ]; + for (name, body) in fakes { + crate::executable::write_executable( + &bin.join(name), + format!( + "#!/bin/sh\nprintf '%s\\n' \"{name} $*\" >> '{}'\n{body}", + calls.display() + ), + ); + } + let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()); + let result = Command::new("sh") + .args(["-c", COLLECT]) + .env("PATH", path) .env_remove("DOCKER_HOST") .output() .unwrap(); diff --git a/crates/nemoclaw-provider/src/lib.rs b/crates/nemoclaw-provider/src/lib.rs index 2276600b887..5fdfe5da14a 100644 --- a/crates/nemoclaw-provider/src/lib.rs +++ b/crates/nemoclaw-provider/src/lib.rs @@ -7,6 +7,9 @@ pub use nemoclaw_tofu::*; mod capacity; mod discovery; +#[cfg(all(test, target_os = "linux"))] +#[path = "../../test-support/executable.rs"] +mod executable; mod gateway; pub mod hardware; mod hardware_data; diff --git a/crates/nemoclaw-runtime/src/lib.rs b/crates/nemoclaw-runtime/src/lib.rs index a58176dac40..ef73cbb8d74 100644 --- a/crates/nemoclaw-runtime/src/lib.rs +++ b/crates/nemoclaw-runtime/src/lib.rs @@ -13,6 +13,9 @@ pub mod schema; pub mod snapshot; pub mod vllm; pub use tokio_util::sync::CancellationToken; +#[cfg(all(test, feature = "execution", target_os = "linux"))] +#[path = "../../test-support/executable.rs"] +mod executable; #[cfg(all(feature = "execution", target_os = "linux"))] mod execution; #[cfg(test)] diff --git a/crates/nemoclaw-runtime/src/vllm/runtime/inline_recipe.rs b/crates/nemoclaw-runtime/src/vllm/runtime/inline_recipe.rs index 68d8c5091e5..23d794fdb38 100644 --- a/crates/nemoclaw-runtime/src/vllm/runtime/inline_recipe.rs +++ b/crates/nemoclaw-runtime/src/vllm/runtime/inline_recipe.rs @@ -113,18 +113,13 @@ impl Runner for PackagedRecipe<'_> { #[cfg(test)] mod tests { use super::*; - use std::os::unix::fs::symlink; #[tokio::test] async fn pinned_executable_receives_structured_input_and_tampering_stops_execution() { let service = crate::fixture(); let mut recipe = service.recipe.clone().unwrap(); let root = tempfile::tempdir().unwrap(); - // Alias only the directory: the pinned executable remains a regular - // existing binary, and its path still exercises spaces without a shell. - let cat = std::fs::canonicalize("/bin/cat").unwrap(); - let directory = root.path().join("tools with spaces"); - symlink(cat.parent().unwrap(), &directory).unwrap(); - let executable = directory.join(cat.file_name().unwrap()); + let executable = root.path().join("tool with spaces"); + crate::executable::write_executable(&executable, "#!/bin/sh\ncat\n"); recipe.preparation.executable = executable.to_str().unwrap().into(); recipe.preparation.sha256 = crate::files::hash_file(&executable).unwrap(); recipe.verification = recipe.preparation.clone(); @@ -143,10 +138,7 @@ mod tests { .unwrap(); let output: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); assert_eq!(output["modelDirectory"], root.path().to_str().unwrap()); - // Replace the alias with local tampered bytes; never modify the host binary. - std::fs::remove_file(&directory).unwrap(); - std::fs::create_dir(&directory).unwrap(); - std::fs::write(&executable, b"changed recipe executable").unwrap(); + std::fs::write(&executable, b"#!/bin/sh\nexit 0\n").unwrap(); assert!(matches!( runner .run(Action::Prepare, &request, &CancellationToken::new()) diff --git a/crates/nemoclaw-runtime/src/vllm/runtime/process.rs b/crates/nemoclaw-runtime/src/vllm/runtime/process.rs index 20807c8cf6b..81ddb6f9915 100644 --- a/crates/nemoclaw-runtime/src/vllm/runtime/process.rs +++ b/crates/nemoclaw-runtime/src/vllm/runtime/process.rs @@ -98,16 +98,12 @@ mod tests { let bin = root.path().join("bin"); std::fs::create_dir_all(&bin).unwrap(); let python = bin.join("python3"); - // The existing interpreter accepts the production -m argument and - // reads the module-named fixture from the child's working directory. - // No newly written fixture is executed; inherited writable descriptors - // cannot prevent this child from starting. - std::os::unix::fs::symlink("/bin/sh", &python).unwrap(); - std::fs::write( - root.path().join("vllm.entrypoints.openai.api_server"), - "[ \"$1\" = --model ] && [ \"$2\" = \"$TEST_MODEL_DIRECTORY\" ] || exit 1\ntest \"$VLLM_API_KEY\" = \"$(/bin/cat \"$TEST_KEY_FILE\")\"\n", - ) - .unwrap(); + // A disposable executable stands in for Python/vLLM and verifies the + // process boundary. The readiness fixture independently checks HTTP. + crate::executable::write_executable( + &python, + "#!/bin/sh\n[ \"$1 $2 $3\" = '-m vllm.entrypoints.openai.api_server --model' ] && [ \"$4\" = \"$TEST_MODEL_DIRECTORY\" ] || exit 1\ntest \"$VLLM_API_KEY\" = \"$(/bin/cat \"$TEST_KEY_FILE\")\"\n", + ); let prepared = PreparedModel { model: root.path().join("model"), environment: [ @@ -131,7 +127,6 @@ mod tests { Some(key.clone()), ) .unwrap(); - command.command_mut().current_dir(root.path()); assert!(command.spawn().unwrap().wait().await.unwrap().success()); assert!(readiness.url.ends_with("/v1/models")); let expected = format!("Bearer {key}"); diff --git a/crates/nemoclaw-sdk/src/lib.rs b/crates/nemoclaw-sdk/src/lib.rs index 703cb940e07..550b5d2af4f 100644 --- a/crates/nemoclaw-sdk/src/lib.rs +++ b/crates/nemoclaw-sdk/src/lib.rs @@ -48,6 +48,9 @@ pub mod services; mod state; pub use nemoclaw_backend::Error; pub mod bundle; +#[cfg(all(test, unix))] +#[path = "../../test-support/executable.rs"] +mod executable; mod process; pub use tokio_util::sync::CancellationToken; mod deployment; diff --git a/crates/nemoclaw-sdk/src/process.rs b/crates/nemoclaw-sdk/src/process.rs index be809bffd68..aaca76e05f0 100644 --- a/crates/nemoclaw-sdk/src/process.rs +++ b/crates/nemoclaw-sdk/src/process.rs @@ -448,20 +448,18 @@ fn kubernetes_connection_environment_requires_explicit_operation_overrides() { #[tokio::test] async fn only_normal_apply_failure_can_establish_postcondition_evidence() { let directory = tempfile::tempdir().unwrap(); - // Let the existing interpreter read the fixture even if another child - // inherited a writable descriptor while the script was being created. - std::fs::write( - directory.path().join("apply"), + let binary = directory.path().join("tofu"); + crate::executable::write_executable( + &binary, r##"#!/bin/sh printf '%s\n' '{"type":"version","ui":"1.2"}' '{"type":"diagnostic","diagnostic":{"severity":"error","summary":"Resource postcondition failed","snippet":{"context":"data.example_readiness.main.lifecycle.postcondition[0]"}}}' -exit "$2" +exit "$3" "##, - ) - .unwrap(); + ); for (exit, expected) in [("1", true), ("2", false)] { let error = run_with_progress( directory.path(), - Path::new("/bin/sh"), + &binary, &["apply", "-json", exit], &BTreeMap::new(), &CancellationToken::new(), diff --git a/crates/nemoclaw-sdk/tests/main.rs b/crates/nemoclaw-sdk/tests/main.rs index 5441a0e9375..00b5a49534f 100644 --- a/crates/nemoclaw-sdk/tests/main.rs +++ b/crates/nemoclaw-sdk/tests/main.rs @@ -5,6 +5,9 @@ #[path = "support/examples.rs"] mod examples; +#[cfg(unix)] +#[path = "../../test-support/executable.rs"] +mod executable; #[path = "../../test-support/kube_api.rs"] mod kube_api; #[path = "support/kube_client.rs"] diff --git a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs index 3bef922b988..f9519d3f357 100644 --- a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs +++ b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs @@ -21,7 +21,6 @@ use nemoclaw_sdk::{ use serde_json::{Value, json}; use std::{ fs, - os::unix::fs::PermissionsExt, path::{Path, PathBuf}, sync::{Arc, Mutex, MutexGuard, PoisonError}, }; @@ -80,8 +79,7 @@ fn write_bundle(directory: &Path, script: &str) { let path = directory.join(&name); fs::create_dir_all(path.parent().unwrap()).unwrap(); if name == tofu { - fs::write(&path, script).unwrap(); - fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + crate::executable::write_executable(&path, script); } else { fs::write(&path, b"non-executable fixture").unwrap(); } @@ -94,27 +92,6 @@ fn write_bundle(directory: &Path, script: &str) { .unwrap(); } -/// Run the script once. The kernel refuses to execute a file that any process -/// holds open for writing, and a child that another thread forked while this -/// one wrote the script keeps that descriptor until it executes something. After -/// one successful run no writer remains. -fn warm(tofu: &Path) { - for _ in 0..100 { - match std::process::Command::new(tofu).arg("init").output() { - Err(error) if error.kind() == std::io::ErrorKind::ExecutableFileBusy => { - std::thread::sleep(std::time::Duration::from_millis(20)); - } - result => { - result.expect( - "cannot run the scripted tofu; is the temporary directory mounted noexec?", - ); - return; - } - } - } - panic!("the scripted tofu stayed busy"); -} - /// Scripted tests of one process run one at a time. `Deployment` holds a lock /// file for each operation, and a child that another thread forks while the lock /// is held keeps the lock until it executes, so a test's next operation can find @@ -155,8 +132,6 @@ impl Scripted { .replace("@CONTROL@", "ed(scripted.control())) .replace("@STATE@", "ed(scripted.state())); write_bundle(&scripted.bundle(), &script); - warm(&scripted.bundle().join("libexec").join(executable("tofu"))); - let _ = fs::remove_file(scripted.control().join("calls")); scripted } diff --git a/crates/test-support/executable.rs b/crates/test-support/executable.rs new file mode 100644 index 00000000000..2ca24706e98 --- /dev/null +++ b/crates/test-support/executable.rs @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Test executables that a concurrently spawned child cannot keep busy. +//! +//! The kernel refuses to execute a file that any process holds open for +//! writing. A child that another test thread forks while this one writes a +//! file inherits the writable descriptor until it executes, so a script this +//! process writes can fail to start with `ExecutableFileBusy`. Here a separate +//! process writes the file; this process never opens it, so no fork can +//! inherit a writable descriptor. + +use std::{ + io::Write, + path::Path, + process::{Command, Stdio}, +}; + +/// Create `path` with `contents` and mode 0700. +pub fn write_executable(path: &Path, contents: impl AsRef<[u8]>) { + let mut writer = Command::new("/bin/sh") + .args(["-c", "umask 077 && cat > \"$1\" && chmod 700 \"$1\"", "sh"]) + .arg(path) + .stdin(Stdio::piped()) + .spawn() + .expect("cannot start /bin/sh to write a test executable"); + writer + .stdin + .take() + .expect("piped stdin") + .write_all(contents.as_ref()) + .expect("cannot send a test executable to /bin/sh"); + let status = writer.wait().expect("cannot wait for /bin/sh"); + assert!( + status.success(), + "cannot write {}: {status}", + path.display() + ); +} From 8da5045768dd8df6419ddf8c7614992d2dbc65b7 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Tue, 13 Oct 2026 11:02:56 -0700 Subject: [PATCH 2/3] test(sdk): run scripted OpenTofu tests concurrently The scripted tests serialized themselves because a child forked by another thread could keep a Deployment's lock file locked until it executed. Since #13056, Store::drop unlocks the file explicitly, so the shared lock is gone when an operation ends whatever descriptors remain. Without the mutex the SDK integration binary runs in about 5 s instead of 17 s under cargo test. --- crates/nemoclaw-sdk/tests/support/scripted_tofu.rs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs index f9519d3f357..c2d23df0d52 100644 --- a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs +++ b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs @@ -22,7 +22,7 @@ use serde_json::{Value, json}; use std::{ fs, path::{Path, PathBuf}, - sync::{Arc, Mutex, MutexGuard, PoisonError}, + sync::{Arc, Mutex}, }; /// `@CONTROL@` and `@STATE@` become the control directory and the state @@ -92,30 +92,20 @@ fn write_bundle(directory: &Path, script: &str) { .unwrap(); } -/// Scripted tests of one process run one at a time. `Deployment` holds a lock -/// file for each operation, and a child that another thread forks while the lock -/// is held keeps the lock until it executes, so a test's next operation can find -/// the lock held. Nextest runs each test in its own process, where nothing -/// waits here; `cargo test` runs them as threads of one process. -static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); - /// A temporary bundle with a scripted `tofu`, a control directory, and the path /// of a state directory that `Deployment` creates. A test creates one. pub struct Scripted { - _turn: MutexGuard<'static, ()>, _directory: tempfile::TempDir, root: PathBuf, } impl Scripted { pub fn new() -> Self { - let turn = ONE_AT_A_TIME.lock().unwrap_or_else(PoisonError::into_inner); let directory = tempfile::tempdir().unwrap(); // The script compares its physical working directory with the state // directory, and a macOS temporary path traverses a symbolic link. let root = directory.path().canonicalize().unwrap(); let scripted = Self { - _turn: turn, _directory: directory, root, }; From a356937e004048a50195006c55f9b92f7956b638 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Tue, 13 Oct 2026 11:46:38 -0700 Subject: [PATCH 3/3] test(sdk): share the verified test bundle writer (#13113) `deployment.rs` and `scripted_tofu.rs` now share one test bundle writer. Stacked on #13112. ## Why Both tests wrote a bundle whose manifest verifies. `scripted_tofu.rs` (#13081) kept a copy of `deployment.rs::write_bundle` that differed only for `libexec/tofu`, because `deployment.rs` also runs on Windows and the scripted copy needs Unix. ## Change - `tests/support/bundle.rs` adds `write_bundle(directory, tofu: Option<&str>)`. Without a script, every file is a non-executable fixture. With one, `libexec/tofu` is that script, written with `write_executable` from #13111. Passing a script on a platform other than Unix panics. - `deployment.rs` and `scripted_tofu.rs` call it and drop their own copies. I left two other duplicates alone: - `Events` in `nemoclaw-e2e/tests/helm_recovery.rs`, which is two methods long. - `Snapshot` there and `Untouched` in `kubernetes_interruption.rs`, which check different state. Both sit in other crates, so sharing them would mean adding them to `nemoclaw-test-fixtures` for little gain. ## Validation - `cargo test -p nemoclaw-sdk --test integration`: 444 passed. - `cargo ci` on linux_arm64: all steps passed. GitHub CI checks the Windows build of `deployment.rs`; I couldn't cross-compile it here. --- crates/nemoclaw-sdk/tests/deployment.rs | 29 +---------- crates/nemoclaw-sdk/tests/main.rs | 2 + crates/nemoclaw-sdk/tests/support/bundle.rs | 48 +++++++++++++++++++ .../tests/support/scripted_tofu.rs | 35 +------------- 4 files changed, 54 insertions(+), 60 deletions(-) create mode 100644 crates/nemoclaw-sdk/tests/support/bundle.rs diff --git a/crates/nemoclaw-sdk/tests/deployment.rs b/crates/nemoclaw-sdk/tests/deployment.rs index 395116f8012..bf2b1164a8d 100644 --- a/crates/nemoclaw-sdk/tests/deployment.rs +++ b/crates/nemoclaw-sdk/tests/deployment.rs @@ -2,14 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 use nemoclaw_sdk::{ - CancellationToken, Deployment, Error, ObservationError, Progress, Secrets, - bundle::{Bundle, Manifest, hash_file, required_files}, - compile::OPENTOFU_VERSION, + CancellationToken, Deployment, Error, ObservationError, Progress, Secrets, bundle::Bundle, config::Document, }; use std::{ fs, - path::Path, sync::{ Arc, Mutex, atomic::{AtomicUsize, Ordering}, @@ -31,28 +28,6 @@ async fn invalid_programmatic_configuration_cannot_create_deployment_state() { assert!(!state.exists()); } -/// A bundle whose hashes verify, so opening it succeeds. Its files cannot -/// execute, so no operation that reaches OpenTofu can do anything. -fn write_bundle(directory: &Path) { - let mut manifest = Manifest { - version: "0.1.0".into(), - rust: "1.98.1".into(), - opentofu: OPENTOFU_VERSION.into(), - files: Default::default(), - }; - for name in required_files(&manifest.version).unwrap() { - let path = directory.join(&name); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(&path, b"non-executable fixture").unwrap(); - manifest.files.insert(name, hash_file(&path).unwrap()); - } - fs::write( - directory.join("manifest.json"), - serde_json::to_vec(&manifest).unwrap(), - ) - .unwrap(); -} - #[derive(Default)] struct CountingSecrets(AtomicUsize); impl Secrets for CountingSecrets { @@ -67,7 +42,7 @@ async fn a_document_that_fails_validation_is_rejected_before_the_bundle_opens_or { let directory = tempfile::tempdir().unwrap(); let bundle = directory.path().join("bundle"); - write_bundle(&bundle); + crate::bundle::write_bundle(&bundle, None); assert!(Bundle::open(&bundle).is_ok(), "the bundle must be valid"); let document = Document::default(); let mut defaulted = document.clone(); diff --git a/crates/nemoclaw-sdk/tests/main.rs b/crates/nemoclaw-sdk/tests/main.rs index 00b5a49534f..e9c584b040d 100644 --- a/crates/nemoclaw-sdk/tests/main.rs +++ b/crates/nemoclaw-sdk/tests/main.rs @@ -3,6 +3,8 @@ //! SDK integration tests, linked into one binary so the SDK links once. //! Each file is a module; helpers under support/ are shared by all of them. +#[path = "support/bundle.rs"] +mod bundle; #[path = "support/examples.rs"] mod examples; #[cfg(unix)] diff --git a/crates/nemoclaw-sdk/tests/support/bundle.rs b/crates/nemoclaw-sdk/tests/support/bundle.rs new file mode 100644 index 00000000000..baed43972fc --- /dev/null +++ b/crates/nemoclaw-sdk/tests/support/bundle.rs @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Bundles that verify without a build, for tests that open one. + +use nemoclaw_sdk::{ + bundle::{Manifest, executable, hash_file, required_files}, + compile::OPENTOFU_VERSION, +}; +use std::{fs, path::Path}; + +/// Write a bundle whose hashes verify, so opening it succeeds. With `tofu`, +/// `libexec/tofu` is that shell script; every other file cannot execute, so +/// without it no operation that reaches OpenTofu can do anything. The SDK +/// requires `rust` to be non-empty and `version` to be a semantic version, so +/// these values need not match the toolchain or the workspace version. +pub fn write_bundle(directory: &Path, tofu: Option<&str>) { + let mut manifest = Manifest { + version: "0.1.0".into(), + rust: "1.98.1".into(), + opentofu: OPENTOFU_VERSION.into(), + files: Default::default(), + }; + let tofu_file = format!("libexec/{}", executable("tofu")); + for name in required_files(&manifest.version).unwrap() { + let path = directory.join(&name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + match tofu.filter(|_| name == tofu_file) { + Some(script) => write_script(&path, script), + None => fs::write(&path, b"non-executable fixture").unwrap(), + } + manifest.files.insert(name, hash_file(&path).unwrap()); + } + fs::write( + directory.join("manifest.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); +} + +#[cfg(unix)] +fn write_script(path: &Path, script: &str) { + crate::executable::write_executable(path, script); +} + +#[cfg(not(unix))] +fn write_script(_: &Path, _: &str) { + panic!("a scripted tofu needs a Unix shell"); +} diff --git a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs index c2d23df0d52..90c1ae3eaea 100644 --- a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs +++ b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs @@ -13,8 +13,7 @@ use nemoclaw_sdk::{ CancellationToken, Deployment, ObservationError, Progress, Secrets, StepOutcome, - bundle::{Manifest, executable, hash_file, required_files}, - compile::{Generations, OPENTOFU_VERSION, Target}, + compile::{Generations, Target}, config::Document, kubernetes::{GATEWAY_KIND, STORAGE_KIND, gateway::ADDRESS as HELM_RELEASE}, }; @@ -62,36 +61,6 @@ case "$1" in esac "##; -/// A bundle whose files verify; only `libexec/tofu` can execute. Adapted from -/// `deployment.rs::write_bundle`, which keeps its own copy because it also runs -/// on Windows. The SDK requires `rust` to be non-empty and `version` to be a -/// semantic version, so these values need not match the toolchain or the -/// workspace version. -fn write_bundle(directory: &Path, script: &str) { - let mut manifest = Manifest { - version: "0.1.0".into(), - rust: "1.98.1".into(), - opentofu: OPENTOFU_VERSION.into(), - files: Default::default(), - }; - let tofu = format!("libexec/{}", executable("tofu")); - for name in required_files(&manifest.version).unwrap() { - let path = directory.join(&name); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - if name == tofu { - crate::executable::write_executable(&path, script); - } else { - fs::write(&path, b"non-executable fixture").unwrap(); - } - manifest.files.insert(name, hash_file(&path).unwrap()); - } - fs::write( - directory.join("manifest.json"), - serde_json::to_vec(&manifest).unwrap(), - ) - .unwrap(); -} - /// A temporary bundle with a scripted `tofu`, a control directory, and the path /// of a state directory that `Deployment` creates. A test creates one. pub struct Scripted { @@ -121,7 +90,7 @@ impl Scripted { let script = SCRIPT .replace("@CONTROL@", "ed(scripted.control())) .replace("@STATE@", "ed(scripted.state())); - write_bundle(&scripted.bundle(), &script); + crate::bundle::write_bundle(&scripted.bundle(), Some(&script)); scripted }