From f990c5dc9f00fa110fd777015dd8e4bc620a5825 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 17:34:06 +0000 Subject: [PATCH 1/7] test(data_plane): binding a large plan's IN-list hole is linear in the plan's size Failing test first: a plan with 30 IN-list holes of 2000 placeholders each; binding two of them must take well under the budget (the current binding compares every plan value with every placeholder, ~30 s per bound query at the x10 scale). Co-Authored-By: Claude Opus 5.5 --- data_plane/src/placeholders.rs | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/data_plane/src/placeholders.rs b/data_plane/src/placeholders.rs index 9de8259a0..2943cae88 100644 --- a/data_plane/src/placeholders.rs +++ b/data_plane/src/placeholders.rs @@ -386,6 +386,68 @@ mod tests { assert!(error.contains("__sil_Y_0"), "{error}"); } + /// Binding one slot of a plan that holds many large IN-list holes (an + /// intent with a dozen dependent queries, 2000 planned values each) + /// costs time linear in the plan's size, not in the plan's size times + /// the slot's placeholder count: each value is looked up, not compared + /// with every placeholder. (At the x10 scale a quadratic binding took + /// ~30 s per bound query.) + #[test] + fn binding_a_large_plan_is_linear_in_its_size() { + let holes = 30; + let planned = 2000; + let slots: Vec> = (0..holes) + .map(|h| { + (0..planned) + .map(|i| utf8(&format!("__sil_Y{h}_{i}"))) + .collect() + }) + .collect(); + let eq = |value: &ScalarValue| { + json!({"Compare": {"left": column(), "op": "Eq", "right": literal(value), + "semantics": "Sql"}}) + }; + let nodes: Vec = slots + .iter() + .enumerate() + .map(|(h, p)| match h % 2 { + 0 => json!({"id": h, "Filter": {"pred": {"BoolOr": p.iter().map(eq).collect::>()}}}), + _ => json!({"id": h, "Scan": {"predicates": [{"InList": {"expr": column(), + "list": p.iter().map(literal).collect::>(), "negated": false}}]}}), + }) + .collect(); + let mut dag = json!({ "nodes": nodes }); + let values: Vec = (0..1500).map(|i| format!("svc{i}")).collect(); + let values: Vec<&str> = values.iter().map(String::as_str).collect(); + let started = std::time::Instant::now(); + assert!(bind_json(&mut dag, &slot(SlotPosition::InList, &slots[0], &values)).unwrap()); + assert!(bind_json(&mut dag, &slot(SlotPosition::InList, &slots[1], &values)).unwrap()); + let elapsed = started.elapsed(); + assert_eq!( + dag["nodes"][0]["Filter"]["pred"]["InList"]["list"] + .as_array() + .unwrap() + .len(), + 1500 + ); + assert_eq!( + dag["nodes"][1]["Scan"]["predicates"][0]["InList"]["list"] + .as_array() + .unwrap() + .len(), + 1500 + ); + // The other holes keep their placeholders. + assert_eq!( + dag["nodes"][2]["Filter"]["pred"], + json!({"BoolOr": slots[2].iter().map(eq).collect::>()}) + ); + assert!( + elapsed < std::time::Duration::from_secs(3), + "binding took {elapsed:?}" + ); + } + /// An expression without the slot's placeholders is left as it is. #[test] fn other_expressions_are_unchanged() { From eb33b0d52269b7bb09b858e8bc2958d4edab8fe3 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 17:34:17 +0000 Subject: [PATCH 2/7] perf(data_plane): bind an intent query's holes by hashed placeholder lookup The binding compared every value of the serialized plan with every placeholder of the slot (and Utf8 texts again in the leftover check), so a bound query cost plan size x placeholders: with 5000-value IN-list holes in a 3.3 MB x10 plan, ~30 s per bound query (OB_fast_5m, OB_slow_30m, OB_endpoints, OF_q2). The placeholders' JSON texts and Utf8 texts are now hash sets, and only one-level (scalar-shaped) values are looked up: linear in the plan's size. Same rewrite and same errors. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/placeholders.rs | 55 ++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 13 deletions(-) diff --git a/data_plane/src/placeholders.rs b/data_plane/src/placeholders.rs index 2943cae88..063bd9078 100644 --- a/data_plane/src/placeholders.rs +++ b/data_plane/src/placeholders.rs @@ -12,7 +12,7 @@ //! without naming each operator; a placeholder left in a form it does not //! know is an error rather than a silently empty answer. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashSet}; use asap_executor::planner::ir::scalar::expr_ir::ScalarValue; use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPNodeId}; @@ -88,11 +88,7 @@ pub fn bind_json(json: &mut Json, slot: &SlotBinding) -> Result { slot.values )); } - let rewrite = Rewrite { - placeholders: &placeholders, - values: &values, - position: slot.position, - }; + let rewrite = Rewrite::new(&placeholders, &values, slot.position); let changed = rewrite.apply(json); if let Some(left) = rewrite.find(json) { return Err(format!( @@ -136,20 +132,54 @@ fn parse_integer(text: &str) -> Option { /// One slot's rewrite of serialized plan parts. struct Rewrite<'a> { - placeholders: &'a [Json], + /// The placeholders' JSON text: a plan part is looked up here, not + /// compared with each placeholder (a slot may hold thousands, and a + /// plan holds every query's). + placeholders: HashSet, + /// The text of each `Utf8` placeholder. + placeholder_texts: HashSet<&'a str>, values: &'a [Json], position: SlotPosition, } -impl Rewrite<'_> { +impl<'a> Rewrite<'a> { + fn new(placeholders: &'a [Json], values: &'a [Json], position: SlotPosition) -> Self { + Self { + placeholders: placeholders.iter().map(Json::to_string).collect(), + placeholder_texts: placeholders + .iter() + .filter_map(|p| p.get("Utf8").and_then(Json::as_str)) + .collect(), + values, + position, + } + } + + /// Whether `json` is one of the placeholders. A serialized scalar is a + /// bare JSON scalar or a one-field object holding one (`{"Utf8": ..}`), + /// so anything deeper is not looked up. + fn is_placeholder(&self, json: &Json) -> bool { + let shallow = match json { + Json::Object(fields) => { + fields.len() == 1 + && fields + .values() + .all(|value| !value.is_object() && !value.is_array()) + } + Json::Array(_) => false, + _ => true, + }; + shallow && self.placeholders.contains(&json.to_string()) + } + /// Whether `json` is one of the placeholders, bare (`Some(false)`) or as /// a literal expression (`Some(true)`). fn placeholder(&self, json: &Json) -> Option { - if self.placeholders.contains(json) { + if self.is_placeholder(json) { return Some(false); } let literal = json.as_object().filter(|o| o.len() == 1)?.get("Literal")?; - self.placeholders.contains(literal).then_some(true) + self.is_placeholder(literal).then_some(true) } /// The values, bare or as literal expressions. @@ -225,12 +255,11 @@ impl Rewrite<'_> { /// A placeholder still in `json`, as text. fn find(&self, json: &Json) -> Option { - if self.placeholders.contains(json) { + if self.is_placeholder(json) { return Some(json.to_string()); } if let Json::String(text) = json { - let as_text = |p: &Json| p.get("Utf8").and_then(Json::as_str) == Some(text.as_str()); - if self.placeholders.iter().any(as_text) { + if self.placeholder_texts.contains(text.as_str()) { return Some(json.to_string()); } } From bc0ab5b0df15518c725b3949a8624effadf54ebb Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 17:56:06 +0000 Subject: [PATCH 3/7] test(data_plane): binding a plan of many nodes prepares each slot once Failing test: bind() rewrote node by node through bind_json, which prepared the slot (placeholders and values to JSON, their hash sets) for every node: ~2.4 s per bound query on the x10 plan (491 nodes, 5000 placeholders). PreparedSlot is the seam; its stub still prepares per call. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/placeholders.rs | 56 ++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/data_plane/src/placeholders.rs b/data_plane/src/placeholders.rs index 063bd9078..128dc82a0 100644 --- a/data_plane/src/placeholders.rs +++ b/data_plane/src/placeholders.rs @@ -98,6 +98,25 @@ pub fn bind_json(json: &mut Json, slot: &SlotBinding) -> Result { Ok(changed) } +/// A slot ready to rewrite plan parts: its placeholders and bound values +/// as JSON, checked once. +pub struct PreparedSlot { + slot: SlotBinding, +} + +impl PreparedSlot { + /// Fails as [`bind_json`] does for a slot with no placeholders, a value + /// not of their type, or a comparison bound to other than one value. + pub fn new(slot: &SlotBinding) -> Result { + Ok(Self { slot: slot.clone() }) + } + + /// [`bind_json`] of `json` for this slot. + pub fn rewrite(&self, json: &mut Json) -> Result { + bind_json(json, &self.slot) + } +} + /// The slot's values as JSON scalars of its placeholders' type. fn bound_values(slot: &SlotBinding) -> Result, String> { let bad = |value: &str, kind: &str| format!("bound value {value:?} is not a {kind}"); @@ -477,6 +496,43 @@ mod tests { ); } + /// [`bind`] over a plan of many nodes prepares each slot once, not + /// once per node: 400 nodes and one 5000-placeholder hole bind in well + /// under the budget (preparing the slot per node took ~2.4 s per bound + /// query on the x10 plan). + #[test] + fn binding_a_plan_of_many_nodes_prepares_each_slot_once() { + let p: Vec = (0..5000).map(|i| utf8(&format!("__sil_Y_{i}"))).collect(); + let mut nodes: Vec = (0..400) + .map(|id| json!({"id": id, "payload": {"Project": {"cols": [{"Column": id}]}}})) + .collect(); + nodes.push( + json!({"id": 400, "payload": {"Filter": {"pred": {"InList": {"expr": column(), + "list": p.iter().map(literal).collect::>(), "negated": false}}}}}), + ); + let dag = json!({"nodes": nodes, "edges": [], "roots": [400], "scalar_roots": []}); + let started = std::time::Instant::now(); + let mut changed = BTreeSet::new(); + let slot = slot(SlotPosition::InList, &p, &["a", "b"]); + let prepared = PreparedSlot::new(&slot).unwrap(); + let mut bound = dag.clone(); + for node in bound["nodes"].as_array_mut().unwrap() { + if prepared.rewrite(node).unwrap() { + changed.insert(node["id"].as_u64().unwrap()); + } + } + let elapsed = started.elapsed(); + assert_eq!(changed, BTreeSet::from([400])); + assert_eq!( + bound["nodes"][400]["payload"]["Filter"]["pred"]["InList"]["list"], + json!([literal(&utf8("a")), literal(&utf8("b"))]) + ); + assert!( + elapsed < std::time::Duration::from_secs(1), + "binding took {elapsed:?}" + ); + } + /// An expression without the slot's placeholders is left as it is. #[test] fn other_expressions_are_unchanged() { From 29656bf91fefbfc07d9181488dc15514b2c2e299 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 17:58:26 +0000 Subject: [PATCH 4/7] perf(data_plane): prepare each bound slot once per plan, not once per node bind() went through bind_json per node, which converted the slot's placeholders and values to JSON and hashed them again for each of the plan's nodes: ~2.4 s per bound query on the x10 plan (491 nodes, 5000 placeholders). PreparedSlot prepares a slot once; bind() rewrites each node with it, then the plan's other fields (edges, roots) rather than walking the nodes a second time. Binding the x10 plan (copy, rewrite, deserialize) now takes ~110 ms. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/placeholders.rs | 86 +++++++++++++++++++--------------- 1 file changed, 48 insertions(+), 38 deletions(-) diff --git a/data_plane/src/placeholders.rs b/data_plane/src/placeholders.rs index 128dc82a0..59a537895 100644 --- a/data_plane/src/placeholders.rs +++ b/data_plane/src/placeholders.rs @@ -51,19 +51,24 @@ pub fn bind( let mut json = dag.clone(); let mut changed = BTreeSet::new(); for slot in slots { + let prepared = PreparedSlot::new(slot)?; let nodes = json["nodes"] .as_array_mut() .ok_or("the plan has no node list")?; for node in nodes { - if bind_json(node, slot)? { + if prepared.rewrite(node)? { let id = serde_json::from_value(node["id"].clone()) .map_err(|e| format!("a node id: {e}"))?; changed.insert(id); } } - // The edges, and anything else the plan holds; this also checks - // that no placeholder is left anywhere. - bind_json(&mut json, slot)?; + // The edges, and anything else the plan holds beside its nodes + // (each node is checked above); this also checks that no + // placeholder is left anywhere. + let fields = json.as_object_mut().ok_or("the plan is not an object")?; + for (_, field) in fields.iter_mut().filter(|(name, _)| *name != "nodes") { + prepared.rewrite(field)?; + } } let bound = serde_json::from_value(json).map_err(|e| format!("the bound plan: {e}"))?; Ok((bound, changed)) @@ -72,48 +77,52 @@ pub fn bind( /// Rewrites `json` (any serialized part of a plan) for `slot`; whether it /// changed. Fails as [`bind`] does, a placeholder left over included. pub fn bind_json(json: &mut Json, slot: &SlotBinding) -> Result { - if slot.placeholders.is_empty() { - return Err("the slot has no placeholders".into()); - } - let placeholders: Vec = slot - .placeholders - .iter() - .map(|p| serde_json::to_value(p).map_err(|e| e.to_string())) - .collect::>()?; - let values = bound_values(slot)?; - if slot.position == SlotPosition::Comparison && values.len() != 1 { - return Err(format!( - "a comparison hole takes exactly one value, not {} ({:?})", - values.len(), - slot.values - )); - } - let rewrite = Rewrite::new(&placeholders, &values, slot.position); - let changed = rewrite.apply(json); - if let Some(left) = rewrite.find(json) { - return Err(format!( - "placeholder {left} is left in a form the binding does not rewrite" - )); - } - Ok(changed) + PreparedSlot::new(slot)?.rewrite(json) } /// A slot ready to rewrite plan parts: its placeholders and bound values -/// as JSON, checked once. +/// as JSON, checked once (preparing a slot of thousands of placeholders +/// costs milliseconds; [`bind`] prepares each slot once for every node). pub struct PreparedSlot { - slot: SlotBinding, + rewrite: Rewrite, } impl PreparedSlot { /// Fails as [`bind_json`] does for a slot with no placeholders, a value /// not of their type, or a comparison bound to other than one value. pub fn new(slot: &SlotBinding) -> Result { - Ok(Self { slot: slot.clone() }) + if slot.placeholders.is_empty() { + return Err("the slot has no placeholders".into()); + } + let placeholders: Vec = slot + .placeholders + .iter() + .map(|p| serde_json::to_value(p).map_err(|e| e.to_string())) + .collect::>()?; + let values = bound_values(slot)?; + if slot.position == SlotPosition::Comparison && values.len() != 1 { + return Err(format!( + "a comparison hole takes exactly one value, not {} ({:?})", + values.len(), + slot.values + )); + } + Ok(Self { + rewrite: Rewrite::new(&placeholders, values, slot.position), + }) } - /// [`bind_json`] of `json` for this slot. + /// Rewrites `json` (any serialized part of a plan) for this slot; + /// whether it changed. Fails as [`bind`] does on a placeholder left + /// over. pub fn rewrite(&self, json: &mut Json) -> Result { - bind_json(json, &self.slot) + let changed = self.rewrite.apply(json); + if let Some(left) = self.rewrite.find(json) { + return Err(format!( + "placeholder {left} is left in a form the binding does not rewrite" + )); + } + Ok(changed) } } @@ -150,24 +159,25 @@ fn parse_integer(text: &str) -> Option { } /// One slot's rewrite of serialized plan parts. -struct Rewrite<'a> { +struct Rewrite { /// The placeholders' JSON text: a plan part is looked up here, not /// compared with each placeholder (a slot may hold thousands, and a /// plan holds every query's). placeholders: HashSet, /// The text of each `Utf8` placeholder. - placeholder_texts: HashSet<&'a str>, - values: &'a [Json], + placeholder_texts: HashSet, + values: Vec, position: SlotPosition, } -impl<'a> Rewrite<'a> { - fn new(placeholders: &'a [Json], values: &'a [Json], position: SlotPosition) -> Self { +impl Rewrite { + fn new(placeholders: &[Json], values: Vec, position: SlotPosition) -> Self { Self { placeholders: placeholders.iter().map(Json::to_string).collect(), placeholder_texts: placeholders .iter() .filter_map(|p| p.get("Utf8").and_then(Json::as_str)) + .map(str::to_string) .collect(), values, position, From 5e45fc7ea5f40c400e718d950f6c45d6246d19cf Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 18:19:13 +0000 Subject: [PATCH 5/7] test(data_plane): a window's independent views run apart with identical views Failing test first: every public workload plan (no KLL) stores byte-identical view files whether a refresh group's views that share no node below them run as one run or apart, and some plans run a group in several parts (asap_precompute_window_view_parts above 1). Adds the --precompute-split-views option (EngineOptions::precompute_split_views, default true), not read yet. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/engine.rs | 6 ++ data_plane/src/main.rs | 6 ++ data_plane/tests/precompute_pool.rs | 88 +++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+) diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index 8f9f09476..596dcca4a 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -138,6 +138,11 @@ pub struct EngineOptions { /// default 1: each window runs on its precompute thread. Above 1 a /// window commits sooner for more CPU (the pool's split overhead). pub precompute_parallelism: usize, + /// Whether a refresh group's views that share no node below them run + /// as separate runs of a window, at once, each on its own thread + /// (default true): the window commits after its slowest part. The + /// stored rows are the same either way. + pub precompute_split_views: bool, /// 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. @@ -244,6 +249,7 @@ impl Default for EngineOptions { query_threads: std::thread::available_parallelism().map_or(1, usize::from), query_parallelism: std::thread::available_parallelism().map_or(1, usize::from), precompute_parallelism: 1, + precompute_split_views: true, query_pool_threads: std::thread::available_parallelism().map_or(1, usize::from), query_min_split_rows: None, share_one_evaluation_results: true, diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index 811dd26cf..6c0f85dc4 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -134,6 +134,11 @@ struct Args { /// any value): above 1, windows commit sooner for more CPU. Default 1. #[arg(long, default_value_t = EngineOptions::default().precompute_parallelism)] precompute_parallelism: usize, + /// Whether a refresh group's views that share no node below them run + /// as separate runs of a window at once, each on its own thread (the + /// stored rows are the same either way). Default true. + #[arg(long, action = clap::ArgAction::Set, default_value_t = EngineOptions::default().precompute_split_views)] + precompute_split_views: bool, /// 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)] @@ -266,6 +271,7 @@ async fn main() -> anyhow::Result<()> { query_threads: args.query_threads, query_parallelism: args.query_parallelism, precompute_parallelism: args.precompute_parallelism, + precompute_split_views: args.precompute_split_views, query_pool_threads: args.query_pool_threads, share_one_evaluation_results: !args.no_shared_results, label_pushdown: !args.no_label_pushdown, diff --git a/data_plane/tests/precompute_pool.rs b/data_plane/tests/precompute_pool.rs index 5e6b6bd5a..b4aba9be9 100644 --- a/data_plane/tests/precompute_pool.rs +++ b/data_plane/tests/precompute_pool.rs @@ -518,3 +518,91 @@ async fn a_big_window_split_by_series_is_ready_within_its_deadline() { "{label}: the window was ready after {ready:?}" ); } + +/// [`view_files`] with a window's independent views (no node in common +/// below them) run as one run (`split` false) or as one run each on its own +/// thread; returns the files and whether some group ran in several parts. +async fn view_files_split( + plan: &InstallablePlan, + split: bool, +) -> (BTreeMap>, u64, bool) { + let dir = std::env::temp_dir().join(format!( + "precompute-split-{}-{split}-{}", + std::process::id(), + rand_suffix() + )); + let _ = std::fs::remove_dir_all(&dir); + let (app, state) = data_plane( + plan, + EngineOptions { + precompute_split_views: split, + ..options(1, Some(dir.clone())) + }, + ); + for (minute, body) in requests(plan, SERIES, START_MS, END_MS) + .into_iter() + .enumerate() + { + assert_eq!(write(&app, body).await, StatusCode::NO_CONTENT); + common::barrier(&app, START_MS + (minute as i64 + 1) * 60_000).await; + } + common::barrier(&app, END_MS).await; + let failed = state.engine.stats().windows_failed; + let parted = state.engine.render_metrics().lines().any(|line| { + line.starts_with("asap_precompute_window_view_parts{") + && line.rsplit(' ').next().is_some_and(|parts| parts != "1") + }); + let mut files = BTreeMap::new(); + let mut directories = vec![dir.clone()]; + while let Some(directory) = directories.pop() { + for entry in std::fs::read_dir(&directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + directories.push(path); + continue; + } + files.insert( + path.strip_prefix(&dir) + .unwrap() + .to_string_lossy() + .to_string(), + std::fs::read(&path).unwrap(), + ); + } + } + state.engine.stop(); + let _ = std::fs::remove_dir_all(&dir); + (files, failed, parted) +} + +/// A refresh group's views that share no node below them (views over +/// different tables, say) are computed as separate runs at once, so a +/// window commits after its slowest part rather than after all of them. +/// Every public workload plan without a KLL sketch stores byte-identical +/// view files either way, no window fails, and some plans have a group run +/// in several parts. +#[tokio::test(flavor = "multi_thread")] +async fn independent_views_of_a_window_run_apart_with_identical_views() { + let mut compared = 0; + let mut parted = 0; + let mut mismatches = Vec::new(); + for (label, plan) in plans() { + if has_kll(&plan) { + continue; + } + let (whole, failed, _) = view_files_split(&plan, false).await; + assert_eq!(failed, 0, "{label}: windows failed as one run"); + let (apart, failed, was_parted) = view_files_split(&plan, true).await; + if failed > 0 || apart != whole { + mismatches.push(format!( + "{label}: {failed} windows failed in parts, files equal: {}", + apart == whole + )); + } + compared += 1; + parted += usize::from(was_parted); + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); + assert!(compared >= 10, "only {compared} plans compared"); + assert!(parted >= 3, "only {parted} plans had a group run in parts"); +} From cdf237c1c89bd3603b43d0de5ef56636a94cce0c Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 18:52:26 +0000 Subject: [PATCH 6/7] perf(data_plane): run a window's independent views apart, at once A refresh group's views that share no node below them (views over different tables, say) are compiled as separate parts; a window runs its parts at once, one thread each (the first on the precompute thread), so it commits after its slowest part rather than after all of them. The stored rows are the same (byte-identical view files over the public workloads). The parts' CPU counts as the precompute thread's phase CPU. On by default; --precompute-split-views false runs each window whole. The asap_precompute_window_view_parts gauge reports the parts per group. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/engine.rs | 7 +- data_plane/src/ingestion.rs | 174 ++++++++++++++++++++++++++++++++---- data_plane/src/metrics.rs | 16 ++++ 3 files changed, 179 insertions(+), 18 deletions(-) diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index 596dcca4a..7769214fd 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -449,7 +449,8 @@ impl EngineHandle { let precompute = Arc::new( precompute .with_raw_reads(options.label_pushdown, ingestion_raw_reads.clone()) - .with_parallelism(options.precompute_parallelism), + .with_parallelism(options.precompute_parallelism) + .with_split_views(options.precompute_split_views), ); // Push mode: the groups the shards build by push. let push_groups: Vec> = match options.precompute_mode { @@ -1639,11 +1640,15 @@ fn spawn_precompute( .metrics .precompute_threads .store(options.threads as u64, Ordering::Relaxed); + let view_parts = precompute.view_parts(); for (group, &split) in precompute.tasks().split_by_series.iter().enumerate() { let parts = if split { options.threads } else { 1 }; shared.metrics.precompute_windows[group] .parts .store(parts as u64, Ordering::Relaxed); + shared.metrics.precompute_windows[group] + .view_parts + .store(view_parts[group] as u64, Ordering::Relaxed); } // Windows taken from the backlog and not yet committed: one at a time // when the committer computes them itself; with workers, two per diff --git a/data_plane/src/ingestion.rs b/data_plane/src/ingestion.rs index ff5930a48..45ac39e61 100644 --- a/data_plane/src/ingestion.rs +++ b/data_plane/src/ingestion.rs @@ -140,6 +140,11 @@ struct RefreshGroupRun { /// `view_retention_margin_ms`: how long the store keeps their rows. views: Vec, compiled: CompiledPhysicalDAG, + /// The group's run in independent parts, when its views fall into + /// several sets that share no node below them (views over different + /// tables, say): each part computes its set's views; empty when there + /// is one set. + parts: Vec, width_ms: i64, /// The views of other groups its runs read. reads: Vec, @@ -281,6 +286,20 @@ impl Ingestion { views: ids.clone(), error, })?; + let view_sets = independent_view_sets(&index, &ids, &stop); + let parts = match view_sets.len() { + 0 | 1 => Vec::new(), + _ => view_sets + .iter() + .map(|set| { + let roots: Vec = set.iter().map(|&id| id as u64).collect(); + compile(dag, &read_views, &roots).map_err(|error| IngestionError::Compile { + views: set.clone(), + error, + }) + }) + .collect::, _>>()?, + }; let metrics = index.metrics_below(&ids, &read); let started_by = index.metrics_below(&ids, &BTreeSet::new()); let margin_ms = options.view_retention_margin_ms; @@ -297,6 +316,7 @@ impl Ingestion { runs.push(RefreshGroupRun { views, compiled, + parts, width_ms: millis(window.width_ms), reads: read.iter().copied().collect(), readers: Vec::new(), @@ -370,6 +390,7 @@ impl Ingestion { label_pushdown: true, raw_read_counts: None, parallelism: 1, + split_views: true, }, )) } @@ -890,6 +911,44 @@ pub struct RefreshTaskGraph { pub split_by_series: Vec, } +/// `views` (of one refresh group) in sets that share no node below them, +/// not reading through `stop` (the other groups' views it reads): each set +/// can run apart from the others. In `views`' order, each set and the sets +/// by their first view. +fn independent_view_sets( + index: &DagIndex, + views: &[PhysicalASAPNodeId], + stop: &HashSet, +) -> Vec> { + // Each set's views and the nodes below them. + let mut sets: Vec<(Vec, BTreeSet)> = Vec::new(); + for &view in views { + let mut nodes = index.below(&[view], stop); + let mut members = vec![view]; + // Merge every set sharing a node with this view's. + let mut index_of_set = 0; + while index_of_set < sets.len() { + if sets[index_of_set].1.is_disjoint(&nodes) { + index_of_set += 1; + continue; + } + let (more, below) = sets.remove(index_of_set); + members.splice(0..0, more); + nodes.extend(below); + } + sets.push((members, nodes)); + } + let mut sets: Vec> = sets + .into_iter() + .map(|(mut members, _)| { + members.sort_by_key(|id| views.iter().position(|v| v == id)); + members + }) + .collect(); + sets.sort_by_key(|set| views.iter().position(|v| *v == set[0])); + sets +} + /// Whether `operator` computes each series' rows from that series' input /// rows alone, so a run over a subset of the series yields exactly those /// series' rows. Conservative: a raw `Scan` that keeps the series @@ -952,6 +1011,10 @@ pub struct Precompute { /// worker pool ([`RunContext::with_parallelism`]: the same states for /// any value); 1 (the default) runs each window on its own thread. parallelism: usize, + /// Whether a window of a group with independent parts + /// ([`RefreshGroupRun::parts`]) runs them at once, one thread each; + /// default true. + split_views: bool, } impl Precompute { @@ -963,6 +1026,26 @@ impl Precompute { self } + /// Runs the independent parts of a group's window (views sharing no + /// node below them) at once, one thread each, when `split`; else as + /// one run. The stored rows are the same either way. + pub fn with_split_views(mut self, split: bool) -> Self { + self.split_views = split; + self + } + + /// For each refresh group, the runs a window is computed in: its + /// independent parts when they run apart, else 1. + pub fn view_parts(&self) -> Vec { + self.runs + .iter() + .map(|run| match self.split_views { + true => run.parts.len().max(1), + false => 1, + }) + .collect() + } + /// The runs' raw reads select series by the `Scan`'s label predicates /// when `label_pushdown`, and count their rows in `counts`. pub fn with_raw_reads(mut self, label_pushdown: bool, counts: Arc) -> Self { @@ -1016,8 +1099,10 @@ impl Precompute { if missing.is_empty() { return Ok(Computed::AlreadyStored); } - let outputs = { - let mut store = RunStore::for_partition(raw_data, views, partition); + // One run of `compiled` over the window: its roots' rows, and the + // worker pool's CPU it used. + let run = |compiled: &CompiledPhysicalDAG| -> Result<(Vec<(u64, Vec)>, u64), asap_executor::Error> { + let mut store = RunStore::for_partition(raw_data.clone(), views.clone(), partition); if !self.label_pushdown { store = store.without_label_pushdown(); } @@ -1025,7 +1110,7 @@ impl Precompute { store = store.with_raw_read_counts(counts.clone()); } let store = Arc::new(store); - let instance = group.compiled.instantiate(store)?; + let instance = compiled.instantiate(store)?; let context = RunContext::new( Scope::Ingestion { window_start_ms: start, @@ -1034,38 +1119,81 @@ impl Precompute { self.limits.clone(), )? .with_parallelism(self.parallelism); - let outputs = - block_on(instance.execute_ingestion(group.compiled.roots(), context.clone())?); + let outputs = block_on(instance.execute_ingestion(compiled.roots(), context.clone())?)?; + let rows = compiled + .roots() + .iter() + .copied() + .zip(outputs) + .map(|(root, batches)| (root, batches.iter().map(|batch| (**batch).clone()).collect())) + .collect(); + Ok((rows, context.parallel_cpu_ns())) + }; + let outputs = if self.split_views && group.parts.len() > 1 { + // The parts at once: all but the first on threads of their own, + // whose CPU (and their pool's) counts as this thread's. + std::thread::scope(|scope| { + let others: Vec<_> = group.parts[1..] + .iter() + .map(|part| { + let run = &run; + scope.spawn(move || { + let started = crate::metrics::thread_cpu_ns(); + run(part).map(|(rows, pool_ns)| { + ( + rows, + pool_ns + + crate::metrics::thread_cpu_ns().saturating_sub(started), + ) + }) + }) + }) + .collect(); + let mut rows = Vec::new(); + let mut first = run(&group.parts[0]); + for other in others { + let other = other + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + match (&mut first, other) { + (Ok((first_rows, cpu_ns)), Ok((more, more_ns))) => { + first_rows.extend(more); + *cpu_ns += more_ns; + } + (Ok(_), Err(error)) => first = Err(error), + (Err(_), _) => {} + } + } + let (part_rows, offloaded_ns) = first?; + rows.extend(part_rows); + crate::metrics::add_offloaded_cpu_ns(offloaded_ns); + Ok::<_, asap_executor::Error>(rows) + })? + } else { + let (rows, pool_ns) = run(&group.compiled)?; // The pool's work on this run counts as this thread's phase CPU. - crate::metrics::add_offloaded_cpu_ns(context.parallel_cpu_ns()); - outputs? + crate::metrics::add_offloaded_cpu_ns(pool_ns); + rows }; Ok(self.computed(window.group, missing, outputs)) } /// The rows of views `missing` (by index in the group) from a run's /// outputs, one per root. - fn computed>( + fn computed( &self, group: usize, missing: Vec, - outputs: impl IntoIterator>, + outputs: impl IntoIterator)>, ) -> Computed { let group = &self.runs[group]; - let mut by_root: BTreeMap> = group - .compiled - .roots() - .iter() - .copied() - .zip(outputs) - .collect(); + let mut by_root: BTreeMap> = outputs.into_iter().collect(); Computed::Ran( missing .into_iter() .map(|index| { let batches = by_root .remove(&(group.views[index].node_id as u64)) - .map(|batches| batches.iter().map(|batch| (**batch).clone()).collect()) .unwrap_or_default(); (index, batches) }) @@ -1090,6 +1218,18 @@ impl Precompute { let outputs = instance .execute_ingestion(run.compiled.roots(), context)? .await?; + let outputs = + run.compiled + .roots() + .iter() + .copied() + .zip(outputs) + .map(|(root, batches)| { + ( + root, + batches.iter().map(|batch| (**batch).clone()).collect(), + ) + }); Ok(this.computed(group, (0..run.views.len()).collect(), outputs)) } } diff --git a/data_plane/src/metrics.rs b/data_plane/src/metrics.rs index 14c6024b3..89911262b 100644 --- a/data_plane/src/metrics.rs +++ b/data_plane/src/metrics.rs @@ -160,6 +160,9 @@ pub struct WindowLatency { pub ready_max_ms: AtomicU64, /// The runs a window is split into, by series (1: one run). pub parts: AtomicU64, + /// The independent runs a window computes its views in at once (views + /// sharing no node below them); 1 when it is one run. + pub view_parts: AtomicU64, } impl WindowLatency { @@ -816,6 +819,19 @@ pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { windows.parts.load(Ordering::Relaxed) ); } + family( + &mut out, + "asap_precompute_window_view_parts", + "gauge", + "The independent runs (views sharing no node below them) a refresh group's window computes at once; 1 when it is one run.", + ); + for (group, windows) in metrics.precompute_windows.iter().enumerate() { + let _ = writeln!( + out, + "asap_precompute_window_view_parts{{group=\"{group}\"}} {}", + windows.view_parts.load(Ordering::Relaxed) + ); + } family( &mut out, "asap_precompute_busy_seconds_total", From c58ee18b77d1b0d2d633433d0e1fcdc30dfd4245 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 4 Dec 2026 19:18:21 +0000 Subject: [PATCH 7/7] perf(data_plane): name the precompute part threads A window's parts other than the first run on threads named precompute-part, so per-thread CPU sampling counts them as precompute; a part thread that cannot start fails the window. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/ingestion.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/data_plane/src/ingestion.rs b/data_plane/src/ingestion.rs index 45ac39e61..9507f553b 100644 --- a/data_plane/src/ingestion.rs +++ b/data_plane/src/ingestion.rs @@ -1137,18 +1137,26 @@ impl Precompute { .iter() .map(|part| { let run = &run; - scope.spawn(move || { - let started = crate::metrics::thread_cpu_ns(); - run(part).map(|(rows, pool_ns)| { - ( - rows, - pool_ns - + crate::metrics::thread_cpu_ns().saturating_sub(started), - ) + std::thread::Builder::new() + .name("precompute-part".into()) + .spawn_scoped(scope, move || { + let started = crate::metrics::thread_cpu_ns(); + run(part).map(|(rows, pool_ns)| { + ( + rows, + pool_ns + + crate::metrics::thread_cpu_ns() + .saturating_sub(started), + ) + }) }) - }) }) - .collect(); + .collect::>>() + .map_err(|error| { + asap_executor::Error::Invalid(format!( + "starting a precompute part: {error}" + )) + })?; let mut rows = Vec::new(); let mut first = run(&group.parts[0]); for other in others {