From 27d2e303b926e92068bc82e7f15f95b5cfe859c8 Mon Sep 17 00:00:00 2001 From: Nikhil Sinha Date: Fri, 4 Dec 2026 19:56:54 +0530 Subject: [PATCH 1/4] fix(query): protect server from memory exhaustion Bound the default DataFusion memory pool and concurrent query admission using detected cgroup memory. Queue requests for up to ten seconds when all admission slots are busy, and retain permits until streaming queries finish or are cancelled.\n\nUse memory-aware partition defaults and smaller execution batches so constrained deployments reject oversized queries cleanly instead of exhausting the server. --- src/cli.rs | 42 +++++++++++++++-- src/query/mod.rs | 117 +++++++++++++++++++++++++++++++++++------------ 2 files changed, 127 insertions(+), 32 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 82d950553..e295b62be 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -17,7 +17,8 @@ */ use clap::{Parser, value_parser}; -use std::{env, fs, ops::Mul, path::PathBuf}; +use std::{env, fs, path::PathBuf}; +use sysinfo::System; use url::Url; @@ -37,6 +38,22 @@ pub const DEFAULT_PASSWORD: &str = "admin"; pub const DATASET_FIELD_COUNT_LIMIT: usize = 1000; const DEFAULT_PARQUET_METADATA_CACHE_SIZE: usize = 50 * 1024 * 1024; // 50 MB +const MEMORY_PER_TARGET_PARTITION: u64 = 256 * 1024 * 1024; + +fn target_partitions_for_resources(cpus: usize, total_memory: u64) -> u64 { + let cpu_limit = cpus.saturating_mul(4).max(1); + let memory_limit = (total_memory / MEMORY_PER_TARGET_PARTITION).max(1) as usize; + cpu_limit.min(memory_limit) as u64 +} + +fn default_target_partitions() -> u64 { + let mut system = System::new(); + system.refresh_memory(); + let total_memory = system + .cgroup_limits() + .map_or_else(|| system.total_memory(), |cgroup| cgroup.total_memory); + target_partitions_for_resources(num_cpus::get(), total_memory) +} #[derive(Parser)] #[command( name = "parseable", @@ -222,7 +239,7 @@ pub struct Options { #[arg( long, env = "P_DATAFUSION_TARGET_PARTITIONS", - default_value_t = num_cpus::get().mul(4).max(1) as u64, + default_value_t = default_target_partitions(), value_parser = value_parser!(u64).range(1..), help = "Number of partitions for DF to split execution into" )] @@ -484,7 +501,7 @@ pub struct Options { #[arg( long, env = "P_EXECUTION_BATCH_SIZE", - default_value = "20000", + default_value = "8192", help = "batch size for query execution" )] pub execution_batch_size: usize, @@ -898,3 +915,22 @@ impl Options { }) } } + +#[cfg(test)] +mod tests { + use super::target_partitions_for_resources; + + #[test] + fn target_partitions_are_bounded_by_memory() { + assert_eq!(target_partitions_for_resources(16, 1024 * 1024 * 1024), 4); + assert_eq!( + target_partitions_for_resources(16, 16 * 1024 * 1024 * 1024), + 64 + ); + } + + #[test] + fn target_partitions_never_reach_zero() { + assert_eq!(target_partitions_for_resources(0, 0), 1); + } +} diff --git a/src/query/mod.rs b/src/query/mod.rs index 1acbd0188..7eb0a0bed 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -90,6 +90,38 @@ type BoxedBatchStream = SendableRecordBatchStream; /// Result type returned by query execution: either collected batches or a streaming adapter, plus field names. type QueryResult = Result<(Either, BoxedBatchStream>, Vec), ExecuteError>; const DEFAULT_COUNTS_TOP_K: usize = 10; +const DEFAULT_QUERY_MEMORY_DIVISOR: u64 = 8; +const MEMORY_PER_CONCURRENT_QUERY: u64 = 1024 * 1024 * 1024; +const MAX_CONCURRENT_QUERIES: usize = 4; +const QUERY_ADMISSION_WAIT: std::time::Duration = std::time::Duration::from_secs(10); + +fn detected_memory_limit() -> u64 { + let mut system = System::new(); + system.refresh_memory(); + system + .cgroup_limits() + .map_or_else(|| system.total_memory(), |cgroup| cgroup.total_memory) +} + +fn default_query_memory_pool_size(total_memory: u64) -> usize { + usize::try_from(total_memory / DEFAULT_QUERY_MEMORY_DIVISOR) + .unwrap_or(usize::MAX) + .max(1) +} + +fn max_concurrent_queries(total_memory: u64) -> usize { + usize::try_from(total_memory / MEMORY_PER_CONCURRENT_QUERY) + .unwrap_or(usize::MAX) + .clamp(1, MAX_CONCURRENT_QUERIES) +} + +fn is_count_projection(expr: &Expr) -> bool { + match expr { + Expr::Column(column) => column.name.eq_ignore_ascii_case("count(*)"), + Expr::Alias(alias) => is_count_projection(&alias.expr), + _ => false, + } +} pub static SCHEMA_PROVIDER: OnceCell> = OnceCell::new(); @@ -106,6 +138,12 @@ pub static QUERY_SESSION_STATE: Lazy = pub static QUERY_RUNTIME: Lazy = Lazy::new(|| Runtime::new().expect("Runtime should be constructible")); +static QUERY_ADMISSION: Lazy> = Lazy::new(|| { + Arc::new(tokio::sync::Semaphore::new(max_concurrent_queries( + detected_memory_limit(), + ))) +}); + /// A dropped caller must not leave query planning running on QUERY_RUNTIME. struct AbortQueryOnDrop(tokio::task::JoinHandle); @@ -230,8 +268,11 @@ async fn enough_available_memory() -> Result<(), ExecuteError> { tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; } }; - if let Err(e) = tokio::time::timeout(tokio::time::Duration::from_secs(10), f).await { - Err(ExecuteError::ServerBusy(e)) + if tokio::time::timeout(tokio::time::Duration::from_secs(10), f) + .await + .is_err() + { + Err(ExecuteError::ServerBusy) } else { Ok(()) } @@ -327,21 +368,12 @@ impl Query { .with_disk_manager_builder(DiskManager::builder()) .with_metadata_cache_limit(PARSEABLE.options.parquet_metadata_cache_size); - let (pool_size, fraction) = match PARSEABLE.options.query_memory_pool_size { - Some(size) => (size, 1.), - None => { - let mut system = System::new(); - system.refresh_memory(); - let available_mem = if let Some(cgroup) = system.cgroup_limits() { - cgroup.total_memory - } else { - system.total_memory() - }; - (available_mem as usize, 0.85) - } - }; + let pool_size = PARSEABLE + .options + .query_memory_pool_size + .unwrap_or_else(|| default_query_memory_pool_size(detected_memory_limit())); - let runtime_config = runtime_config.with_memory_limit(pool_size, fraction); + let runtime_config = runtime_config.with_memory_limit(pool_size, 1.0); let runtime = Arc::new(runtime_config.build().unwrap()); // All the config options are explained here - @@ -351,7 +383,7 @@ impl Query { .with_prefer_existing_sort(true) .with_collect_statistics(true) //batch size has been made configurable via environment variable - //default value is 20000 + // default value is 8192 .with_batch_size(PARSEABLE.options.execution_batch_size) .with_target_partitions(PARSEABLE.options.target_partitions as usize); @@ -434,6 +466,15 @@ impl Query { ) )] pub async fn execute(&self, is_streaming: bool, tenant_id: &Option) -> QueryResult { + let mut query_admission = Some( + tokio::time::timeout( + QUERY_ADMISSION_WAIT, + QUERY_ADMISSION.clone().acquire_owned(), + ) + .await + .map_err(|_| ExecuteError::ServerBusy)? + .map_err(|_| ExecuteError::ServerBusy)?, + ); let ctx = QUERY_SESSION.get_ctx(); let mut logical_plan = self.final_logical_plan(tenant_id); let (hot_tier_guards, guarded_hot_tier_streams) = @@ -483,6 +524,7 @@ impl Query { plan: plan.clone(), active_streams: AtomicUsize::new(output_partitions), _hot_tier_guards: hot_tier_guards, + _query_admission: query_admission.take(), }); let partition_streams = execute_stream_partitioned(plan.clone(), task_ctx.clone())?; @@ -592,14 +634,7 @@ impl Query { expr: inner_expr, name: alias_name, .. - }) => { - if let Expr::Column(Column { name, .. }) = &**inner_expr - && name.to_lowercase() == "count(*)" - { - return Some(alias_name); - } - None - } + }) if is_count_projection(inner_expr) => Some(alias_name), // Unsupported expression type _ => None, } @@ -1191,8 +1226,8 @@ pub mod error { StreamNotFound(#[from] StreamNotFound), #[error("{0}: {1}s")] Timeout(Elapsed, u64), - #[error("{0}: Not enough memory available to serve the request")] - ServerBusy(Elapsed), + #[error("Not enough memory available to serve the request")] + ServerBusy, } impl actix_web::ResponseError for ExecuteError { @@ -1202,7 +1237,7 @@ pub mod error { ExecuteError::Datafusion(_) => StatusCode::INTERNAL_SERVER_ERROR, ExecuteError::StreamNotFound(_) => StatusCode::NOT_FOUND, ExecuteError::Timeout(_, _) => StatusCode::REQUEST_TIMEOUT, - ExecuteError::ServerBusy(_) => StatusCode::SERVICE_UNAVAILABLE, + ExecuteError::ServerBusy => StatusCode::SERVICE_UNAVAILABLE, } } @@ -1219,6 +1254,7 @@ struct MonitorState { plan: Arc, active_streams: AtomicUsize, _hot_tier_guards: Vec, + _query_admission: Option, } /// A wrapper that monitors the ExecutionPlan and logs metrics when the stream finishes. @@ -1308,12 +1344,35 @@ mod tests { use super::{ AbortQueryOnDrop, DataFusionError, RecordBatch, RecordBatchStreamAdapter, - forward_partition_batches, + default_query_memory_pool_size, forward_partition_batches, is_count_projection, + max_concurrent_queries, }; use crate::query::{ CountConditions, CountsRequest, flatten_objects_for_count, resolve_stream_names, }; + #[test] + fn default_query_pool_keeps_server_headroom() { + assert_eq!( + default_query_memory_pool_size(1024 * 1024 * 1024), + 128 * 1024 * 1024 + ); + } + + #[test] + fn query_concurrency_is_bounded_by_memory() { + assert_eq!(max_concurrent_queries(1024 * 1024 * 1024), 1); + assert_eq!(max_concurrent_queries(16 * 1024 * 1024 * 1024), 4); + } + + #[test] + fn nested_count_alias_is_still_a_count_projection() { + let expr = datafusion::prelude::col("count(*)") + .alias("count(*)") + .alias("rows"); + assert!(is_count_projection(&expr)); + } + #[tokio::test] async fn test_partition_scan_stops_when_receiver_drops() { let schema = std::sync::Arc::new(datafusion::arrow::datatypes::Schema::empty()); From 80b4942785de5c1adb38d28bda8c0e4e52f10cbd Mon Sep 17 00:00:00 2001 From: Nikhil Sinha Date: Sun, 6 Dec 2026 20:58:01 +0530 Subject: [PATCH 2/4] fix(query): harden memory admission under concurrent load --- Cargo.lock | 191 +++++++------ Cargo.toml | 1 + src/alerts/alerts_utils.rs | 2 +- src/cli.rs | 38 ++- src/handlers/airplane.rs | 2 +- src/handlers/http/query.rs | 33 ++- src/query/mod.rs | 541 ++++++++++++++++++++++++++++++------- 7 files changed, 609 insertions(+), 199 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cc4bde5e5..336ec79de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -36,9 +36,9 @@ dependencies = [ [[package]] name = "actix-http" -version = "3.22.1" +version = "3.22.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef789744a2e6e678dd2dee90b2aecc084022709378f28d9d0eee6d7d299e36b8" +checksum = "538e4a072ba8ac33259db2fbacd60d6a800a0253e47d90f3ae992bbaca7838d6" dependencies = [ "actix-codec", "actix-service", @@ -59,6 +59,7 @@ dependencies = [ "http 0.2.12", "httparse", "httpdate", + "impl-more", "itoa", "language-tags", "local-channel", @@ -87,9 +88,9 @@ dependencies = [ [[package]] name = "actix-router" -version = "0.5.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "125f4331c1f10734a96c038bc7503dff22d8ccd5f82b214e6696728561ef1149" +checksum = "1840555f2325618d060b4519df8b0fc18c54b2db4495b4fc3e2c45b095252780" dependencies = [ "bytestring", "cfg-if", @@ -167,9 +168,9 @@ dependencies = [ [[package]] name = "actix-web" -version = "4.20.0" +version = "4.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "618475ea8d22e5ad6e8aefaf9f56253b6ad856a7522716bea0b48bbb772341ff" +checksum = "c6e038cbbf0d2448cce380005ce6a80bcf83acc9e28cd153b372481968c90cda" dependencies = [ "actix-codec", "actix-http", @@ -321,9 +322,9 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "ahash" -version = "0.8.15" +version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" +checksum = "df3ca8d1551af9c10613a1d38022524dc2ea76206f87b36e9d273bbe8e3e8d05" dependencies = [ "cfg-if", "const-random", @@ -366,18 +367,18 @@ checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" [[package]] name = "android_system_properties" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +checksum = "204ddd8b860c1ff4b89d3cef1d23180caa4d0c34d34c9c2b009bc441ffb94d0f" dependencies = [ "libc", ] [[package]] name = "anstream" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +checksum = "85c097ce94629611e0a15ef1078a2fe2ce3b4a0f4b44708e85eeb09dd5f188eb" dependencies = [ "anstyle", "anstyle-parse", @@ -390,37 +391,37 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.14" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7" [[package]] name = "anstyle-parse" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +checksum = "a0571a23d2188b4aae7adc1df454cc81d6232cf37674fa717ac119f6c74d0dc1" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +checksum = "76a5cf9d05ffa9c878c447b33b069605e890ebcd36d2761f86367873c2ecaa7f" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.101.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.11" +version = "3.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +checksum = "2c2d00c1b2d84cef823d89d4da02ad8ff1e76c969e029da990b40f16dc834221" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.101.0", ] [[package]] @@ -521,9 +522,9 @@ dependencies = [ [[package]] name = "arrow-buffer" -version = "60.1.0" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd46a530bc1a8e763102fc36c1dc0f51f3ffa150c78e7f5658ccb54b1458ade" +checksum = "6c6bf2edf52662586214410c6030204215453eb86b8715037e8951326e173b19" dependencies = [ "bytes", "half", @@ -796,7 +797,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "hex", - "http 1.5.0", + "http 1.6.0", "sha1 0.10.7", "time", "tokio", @@ -875,7 +876,7 @@ dependencies = [ "bytes", "bytes-utils", "fastrand 2.5.0", - "http 1.5.0", + "http 1.6.0", "http-body", "percent-encoding", "pin-project-lite", @@ -903,7 +904,7 @@ dependencies = [ "aws-types", "bytes", "fastrand 2.5.0", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -933,9 +934,9 @@ dependencies = [ [[package]] name = "aws-sdk-sts" -version = "1.129.0" +version = "1.130.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "801a8310fa3cb59c4f74679421170c2a93b3e91ccb02f9e1305cc99f4dc5aaa6" +checksum = "a08c6cd0304172f42fcfd618a606f26fd00bd6cab248bc22a492f6c821b31dd1" dependencies = [ "arc-swap", "aws-credential-types", @@ -952,7 +953,7 @@ dependencies = [ "aws-smithy-xml", "aws-types", "fastrand 2.5.0", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -971,7 +972,7 @@ dependencies = [ "form_urlencoded", "hex", "hmac", - "http 1.5.0", + "http 1.6.0", "percent-encoding", "sha2 0.11.3", "time", @@ -1001,7 +1002,7 @@ dependencies = [ "bytes-utils", "futures-core", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "percent-encoding", @@ -1019,7 +1020,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "h2 0.4.21", - "http 1.5.0", + "http 1.6.0", "hyper", "hyper-rustls", "hyper-util", @@ -1083,7 +1084,7 @@ dependencies = [ "aws-smithy-types", "bytes", "fastrand 2.5.0", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "pin-project-lite", @@ -1101,7 +1102,7 @@ dependencies = [ "aws-smithy-runtime-api-macros", "aws-smithy-types", "bytes", - "http 1.5.0", + "http 1.6.0", "pin-project-lite", "tokio", "tracing", @@ -1127,7 +1128,7 @@ checksum = "f7ef30d39e131651359b60a1c560de9a9502a4c3754172ab2d6e8734fe21bcba" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", - "http 1.5.0", + "http 1.6.0", ] [[package]] @@ -1140,7 +1141,7 @@ dependencies = [ "bytes", "bytes-utils", "futures-core", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "itoa", @@ -1188,7 +1189,7 @@ dependencies = [ "axum-core", "bytes", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "itoa", @@ -1212,7 +1213,7 @@ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ "bytes", "futures-core", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "mime", @@ -1342,9 +1343,9 @@ dependencies = [ [[package]] name = "brotli" -version = "9.1.3" +version = "9.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +checksum = "8aa80dae1bf2461007e6b64308edc7c59b1aca84e5b0fc59dc0a22606d897a86" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1353,9 +1354,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "6.4.1" +version = "6.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50986a054f56ca3e15382f3c09abee2bf494c00311b238daae118a06bc1c15f1" +checksum = "968e28b51837a735d00f25c8d10cca6ab376cec4813a65bb8eab1bbce97502c2" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1369,9 +1370,9 @@ checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "byteorder" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816" [[package]] name = "bytes" @@ -1452,9 +1453,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +checksum = "53b4e5299ae8fd0d9e848f3efafd5b4feed729b8c731df9d62375cb1efdc3f4e" dependencies = [ "find-msvc-tools", "jobserver", @@ -1599,9 +1600,9 @@ checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" [[package]] name = "colorchoice" -version = "1.0.5" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +checksum = "8f7f11958434c85b6efac08f8299dc08bd263184ce080232e2168940cda4368e" [[package]] name = "combine" @@ -2971,9 +2972,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" +checksum = "f35b0b9b788e7109a8eb0607f5c8a13495edee3ef8e246f60f0664a7cd25b277" [[package]] name = "fixedbitset" @@ -3229,7 +3230,7 @@ dependencies = [ "fnv", "futures-core", "futures-sink", - "http 1.5.0", + "http 1.6.0", "indexmap", "slab", "tokio", @@ -3395,9 +3396,9 @@ dependencies = [ [[package]] name = "http" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" dependencies = [ "bytes", "itoa", @@ -3419,7 +3420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http 1.6.0", ] [[package]] @@ -3430,7 +3431,7 @@ checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", - "http 1.5.0", + "http 1.6.0", "http-body", "pin-project-lite", ] @@ -3489,7 +3490,7 @@ dependencies = [ "futures-channel", "futures-core", "h2 0.4.21", - "http 1.5.0", + "http 1.6.0", "http-body", "httparse", "httpdate", @@ -3506,7 +3507,7 @@ version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ - "http 1.5.0", + "http 1.6.0", "hyper", "hyper-util", "rustls", @@ -3540,7 +3541,7 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body", "httparse", "hyper", @@ -3690,9 +3691,9 @@ dependencies = [ [[package]] name = "impl-more" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d3a73c82a0b0747dba739b380c046a140b5ae747234bf701df3460282da7193" +checksum = "a41ae4255f9f994320051d8b3014430cc61d82f44e8704ecbd3e697f05897422" [[package]] name = "indexmap" @@ -3933,9 +3934,9 @@ dependencies = [ [[package]] name = "liblzma-sys" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c7e3581f367a78d7b7e7ae948d023310556f0cfc13156c2e4e00e25616492b9" +checksum = "21107a18c9a517bbcea5fef39844b052ae223095ff715b980545858dc7a1c670" dependencies = [ "cc", "libc", @@ -4085,9 +4086,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.3" +version = "2.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +checksum = "4566d79b1fa17cb1520b5ec00f8d8865b2121b8e2e27a6ebbac504f45d86eb36" [[package]] name = "mime" @@ -4329,7 +4330,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body-util", "httparse", "humantime", @@ -4438,7 +4439,7 @@ checksum = "5683015d09e2df236ef005b17f6f196f0d5f6313c4fa43a7b6a53b52776e4331" dependencies = [ "async-trait", "bytes", - "http 1.5.0", + "http 1.6.0", "opentelemetry", "reqwest 0.13.5", ] @@ -4449,7 +4450,7 @@ version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35" dependencies = [ - "http 1.5.0", + "http 1.6.0", "opentelemetry", "opentelemetry-http", "opentelemetry-proto", @@ -4510,12 +4511,12 @@ dependencies = [ [[package]] name = "os_pipe" -version = "1.2.3" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +checksum = "54a351c59c9045dfd196da7bc84279dbe6d891c2fc0bb19b988de169dd60f1c9" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.101.0", ] [[package]] @@ -4655,7 +4656,7 @@ dependencies = [ "hex", "hostname", "hotpath", - "http 1.5.0", + "http 1.6.0", "http-auth-basic", "human-size", "humantime", @@ -4703,6 +4704,7 @@ dependencies = [ "tempfile", "thiserror 2.0.21", "tikv-jemalloc-ctl", + "tikv-jemalloc-sys", "tikv-jemallocator", "tokio", "tokio-stream", @@ -4828,9 +4830,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.18" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pkg-config" @@ -5447,7 +5449,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "hyper", @@ -5490,7 +5492,7 @@ dependencies = [ "futures-core", "futures-util", "h2 0.4.21", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "hyper", @@ -5569,9 +5571,9 @@ checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" [[package]] name = "rustc-hash" -version = "2.1.3" +version = "2.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +checksum = "ca420ddf5554e546a707e0ecb8bd311d505ee00b40982a7064b8bdc48aa59336" [[package]] name = "rustc_version" @@ -5610,9 +5612,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.46" +version = "0.23.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +checksum = "86c8de8f13bac4bb046743409c751e2343621c0293a805c143ede57c5c95c3f8" dependencies = [ "aws-lc-rs", "log", @@ -6002,9 +6004,9 @@ dependencies = [ [[package]] name = "signal-hook-registry" -version = "1.4.8" +version = "1.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +checksum = "e8688983a5d291cd2220e0f2823aa7b29a2c221ae7066b5815408ea3a3808a34" dependencies = [ "errno", "libc", @@ -6171,9 +6173,9 @@ dependencies = [ [[package]] name = "sync_wrapper" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +checksum = "38e2e59f9899319b8392d162b49e5c1aa92bea310f46378de43eba6e47f5aebb" dependencies = [ "futures-core", ] @@ -6533,7 +6535,7 @@ dependencies = [ "bytes", "flate2", "h2 0.4.21", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "hyper", @@ -6585,7 +6587,7 @@ checksum = "323c7492987fadf7b27005a4597c977ffa51907a146621273bda37e231aff406" dependencies = [ "base64 0.22.1", "bytes", - "http 1.5.0", + "http 1.6.0", "http-body", "pin-project", "tokio-stream", @@ -6625,7 +6627,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body", "http-body-util", "pin-project-lite", @@ -7372,6 +7374,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-link" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4" + [[package]] name = "windows-numerics" version = "0.2.0" @@ -7464,6 +7472,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-sys" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c" +dependencies = [ + "windows-link 0.101.0", +] + [[package]] name = "windows-targets" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index acafcf340..ae366fad4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -204,6 +204,7 @@ tikv-jemallocator = { version = "0.7.0", features = [ "background_threads", ] } tikv-jemalloc-ctl = { version = "0.7.0", features = ["stats"] } +tikv-jemalloc-sys = "0.7.1" [build-dependencies] cargo_toml = "0.22.3" diff --git a/src/alerts/alerts_utils.rs b/src/alerts/alerts_utils.rs index 1d95133ec..d341c6a17 100644 --- a/src/alerts/alerts_utils.rs +++ b/src/alerts/alerts_utils.rs @@ -124,7 +124,7 @@ async fn execute_local_query( filter_tag: None, }; - let (records, _) = execute(query, false, tenant_id) + let (records, _, _query_admission) = execute(query, false, tenant_id) .await .map_err(|err| AlertError::CustomError(format!("Failed to execute query: {err}")))?; diff --git a/src/cli.rs b/src/cli.rs index e295b62be..ab4452793 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -38,6 +38,7 @@ pub const DEFAULT_PASSWORD: &str = "admin"; pub const DATASET_FIELD_COUNT_LIMIT: usize = 1000; const DEFAULT_PARQUET_METADATA_CACHE_SIZE: usize = 50 * 1024 * 1024; // 50 MB +pub(crate) const DEFAULT_MAX_CONCURRENT_QUERIES: u32 = 5; const MEMORY_PER_TARGET_PARTITION: u64 = 256 * 1024 * 1024; fn target_partitions_for_resources(cpus: usize, total_memory: u64) -> u64 { @@ -46,13 +47,31 @@ fn target_partitions_for_resources(cpus: usize, total_memory: u64) -> u64 { cpu_limit.min(memory_limit) as u64 } -fn default_target_partitions() -> u64 { +pub(crate) fn detected_memory_limit() -> u64 { let mut system = System::new(); system.refresh_memory(); - let total_memory = system - .cgroup_limits() - .map_or_else(|| system.total_memory(), |cgroup| cgroup.total_memory); - target_partitions_for_resources(num_cpus::get(), total_memory) + + let cgroup_file_limit = [ + "/sys/fs/cgroup/memory.max", + "/sys/fs/cgroup/memory/memory.limit_in_bytes", + ] + .into_iter() + .find_map(|path| fs::read_to_string(path).ok()?.trim().parse::().ok()); + + [ + Some(system.total_memory()), + system.cgroup_limits().map(|cgroup| cgroup.total_memory), + cgroup_file_limit, + ] + .into_iter() + .flatten() + .filter(|limit| *limit > 0) + .min() + .unwrap_or_else(|| system.total_memory()) +} + +fn default_target_partitions() -> u64 { + target_partitions_for_resources(num_cpus::get(), detected_memory_limit()) } #[derive(Parser)] #[command( @@ -480,6 +499,15 @@ pub struct Options { )] pub query_memory_pool_size: Option, + #[arg( + long, + env = "P_MAX_CONCURRENT_QUERIES", + default_value = "5", + value_parser = value_parser!(u32).range(1..), + help = "Maximum number of queries that can execute concurrently" + )] + pub max_concurrent_queries: Option, + #[arg( long, env = "P_PARQUET_METADATA_CACHE_SIZE", diff --git a/src/handlers/airplane.rs b/src/handlers/airplane.rs index e0404e37b..174faeb11 100644 --- a/src/handlers/airplane.rs +++ b/src/handlers/airplane.rs @@ -193,7 +193,7 @@ impl FlightService for AirServiceImpl { })?; let time = Instant::now(); - let (records, _) = execute(query, false, &None) + let (records, _, _query_admission) = execute(query, false, &None) .await .map_err(|err| Status::internal(err.to_string()))?; diff --git a/src/handlers/http/query.rs b/src/handlers/http/query.rs index 13a8b78dd..60f0270e5 100644 --- a/src/handlers/http/query.rs +++ b/src/handlers/http/query.rs @@ -41,6 +41,7 @@ use serde_json::{Value, json}; use std::collections::HashMap; use std::pin::Pin; use std::sync::Arc; +use std::task::{Context, Poll}; use std::time::Instant; use tokio::task::JoinSet; use tracing::{error, info, warn}; @@ -50,7 +51,9 @@ use crate::metrics::{QUERY_EXECUTE_TIME, increment_query_calls_by_date}; use crate::parseable::{DEFAULT_TENANT, PARSEABLE, StreamNotFound}; use crate::query::error::ExecuteError; use crate::query::resolve_stream_names; -use crate::query::{CountsRecord, CountsRequest, QUERY_SESSION, Query as LogicalQuery, execute}; +use crate::query::{ + CountsRecord, CountsRequest, QUERY_SESSION, Query as LogicalQuery, QueryAdmissionGuard, execute, +}; use crate::rbac::Users; use crate::response::QueryResponse; use crate::storage::ObjectStorageError; @@ -103,7 +106,7 @@ pub async fn get_records_and_fields( user_auth_for_datasets(&permissions, &tables, tenant_id).await?; - let (records, fields) = execute(query, false, tenant_id).await?; + let (records, fields, _query_admission) = execute(query, false, tenant_id).await?; let records = match records { Either::Left(vec_rb) => vec_rb, @@ -142,7 +145,7 @@ pub async fn get_records_and_fields_for_authorized_query( .default_schema = tenant_id.as_deref().unwrap_or("public").to_owned(); let query: LogicalQuery = into_query(query_request, &session_state, time_range).await?; - let (records, fields) = execute(query, false, tenant_id).await?; + let (records, fields, _query_admission) = execute(query, false, tenant_id).await?; let records = match records { Either::Left(vec_rb) => vec_rb, @@ -285,7 +288,8 @@ async fn handle_non_streaming_query( tenant_id: &Option, ) -> Result { let first_table_name = table_name[0].clone(); - let (records, fields) = execute(query, query_request.streaming, tenant_id).await?; + let (records, fields, _query_admission) = + execute(query, query_request.streaming, tenant_id).await?; let records = match records { Either::Left(rbs) => rbs, Either::Right(_) => { @@ -338,7 +342,8 @@ async fn handle_streaming_query( tenant_id: &Option, ) -> Result { let first_table_name = table_name[0].clone(); - let (records_stream, fields) = execute(query, query_request.streaming, tenant_id).await?; + let (records_stream, fields, query_admission) = + execute(query, query_request.streaming, tenant_id).await?; let records_stream = match records_stream { Either::Left(_) => { return Err(QueryError::MalformedQuery( @@ -385,12 +390,30 @@ async fn handle_streaming_query( Box::pin(stream) as Pin>>> }; + let stream = AdmissionGuardedHttpStream { + inner: stream, + _query_admission: query_admission, + }; + Ok(HttpResponse::Ok() .content_type("application/x-ndjson") .insert_header((TIME_ELAPSED_HEADER, total_time.as_str())) .streaming(stream)) } +struct AdmissionGuardedHttpStream { + inner: S, + _query_admission: Arc, +} + +impl Stream for AdmissionGuardedHttpStream { + type Item = S::Item; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_next(cx) + } +} + fn create_batch_processor() -> impl FnMut(Result) -> Result { move |batch_result| match batch_result { diff --git a/src/query/mod.rs b/src/query/mod.rs index 7eb0a0bed..ff4cb3534 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -29,6 +29,7 @@ use datafusion::catalog::SchemaProvider; use datafusion::common::tree_node::{Transformed, TreeNodeRecursion}; use datafusion::error::DataFusionError; use datafusion::execution::disk_manager::DiskManager; +use datafusion::execution::memory_pool::{FairSpillPool, TrackConsumersPool}; use datafusion::execution::{ RecordBatchStream, SendableRecordBatchStream, SessionState, SessionStateBuilder, }; @@ -45,21 +46,22 @@ use datafusion::prelude::*; use datafusion::sql::parser::DFParser; use datafusion::sql::resolve::resolve_table_references; use datafusion::sql::sqlparser::dialect::PostgreSqlDialect; -use futures::Stream; -use futures::StreamExt; +use futures::{Stream, StreamExt}; use itertools::Itertools; use once_cell::sync::{Lazy, OnceCell}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::collections::BTreeSet; +use std::num::NonZeroUsize; use std::ops::Bound; use std::pin::Pin; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, RwLock}; use std::task::{Context, Poll}; use sysinfo::{MemoryRefreshKind, RefreshKind, System}; use tokio::runtime::Runtime; -use tokio_stream::wrappers::UnboundedReceiverStream; +use tokio_stream::wrappers::ReceiverStream; +use tokio_util::sync::CancellationToken; use tracing::Instrument; use self::error::ExecuteError; @@ -75,6 +77,7 @@ use crate::catalog::Snapshot as CatalogSnapshot; use crate::catalog::column::{Int64Type, TypedStatistics}; use crate::catalog::manifest::Manifest; use crate::catalog::snapshot::Snapshot; +use crate::cli::{DEFAULT_MAX_CONCURRENT_QUERIES, detected_memory_limit}; use crate::event::DEFAULT_TIMESTAMP_KEY; use crate::handlers::http::query::QueryError; use crate::hottier::{GLOBAL_HOTTIER, HotTierQueryGuard}; @@ -87,32 +90,50 @@ use crate::utils::time::{DATE_BIN_EPOCH_ANCHOR, TimeRange, count_api_bin_interva /// Boxed record-batch stream used as the streaming half of query results. type BoxedBatchStream = SendableRecordBatchStream; -/// Result type returned by query execution: either collected batches or a streaming adapter, plus field names. -type QueryResult = Result<(Either, BoxedBatchStream>, Vec), ExecuteError>; +/// Result type returned by query execution: batches or a stream, field names, and admission guard. +type QueryResult = Result< + ( + Either, BoxedBatchStream>, + Vec, + Arc, + ), + ExecuteError, +>; const DEFAULT_COUNTS_TOP_K: usize = 10; -const DEFAULT_QUERY_MEMORY_DIVISOR: u64 = 8; -const MEMORY_PER_CONCURRENT_QUERY: u64 = 1024 * 1024 * 1024; -const MAX_CONCURRENT_QUERIES: usize = 4; -const QUERY_ADMISSION_WAIT: std::time::Duration = std::time::Duration::from_secs(10); - -fn detected_memory_limit() -> u64 { - let mut system = System::new(); - system.refresh_memory(); - system - .cgroup_limits() - .map_or_else(|| system.total_memory(), |cgroup| cgroup.total_memory) +const DEFAULT_QUERY_MEMORY_PERCENT: u64 = 85; +const MEMORY_PRESSURE_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100); +const MEMORY_PRESSURE_RESUME_THRESHOLD_RATIO: f64 = 0.9; + +#[derive(Clone, Copy)] +enum QueryAdmissionMode { + Shared, + Exclusive, +} + +impl QueryAdmissionMode { + fn permits(self, max_concurrent_queries: u32) -> u32 { + match self { + Self::Shared => 1, + Self::Exclusive => max_concurrent_queries, + } + } +} + +fn max_concurrent_queries() -> u32 { + PARSEABLE + .options + .max_concurrent_queries + .unwrap_or(DEFAULT_MAX_CONCURRENT_QUERIES) } fn default_query_memory_pool_size(total_memory: u64) -> usize { - usize::try_from(total_memory / DEFAULT_QUERY_MEMORY_DIVISOR) + usize::try_from(total_memory.saturating_mul(DEFAULT_QUERY_MEMORY_PERCENT) / 100) .unwrap_or(usize::MAX) .max(1) } -fn max_concurrent_queries(total_memory: u64) -> usize { - usize::try_from(total_memory / MEMORY_PER_CONCURRENT_QUERY) - .unwrap_or(usize::MAX) - .clamp(1, MAX_CONCURRENT_QUERIES) +fn should_check_memory_pressure(enabled: bool, threshold: f32) -> bool { + enabled && threshold < 100.0 } fn is_count_projection(expr: &Expr) -> bool { @@ -139,11 +160,185 @@ pub static QUERY_RUNTIME: Lazy = Lazy::new(|| Runtime::new().expect("Runtime should be constructible")); static QUERY_ADMISSION: Lazy> = Lazy::new(|| { - Arc::new(tokio::sync::Semaphore::new(max_concurrent_queries( - detected_memory_limit(), - ))) + Arc::new(tokio::sync::Semaphore::new( + max_concurrent_queries() as usize + )) }); +static MEMORY_PRESSURE_VICTIM: AtomicBool = AtomicBool::new(false); + +struct MemoryPressureVictim; + +impl Drop for MemoryPressureVictim { + fn drop(&mut self) { + MEMORY_PRESSURE_VICTIM.store(false, Ordering::Release); + } +} + +fn memory_pressure_limit(total_memory: u64, threshold: f32) -> u64 { + (total_memory as f64 * threshold as f64 / 100.0) as u64 +} + +fn memory_pressure_resume_threshold(total_memory: u64, threshold: f32) -> u64 { + (memory_pressure_limit(total_memory, threshold) as f64 * MEMORY_PRESSURE_RESUME_THRESHOLD_RATIO) + as u64 +} + +async fn monitor_memory_pressure( + monitor_stop: CancellationToken, + pressure_cancellation: CancellationToken, + cancelled_for_memory_pressure: Arc, +) { + let limit = memory_pressure_limit( + detected_memory_limit(), + PARSEABLE.options.memory_utilization_threshold, + ); + + loop { + tokio::select! { + _ = monitor_stop.cancelled() => return, + _ = tokio::time::sleep(MEMORY_PRESSURE_POLL_INTERVAL) => {} + } + + if current_memory_usage() < limit + || MEMORY_PRESSURE_VICTIM + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + continue; + } + + let _victim = MemoryPressureVictim; + if current_memory_usage() < limit { + continue; + } + + tracing::warn!( + memory_usage = current_memory_usage(), + memory_limit = limit, + "Cancelling query because memory utilization threshold was exceeded" + ); + cancelled_for_memory_pressure.store(true, Ordering::Release); + pressure_cancellation.cancel(); + + // Keep the victim claim until the cancelled query has dropped its guard. This lets + // its allocations unwind before another query is selected if pressure remains high. + monitor_stop.cancelled().await; + return; + } +} + +#[cfg(not(target_env = "msvc"))] +fn reclaim_allocator_memory() { + let Ok(narenas) = tikv_jemalloc_ctl::arenas::narenas::read() else { + return; + }; + + for arena in 0..narenas { + let name = format!("arena.{arena}.purge\0"); + unsafe { + let _ = tikv_jemalloc_sys::mallctl( + name.as_ptr().cast(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + 0, + ); + } + } +} + +#[cfg(target_env = "msvc")] +fn reclaim_allocator_memory() {} + +/// Holds a query execution slot until result serialization has released its memory. +pub struct QueryAdmissionGuard { + permit: Option, + monitor_stop: CancellationToken, + pressure_cancellation: CancellationToken, + cancelled_for_memory_pressure: Arc, +} + +impl Drop for QueryAdmissionGuard { + fn drop(&mut self) { + self.monitor_stop.cancel(); + let Some(permit) = self.permit.take() else { + return; + }; + let reclaim_memory = self.cancelled_for_memory_pressure.load(Ordering::Acquire); + drop(permit); + + if reclaim_memory { + QUERY_RUNTIME.spawn(async { + let _ = tokio::task::spawn_blocking(reclaim_allocator_memory).await; + }); + } + } +} + +async fn acquire_query_admission( + mode: QueryAdmissionMode, +) -> Result { + // Queue behind active queries. The request or SQL timeout remains responsible for + // cancellation; a short admission timeout creates retry storms under concurrent load. + let permit = QUERY_ADMISSION + .clone() + .acquire_many_owned(mode.permits(max_concurrent_queries())) + .await + .map_err(|_| ExecuteError::AdmissionTimeout)?; + + let check_memory_pressure = should_check_memory_pressure( + PARSEABLE.options.resource_check_enabled, + PARSEABLE.options.memory_utilization_threshold, + ); + + if check_memory_pressure { + wait_for_memory_headroom().await; + } + + let monitor_stop = CancellationToken::new(); + let pressure_cancellation = CancellationToken::new(); + let cancelled_for_memory_pressure = Arc::new(AtomicBool::new(false)); + if check_memory_pressure { + QUERY_RUNTIME.spawn(monitor_memory_pressure( + monitor_stop.clone(), + pressure_cancellation.clone(), + cancelled_for_memory_pressure.clone(), + )); + } + + Ok(QueryAdmissionGuard { + permit: Some(permit), + monitor_stop, + pressure_cancellation, + cancelled_for_memory_pressure, + }) +} + +fn should_retry_exclusively(is_streaming: bool, error: &ExecuteError) -> bool { + !is_streaming + && (matches!(error, ExecuteError::ServerBusy) + || matches!( + error, + ExecuteError::Datafusion(error) + if matches!(error.find_root(), DataFusionError::ResourcesExhausted(_)) + )) +} + +async fn execute_attempt( + query: &Query, + is_streaming: bool, + tenant_id: &Option, + query_admission: QueryAdmissionGuard, +) -> QueryResult { + let pressure_cancellation = query_admission.pressure_cancellation.clone(); + tokio::select! { + biased; + _ = pressure_cancellation.cancelled() => Err(ExecuteError::ServerBusy), + result = query.execute(is_streaming, tenant_id, query_admission) => result, + } +} + /// A dropped caller must not leave query planning running on QUERY_RUNTIME. struct AbortQueryOnDrop(tokio::task::JoinHandle); @@ -248,33 +443,39 @@ impl InMemorySessionContext { } } -async fn enough_available_memory() -> Result<(), ExecuteError> { - let mut s = System::new_with_specifics( +fn current_memory_usage() -> u64 { + if let Some(usage) = [ + "/sys/fs/cgroup/memory.current", + "/sys/fs/cgroup/memory/memory.usage_in_bytes", + ] + .into_iter() + .find_map(|path| { + std::fs::read_to_string(path) + .ok()? + .trim() + .parse::() + .ok() + }) { + return usage; + } + + let system = System::new_with_specifics( RefreshKind::nothing().with_memory(MemoryRefreshKind::everything()), ); - let threshold = (PARSEABLE.options.memory_utilization_threshold / 100.0) as f64; - let f = async { - loop { - if let Some(cgroup) = s.cgroup_limits() { - if (cgroup.rss as f64) < threshold * (cgroup.total_memory as f64) { - return; - } - } else { - s.refresh_memory(); - if (s.used_memory() as f64) < threshold * (s.total_memory() as f64) { - return; - } - } - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - } - }; - if tokio::time::timeout(tokio::time::Duration::from_secs(10), f) - .await - .is_err() - { - Err(ExecuteError::ServerBusy) - } else { - Ok(()) + system + .cgroup_limits() + .map_or_else(|| system.used_memory(), |cgroup| cgroup.rss) +} + +async fn wait_for_memory_headroom() { + let memory_limit = detected_memory_limit(); + let resume_threshold = memory_pressure_resume_threshold( + memory_limit, + PARSEABLE.options.memory_utilization_threshold, + ); + + while current_memory_usage() >= resume_threshold { + tokio::time::sleep(MEMORY_PRESSURE_POLL_INTERVAL).await; } } @@ -283,15 +484,27 @@ async fn enough_available_memory() -> Result<(), ExecuteError> { pub async fn execute(query: Query, is_streaming: bool, tenant_id: &Option) -> QueryResult { let id = tenant_id.clone(); - // before executing query, check whether enough memory is available or not - // use resource check env var as gate - if PARSEABLE.options.resource_check_enabled { - enough_available_memory().await?; - } + let query_admission = acquire_query_admission(QueryAdmissionMode::Shared).await?; let mut task = AbortQueryOnDrop(QUERY_RUNTIME.spawn(async move { tokio::time::timeout( std::time::Duration::from_secs(PARSEABLE.options.sql_timeout), - query.execute(is_streaming, &id), + async { + let result = execute_attempt(&query, is_streaming, &id, query_admission).await; + let Err(error) = result else { + return result; + }; + if !should_retry_exclusively(is_streaming, &error) { + return Err(error); + } + + tracing::warn!( + %error, + "Retrying memory-constrained query with exclusive admission" + ); + let exclusive_admission = + acquire_query_admission(QueryAdmissionMode::Exclusive).await?; + execute_attempt(&query, is_streaming, &id, exclusive_admission).await + }, ) .await .map_err(|e| ExecuteError::Timeout(e, PARSEABLE.options.sql_timeout))? @@ -301,19 +514,33 @@ pub async fn execute(query: Query, is_streaming: bool, tenant_id: &Option>, + tx: tokio::sync::mpsc::Sender>, + cancellation: CancellationToken, + cancelled_for_memory_pressure: Arc, + cancellation_error_sent: Arc, ) { loop { tokio::select! { biased; + _ = cancellation.cancelled() => { + if cancelled_for_memory_pressure.load(Ordering::Acquire) + && !cancellation_error_sent.swap(true, Ordering::AcqRel) + { + let _ = tx.send(Err(DataFusionError::ResourcesExhausted( + "Query cancelled because memory utilization threshold was exceeded" + .to_owned(), + ))).await; + } + break; + }, _ = tx.closed() => break, next = stream.next() => match next { Some(batch) => { - if tx.send(batch).is_err() { + if tx.send(batch).await.is_err() { break; } } @@ -373,7 +600,9 @@ impl Query { .query_memory_pool_size .unwrap_or_else(|| default_query_memory_pool_size(detected_memory_limit())); - let runtime_config = runtime_config.with_memory_limit(pool_size, 1.0); + let memory_pool = + TrackConsumersPool::new(FairSpillPool::new(pool_size), NonZeroUsize::new(5).unwrap()); + let runtime_config = runtime_config.with_memory_pool(Arc::new(memory_pool)); let runtime = Arc::new(runtime_config.build().unwrap()); // All the config options are explained here - @@ -459,22 +688,18 @@ impl Query { /// if streaming is false, it returns a vector of record batches #[tracing::instrument( name = "datafusion.execute", - skip(self, is_streaming, tenant_id), + skip(self, is_streaming, tenant_id, query_admission), fields( db.system.name = "datafusion", db.operation.name = "SELECT", ) )] - pub async fn execute(&self, is_streaming: bool, tenant_id: &Option) -> QueryResult { - let mut query_admission = Some( - tokio::time::timeout( - QUERY_ADMISSION_WAIT, - QUERY_ADMISSION.clone().acquire_owned(), - ) - .await - .map_err(|_| ExecuteError::ServerBusy)? - .map_err(|_| ExecuteError::ServerBusy)?, - ); + async fn execute( + &self, + is_streaming: bool, + tenant_id: &Option, + query_admission: QueryAdmissionGuard, + ) -> QueryResult { let ctx = QUERY_SESSION.get_ctx(); let mut logical_plan = self.final_logical_plan(tenant_id); let (hot_tier_guards, guarded_hot_tier_streams) = @@ -491,9 +716,9 @@ impl Query { .map(|f| f.name()) .cloned() .collect_vec(); - if fields.is_empty() && !is_streaming { - return Ok((Either::Left(vec![]), fields)); + let query_admission = Arc::new(query_admission); + return Ok((Either::Left(vec![]), fields, query_admission)); } let plan = ctx.state().create_physical_plan(df.logical_plan()).await?; @@ -524,30 +749,38 @@ impl Query { plan: plan.clone(), active_streams: AtomicUsize::new(output_partitions), _hot_tier_guards: hot_tier_guards, - _query_admission: query_admission.take(), }); - let partition_streams = execute_stream_partitioned(plan.clone(), task_ctx.clone())?; - - let (tx, rx) = tokio::sync::mpsc::unbounded_channel::< - Result, - >(); + let partition_streams = execute_stream_partitioned(plan.clone(), task_ctx)?; + let (tx, rx) = tokio::sync::mpsc::channel(output_partitions.max(1)); + let cancellation = query_admission.pressure_cancellation.clone(); + let cancelled_for_memory_pressure = + query_admission.cancelled_for_memory_pressure.clone(); + let cancellation_error_sent = Arc::new(AtomicBool::new(false)); - for s in partition_streams.into_iter() { - let wrapped = - PartitionedMetricMonitor::new(s, monitor_state.clone(), tenant_id.clone()); - let tx = tx.clone(); + for stream in partition_streams { + let monitored = + PartitionedMetricMonitor::new(stream, monitor_state.clone(), tenant_id.clone()); let span = tracing::Span::current(); - tokio::spawn(forward_partition_batches(Box::pin(wrapped), tx).instrument(span)); + tokio::spawn( + forward_partition_batches( + Box::pin(monitored), + tx.clone(), + cancellation.clone(), + cancelled_for_memory_pressure.clone(), + cancellation_error_sent.clone(), + ) + .instrument(span), + ); } drop(tx); - let merged = UnboundedReceiverStream::new(rx); - let final_stream = RecordBatchStreamAdapter::new(plan.schema(), merged); + let final_stream = + RecordBatchStreamAdapter::new(plan.schema(), ReceiverStream::new(rx)); Either::Right(Box::pin(final_stream) as SendableRecordBatchStream) }; - Ok((results, fields)) + Ok((results, fields, Arc::new(query_admission))) } pub async fn get_dataframe( @@ -1228,6 +1461,8 @@ pub mod error { Timeout(Elapsed, u64), #[error("Not enough memory available to serve the request")] ServerBusy, + #[error("All query execution slots are busy")] + AdmissionTimeout, } impl actix_web::ResponseError for ExecuteError { @@ -1238,6 +1473,7 @@ pub mod error { ExecuteError::StreamNotFound(_) => StatusCode::NOT_FOUND, ExecuteError::Timeout(_, _) => StatusCode::REQUEST_TIMEOUT, ExecuteError::ServerBusy => StatusCode::SERVICE_UNAVAILABLE, + ExecuteError::AdmissionTimeout => StatusCode::SERVICE_UNAVAILABLE, } } @@ -1254,7 +1490,6 @@ struct MonitorState { plan: Arc, active_streams: AtomicUsize, _hot_tier_guards: Vec, - _query_admission: Option, } /// A wrapper that monitors the ExecutionPlan and logs metrics when the stream finishes. @@ -1343,26 +1578,73 @@ mod tests { use serde_json::json; use super::{ - AbortQueryOnDrop, DataFusionError, RecordBatch, RecordBatchStreamAdapter, - default_query_memory_pool_size, forward_partition_batches, is_count_projection, - max_concurrent_queries, + AbortQueryOnDrop, DataFusionError, QueryAdmissionGuard, QueryAdmissionMode, RecordBatch, + RecordBatchStreamAdapter, default_query_memory_pool_size, forward_partition_batches, + is_count_projection, memory_pressure_limit, memory_pressure_resume_threshold, + should_check_memory_pressure, should_retry_exclusively, }; + use crate::query::error::ExecuteError; use crate::query::{ CountConditions, CountsRequest, flatten_objects_for_count, resolve_stream_names, }; #[test] - fn default_query_pool_keeps_server_headroom() { + fn default_query_pool_matches_main() { assert_eq!( default_query_memory_pool_size(1024 * 1024 * 1024), - 128 * 1024 * 1024 + 1024 * 1024 * 1024 * 85 / 100 ); } #[test] - fn query_concurrency_is_bounded_by_memory() { - assert_eq!(max_concurrent_queries(1024 * 1024 * 1024), 1); - assert_eq!(max_concurrent_queries(16 * 1024 * 1024 * 1024), 4); + fn memory_pressure_check_is_disabled_at_full_threshold() { + assert!(!should_check_memory_pressure(true, 100.0)); + assert!(!should_check_memory_pressure(false, 80.0)); + assert!(should_check_memory_pressure(true, 80.0)); + } + + #[test] + fn memory_pressure_uses_hysteresis_for_new_queries() { + let gib = 1024 * 1024 * 1024; + let pressure_limit = memory_pressure_limit(32 * gib, 70.0); + assert_eq!( + memory_pressure_resume_threshold(32 * gib, 70.0), + (pressure_limit as f64 * 0.9) as u64 + ); + } + + #[test] + fn only_batch_memory_failures_use_exclusive_retry() { + let exhausted = ExecuteError::Datafusion(DataFusionError::ResourcesExhausted( + "test pool exhausted".to_owned(), + )); + let wrapped_exhausted = ExecuteError::Datafusion(DataFusionError::Context( + "collect partition".to_owned(), + Box::new(DataFusionError::ResourcesExhausted( + "test pool exhausted".to_owned(), + )), + )); + assert!(should_retry_exclusively(false, &exhausted)); + assert!(should_retry_exclusively(false, &wrapped_exhausted)); + assert!(should_retry_exclusively(false, &ExecuteError::ServerBusy)); + assert!(!should_retry_exclusively(true, &exhausted)); + assert!(!should_retry_exclusively(true, &ExecuteError::ServerBusy)); + } + + #[tokio::test] + async fn exclusive_admission_owns_every_query_slot() { + let max_concurrent_queries = 5; + let semaphore = + std::sync::Arc::new(tokio::sync::Semaphore::new(max_concurrent_queries as usize)); + let exclusive = semaphore + .clone() + .acquire_many_owned(QueryAdmissionMode::Exclusive.permits(max_concurrent_queries)) + .await + .unwrap(); + + assert!(semaphore.clone().try_acquire_owned().is_err()); + drop(exclusive); + assert!(semaphore.try_acquire_owned().is_ok()); } #[test] @@ -1374,7 +1656,31 @@ mod tests { } #[tokio::test] - async fn test_partition_scan_stops_when_receiver_drops() { + async fn query_admission_releases_with_last_owner() { + let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); + let monitor_stop = tokio_util::sync::CancellationToken::new(); + let pressure_cancellation = tokio_util::sync::CancellationToken::new(); + let permit = std::sync::Arc::new(QueryAdmissionGuard { + permit: Some(semaphore.clone().acquire_owned().await.unwrap()), + monitor_stop: monitor_stop.clone(), + pressure_cancellation: pressure_cancellation.clone(), + cancelled_for_memory_pressure: std::sync::Arc::new(std::sync::atomic::AtomicBool::new( + false, + )), + }); + let response = permit.clone(); + + drop(permit); + assert!(semaphore.clone().try_acquire_owned().is_err()); + + drop(response); + assert!(semaphore.try_acquire_owned().is_ok()); + assert!(monitor_stop.is_cancelled()); + assert!(!pressure_cancellation.is_cancelled()); + } + + #[tokio::test] + async fn partition_scan_stops_when_receiver_drops() { let schema = std::sync::Arc::new(datafusion::arrow::datatypes::Schema::empty()); let (polled_tx, polled_rx) = tokio::sync::oneshot::channel(); let mut polled_tx = Some(polled_tx); @@ -1385,8 +1691,14 @@ mod tests { std::task::Poll::>>::Pending }); let stream = RecordBatchStreamAdapter::new(schema, pending); - let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); - let worker = tokio::spawn(forward_partition_batches(Box::pin(stream), tx)); + let (tx, rx) = tokio::sync::mpsc::channel(1); + let worker = tokio::spawn(forward_partition_batches( + Box::pin(stream), + tx, + tokio_util::sync::CancellationToken::new(), + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + )); tokio::time::timeout(std::time::Duration::from_secs(1), polled_rx) .await .expect("partition must be polled") @@ -1398,6 +1710,35 @@ mod tests { .expect("partition worker panicked"); } + #[tokio::test] + async fn memory_pressure_cancels_stream_with_resource_error() { + let schema = std::sync::Arc::new(datafusion::arrow::datatypes::Schema::empty()); + let pending = futures::stream::pending::>(); + let stream = RecordBatchStreamAdapter::new(schema, pending); + let (tx, mut rx) = tokio::sync::mpsc::channel(1); + let cancellation = tokio_util::sync::CancellationToken::new(); + let cancelled_for_memory_pressure = + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let worker = tokio::spawn(forward_partition_batches( + Box::pin(stream), + tx, + cancellation.clone(), + cancelled_for_memory_pressure, + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + )); + + cancellation.cancel(); + let result = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv()) + .await + .expect("cancellation error must arrive") + .expect("stream must send a cancellation error"); + assert!(matches!( + result, + Err(DataFusionError::ResourcesExhausted(_)) + )); + worker.await.expect("partition worker must stop"); + } + #[tokio::test] async fn test_dropped_query_aborts_planning_task() { struct SignalOnDrop(Option>); From b3173a519473cccc578ee283c063815c0b93b1bf Mon Sep 17 00:00:00 2001 From: Nikhil Sinha Date: Sun, 6 Dec 2026 21:52:37 +0530 Subject: [PATCH 3/4] fix review comments --- Cargo.toml | 2 +- src/handlers/airplane.rs | 33 +++++- src/handlers/http/modal/ssl_acceptor.rs | 3 + src/handlers/http/query.rs | 29 +++-- src/handlers/http/query_context.rs | 4 +- src/handlers/http/traces.rs | 13 ++- src/main.rs | 4 + src/query/mod.rs | 139 +++++++++++++++++++++--- 8 files changed, 191 insertions(+), 36 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ae366fad4..f2346042b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ rdkafka = { version = "0.39.0", optional = true, features = [ "tracing", "libz-static", ] } -sasl2-sys = { version = "0.1.22+2.1.28", optional = true, features = ["vendored"] } +sasl2-sys = { version = "0.1.22", optional = true, features = ["vendored"] } # AWS MSK IAM authentication for Kafka (SASL/OAUTHBEARER token signing) aws-msk-iam-sasl-signer = { version = "1.0.2", optional = true } aws-types = { version = "1.7.0", optional = true } diff --git a/src/handlers/airplane.rs b/src/handlers/airplane.rs index 174faeb11..cdd79476a 100644 --- a/src/handlers/airplane.rs +++ b/src/handlers/airplane.rs @@ -20,6 +20,9 @@ use arrow_flight::PollInfo; use arrow_flight::flight_service_server::FlightServiceServer; use arrow_schema::ArrowError; use std::net::SocketAddr; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; use std::time::Instant; use tonic::codec::CompressionEncoding; use tracing::{error, info}; @@ -33,8 +36,8 @@ use crate::handlers::http::query::into_query; use crate::handlers::livetail::cross_origin_config; use crate::metrics::QUERY_EXECUTE_TIME; use crate::parseable::{DEFAULT_TENANT, PARSEABLE}; -use crate::query::{QUERY_SESSION, execute, resolve_stream_names}; -use crate::utils::arrow::flight::{get_query_from_ticket, into_flight_data}; +use crate::query::{QUERY_SESSION, QueryAdmissionGuard, execute, resolve_stream_names}; +use crate::utils::arrow::flight::{DoGetStream, get_query_from_ticket, into_flight_data}; use crate::utils::time::TimeRange; use crate::utils::{get_tenant_id_from_key, user_auth_for_datasets}; use arrow_flight::{ @@ -43,7 +46,7 @@ use arrow_flight::{ flight_service_server::FlightService, }; use arrow_ipc::writer::IpcWriteOptions; -use futures::stream; +use futures::{Stream, stream}; use tonic::{Request, Response, Status, Streaming}; use crate::handlers::livetail::extract_session_key; @@ -53,6 +56,19 @@ use crate::rbac::Users; #[derive(Clone, Debug)] pub struct AirServiceImpl {} +struct AdmissionGuardedFlightStream { + inner: S, + _query_admission: Arc, +} + +impl Stream for AdmissionGuardedFlightStream { + type Item = S::Item; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_next(cx) + } +} + #[tonic::async_trait] impl FlightService for AirServiceImpl { type HandshakeStream = stream::BoxStream<'static, Result>; @@ -193,7 +209,7 @@ impl FlightService for AirServiceImpl { })?; let time = Instant::now(); - let (records, _, _query_admission) = execute(query, false, &None) + let (records, _, query_admission) = execute(query, false, &None) .await .map_err(|err| Status::internal(err.to_string()))?; @@ -218,7 +234,14 @@ impl FlightService for AirServiceImpl { let schema = Schema::try_merge(schemas).map_err(|err| Status::internal(err.to_string()))?; */ // Taxi out airplane - let out = into_flight_data(records); + let out = into_flight_data(records).map(|response| { + response.map(|stream| { + Box::pin(AdmissionGuardedFlightStream { + inner: stream, + _query_admission: query_admission, + }) as DoGetStream + }) + }); let time = time.elapsed().as_secs_f64(); let tenant_id = get_tenant_id_from_key(&key); diff --git a/src/handlers/http/modal/ssl_acceptor.rs b/src/handlers/http/modal/ssl_acceptor.rs index d2462cc96..2e5e284e0 100644 --- a/src/handlers/http/modal/ssl_acceptor.rs +++ b/src/handlers/http/modal/ssl_acceptor.rs @@ -32,6 +32,9 @@ pub fn get_ssl_acceptor( ) -> anyhow::Result> { match (tls_cert, tls_key) { (Some(cert), Some(key)) => { + // Keep this consistent with the process-wide Ring provider installed + // in main. Rustls has no non-deprecated Ring provider constructor. + #[allow(deprecated)] let provider = Arc::new(rustls::crypto::ring::default_provider()); let server_config = ServerConfig::builder_with_provider(provider) .with_safe_default_protocol_versions()? diff --git a/src/handlers/http/query.rs b/src/handlers/http/query.rs index 60f0270e5..15940b448 100644 --- a/src/handlers/http/query.rs +++ b/src/handlers/http/query.rs @@ -86,7 +86,14 @@ pub async fn get_records_and_fields( query_request: &Query, creds: &SessionKey, tenant_id: &Option, -) -> Result<(Option>, Option>), QueryError> { +) -> Result< + ( + Option>, + Option>, + Arc, + ), + QueryError, +> { let mut session_state = QUERY_SESSION.get_ctx().state(); let time_range = TimeRange::parse_human_time(&query_request.start_time, &query_request.end_time)?; @@ -106,7 +113,7 @@ pub async fn get_records_and_fields( user_auth_for_datasets(&permissions, &tables, tenant_id).await?; - let (records, fields, _query_admission) = execute(query, false, tenant_id).await?; + let (records, fields, query_admission) = execute(query, false, tenant_id).await?; let records = match records { Either::Left(vec_rb) => vec_rb, @@ -115,7 +122,7 @@ pub async fn get_records_and_fields( } }; - Ok((Some(records), Some(fields))) + Ok((Some(records), Some(fields), query_admission)) } /// Executes a query after the caller has already loaded and authorized the streams. @@ -126,7 +133,14 @@ pub async fn get_records_and_fields_for_authorized_query( query_request: &Query, authorized_tables: &[String], tenant_id: &Option, -) -> Result<(Option>, Option>), QueryError> { +) -> Result< + ( + Option>, + Option>, + Arc, + ), + QueryError, +> { let mut session_state = QUERY_SESSION.get_ctx().state(); let time_range = TimeRange::parse_human_time(&query_request.start_time, &query_request.end_time)?; @@ -145,7 +159,7 @@ pub async fn get_records_and_fields_for_authorized_query( .default_schema = tenant_id.as_deref().unwrap_or("public").to_owned(); let query: LogicalQuery = into_query(query_request, &session_state, time_range).await?; - let (records, fields, _query_admission) = execute(query, false, tenant_id).await?; + let (records, fields, query_admission) = execute(query, false, tenant_id).await?; let records = match records { Either::Left(vec_rb) => vec_rb, @@ -154,7 +168,7 @@ pub async fn get_records_and_fields_for_authorized_query( } }; - Ok((Some(records), Some(fields))) + Ok((Some(records), Some(fields), query_admission)) } pub async fn query(req: HttpRequest, query_request: Query) -> Result { @@ -567,7 +581,8 @@ pub async fn get_counts( let creds = extract_session_key_from_req(&req)?; - let (records, _) = get_records_and_fields(&query_request, &creds, &tenant_id).await?; + let (records, _, _query_admission) = + get_records_and_fields(&query_request, &creds, &tenant_id).await?; if let Some(records) = records { let json_records = record_batches_to_json(&records)?; diff --git a/src/handlers/http/query_context.rs b/src/handlers/http/query_context.rs index f2edb2f93..6060276b1 100644 --- a/src/handlers/http/query_context.rs +++ b/src/handlers/http/query_context.rs @@ -946,7 +946,7 @@ async fn execute_log_context_anchor_count( filter_tags: None, }; - let (records, _) = + let (records, _, _query_admission) = get_records_and_fields_for_authorized_query(&query_request, authorized_datasets, tenant_id) .await?; let records = records.unwrap_or_default(); @@ -992,7 +992,7 @@ async fn execute_log_context_rows( filter_tags: None, }; - let (records, _) = + let (records, _, _query_admission) = get_records_and_fields_for_authorized_query(&query_request, authorized_datasets, tenant_id) .await?; let records = records.unwrap_or_default(); diff --git a/src/handlers/http/traces.rs b/src/handlers/http/traces.rs index e5ac7a16f..8de573019 100644 --- a/src/handlers/http/traces.rs +++ b/src/handlers/http/traces.rs @@ -738,12 +738,13 @@ async fn execute_trace_query( match target { TraceQueryTarget::Local(credentials) => { - let (records, _) = get_records_and_fields(&request, &credentials, tenant_id) - .await - .map_err(|error| { - error!("traces/{query_name} query failed: {error:?}"); - TraceError::Query(error) - })?; + let (records, _, _query_admission) = + get_records_and_fields(&request, &credentials, tenant_id) + .await + .map_err(|error| { + error!("traces/{query_name} query failed: {error:?}"); + TraceError::Query(error) + })?; let records = records.unwrap_or_default(); let records = record_batches_to_json(&records) .map_err(|error| TraceError::BadRequest(error.to_string()))?; diff --git a/src/main.rs b/src/main.rs index 9e42c4bb6..7d8b5cba4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -54,6 +54,10 @@ async fn main() -> anyhow::Result<()> { // Install the rustls crypto provider before any TLS operations. // This is required for rustls 0.23+ which needs an explicit crypto provider. // If the installation fails, log a warning but continue execution. + // Ring remains our selected rustls provider. Rustls deprecated its provider + // constructor because Ring does not offer post-quantum key exchange, but there + // is no replacement Ring constructor. + #[allow(deprecated)] if let Err(e) = rustls::crypto::ring::default_provider().install_default() { warn!("Failed to install rustls crypto provider: {:?}", e); } diff --git a/src/query/mod.rs b/src/query/mod.rs index ff4cb3534..3308e40cc 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -479,16 +479,25 @@ async fn wait_for_memory_headroom() { } } +async fn run_with_query_timeout( + future: impl std::future::Future, + sql_timeout: u64, +) -> QueryResult { + tokio::time::timeout(std::time::Duration::from_secs(sql_timeout), future) + .await + .map_err(|error| ExecuteError::Timeout(error, sql_timeout))? +} + /// This function executes a query on the dedicated runtime, ensuring that the query is not isolated to a single thread/CPU /// at a time and has access to the entire thread pool, enabling better concurrent processing, and thus quicker results. pub async fn execute(query: Query, is_streaming: bool, tenant_id: &Option) -> QueryResult { let id = tenant_id.clone(); + let sql_timeout = PARSEABLE.options.sql_timeout; - let query_admission = acquire_query_admission(QueryAdmissionMode::Shared).await?; let mut task = AbortQueryOnDrop(QUERY_RUNTIME.spawn(async move { - tokio::time::timeout( - std::time::Duration::from_secs(PARSEABLE.options.sql_timeout), + run_with_query_timeout( async { + let query_admission = acquire_query_admission(QueryAdmissionMode::Shared).await?; let result = execute_attempt(&query, is_streaming, &id, query_admission).await; let Err(error) = result else { return result; @@ -505,9 +514,9 @@ pub async fn execute(query: Query, is_streaming: bool, tenant_id: &Option, cancellation_error_sent: Arc, ) { + let mut cancelled = false; loop { tokio::select! { biased; _ = cancellation.cancelled() => { - if cancelled_for_memory_pressure.load(Ordering::Acquire) - && !cancellation_error_sent.swap(true, Ordering::AcqRel) - { - let _ = tx.send(Err(DataFusionError::ResourcesExhausted( - "Query cancelled because memory utilization threshold was exceeded" - .to_owned(), - ))).await; - } + cancelled = true; break; }, _ = tx.closed() => break, next = stream.next() => match next { Some(batch) => { - if tx.send(batch).await.is_err() { - break; + tokio::select! { + biased; + _ = cancellation.cancelled() => { + cancelled = true; + break; + }, + _ = tx.closed() => break, + result = tx.send(batch) => { + if result.is_err() { + break; + } + } } } None => break, }, } } + + // Release the DataFusion stream and its reservations before waiting for channel capacity. + drop(stream); + if cancelled + && cancelled_for_memory_pressure.load(Ordering::Acquire) + && !cancellation_error_sent.swap(true, Ordering::AcqRel) + { + let _ = tx + .send(Err(DataFusionError::ResourcesExhausted( + "Query cancelled because memory utilization threshold was exceeded".to_owned(), + ))) + .await; + } } // A query request by client @@ -1581,7 +1607,7 @@ mod tests { AbortQueryOnDrop, DataFusionError, QueryAdmissionGuard, QueryAdmissionMode, RecordBatch, RecordBatchStreamAdapter, default_query_memory_pool_size, forward_partition_batches, is_count_projection, memory_pressure_limit, memory_pressure_resume_threshold, - should_check_memory_pressure, should_retry_exclusively, + run_with_query_timeout, should_check_memory_pressure, should_retry_exclusively, }; use crate::query::error::ExecuteError; use crate::query::{ @@ -1647,6 +1673,23 @@ mod tests { assert!(semaphore.try_acquire_owned().is_ok()); } + #[tokio::test] + async fn query_timeout_includes_admission_wait() { + let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); + let _active_query = semaphore.clone().acquire_owned().await.unwrap(); + + let result = run_with_query_timeout( + async move { + let _queued_query = semaphore.acquire_owned().await.unwrap(); + unreachable!("the queued query should time out before admission") + }, + 0, + ) + .await; + + assert!(matches!(result, Err(ExecuteError::Timeout(_, 0)))); + } + #[test] fn nested_count_alias_is_still_a_count_projection() { let expr = datafusion::prelude::col("count(*)") @@ -1739,6 +1782,72 @@ mod tests { worker.await.expect("partition worker must stop"); } + #[tokio::test] + async fn memory_pressure_interrupts_blocked_partition_send() { + struct SignalOnDrop(Option>); + impl Drop for SignalOnDrop { + fn drop(&mut self) { + if let Some(sender) = self.0.take() { + let _ = sender.send(()); + } + } + } + + let schema = std::sync::Arc::new(datafusion::arrow::datatypes::Schema::empty()); + let batch_schema = schema.clone(); + let (stream_dropped_tx, stream_dropped_rx) = tokio::sync::oneshot::channel(); + let stream_drop_signal = SignalOnDrop(Some(stream_dropped_tx)); + let (second_batch_tx, second_batch_rx) = tokio::sync::oneshot::channel(); + let mut second_batch_tx = Some(second_batch_tx); + let mut batch_index = 0; + let batches = futures::stream::poll_fn(move |_| { + let _keep_drop_signal_alive = &stream_drop_signal; + if batch_index >= 2 { + return std::task::Poll::Pending; + } + batch_index += 1; + if batch_index == 2 + && let Some(sender) = second_batch_tx.take() + { + let _ = sender.send(()); + } + std::task::Poll::Ready(Some(Ok(RecordBatch::new_empty(batch_schema.clone())))) + }); + let stream = RecordBatchStreamAdapter::new(schema, batches); + let (tx, mut rx) = tokio::sync::mpsc::channel(1); + let cancellation = tokio_util::sync::CancellationToken::new(); + let worker = tokio::spawn(forward_partition_batches( + Box::pin(stream), + tx, + cancellation.clone(), + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)), + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + )); + + tokio::time::timeout(std::time::Duration::from_secs(1), second_batch_rx) + .await + .expect("second batch must be polled") + .expect("second batch poll notification must arrive"); + cancellation.cancel(); + + tokio::time::timeout(std::time::Duration::from_secs(1), stream_dropped_rx) + .await + .expect("stream must be dropped while the output channel is full") + .expect("stream drop notification must arrive"); + + assert!( + rx.recv() + .await + .expect("first batch must be buffered") + .is_ok() + ); + assert!(matches!( + rx.recv().await.expect("cancellation error must arrive"), + Err(DataFusionError::ResourcesExhausted(_)) + )); + worker.await.expect("partition worker must stop"); + } + #[tokio::test] async fn test_dropped_query_aborts_planning_task() { struct SignalOnDrop(Option>); From bd19099a1c5f98a764a454700ad6d463616cc640 Mon Sep 17 00:00:00 2001 From: Nikhil Sinha Date: Sun, 6 Dec 2026 22:08:44 +0530 Subject: [PATCH 4/4] fix review comments --- src/handlers/airplane.rs | 1 + src/query/mod.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/handlers/airplane.rs b/src/handlers/airplane.rs index cdd79476a..c9cded032 100644 --- a/src/handlers/airplane.rs +++ b/src/handlers/airplane.rs @@ -234,6 +234,7 @@ impl FlightService for AirServiceImpl { let schema = Schema::try_merge(schemas).map_err(|err| Status::internal(err.to_string()))?; */ // Taxi out airplane + query_admission.stop_memory_pressure_monitor(); let out = into_flight_data(records).map(|response| { response.map(|stream| { Box::pin(AdmissionGuardedFlightStream { diff --git a/src/query/mod.rs b/src/query/mod.rs index 3308e40cc..d17102f24 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -259,6 +259,13 @@ pub struct QueryAdmissionGuard { cancelled_for_memory_pressure: Arc, } +impl QueryAdmissionGuard { + /// Stops memory-pressure cancellation while retaining the query admission permit. + pub fn stop_memory_pressure_monitor(&self) { + self.monitor_stop.cancel(); + } +} + impl Drop for QueryAdmissionGuard { fn drop(&mut self) { self.monitor_stop.cancel(); @@ -1722,6 +1729,27 @@ mod tests { assert!(!pressure_cancellation.is_cancelled()); } + #[tokio::test] + async fn stopping_pressure_monitor_retains_query_admission() { + let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); + let monitor_stop = tokio_util::sync::CancellationToken::new(); + let permit = QueryAdmissionGuard { + permit: Some(semaphore.clone().acquire_owned().await.unwrap()), + monitor_stop: monitor_stop.clone(), + pressure_cancellation: tokio_util::sync::CancellationToken::new(), + cancelled_for_memory_pressure: std::sync::Arc::new(std::sync::atomic::AtomicBool::new( + false, + )), + }; + + permit.stop_memory_pressure_monitor(); + + assert!(monitor_stop.is_cancelled()); + assert!(semaphore.clone().try_acquire_owned().is_err()); + drop(permit); + assert!(semaphore.try_acquire_owned().is_ok()); + } + #[tokio::test] async fn partition_scan_stops_when_receiver_drops() { let schema = std::sync::Arc::new(datafusion::arrow::datatypes::Schema::empty());