diff --git a/benchmarks/src/bin/benchmark_runner.rs b/benchmarks/src/bin/benchmark_runner.rs index 15024da0ca444..bfda51dbb0442 100644 --- a/benchmarks/src/bin/benchmark_runner.rs +++ b/benchmarks/src/bin/benchmark_runner.rs @@ -21,7 +21,9 @@ use datafusion_benchmarks::sql_benchmark_runner::{ use datafusion_benchmarks::sql_benchmark_suite::{ ReservedOptions, SuiteExample, SuiteMetadata, discover_suites, }; -use datafusion_benchmarks::util::{BenchmarkRun, CommonOpt, print_memory_stats}; +use datafusion_benchmarks::util::{ + BenchmarkRun, CommonOpt, build_runtime, print_memory_stats, +}; use datafusion_common::instant::Instant; use datafusion_common::{DataFusionError, exec_datafusion_err}; use datafusion_common_runtime::SpawnedTask; @@ -42,10 +44,10 @@ static ALLOC: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc; #[global_allocator] static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; -#[tokio::main] -async fn main() { +fn main() { env_logger::init(); - if let Err(error) = run_cli().await { + let runtime = build_runtime().expect("failed to build the Tokio runtime"); + if let Err(error) = runtime.block_on(run_cli()) { eprintln!("Error: {error}"); std::process::exit(1); } @@ -910,6 +912,7 @@ mod tests { max_iterations: 1000, lockstep_in: None, lockstep_out: None, + reset_memory: false, partitions: None, batch_size: None, mem_pool_type: "fair".to_string(), diff --git a/benchmarks/src/bin/dfbench.rs b/benchmarks/src/bin/dfbench.rs index 37e78600e2822..a1e3bd1e6bb22 100644 --- a/benchmarks/src/bin/dfbench.rs +++ b/benchmarks/src/bin/dfbench.rs @@ -48,11 +48,12 @@ enum Options { } // Main benchmark runner entrypoint -#[tokio::main] -pub async fn main() -> Result<()> { +pub fn main() -> Result<()> { env_logger::init(); + datafusion_benchmarks::util::build_runtime()?.block_on(run(Cli::parse())) +} - let cli = Cli::parse(); +async fn run(cli: Cli) -> Result<()> { match cli.command { Options::Cancellation(opt) => opt.run().await, Options::Clickbench(opt) => opt.run().await, diff --git a/benchmarks/src/bin/external_aggr.rs b/benchmarks/src/bin/external_aggr.rs index 10dbef0b858d8..aa507883442e1 100644 --- a/benchmarks/src/bin/external_aggr.rs +++ b/benchmarks/src/bin/external_aggr.rs @@ -26,7 +26,7 @@ use datafusion::execution::runtime_env::RuntimeEnvBuilder; use datafusion::physical_plan::display::DisplayableExecutionPlan; use datafusion::physical_plan::{collect, displayable}; use datafusion::prelude::*; -use datafusion_benchmarks::util::{BenchmarkRun, CommonOpt, QueryResult}; +use datafusion_benchmarks::util::{BenchmarkRun, CommonOpt, QueryResult, build_runtime}; use datafusion_common::instant::Instant; use datafusion_common::utils::get_available_parallelism; use datafusion_common::{DEFAULT_PARQUET_EXTENSION, exec_err}; @@ -335,11 +335,12 @@ impl ExternalAggrConfig { } } -#[tokio::main] -pub async fn main() -> Result<()> { +pub fn main() -> Result<()> { env_logger::init(); + build_runtime()?.block_on(run(Cli::parse())) +} - let cli = Cli::parse(); +async fn run(cli: Cli) -> Result<()> { match cli.command { ExternalAggrOpt::Benchmark(opt) => opt.run().await?, } diff --git a/benchmarks/src/bin/imdb.rs b/benchmarks/src/bin/imdb.rs index 4f3dcbc2c21ca..ccc3d081c0208 100644 --- a/benchmarks/src/bin/imdb.rs +++ b/benchmarks/src/bin/imdb.rs @@ -7,6 +7,7 @@ use clap::{Parser, Subcommand}; use datafusion::error::Result; use datafusion_benchmarks::imdb; +use datafusion_benchmarks::util::build_runtime; #[cfg(feature = "snmalloc")] #[global_allocator] @@ -38,10 +39,13 @@ enum BenchmarkSubCommandOpt { DataFusionBenchmark(Box), } -#[tokio::main] -pub async fn main() -> Result<()> { +pub fn main() -> Result<()> { env_logger::init(); - match Cli::parse().command { + build_runtime()?.block_on(run(Cli::parse())) +} + +async fn run(cli: Cli) -> Result<()> { + match cli.command { ImdbOpt::Benchmark(BenchmarkSubCommandOpt::DataFusionBenchmark(opt)) => { Box::pin(opt.run()).await } diff --git a/benchmarks/src/dict.rs b/benchmarks/src/dict.rs index bb94fa3f1ad8f..e47d58cfa5bb7 100644 --- a/benchmarks/src/dict.rs +++ b/benchmarks/src/dict.rs @@ -697,6 +697,7 @@ mod tests { max_iterations: 1000, lockstep_in: None, lockstep_out: None, + reset_memory: false, partitions: Some(1), batch_size: None, mem_pool_type: "fair".to_string(), diff --git a/benchmarks/src/imdb/run.rs b/benchmarks/src/imdb/run.rs index f6b6115439c47..dd12cf72df545 100644 --- a/benchmarks/src/imdb/run.rs +++ b/benchmarks/src/imdb/run.rs @@ -495,6 +495,7 @@ mod tests { max_iterations: 1000, lockstep_in: None, lockstep_out: None, + reset_memory: false, partitions: Some(2), batch_size: Some(8192), mem_pool_type: "fair".to_string(), @@ -536,6 +537,7 @@ mod tests { max_iterations: 1000, lockstep_in: None, lockstep_out: None, + reset_memory: false, partitions: Some(2), batch_size: Some(8192), mem_pool_type: "fair".to_string(), diff --git a/benchmarks/src/sql_benchmark_runner.rs b/benchmarks/src/sql_benchmark_runner.rs index 05a28e25fd32d..123c1cbed5913 100644 --- a/benchmarks/src/sql_benchmark_runner.rs +++ b/benchmarks/src/sql_benchmark_runner.rs @@ -807,6 +807,7 @@ mod tests { max_iterations: 1000, lockstep_in: None, lockstep_out: None, + reset_memory: false, partitions: None, batch_size: None, mem_pool_type: "fair".to_string(), diff --git a/benchmarks/src/tpch/run.rs b/benchmarks/src/tpch/run.rs index ccea71ad0d4b8..02d21dcdd3b51 100644 --- a/benchmarks/src/tpch/run.rs +++ b/benchmarks/src/tpch/run.rs @@ -430,6 +430,7 @@ mod tests { max_iterations: 1000, lockstep_in: None, lockstep_out: None, + reset_memory: false, partitions: Some(2), batch_size: Some(8192), mem_pool_type: "fair".to_string(), @@ -473,6 +474,7 @@ mod tests { max_iterations: 1000, lockstep_in: None, lockstep_out: None, + reset_memory: false, partitions: Some(2), batch_size: Some(8192), mem_pool_type: "fair".to_string(), diff --git a/benchmarks/src/util/mod.rs b/benchmarks/src/util/mod.rs index 749bbce47102c..029017f192ddc 100644 --- a/benchmarks/src/util/mod.rs +++ b/benchmarks/src/util/mod.rs @@ -5,11 +5,13 @@ //! Shared benchmark utilities mod memory; mod options; +mod reset; mod run; mod sampler; pub mod simulated_object_store; pub use memory::print_memory_stats; pub use options::{CommonOpt, QueryOpt}; +pub use reset::build_runtime; pub use run::{BenchQuery, BenchmarkRun, QueryResult}; pub use sampler::Sampler; diff --git a/benchmarks/src/util/options.rs b/benchmarks/src/util/options.rs index 302dc0f12e5f2..2787b95d28e30 100644 --- a/benchmarks/src/util/options.rs +++ b/benchmarks/src/util/options.rs @@ -88,6 +88,11 @@ pub struct CommonOpt { /// FIFO that this process reports `ready` / `elapsed` to. Requires --lockstep-in #[arg(long = "lockstep-out", requires = "lockstep_in")] pub lockstep_out: Option, + + /// Before each iteration, return free memory to the OS, so that the iteration does not depend + /// on what ran before it. Requires the `mimalloc_extended` feature + #[arg(long = "reset-memory")] + pub reset_memory: bool, } /// Session configuration overrides shared by query benchmarks. @@ -136,9 +141,10 @@ impl CommonOpt { /// Returns the [`Sampler`] that controls the iteration loop of one query. pub fn sampler(&self) -> Sampler { if let (Some(input), Some(output)) = (&self.lockstep_in, &self.lockstep_out) { - return Sampler::lockstep(Lockstep::global(input, output)); + return Sampler::lockstep(Lockstep::global(input, output)) + .with_reset_memory(self.reset_memory); } - match self.max_time { + let sampler = match self.max_time { None => Sampler::fixed(self.iterations), Some(secs) => Sampler::adaptive( self.iterations, @@ -146,7 +152,8 @@ impl CommonOpt { Duration::from_secs_f64(secs), self.target_precision, ), - } + }; + sampler.with_reset_memory(self.reset_memory) } /// Return an appropriately configured `SessionConfig` @@ -387,6 +394,7 @@ mod tests { max_iterations: 1000, lockstep_in: None, lockstep_out: None, + reset_memory: false, partitions: None, batch_size: None, mem_pool_type: "fair".to_string(), diff --git a/benchmarks/src/util/reset.rs b/benchmarks/src/util/reset.rs new file mode 100644 index 0000000000000..8e66997e8e529 --- /dev/null +++ b/benchmarks/src/util/reset.rs @@ -0,0 +1,272 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Returns memory to the OS between iterations, so that the speed of an +//! iteration does not depend on what ran before it. +//! +//! # Problem +//! +//! mimalloc keeps freed memory for reuse instead of returning it to the OS. +//! After a query that used a lot of memory, the next iteration finds free +//! pages and runs faster than after a query that used little. So one query can +//! change the timing of the next query in the same process. +//! +//! # Design +//! +//! mimalloc gives each thread its own heap. `mi_collect(true)` frees the +//! unused memory of the calling thread's heap, and then returns all free +//! memory to the OS. It cannot clean the heap of another thread, so a +//! collection must run on each thread. The threads stay alive. Only their +//! free memory goes back to the OS. +//! +//! Tokio cannot run a closure on each of its threads, so [`reset_memory`] +//! spawns one task per thread and makes each task wait at a barrier. A task +//! that waits keeps its thread busy, so no thread can run two of the tasks: +//! +//! ```text +//! main thread: spawn N tasks ─┐ +//! each thread: arrive ── collect ── arrive ── collect ── arrive +//! │ │ +//! │ └ frees memory that another thread +//! │ owned and released in round one +//! └ all N + 1 threads are now held, one task each +//! ``` +//! +//! N counts the worker threads and the blocking threads. Tokio reports only +//! the workers, so [`build_runtime`] counts every thread as it starts and +//! stops. +//! +//! The reset runs before the timed part of an iteration. In lockstep mode it +//! runs before the process sends `ready`, so it never overlaps a timed +//! iteration of the other process. +//! +//! | Case | Behavior | +//! |------|----------| +//! | A thread stays busy | The reset stops after [`TIMEOUT`] and prints a warning | +//! | A worker blocks while it holds the task of a parked worker | The main thread spawns an empty task every [`NUDGE_INTERVAL`] to wake workers | +//! | The build does not use mimalloc with `mimalloc_extended` | The process stops with an error | + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +use datafusion_common::instant::Instant; +use tokio::runtime::{Builder, Handle, Runtime}; + +/// Longest wait for a busy thread. An idle runtime needs milliseconds. +const TIMEOUT: Duration = Duration::from_secs(2); + +/// How often the main thread wakes workers while it waits. +const NUDGE_INTERVAL: Duration = Duration::from_millis(1); + +/// Worker and blocking threads of the runtime that [`build_runtime`] returns. +static THREADS: AtomicUsize = AtomicUsize::new(0); + +/// Builds the multi-threaded runtime that `--reset-memory` needs. +pub fn build_runtime() -> std::io::Result { + Builder::new_multi_thread() + .enable_all() + .on_thread_start(|| { + THREADS.fetch_add(1, Ordering::SeqCst); + }) + .on_thread_stop(|| { + THREADS.fetch_sub(1, Ordering::SeqCst); + }) + .build() +} + +/// A barrier that stops waiting at a deadline. +struct Gate { + expected: usize, + deadline: Instant, + state: Mutex, + changed: Condvar, +} + +impl Gate { + fn new(expected: usize, deadline: Instant) -> Self { + Self { + expected, + deadline, + state: Mutex::new(GateState::default()), + changed: Condvar::new(), + } + } + + /// Returns whether all threads arrived before the deadline. + /// + /// A thread that the timeout releases can run the task of the busy thread. + /// That late arrival must not complete the count, so a timeout closes the + /// gate for all threads. + /// + /// A worker takes tasks in batches. It can block here with the task of a + /// parked worker in its local queue, and nothing wakes that worker. The + /// main thread passes `nudge` to spawn empty tasks, which wake workers until + /// one of them steals the task. + fn arrive(&self, nudge: Option<&Handle>) -> bool { + let mut state = self.state.lock().unwrap(); + state.arrived += 1; + if state.arrived == self.expected && !state.closed { + self.changed.notify_all(); + return true; + } + while !state.closed && state.arrived < self.expected { + let now = Instant::now(); + if now >= self.deadline { + state.closed = true; + self.changed.notify_all(); + break; + } + let mut wait = self.deadline - now; + if let Some(handle) = nudge { + handle.spawn(async {}); + wait = wait.min(NUDGE_INTERVAL); + } + (state, _) = self.changed.wait_timeout(state, wait).unwrap(); + } + !state.closed + } +} + +#[derive(Default)] +struct GateState { + arrived: usize, + closed: bool, +} + +/// Runs `action` twice on each of the `workers + blocking` runtime threads and +/// on the calling thread. Returns whether every thread did so before `timeout`. +/// +/// Spawning one task per thread is not enough: Tokio does not promise to put +/// each task on a different thread. One worker can run two of the tasks while +/// another runs none. The three gates fix that: +/// +/// | Gate | Every thread waits here until all threads have... | Why | +/// |------|--------------------------------------------------|-----| +/// | 1 | taken a task | A thread that waits cannot take a second task, so each thread holds exactly one | +/// | 2 | run `action` once | Round one can free blocks into the heap of another thread. Round two returns them | +/// | 3 | run `action` twice | The caller returns only after every thread has finished | +fn on_every_thread( + handle: &Handle, + workers: usize, + blocking: usize, + timeout: Duration, + action: fn(), +) -> bool { + let deadline = Instant::now() + timeout; + let expected = workers + blocking + 1; + let gates: Arc<[Gate; 3]> = + Arc::new(std::array::from_fn(|_| Gate::new(expected, deadline))); + let run = move |gates: &[Gate; 3], nudge: Option<&Handle>| { + let mut all = gates[0].arrive(nudge); + for gate in &gates[1..] { + action(); + all &= gate.arrive(nudge); + } + all + }; + for _ in 0..workers { + let gates = Arc::clone(&gates); + handle.spawn(async move { run(&gates, None) }); + } + for _ in 0..blocking { + let gates = Arc::clone(&gates); + handle.spawn_blocking(move || run(&gates, None)); + } + run(&gates, Some(handle)) +} + +/// Returns all free memory of all threads to the OS. Must run on the thread +/// that called `Runtime::block_on`, outside the timed part of an iteration. +pub(super) fn reset_memory() { + // With `snmalloc`, the global allocator is not mimalloc, so a collection + // has no effect. + if !cfg!(all( + feature = "mimalloc", + feature = "mimalloc_extended", + not(feature = "snmalloc") + )) { + panic!( + "--reset-memory requires the features `mimalloc` and `mimalloc_extended`, \ + without `snmalloc`" + ); + } + let handle = Handle::current(); + let workers = handle.metrics().num_workers(); + let blocking = THREADS.load(Ordering::SeqCst).saturating_sub(workers); + if !on_every_thread(&handle, workers, blocking, TIMEOUT, collect) { + eprintln!("--reset-memory: a thread was busy, the reset is incomplete"); + } + collect(); +} + +#[cfg(all(feature = "mimalloc", feature = "mimalloc_extended"))] +fn collect() { + // `force = true` frees the unused memory of this thread's heap, and then + // returns all free memory of the process to the OS, without the usual + // purge delay. + // SAFETY: `mi_collect` has no preconditions. + unsafe { libmimalloc_sys::mi_collect(true) } +} + +#[cfg(not(all(feature = "mimalloc", feature = "mimalloc_extended")))] +fn collect() {} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::thread::ThreadId; + + static SEEN: Mutex> = Mutex::new(vec![]); + fn see() { + SEEN.lock().unwrap().push(std::thread::current().id()); + } + + #[test] + fn visits_every_thread_twice_and_survives_a_busy_thread() { + let rt = Builder::new_multi_thread() + .worker_threads(4) + .build() + .unwrap(); + let handle = rt.handle(); + rt.block_on(async { + let warm = Arc::new(std::sync::Barrier::new(4)); + let tasks: Vec<_> = (0..3) + .map(|_| { + let warm = Arc::clone(&warm); + handle.spawn_blocking(move || warm.wait()) + }) + .collect(); + warm.wait(); + for task in tasks { + task.await.unwrap(); + } + for _ in 0..50 { + SEEN.lock().unwrap().clear(); + assert!(on_every_thread(handle, 4, 3, Duration::from_secs(30), see)); + let seen = SEEN.lock().unwrap().clone(); + assert_eq!(seen.len(), 16); + assert_eq!(seen.into_iter().collect::>().len(), 8); + } + + let (started, wait_started) = std::sync::mpsc::channel(); + let busy = handle.spawn(async move { + started.send(()).unwrap(); + std::thread::sleep(Duration::from_millis(600)); + }); + wait_started.recv().unwrap(); + let start = Instant::now(); + assert!(!on_every_thread( + handle, + 4, + 0, + Duration::from_millis(50), + || () + )); + assert!(start.elapsed() < Duration::from_millis(500)); + busy.await.unwrap(); + }); + } +} diff --git a/benchmarks/src/util/sampler.rs b/benchmarks/src/util/sampler.rs index 6e41eed202ebc..a3a5c4f037a72 100644 --- a/benchmarks/src/util/sampler.rs +++ b/benchmarks/src/util/sampler.rs @@ -53,6 +53,7 @@ pub struct Sampler { /// In lockstep mode, whether the orchestrator ended this query with /// `stop`. A sampler dropped before that belongs to a failed query. stopped: bool, + reset_memory: bool, } #[derive(Debug, Clone, Copy)] @@ -72,6 +73,7 @@ impl Sampler { started: Instant::now(), samples: Vec::with_capacity(iterations), stopped: false, + reset_memory: false, } } @@ -96,6 +98,7 @@ impl Sampler { started: Instant::now(), samples: vec![], stopped: false, + reset_memory: false, } } @@ -110,12 +113,24 @@ impl Sampler { started: Instant::now(), samples: vec![], stopped: false, + reset_memory: false, } } + /// Whether to return free memory to the OS before each iteration. + pub fn with_reset_memory(mut self, reset_memory: bool) -> Self { + self.reset_memory = reset_memory; + self + } + /// Returns the index of the next iteration to run, or `None` to stop. pub fn next_iteration(&mut self) -> Option { let n = self.samples.len(); + if self.reset_memory { + // In lockstep mode this precedes `ready`, so the other process does + // not run an iteration at the same time. + super::reset::reset_memory(); + } if let Some(lockstep) = self.lockstep { let run = lockstep.lock().expect("lockstep poisoned").ask(); self.stopped = !run;