From b78a1c452d37e8bca71dd520c61018c8f15db383 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 20:24:20 +0000 Subject: [PATCH 1/3] test(data_plane): concurrent independent queries per round, parallel runs answer like one thread (failing) EngineOptions::query_parallelism and the asap_query_parallel_tasks_total counter are stubs (unused, never incremented). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- data_plane/src/engine.rs | 6 ++ data_plane/src/intent.rs | 75 ++++++++++++++++++++++++ data_plane/src/metrics.rs | 9 +++ data_plane/tests/intent_sil_modes.rs | 88 ++++++++++++++++++++++++++-- 4 files changed, 173 insertions(+), 5 deletions(-) diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index 3255bbf35..aecb5b52c 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -128,6 +128,11 @@ pub struct EngineOptions { /// hold `run_memory_limit_bytes`, so queries may hold up to this many /// times that. pub query_threads: usize, + /// Worker threads one query run splits its grouped builds and merges + /// over (by group key; rayon's global pool, sized once per process), + /// and raw reads convert ingest shards on. 1: every run on its query + /// worker alone. The answers are the same for any value. + pub query_parallelism: usize, /// Compute each query-time `OneEvaluation` node several queries read /// once per evaluation time, as the plan says; `false` computes it in /// every query's run (for comparison). @@ -219,6 +224,7 @@ impl Default for EngineOptions { no_forward: false, run_memory_limit_bytes: 4 << 30, query_threads: std::thread::available_parallelism().map_or(1, usize::from), + query_parallelism: std::thread::available_parallelism().map_or(1, usize::from), share_one_evaluation_results: true, label_pushdown: true, query_time_results_retention_ms: 60_000, diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index 73cc98da3..dbe762c1c 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -1290,6 +1290,81 @@ mod tests { ); } + /// Queries of a round with no dependency between them run at once; a + /// dependent starts when its upstream ends, not when the round's other + /// queries end. q1 100 ms and q2 300 ms (independent), q3 100 ms reads + /// q1: q3 ends at 200 ms, the round and the group at 300 ms (one at a + /// time: 500 ms). + #[tokio::test(start_paused = true)] + async fn independent_queries_in_a_round_run_concurrently() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0)]) + .delay("q1", 100) + .with("q2", &[(&[("host", "b")], 1.0)]) + .delay("q2", 300) + .with("q3", &[(&[("host", "a")], 1.0)]) + .delay("q3", 100); + let mut schedule = schedule(vec![ + query("q1", &[], &[]), + query("q2", &[], &[]), + query("q3", &[("Y", "q1", "host")], &[("Y", "host")]), + ]); + schedule.group_latency_ms = vec![ + GroupLatency { + query_ids: vec!["q1".into(), "q2".into(), "q3".into()], + max_latency_ms: 1000.0, + }, + GroupLatency { + query_ids: vec!["q1".into(), "q3".into()], + max_latency_ms: 1000.0, + }, + ]; + let intent = IntentLoop::new( + schedule, + BindMode::FilterGroupedResult, + Duration::from_secs(10), + ) + .unwrap(); + let round = intent.run_round(&runner, 0, 1_000).await; + assert_eq!(round.duration_ms, 300.0); + assert_eq!(record(&round, "q3").latency_ms, Some(100.0)); + assert_eq!(label_values(record(&round, "q3"), "host"), vec!["a"]); + let latency: Vec<_> = round.groups.iter().map(|g| g.latency_ms).collect(); + assert_eq!(latency, vec![Some(300.0), Some(200.0)]); + // Records stay in the order the round lists its queries. + let ids: Vec<_> = round.queries.iter().map(|q| q.query_id.as_str()).collect(); + assert_eq!(ids, vec!["q1", "q2", "q3"]); + } + + /// A dependent waits for every upstream it reads: q3 reads q1 (100 ms) + /// and q2 (300 ms), so it runs after 300 ms with both bindings. + #[tokio::test(start_paused = true)] + async fn a_dependent_waits_for_every_upstream() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0)]) + .delay("q1", 100) + .with("q2", &[(&[("user", "u")], 1.0)]) + .delay("q2", 300) + .with("q3", &[(&[("host", "a"), ("user", "u")], 1.0)]) + .delay("q3", 50); + let intent = intent(vec![ + query("q1", &[], &[]), + query("q2", &[], &[]), + query( + "q3", + &[("Y", "q1", "host"), ("Z", "q2", "user")], + &[("Y", "host"), ("Z", "user")], + ), + ]); + let round = intent.run_round(&runner, 0, 1_000).await; + assert_eq!(round.duration_ms, 350.0); + let q3 = record(&round, "q3"); + assert_eq!(q3.status, QueryStatus::Answered); + assert_eq!(q3.bindings["Y"], values(&["a"])); + assert_eq!(q3.bindings["Z"], values(&["u"])); + assert_eq!(q3.answer.len(), 1); + } + /// The dependent query answers for the binding the approximate upstream /// issued ({a, c}), not the exact top hosts ({a, b}): it equals the /// exact grouped answer filtered by the issued binding. diff --git a/data_plane/src/metrics.rs b/data_plane/src/metrics.rs index 2feb9c506..f75e52fd1 100644 --- a/data_plane/src/metrics.rs +++ b/data_plane/src/metrics.rs @@ -329,6 +329,9 @@ pub struct Metrics { pub query_raw_reads: std::sync::Arc, /// The same counts for the ingestion runs' raw reads. pub ingestion_raw_reads: std::sync::Arc, + /// Partition tasks the query runs ran on the worker threads + /// (`EngineOptions::query_parallelism`). + pub query_parallel_tasks: std::sync::Arc, } impl Metrics { @@ -372,6 +375,7 @@ impl Metrics { view_tier: std::sync::OnceLock::new(), query_raw_reads: std::sync::Arc::default(), ingestion_raw_reads: std::sync::Arc::default(), + query_parallel_tasks: std::sync::Arc::default(), } } @@ -607,6 +611,11 @@ pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { ); } } + let _ = writeln!( + out, + "# HELP asap_query_parallel_tasks_total Partition tasks the query runs ran on worker threads.\n# TYPE asap_query_parallel_tasks_total counter\nasap_query_parallel_tasks_total {}", + load(&*metrics.query_parallel_tasks) + ); gauge( &mut out, "asap_view_bytes", diff --git a/data_plane/tests/intent_sil_modes.rs b/data_plane/tests/intent_sil_modes.rs index 5255be694..2d41019fe 100644 --- a/data_plane/tests/intent_sil_modes.rs +++ b/data_plane/tests/intent_sil_modes.rs @@ -203,16 +203,30 @@ async fn install_with( plan: &IntentPlan, tables: &BTreeMap<&str, Vec>, label_pushdown: bool, +) -> Arc { + install_options( + plan, + tables, + EngineOptions { + no_forward: true, + label_pushdown, + ..EngineOptions::default() + }, + ) + .await +} + +/// [`install`] with the engine's `options`. +async fn install_options( + plan: &IntentPlan, + tables: &BTreeMap<&str, Vec>, + options: EngineOptions, ) -> Arc { let state = Arc::new( DataPlane::with_options( serde_json::to_string(&plan.plan).unwrap(), "http://127.0.0.1:1".into(), - EngineOptions { - no_forward: true, - label_pushdown, - ..EngineOptions::default() - }, + options, ) .unwrap(), ); @@ -478,3 +492,67 @@ async fn label_pushdown_reads_the_bound_series_only_and_answers_the_same() { ); } } + +/// Query runs split over worker threads answer exactly as runs on one +/// thread: in each planning mode, every round's rows (in order, values to +/// the bit) are equal with `query_parallelism` 1 and 4; with 4 the runs +/// ran partition tasks, with 1 none. +#[tokio::test(flavor = "multi_thread")] +async fn parallel_query_runs_answer_like_sequential_runs() { + let tables = tables(); + for mode in [ + IntentPlanningMode::QueryAtATime, + IntentPlanningMode::IntentOnDemandHoles, + IntentPlanningMode::IntentFull, + ] { + let plan = planned(mode).await; + let schedule = IntentSchedule::per_clock_from_intent_plan(&plan, "triage") + .unwrap() + .remove(0); + let mut answers_by_parallelism = Vec::new(); + for query_parallelism in [1, 4] { + let state = install_options( + &plan, + &tables, + EngineOptions { + no_forward: true, + query_parallelism, + ..EngineOptions::default() + }, + ) + .await; + let intent = IntentLoop::new( + schedule.clone(), + BindMode::ParameterSlot, + Duration::from_secs(30), + ) + .unwrap(); + let mut answers = Vec::new(); + for time_ms in [EVALUATION_MS - 10_000, EVALUATION_MS] { + let round = intent.run_round(&state.engine, 0, time_ms).await; + for id in ["q1", "q2", "q3"] { + let rows = rows_of(&round, id) + .into_iter() + .map(|(labels, value)| format!("{labels:?} {:016x}", value.to_bits())) + .collect::>(); + answers.push((time_ms, id, rows)); + } + } + let tasks = state + .engine + .metrics() + .query_parallel_tasks + .load(Ordering::SeqCst); + if query_parallelism == 1 { + assert_eq!(tasks, 0, "{mode:?}"); + } else { + assert!(tasks > 0, "{mode:?}: no partition task ran"); + } + answers_by_parallelism.push(answers); + } + assert_eq!( + answers_by_parallelism[0], answers_by_parallelism[1], + "{mode:?}" + ); + } +} From c11afb101bf7bd0eb19e94aea9885f942eaf9a91 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 01:44:27 +0000 Subject: [PATCH 2/3] feat(data_plane): parallel query runs and concurrent independent queries per round - --query-parallelism N (EngineOptions::query_parallelism, default the cores) sizes rayon's global pool; each query run splits its grouped builds and merges by group key into N parts (executor RunContext::with_parallelism) and raw reads convert the ingest shards in parallel, keeping their order. Answers are identical for any N. asap_query_parallel_tasks_total counts the partition tasks. - IntentLoop::run_round schedules by dataflow: a query starts as soon as every upstream it reads has finished; independent queries run at once on the query workers. Statuses, bindings, timeouts, group latency and record order are unchanged. - Pins ASAPPlanner feat/parallel-query-exec (stacked on #1553). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- Cargo.toml | 8 +- data_plane/Cargo.toml | 4 +- data_plane/src/engine.rs | 10 +++ data_plane/src/intent.rs | 166 +++++++++++++++++++++++---------------- data_plane/src/main.rs | 6 ++ data_plane/src/query.rs | 72 +++++++++++++---- data_plane/src/store.rs | 35 +++++++-- 7 files changed, 207 insertions(+), 94 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f0aed1d6f..4babb4ffb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,9 +9,11 @@ version = "0.1.0" [workspace.dependencies] # The backend depends on two Planner crates, at one immutable revision: # `asap-planner` to plan and `asap-executor` to execute. Planner IR types -# are reached through `asap_executor::planner`. -asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "b9c7fdfa09f8854d4ae201183637038ee0f6bd36" } -asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "b9c7fdfa09f8854d4ae201183637038ee0f6bd36" } +# are reached through `asap_executor::planner`. Draft pin: the Planner's +# `feat/parallel-query-exec` head (stacked on #1553), for query runs split +# by group key over worker threads. +asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "78ec8c7800ad75386e57f14ee9dc05c22ebf817d" } +asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "78ec8c7800ad75386e57f14ee9dc05c22ebf817d" } # The sketch library the Planner's executor pins, for the byte encodings of # the sketch states the data plane persists; keep it at the Planner's rev # (draft: ASAPPlanner#1553 head, for SIL intents). diff --git a/data_plane/Cargo.toml b/data_plane/Cargo.toml index ec7bf0b61..9423243a3 100644 --- a/data_plane/Cargo.toml +++ b/data_plane/Cargo.toml @@ -33,11 +33,13 @@ prost = "0.13" rmp-serde = "1" snap = "1.1" futures = "0.3" +# Query runs split over worker threads (`--query-parallelism`). +rayon = "1.10" form_urlencoded = "1" [dev-dependencies] # Parses SIL intents for the intent round loop's end-to-end test. -asap-frontend-sil = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "b9c7fdfa09f8854d4ae201183637038ee0f6bd36" } +asap-frontend-sil = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "78ec8c7800ad75386e57f14ee9dc05c22ebf817d" } # Paused time for the intent loop's latency and overrun tests. tokio = { workspace = true, features = ["test-util"] } control_plane.workspace = true diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index aecb5b52c..12d5c7269 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -486,6 +486,16 @@ impl EngineHandle { let mut metrics = Metrics::new(&groups, &query_texts); let query = query.with_raw_reads(options.label_pushdown, metrics.query_raw_reads.clone()); metrics.ingestion_raw_reads = ingestion_raw_reads; + let query_parallelism = options.query_parallelism.max(1); + if query_parallelism > 1 { + // Sized once per process: the first engine's setting holds (an + // error means the pool already exists). + let _ = rayon::ThreadPoolBuilder::new() + .num_threads(query_parallelism) + .thread_name(|index| format!("query-part-{index}")) + .build_global(); + } + let query = query.with_parallelism(query_parallelism, metrics.query_parallel_tasks.clone()); if let Some(tier) = &tier { let _ = metrics.view_tier.set(tier.clone()); } diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index dbe762c1c..9866436a1 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -29,6 +29,8 @@ use std::collections::{BTreeMap, BTreeSet}; use std::future::Future; use std::time::Duration; +use futures::StreamExt; + use serde::{Deserialize, Serialize}; use tokio::time::Instant; @@ -570,77 +572,105 @@ impl IntentLoop { let mut answers: Vec>> = vec![None; queries.len()]; let mut ends: Vec> = vec![None; queries.len()]; let mut records: Vec> = vec![None; queries.len()]; - for &i in &self.order { - let query = &queries[i]; - let mut record = QueryRecord { - query_id: query.query_id.clone(), - status: QueryStatus::Answered, - latency_ms: None, - bindings: Bindings::new(), - answer: vec![], - error: None, - }; - let mut upstream_missing = false; - let mut upstream_not_triggered = false; - for dependency in &query.depends_on { - let upstream = queries - .iter() - .position(|q| q.query_id == dependency.upstream_query_id) - .expect("checked in new"); - match &answers[upstream] { - Some(answer) => { - record.bindings.insert( - dependency.variable.clone(), - binding_values(answer, &dependency.output_column), - ); - } - None if records[upstream] - .as_ref() - .is_some_and(|r| r.status == QueryStatus::NotTriggered) => - { - upstream_not_triggered = true + // Dataflow: a query starts as soon as every upstream it reads has + // finished (the roots at once); queries with no dependency between + // them run concurrently, on the runner's query workers. + let mut started = vec![false; queries.len()]; + let mut running = futures::stream::FuturesUnordered::new(); + loop { + let mut progressed = false; + for &i in &self.order { + let query = &queries[i]; + let upstreams = || { + query.depends_on.iter().map(|dependency| { + queries + .iter() + .position(|q| q.query_id == dependency.upstream_query_id) + .expect("checked in new") + }) + }; + if started[i] || upstreams().any(|upstream| records[upstream].is_none()) { + continue; + } + started[i] = true; + progressed = true; + let mut record = QueryRecord { + query_id: query.query_id.clone(), + status: QueryStatus::Answered, + latency_ms: None, + bindings: Bindings::new(), + answer: vec![], + error: None, + }; + let mut upstream_missing = false; + let mut upstream_not_triggered = false; + for (dependency, upstream) in query.depends_on.iter().zip(upstreams()) { + match &answers[upstream] { + Some(answer) => { + record.bindings.insert( + dependency.variable.clone(), + binding_values(answer, &dependency.output_column), + ); + } + None if records[upstream] + .as_ref() + .is_some_and(|r| r.status == QueryStatus::NotTriggered) => + { + upstream_not_triggered = true + } + None => upstream_missing = true, } - None => upstream_missing = true, + } + if upstream_missing { + record.status = QueryStatus::SkippedUpstream; + records[i] = Some(record); + } else if upstream_not_triggered + || (query.skip_if_empty && record.bindings.values().any(BTreeSet::is_empty)) + { + record.status = QueryStatus::NotTriggered; + records[i] = Some(record); + } else { + running.push(async move { + let started = Instant::now(); + let result = tokio::time::timeout( + self.query_timeout, + bind_and_run(self.mode, runner, query, &record.bindings, time_ms), + ) + .await; + (i, record, started, Instant::now(), result) + }); } } - if upstream_missing { - record.status = QueryStatus::SkippedUpstream; - } else if upstream_not_triggered - || (query.skip_if_empty && record.bindings.values().any(BTreeSet::is_empty)) - { - record.status = QueryStatus::NotTriggered; - } else { - let started = Instant::now(); - let result = tokio::time::timeout( - self.query_timeout, - bind_and_run(self.mode, runner, query, &record.bindings, time_ms), - ) - .await; - let ended = Instant::now(); - ends[i] = Some(ended); - record.latency_ms = Some(millis(ended - started)); - match result { - Ok(Ok(answer)) => { - record.answer = answer - .iter() - .map(|sample| AnswerRow { - labels: (*sample.labels).clone(), - value: sample.value, - }) - .collect(); - answers[i] = Some(answer); - } - Ok(Err(error)) => { - record.status = QueryStatus::Failed; - record.error = Some(error); - } - Err(_) => { - record.status = QueryStatus::Failed; - record.error = Some(format!( - "timed out after {} ms", - self.query_timeout.as_millis() - )); - } + if progressed { + // Skipped queries may have made their dependents ready. + continue; + } + let Some((i, mut record, started, ended, result)) = running.next().await else { + break; + }; + ends[i] = Some(ended); + record.latency_ms = Some(millis(ended - started)); + match result { + Ok(Ok(answer)) => { + record.answer = answer + .iter() + .map(|sample| AnswerRow { + labels: (*sample.labels).clone(), + value: sample.value, + }) + .collect(); + answers[i] = Some(answer); + } + Ok(Err(error)) => { + record.status = QueryStatus::Failed; + record.error = Some(error); + } + Err(_) => { + record.status = QueryStatus::Failed; + record.error = Some(format!( + "timed out after {} ms", + self.query_timeout.as_millis() + )); } } records[i] = Some(record); diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index 3a594e1af..b0af9a884 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -124,6 +124,11 @@ struct Args { /// core). Queries may hold up to this many times the run memory limit. #[arg(long, default_value_t = EngineOptions::default().query_threads)] query_threads: usize, + /// Worker threads one query run splits its grouped builds and merges + /// over (by group key) and reads ingest shards on; 1: one thread per + /// run. Answers are the same for any value. Default: the cores. + #[arg(long, default_value_t = EngineOptions::default().query_parallelism)] + query_parallelism: usize, /// Compute a query-time OneEvaluation node in every query's run instead /// of once per evaluation time (for comparison). #[arg(long)] @@ -240,6 +245,7 @@ async fn main() -> anyhow::Result<()> { no_forward: args.no_forward, run_memory_limit_bytes: args.run_memory_limit_bytes, query_threads: args.query_threads, + query_parallelism: args.query_parallelism, share_one_evaluation_results: !args.no_shared_results, label_pushdown: !args.no_label_pushdown, query_time_results_retention_ms: args.query_time_results_retention_ms, diff --git a/data_plane/src/query.rs b/data_plane/src/query.rs index 93c429dd3..d6b0e2a6d 100644 --- a/data_plane/src/query.rs +++ b/data_plane/src/query.rs @@ -112,6 +112,11 @@ pub struct QueryEngine { label_pushdown: bool, /// Where the runs count their raw reads' rows. raw_read_counts: Option>, + /// Parts each run splits its grouped builds and merges into + /// (`RunContext::with_parallelism`), and where the runs count their + /// partition tasks. + parallelism: usize, + parallel_tasks: Option>, } impl QueryEngine { @@ -200,6 +205,8 @@ impl QueryEngine { result_cache, label_pushdown: true, raw_read_counts: None, + parallelism: 1, + parallel_tasks: None, }) } @@ -213,6 +220,19 @@ impl QueryEngine { /// Raw reads select series by the `Scan`'s label predicates when /// `label_pushdown`, and count their rows in `counts`. + /// Runs split their grouped builds and merges by group key into + /// `parallelism` parts on the worker threads, counting the partition + /// tasks in `tasks`; raw reads then convert ingest shards in parallel. + pub fn with_parallelism( + mut self, + parallelism: usize, + tasks: Arc, + ) -> Self { + self.parallelism = parallelism.max(1); + self.parallel_tasks = Some(tasks); + self + } + pub fn with_raw_reads(mut self, label_pushdown: bool, counts: Arc) -> Self { self.label_pushdown = label_pushdown; self.raw_read_counts = Some(counts); @@ -234,6 +254,7 @@ impl QueryEngine { if !self.label_pushdown { store = store.without_label_pushdown(); } + store = store.with_parallel_shard_reads(self.parallelism > 1); match &self.raw_read_counts { Some(counts) => store.with_raw_read_counts(counts.clone()), None => store, @@ -410,12 +431,11 @@ impl QueryEngine { shared.insert(read, self.output_bound(read, time_ms, snapshot, bound)?); } let run_store = Arc::new(self.run_store(snapshot, shared)); - run_compiled(&compiled, run_store.clone(), time_ms, &self.limits).map_err(|error| { - match run_store.missing_rows() { + self.run_compiled(&compiled, run_store.clone(), time_ms) + .map_err(|error| match run_store.missing_rows() { Some(missing) => Unanswered::MissingRows(missing), None => Unanswered::Execution(error.to_string()), - } - }) + }) } /// `node`'s output at `time_ms`: from the query-time partition when it @@ -451,12 +471,11 @@ impl QueryEngine { shared.insert(read, self.output(read, time_ms, snapshot)?); } let run_store = Arc::new(self.run_store(snapshot, shared)); - run_compiled(&run.compiled, run_store.clone(), time_ms, &self.limits).map_err(|error| { - match run_store.missing_rows() { + self.run_compiled(&run.compiled, run_store.clone(), time_ms) + .map_err(|error| match run_store.missing_rows() { Some(missing) => Unanswered::MissingRows(missing), None => Unanswered::Execution(error.to_string()), - } - }) + }) } } @@ -615,20 +634,39 @@ fn query_time_slot(plan_id: &str, node: PhysicalASAPNodeId) -> anyhow::Result, + time_ms: i64, + ) -> Result, asap_executor::Error> { + let context = RunContext::new( + Scope::Query { + evaluation_time_ms: time_ms, + }, + self.limits.clone(), + )? + .with_parallelism(self.parallelism); + let batches = run_compiled(compiled, store, context.clone()); + if let Some(tasks) = &self.parallel_tasks { + tasks.fetch_add( + context.parallel_tasks() as u64, + std::sync::atomic::Ordering::Relaxed, + ); + } + batches + } +} + +/// The batches of `compiled`'s one root in a query run in `context`. fn run_compiled( compiled: &CompiledPhysicalDAG, store: std::sync::Arc, - time_ms: i64, - limits: &Limits, + context: RunContext, ) -> Result, asap_executor::Error> { let instance = compiled.instantiate(store)?; - let context = RunContext::new( - Scope::Query { - evaluation_time_ms: time_ms, - }, - limits.clone(), - )?; block_on(async { let mut output = instance.execute(compiled.roots(), context)?.remove(0); let mut batches = Vec::new(); diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 7917de062..52d1469ae 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -712,6 +712,9 @@ pub struct RunStore { label_pushdown: bool, /// Where the run counts its raw reads' rows. raw_read_counts: Option>, + /// Whether a raw read reads the ingest shards on rayon's worker + /// threads (the batches keep the shard order). + parallel_shard_reads: bool, } impl RunStore { @@ -736,6 +739,7 @@ impl RunStore { missing_rows: Mutex::new(None), label_pushdown: true, raw_read_counts: None, + parallel_shard_reads: false, } } @@ -746,6 +750,13 @@ impl RunStore { self } + /// Raw reads read the ingest shards in parallel (`true`) or one after + /// another; the batches and their order are the same. + pub fn with_parallel_shard_reads(mut self, parallel: bool) -> Self { + self.parallel_shard_reads = parallel; + self + } + /// The run counts its raw reads' rows in `counts`. pub fn with_raw_read_counts(mut self, counts: Arc) -> Self { self.raw_read_counts = Some(counts); @@ -799,17 +810,31 @@ impl DataStore for RunStore { } else { &unselected }; - let mut batches = Vec::new(); - let mut rows_in_time_range = 0; - for shard in self.raw_data.iter() { - let read = shard + let read_shard = |shard: &Arc| { + shard .read( metric, request, self.raw_reads.as_deref(), self.partition.as_ref(), ) - .inspect_err(|error| self.record_missing(error))?; + .inspect_err(|error| self.record_missing(error)) + }; + let reads: Vec = if self.parallel_shard_reads && self.raw_data.len() > 1 { + use rayon::prelude::*; + self.raw_data + .par_iter() + .map(read_shard) + .collect::>()? + } else { + self.raw_data + .iter() + .map(read_shard) + .collect::>()? + }; + let mut batches = Vec::new(); + let mut rows_in_time_range = 0; + for read in reads { rows_in_time_range += read.rows_in_time_range; batches.extend(read.batches); } From 4467d93c7979549fcc0b97f1ff3c36bedcd31117 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 04:02:38 +0000 Subject: [PATCH 3/3] fix(data_plane): count worker-thread CPU in the query phase; separate query pool size Review findings on parallel query runs: - The partition tasks' worker CPU (executor RunContext::parallel_cpu_ns) and the parallel shard reads' worker CPU are charged to the query worker thread (metrics::add_offloaded_cpu_ns), which Timer and PhaseStats::record include: asap_phase_cpu_seconds_total{phase=query} counts the work wherever it ran; asap_query_parallel_cpu_seconds_total reports the worker share. - --query-pool-threads sizes the worker pool apart from --query-parallelism (parts per run); a failed build_global is logged and asap_query_pool_threads reports the pool's size. Ingest, precompute and persist threads share the cores. - query_min_split_rows (tests) lets small tables split. - Pins ASAPPlanner feat/parallel-query-exec 74621ba2 (split merges by wave, small inputs on one thread, worker CPU per run). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- Cargo.lock | 88 ++++++++++++++++++++-------- Cargo.toml | 4 +- data_plane/Cargo.toml | 2 +- data_plane/src/engine.rs | 44 ++++++++++---- data_plane/src/main.rs | 11 +++- data_plane/src/metrics.rs | 56 +++++++++++++++++- data_plane/src/query.rs | 28 +++++++-- data_plane/src/store.rs | 14 ++++- data_plane/tests/intent_sil_modes.rs | 20 +++++++ 9 files changed, 218 insertions(+), 49 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 92ede5a0c..01e9ad9c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -333,7 +333,7 @@ dependencies = [ [[package]] name = "asap-accuracy" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-types", "asap_sketchlib", @@ -344,7 +344,7 @@ dependencies = [ [[package]] name = "asap-cost" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-types", "asap_sketchlib", @@ -356,7 +356,7 @@ dependencies = [ [[package]] name = "asap-executor" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "ahash", "arrow", @@ -364,6 +364,8 @@ dependencies = [ "asap_sketchlib", "chrono", "futures", + "libc", + "rayon", "regex", "serde", "serde_json", @@ -374,7 +376,7 @@ dependencies = [ [[package]] name = "asap-frontend-common" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-types", "serde", @@ -384,7 +386,7 @@ dependencies = [ [[package]] name = "asap-frontend-metricsql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-frontend-common", "asap-types", @@ -395,7 +397,7 @@ dependencies = [ [[package]] name = "asap-frontend-promql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-frontend-common", "asap-types", @@ -405,7 +407,7 @@ dependencies = [ [[package]] name = "asap-frontend-sil" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-types", "serde", @@ -415,7 +417,7 @@ dependencies = [ [[package]] name = "asap-frontend-sql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-frontend-common", "asap-sql-function-catalog", @@ -427,7 +429,7 @@ dependencies = [ [[package]] name = "asap-planner" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-accuracy", "asap-cost", @@ -450,12 +452,12 @@ dependencies = [ [[package]] name = "asap-sql-function-catalog" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" [[package]] name = "asap-stage0-memo" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-types", ] @@ -463,7 +465,7 @@ dependencies = [ [[package]] name = "asap-stage1-pass1-per-computation-candidates" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-types", "thiserror 2.0.20", @@ -472,7 +474,7 @@ dependencies = [ [[package]] name = "asap-stage1-pass2-reuse-candidates" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-accuracy", "asap-types", @@ -482,7 +484,7 @@ dependencies = [ [[package]] name = "asap-stage2-physical-optimization" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-types", ] @@ -490,7 +492,7 @@ dependencies = [ [[package]] name = "asap-stage3-plan-selection" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap-accuracy", "asap-cost", @@ -505,7 +507,7 @@ dependencies = [ [[package]] name = "asap-types" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "asap_sketchlib", "serde", @@ -911,6 +913,25 @@ dependencies = [ "libc", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -977,6 +998,7 @@ dependencies = [ "http-body-util", "libc", "prost", + "rayon", "reqwest", "rmp-serde", "ryu", @@ -1647,7 +1669,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2489,7 +2511,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "metricsql_common" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "chrono", ] @@ -2497,7 +2519,7 @@ dependencies = [ [[package]] name = "metricsql_parser" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=b9c7fdfa09f8854d4ae201183637038ee0f6bd36#b9c7fdfa09f8854d4ae201183637038ee0f6bd36" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=74621ba2afb820f576a26c37c067e93b057e3716#74621ba2afb820f576a26c37c067e93b057e3716" dependencies = [ "ahash", "chrono", @@ -2944,7 +2966,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3038,6 +3060,26 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "recursive" version = "0.1.1" @@ -3192,7 +3234,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3549,7 +3591,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4107,7 +4149,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 4babb4ffb..e74e4a6eb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,8 +12,8 @@ version = "0.1.0" # are reached through `asap_executor::planner`. Draft pin: the Planner's # `feat/parallel-query-exec` head (stacked on #1553), for query runs split # by group key over worker threads. -asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "78ec8c7800ad75386e57f14ee9dc05c22ebf817d" } -asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "78ec8c7800ad75386e57f14ee9dc05c22ebf817d" } +asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "74621ba2afb820f576a26c37c067e93b057e3716" } +asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "74621ba2afb820f576a26c37c067e93b057e3716" } # The sketch library the Planner's executor pins, for the byte encodings of # the sketch states the data plane persists; keep it at the Planner's rev # (draft: ASAPPlanner#1553 head, for SIL intents). diff --git a/data_plane/Cargo.toml b/data_plane/Cargo.toml index 9423243a3..9f5096102 100644 --- a/data_plane/Cargo.toml +++ b/data_plane/Cargo.toml @@ -39,7 +39,7 @@ form_urlencoded = "1" [dev-dependencies] # Parses SIL intents for the intent round loop's end-to-end test. -asap-frontend-sil = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "78ec8c7800ad75386e57f14ee9dc05c22ebf817d" } +asap-frontend-sil = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "74621ba2afb820f576a26c37c067e93b057e3716" } # Paused time for the intent loop's latency and overrun tests. tokio = { workspace = true, features = ["test-util"] } control_plane.workspace = true diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index 12d5c7269..cce986ee2 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -128,11 +128,20 @@ pub struct EngineOptions { /// hold `run_memory_limit_bytes`, so queries may hold up to this many /// times that. pub query_threads: usize, - /// Worker threads one query run splits its grouped builds and merges - /// over (by group key; rayon's global pool, sized once per process), - /// and raw reads convert ingest shards on. 1: every run on its query - /// worker alone. The answers are the same for any value. + /// Parts one query run splits each grouped build and merge into (by + /// group key, on the query worker pool), turning on parallel raw shard + /// reads too; 1: every run on its query worker alone. The answers are + /// the same for any value. pub query_parallelism: usize, + /// Threads of the query worker pool (rayon's global pool, sized once per + /// process) that runs those parts. Ingest, precompute and persist + /// threads share the same cores; leave them room on a busy server. + pub query_pool_threads: usize, + /// For tests: split query runs' grouped builds and merges over inputs + /// this small (`RunContext::with_min_split_rows`); `None`: the + /// executor's default. + #[doc(hidden)] + pub query_min_split_rows: Option, /// Compute each query-time `OneEvaluation` node several queries read /// once per evaluation time, as the plan says; `false` computes it in /// every query's run (for comparison). @@ -225,6 +234,8 @@ impl Default for EngineOptions { run_memory_limit_bytes: 4 << 30, query_threads: std::thread::available_parallelism().map_or(1, usize::from), query_parallelism: std::thread::available_parallelism().map_or(1, usize::from), + query_pool_threads: std::thread::available_parallelism().map_or(1, usize::from), + query_min_split_rows: None, share_one_evaluation_results: true, label_pushdown: true, query_time_results_retention_ms: 60_000, @@ -488,14 +499,27 @@ impl EngineHandle { metrics.ingestion_raw_reads = ingestion_raw_reads; let query_parallelism = options.query_parallelism.max(1); if query_parallelism > 1 { - // Sized once per process: the first engine's setting holds (an - // error means the pool already exists). - let _ = rayon::ThreadPoolBuilder::new() - .num_threads(query_parallelism) + let threads = options.query_pool_threads.max(1); + // Sized once per process: a second engine in the process (tests) + // keeps the first one's pool. + if let Err(error) = rayon::ThreadPoolBuilder::new() + .num_threads(threads) .thread_name(|index| format!("query-part-{index}")) - .build_global(); + .build_global() + { + tracing::warn!(%error, threads, pool = rayon::current_num_threads(), + "the query worker pool already exists; keeping its size"); + } + metrics + .query_pool_threads + .store(rayon::current_num_threads() as u64, Ordering::Relaxed); } - let query = query.with_parallelism(query_parallelism, metrics.query_parallel_tasks.clone()); + let query = query.with_parallelism( + query_parallelism, + options.query_min_split_rows, + metrics.query_parallel_tasks.clone(), + metrics.query_parallel_cpu_ns.clone(), + ); if let Some(tier) = &tier { let _ = metrics.view_tier.set(tier.clone()); } diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index b0af9a884..054240340 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -124,11 +124,15 @@ struct Args { /// core). Queries may hold up to this many times the run memory limit. #[arg(long, default_value_t = EngineOptions::default().query_threads)] query_threads: usize, - /// Worker threads one query run splits its grouped builds and merges - /// over (by group key) and reads ingest shards on; 1: one thread per - /// run. Answers are the same for any value. Default: the cores. + /// Parts one query run splits its grouped builds and merges into (by + /// group key; also turns on parallel raw shard reads); 1: one thread + /// per run. Answers are the same for any value. Default: the cores. #[arg(long, default_value_t = EngineOptions::default().query_parallelism)] query_parallelism: usize, + /// Threads of the query worker pool those parts run on. Ingest, + /// precompute and persist threads share the cores. Default: the cores. + #[arg(long, default_value_t = EngineOptions::default().query_pool_threads)] + query_pool_threads: usize, /// Compute a query-time OneEvaluation node in every query's run instead /// of once per evaluation time (for comparison). #[arg(long)] @@ -246,6 +250,7 @@ async fn main() -> anyhow::Result<()> { run_memory_limit_bytes: args.run_memory_limit_bytes, query_threads: args.query_threads, query_parallelism: args.query_parallelism, + query_pool_threads: args.query_pool_threads, share_one_evaluation_results: !args.no_shared_results, label_pushdown: !args.no_label_pushdown, query_time_results_retention_ms: args.query_time_results_retention_ms, diff --git a/data_plane/src/metrics.rs b/data_plane/src/metrics.rs index f75e52fd1..5f7bc6d41 100644 --- a/data_plane/src/metrics.rs +++ b/data_plane/src/metrics.rs @@ -28,6 +28,23 @@ pub fn thread_cpu_ns() -> u64 { time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64 } +std::thread_local! { + /// CPU time worker threads used for this thread's runs, in ns. + static OFFLOADED_CPU_NS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Charges `ns` of CPU time that worker threads (the query runs' rayon +/// pool) spent for work this thread waited on, so phases measured on +/// this thread ([`Timer`], [`PhaseStats::record`]) count it. +pub fn add_offloaded_cpu_ns(ns: u64) { + OFFLOADED_CPU_NS.with(|offloaded| offloaded.set(offloaded.get() + ns)); +} + +/// This thread's CPU time plus the worker-thread CPU charged to it. +fn charged_cpu_ns() -> u64 { + thread_cpu_ns() + OFFLOADED_CPU_NS.with(std::cell::Cell::get) +} + /// The start of one measured phase on the current thread. pub struct Timer { cpu_ns: u64, @@ -37,7 +54,7 @@ pub struct Timer { impl Timer { pub fn start() -> Self { Self { - cpu_ns: thread_cpu_ns(), + cpu_ns: charged_cpu_ns(), wall: Instant::now(), } } @@ -53,12 +70,13 @@ pub struct PhaseStats { impl PhaseStats { /// Records one run started at `timer`, ending now on the same thread; - /// returns its wall time in seconds. + /// returns its wall time in seconds. Its CPU time is the thread's plus + /// what worker threads spent for it ([`add_offloaded_cpu_ns`]). pub fn record(&self, timer: Timer) -> f64 { let wall = timer.wall.elapsed(); self.runs.fetch_add(1, Ordering::Relaxed); self.cpu_ns.fetch_add( - thread_cpu_ns().saturating_sub(timer.cpu_ns), + charged_cpu_ns().saturating_sub(timer.cpu_ns), Ordering::Relaxed, ); self.wall_ns @@ -332,6 +350,11 @@ pub struct Metrics { /// Partition tasks the query runs ran on the worker threads /// (`EngineOptions::query_parallelism`). pub query_parallel_tasks: std::sync::Arc, + /// CPU time those tasks and parallel raw shard reads used on the + /// worker threads, in ns; included in the query phases' CPU. + pub query_parallel_cpu_ns: std::sync::Arc, + /// Threads of the query runs' worker pool (0: none). + pub query_pool_threads: AtomicU64, } impl Metrics { @@ -376,6 +399,8 @@ impl Metrics { query_raw_reads: std::sync::Arc::default(), ingestion_raw_reads: std::sync::Arc::default(), query_parallel_tasks: std::sync::Arc::default(), + query_parallel_cpu_ns: std::sync::Arc::default(), + query_pool_threads: AtomicU64::new(0), } } @@ -616,6 +641,17 @@ pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { "# HELP asap_query_parallel_tasks_total Partition tasks the query runs ran on worker threads.\n# TYPE asap_query_parallel_tasks_total counter\nasap_query_parallel_tasks_total {}", load(&*metrics.query_parallel_tasks) ); + let _ = writeln!( + out, + "# HELP asap_query_parallel_cpu_seconds_total CPU time the query runs' worker-thread tasks used (included in phase=\"query\").\n# TYPE asap_query_parallel_cpu_seconds_total counter\nasap_query_parallel_cpu_seconds_total {}", + load(&*metrics.query_parallel_cpu_ns) / 1e9 + ); + gauge( + &mut out, + "asap_query_pool_threads", + "Threads of the query runs' worker pool.", + load(&metrics.query_pool_threads), + ); gauge( &mut out, "asap_view_bytes", @@ -933,6 +969,20 @@ pub fn thread_cpu_seconds() -> BTreeMap { mod tests { use super::*; + /// Worker-thread CPU charged to this thread while a phase runs counts + /// in that phase (a query run's partition tasks on the pool); charged + /// before the phase started, it does not. + #[test] + fn worker_cpu_charged_to_the_thread_counts_in_its_phase() { + let stats = PhaseStats::default(); + add_offloaded_cpu_ns(7_000_000_000); + let timer = Timer::start(); + add_offloaded_cpu_ns(3_000_000_000); + stats.record(timer); + let cpu = stats.cpu_ns.load(Ordering::Relaxed); + assert!((3_000_000_000..4_000_000_000).contains(&cpu), "{cpu} ns"); + } + /// A phase records the thread CPU it burns, and the text format names /// each phase and query. #[test] diff --git a/data_plane/src/query.rs b/data_plane/src/query.rs index d6b0e2a6d..9cc8b5253 100644 --- a/data_plane/src/query.rs +++ b/data_plane/src/query.rs @@ -116,7 +116,12 @@ pub struct QueryEngine { /// (`RunContext::with_parallelism`), and where the runs count their /// partition tasks. parallelism: usize, - parallel_tasks: Option>, + /// `RunContext::with_min_split_rows` for the runs; `None`: default. + min_split_rows: Option, + parallel_tasks: Option<( + Arc, + Arc, + )>, } impl QueryEngine { @@ -206,6 +211,7 @@ impl QueryEngine { label_pushdown: true, raw_read_counts: None, parallelism: 1, + min_split_rows: None, parallel_tasks: None, }) } @@ -222,14 +228,18 @@ impl QueryEngine { /// `label_pushdown`, and count their rows in `counts`. /// Runs split their grouped builds and merges by group key into /// `parallelism` parts on the worker threads, counting the partition - /// tasks in `tasks`; raw reads then convert ingest shards in parallel. + /// tasks in `tasks` and their worker-thread CPU (ns) in `cpu_ns`; raw + /// reads then convert ingest shards in parallel. pub fn with_parallelism( mut self, parallelism: usize, + min_split_rows: Option, tasks: Arc, + cpu_ns: Arc, ) -> Self { self.parallelism = parallelism.max(1); - self.parallel_tasks = Some(tasks); + self.min_split_rows = min_split_rows; + self.parallel_tasks = Some((tasks, cpu_ns)); self } @@ -649,12 +659,22 @@ impl QueryEngine { self.limits.clone(), )? .with_parallelism(self.parallelism); + let context = match self.min_split_rows { + Some(rows) => context.with_min_split_rows(rows), + None => context, + }; let batches = run_compiled(compiled, store, context.clone()); - if let Some(tasks) = &self.parallel_tasks { + // The run's work on the worker threads counts as this query's CPU. + crate::metrics::add_offloaded_cpu_ns(context.parallel_cpu_ns()); + if let Some((tasks, cpu_ns)) = &self.parallel_tasks { tasks.fetch_add( context.parallel_tasks() as u64, std::sync::atomic::Ordering::Relaxed, ); + cpu_ns.fetch_add( + context.parallel_cpu_ns(), + std::sync::atomic::Ordering::Relaxed, + ); } batches } diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 52d1469ae..fcf4bd5ba 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -822,10 +822,18 @@ impl DataStore for RunStore { }; let reads: Vec = if self.parallel_shard_reads && self.raw_data.len() > 1 { use rayon::prelude::*; - self.raw_data + let reads = self + .raw_data .par_iter() - .map(read_shard) - .collect::>()? + .map(|shard| { + let start = crate::metrics::thread_cpu_ns(); + read_shard(shard).map(|read| (read, crate::metrics::thread_cpu_ns() - start)) + }) + .collect::, _>>()?; + // The shards' conversion on the worker threads counts as this + // run's CPU, on the thread that waited for it. + crate::metrics::add_offloaded_cpu_ns(reads.iter().map(|(_, ns)| ns).sum()); + reads.into_iter().map(|(read, _)| read).collect() } else { self.raw_data .iter() diff --git a/data_plane/tests/intent_sil_modes.rs b/data_plane/tests/intent_sil_modes.rs index 2d41019fe..ba43f6e52 100644 --- a/data_plane/tests/intent_sil_modes.rs +++ b/data_plane/tests/intent_sil_modes.rs @@ -517,6 +517,8 @@ async fn parallel_query_runs_answer_like_sequential_runs() { EngineOptions { no_forward: true, query_parallelism, + // The test's tables are small: split them anyway. + query_min_split_rows: Some(0), ..EngineOptions::default() }, ) @@ -543,10 +545,28 @@ async fn parallel_query_runs_answer_like_sequential_runs() { .metrics() .query_parallel_tasks .load(Ordering::SeqCst); + let parallel_cpu_ns = state + .engine + .metrics() + .query_parallel_cpu_ns + .load(Ordering::SeqCst); + // The query phases' CPU includes the worker threads' share. + let text = state.engine.render_metrics(); + let query_cpu_s: f64 = text + .lines() + .filter(|l| l.starts_with("asap_phase_cpu_seconds_total{phase=\"query\"")) + .filter_map(|l| l.rsplit(' ').next()?.parse::().ok()) + .sum(); if query_parallelism == 1 { assert_eq!(tasks, 0, "{mode:?}"); + assert_eq!(parallel_cpu_ns, 0, "{mode:?}"); } else { assert!(tasks > 0, "{mode:?}: no partition task ran"); + assert!(parallel_cpu_ns > 0, "{mode:?}: worker CPU not counted"); + assert!( + query_cpu_s >= parallel_cpu_ns as f64 / 1e9, + "{mode:?}: query CPU {query_cpu_s} s < worker CPU {parallel_cpu_ns} ns" + ); } answers_by_parallelism.push(answers); }