diff --git a/benchmarks/aft-search/slice-descriptors/fix-ort-cli-exit-quiesce.json b/benchmarks/aft-search/slice-descriptors/fix-ort-cli-exit-quiesce.json new file mode 100644 index 0000000000..2058d1fdc3 --- /dev/null +++ b/benchmarks/aft-search/slice-descriptors/fix-ort-cli-exit-quiesce.json @@ -0,0 +1,14 @@ +{ + "slice_class": "non_ranking", + "targeted_mechanism": "none", + "kind": "harness", + "fixtures": [ + "crates/aft/tests/integration/cli_ort_exit_test.rs", + "crates/aft/src/data_layer/meaning.rs", + "crates/aft/src/main.rs" + ], + "slices": [ + "fix-ort-cli-exit-quiesce" + ], + "note": "The one-shot `aft warmup` and `aft index` commands now wait for in-flight ONNX Runtime work before the process ends, as the standalone and daemon shutdowns already do. The only change in data_layer/meaning.rs is a test-hooks-only hold before embedding model creation, which release builds do not compile. No change to search ranking, routing, indexing or the meaning-search fill itself." +} diff --git a/crates/aft/src/data_layer/meaning.rs b/crates/aft/src/data_layer/meaning.rs index b2338576ca..50d7de4f1f 100644 --- a/crates/aft/src/data_layer/meaning.rs +++ b/crates/aft/src/data_layer/meaning.rs @@ -595,6 +595,8 @@ impl Meaning { if let Some(dimensions) = constant_dimensions { return self.fill_constant_vectors_for_test(checkout, config, dimensions); } + #[cfg(feature = "test-hooks")] + hold_model_creation_for_exit_test(); match SemanticEmbeddingModel::from_config(config) { Ok(loaded) => *model = Some((config.clone(), loaded)), Err(error) => return Round::Failed(self.failure(checkout.root(), error, true)), @@ -815,6 +817,31 @@ pub(crate) fn hold_model_loads_for_test(root: &Path) -> impl Drop { Release(root.to_path_buf()) } +/// Holds a fill inside an ONNX Runtime section where it would create its +/// embedding session, so an exit test can see whether a CLI command that is +/// ending waits for that session creation. Set +/// `AFT_TEST_HOLD_FILL_MODEL_CREATION` to a folder: the fill writes `entered` +/// there once it is inside the section, waits until `release` exists, and +/// writes `left` just before it leaves the section. A process that ends +/// without waiting for the section never writes `left`. The hold does not +/// load ONNX Runtime, so the test needs no runtime installed; the model load +/// that follows it then runs as usual. +#[cfg(feature = "test-hooks")] +fn hold_model_creation_for_exit_test() { + let Some(dir) = std::env::var_os("AFT_TEST_HOLD_FILL_MODEL_CREATION").map(PathBuf::from) else { + return; + }; + // Once the process is exiting no new section opens, as for a real load. + let Some(_section) = crate::ort_lifecycle::enter() else { + return; + }; + let _ = std::fs::write(dir.join("entered"), b""); + while !dir.join("release").exists() { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let _ = std::fs::write(dir.join("left"), b""); +} + #[cfg(test)] #[test] fn memory_figure_read_only_failure_changes_invalidate_the_meaning_version() { diff --git a/crates/aft/src/main.rs b/crates/aft/src/main.rs index b2791e6020..fb5aad7bb8 100644 --- a/crates/aft/src/main.rs +++ b/crates/aft/src/main.rs @@ -132,6 +132,30 @@ fn exit_after_log_flush(code: i32) -> i32 { code } +/// Runs a one-shot subcommand that can start ONNX Runtime work (`warmup` and +/// `index` fill meaning-search data) and ends the process with the code +/// it returns. Every such subcommand must end through this function. +/// +/// When the command's own work is done, a background thread can still be +/// inside ONNX Runtime: a meaning-search fill creating its embedding session, +/// for example. Returning from `main` or calling `process::exit` runs ONNX +/// Runtime's C++ static destructors underneath that thread, and the process +/// dies with SIGSEGV after its output is complete. So, as the standalone and +/// supervised shutdowns do, this first refuses new ONNX Runtime work and waits +/// for the work in flight, then ends without native teardown if that work +/// does not finish in time. +/// +/// Code 0 returns so the caller can return from `main` as before; any other +/// code exits here. +fn run_ort_capable_command(command: impl FnOnce() -> i32) { + let code = command(); + if code == 0 { + aft::ort_lifecycle::quiesce_before_return(0); + return; + } + aft::ort_lifecycle::exit_process(code) +} + fn hold_process_storage_lease() -> Arc { let storage = aft::bash_background::storage_dir(None); aft::root_cache::acquire_daemon_storage_lease(&storage).unwrap_or_else(|error| { @@ -368,14 +392,13 @@ fn main() { // Offline semantic collection can use Rayon. This branch exits without // running the server's later process-environment mutations. initialize_global_rayon_pool(); - match cli::index::run(args) { - Ok(cli::index::IndexExit::Success) => return, - Ok(exit) => std::process::exit(exit.code()), + return run_ort_capable_command(|| match cli::index::run(args) { + Ok(exit) => exit.code(), Err(error) => { eprintln!("{error}"); - std::process::exit(1); + 1 } - } + }); } if std::env::args().nth(1).as_deref() == Some("grammar-smoke") { @@ -494,13 +517,13 @@ fn main() { if std::env::args().nth(1).as_deref() == Some("warmup") { let args = std::env::args_os().skip(2).collect::>(); - match cli::warmup::run(args) { - Ok(()) => return, + return run_ort_capable_command(|| match cli::warmup::run(args) { + Ok(()) => 0, Err(error) => { eprintln!("{error}"); - std::process::exit(error.exit_code()); + error.exit_code() } - } + }); } // Writes the large allocations and bursts the global allocator records; diff --git a/crates/aft/tests/integration/cli_ort_exit_test.rs b/crates/aft/tests/integration/cli_ort_exit_test.rs new file mode 100644 index 0000000000..e5c840b26f --- /dev/null +++ b/crates/aft/tests/integration/cli_ort_exit_test.rs @@ -0,0 +1,135 @@ +//! A one-shot CLI command must not end while a background thread is inside +//! ONNX Runtime. Ending runs ONNX Runtime's C++ static destructors, and a +//! meaning-search fill still creating its embedding session then reads freed +//! memory and the process dies with SIGSEGV after its output is complete. + +use std::io::{BufRead, BufReader}; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use crate::test_helpers::aft_binary; + +fn wait_for_file(path: &Path, child: &mut Child, what: &str) { + let deadline = Instant::now() + Duration::from_secs(60); + while !path.exists() { + if let Some(status) = child.try_wait().unwrap() { + panic!("aft exited with {status} before {what}"); + } + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn warmup_exit_waits_for_a_fill_inside_model_creation() { + let temp = tempfile::tempdir().unwrap(); + let home = temp.path().join("home"); + let storage = temp.path().join("storage"); + let root = temp.path().join("root"); + let hold = temp.path().join("hold"); + for dir in [&home, &storage, &root.join("src"), &hold] { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write( + root.join("src/lib.rs"), + "pub fn greet() -> &'static str {\n \"hello\"\n}\n", + ) + .unwrap(); + + // The fill holds inside the section until `release` exists, so warmup + // never sees the meaning-search fill complete and ends through its timeout. + let mut child = Command::new(aft_binary::aft_binary()) + .arg("warmup") + .arg("--root") + .arg(&root) + .args(["--only", "semantic", "--timeout", "2000"]) + .env_clear() + .env("HOME", &home) + .env("USERPROFILE", &home) + .env("APPDATA", &home) + .env("LOCALAPPDATA", &home) + .env("XDG_CONFIG_HOME", &home) + .env("XDG_CACHE_HOME", &home) + .env("XDG_DATA_HOME", &home) + .env("XDG_STATE_HOME", &home) + .env("AFT_STORAGE_DIR", &storage) + .env("AFT_TEST_DISABLE_FILE_WATCHER", "1") + .env("AFT_TEST_HOLD_FILL_MODEL_CREATION", &hold) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let stderr = child.stderr.take().unwrap(); + let (lines_tx, lines_rx) = mpsc::channel(); + let reader = std::thread::spawn(move || { + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + let _ = lines_tx.send(line); + } + }); + + wait_for_file( + &hold.join("entered"), + &mut child, + "the fill entered model creation", + ); + + // The timeout message is printed on the way out, before the exit path. + let deadline = Instant::now() + Duration::from_secs(60); + let mut seen = Vec::new(); + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + match lines_rx.recv_timeout(remaining) { + Ok(line) => { + let done = line.starts_with("aft warmup timed out"); + seen.push(line); + if done { + break; + } + } + Err(error) => { + let _ = child.kill(); + panic!("no warmup timeout message ({error}); stderr so far: {seen:#?}"); + } + } + } + + // Without the quiesce the process ends within milliseconds of that + // message, while the fill is still inside the section. + std::thread::sleep(Duration::from_secs(1)); + let early = child.try_wait().unwrap(); + if early.is_some() { + reader.join().unwrap(); + seen.extend(lines_rx.try_iter()); + panic!( + "warmup exited ({early:?}) while a fill was inside ONNX Runtime model creation; \ + stderr: {seen:#?}" + ); + } + assert!( + !hold.join("left").exists(), + "the fill left the section before it was released" + ); + + std::fs::write(hold.join("release"), b"").unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break status; + } + if Instant::now() >= deadline { + let _ = child.kill(); + panic!("warmup did not exit after the fill was released"); + } + std::thread::sleep(Duration::from_millis(10)); + }; + reader.join().unwrap(); + // The exit code of a timed-out warmup is unchanged. + assert_eq!(status.code(), Some(1), "{status}"); + assert!( + hold.join("left").exists(), + "the process ended before the fill finished its ONNX Runtime section" + ); +} diff --git a/crates/aft/tests/integration/main.rs b/crates/aft/tests/integration/main.rs index 109dab8e95..98ed1e9986 100644 --- a/crates/aft/tests/integration/main.rs +++ b/crates/aft/tests/integration/main.rs @@ -42,6 +42,7 @@ mod callgraph_restart_reuse_test; mod callgraph_test; mod checkpoint_metadata_test; mod cli_help_test; +mod cli_ort_exit_test; mod commands_test; mod compress_cli_commands_test; mod compress_filters_test;