Skip to content
13 changes: 12 additions & 1 deletion data_plane/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -443,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<Option<PushGroup>> = match options.precompute_mode {
Expand Down Expand Up @@ -1633,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
Expand Down
182 changes: 165 additions & 17 deletions data_plane/src/ingestion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,11 @@ struct RefreshGroupRun {
/// `view_retention_margin_ms`: how long the store keeps their rows.
views: Vec<MaterializedView>,
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<CompiledPhysicalDAG>,
width_ms: i64,
/// The views of other groups its runs read.
reads: Vec<PhysicalASAPNodeId>,
Expand Down Expand Up @@ -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<u64> = set.iter().map(|&id| id as u64).collect();
compile(dag, &read_views, &roots).map_err(|error| IngestionError::Compile {
views: set.clone(),
error,
})
})
.collect::<Result<Vec<_>, _>>()?,
};
let metrics = index.metrics_below(&ids, &read);
let started_by = index.metrics_below(&ids, &BTreeSet::new());
let margin_ms = options.view_retention_margin_ms;
Expand All @@ -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(),
Expand Down Expand Up @@ -370,6 +390,7 @@ impl Ingestion {
label_pushdown: true,
raw_read_counts: None,
parallelism: 1,
split_views: true,
},
))
}
Expand Down Expand Up @@ -890,6 +911,44 @@ pub struct RefreshTaskGraph {
pub split_by_series: Vec<bool>,
}

/// `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<PhysicalASAPNodeId>,
) -> Vec<Vec<PhysicalASAPNodeId>> {
// Each set's views and the nodes below them.
let mut sets: Vec<(Vec<PhysicalASAPNodeId>, BTreeSet<PhysicalASAPNodeId>)> = 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<Vec<PhysicalASAPNodeId>> = 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
Expand Down Expand Up @@ -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 {
Expand All @@ -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<usize> {
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<RawReadCounts>) -> Self {
Expand Down Expand Up @@ -1016,16 +1099,18 @@ 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<Batch>)>, 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();
}
if let Some(counts) = &self.raw_read_counts {
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,
Expand All @@ -1034,38 +1119,89 @@ 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;
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::<std::io::Result<Vec<_>>>()
.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 {
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<B: std::ops::Deref<Target = Batch>>(
fn computed(
&self,
group: usize,
missing: Vec<usize>,
outputs: impl IntoIterator<Item = Vec<B>>,
outputs: impl IntoIterator<Item = (u64, Vec<Batch>)>,
) -> Computed {
let group = &self.runs[group];
let mut by_root: BTreeMap<u64, Vec<B>> = group
.compiled
.roots()
.iter()
.copied()
.zip(outputs)
.collect();
let mut by_root: BTreeMap<u64, Vec<Batch>> = 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)
})
Expand All @@ -1090,6 +1226,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))
}
}
Expand Down
6 changes: 6 additions & 0 deletions data_plane/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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,
Expand Down
16 changes: 16 additions & 0 deletions data_plane/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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",
Expand Down
Loading