From b34ea4b37a28c7c7477aab06987f05cf53380f1e Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:24:48 +0100 Subject: [PATCH 1/2] mason: quiesce ONNX Runtime before ORT-capable CLI commands exit aft warmup and aft index returned from main (or called process::exit) without the ONNX Runtime quiesce the standalone and supervised shutdowns run. A meaning-search fill still creating its embedding session on a background thread then ran into ORT's static destructors and the process died with SIGSEGV (exit 139) after its output was complete, as in the v0.67.0 macOS release smoke. Both commands now end through one helper that waits for in-flight ORT sections first. Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- crates/aft/src/data_layer/meaning.rs | 27 ++++ crates/aft/src/main.rs | 41 ++++-- .../tests/integration/cli_ort_exit_test.rs | 135 ++++++++++++++++++ crates/aft/tests/integration/main.rs | 1 + 4 files changed, 195 insertions(+), 9 deletions(-) create mode 100644 crates/aft/tests/integration/cli_ort_exit_test.rs 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..436c228aaa 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 the meaning-search plane) 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..c081fdd0e3 --- /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 plane 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; From de59ca656bc7ce6286f06dd08b9fccc6bdd8e56f Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:32:32 +0100 Subject: [PATCH 2/2] Clarify ONNX exit comments; add search-quality descriptor for the CLI exit fix Co-authored-by: alfonso-aft <289616620+alfonso-aft@users.noreply.github.com> --- .../fix-ort-cli-exit-quiesce.json | 14 ++++++++++++++ crates/aft/src/main.rs | 2 +- crates/aft/tests/integration/cli_ort_exit_test.rs | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 benchmarks/aft-search/slice-descriptors/fix-ort-cli-exit-quiesce.json 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/main.rs b/crates/aft/src/main.rs index 436c228aaa..fb5aad7bb8 100644 --- a/crates/aft/src/main.rs +++ b/crates/aft/src/main.rs @@ -133,7 +133,7 @@ fn exit_after_log_flush(code: i32) -> i32 { } /// Runs a one-shot subcommand that can start ONNX Runtime work (`warmup` and -/// `index` fill the meaning-search plane) and ends the process with the code +/// `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 diff --git a/crates/aft/tests/integration/cli_ort_exit_test.rs b/crates/aft/tests/integration/cli_ort_exit_test.rs index c081fdd0e3..e5c840b26f 100644 --- a/crates/aft/tests/integration/cli_ort_exit_test.rs +++ b/crates/aft/tests/integration/cli_ort_exit_test.rs @@ -39,7 +39,7 @@ fn warmup_exit_waits_for_a_fill_inside_model_creation() { .unwrap(); // The fill holds inside the section until `release` exists, so warmup - // never sees the meaning plane complete and ends through its timeout. + // 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")