From cc562072602653ff71c0d957d1d6e6b95d865edf Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 24 Nov 2026 10:53:01 -0500 Subject: [PATCH 1/2] refactor(query-engine): split precompute pipeline from build specification PrecomputePipeline now owns routing to workers, windows, watermarks, late-data policy and backpressure; what it builds comes from a BuildSpec { routing: R, builds: HashMap> } where each build is a WindowedBuild. PrecomputeEngine is the pipeline given the AggregationConfig-based spec (RoutingConfigSet + AggregationConfig). No behavior change; existing tests change only imports. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014qhwq4jq8TFcKGchhF7Hfb --- .../src/precompute_engine/aggregation_spec.rs | 397 ++++++++++++++++++ .../src/precompute_engine/build_spec.rs | 274 ++++++++++++ .../src/precompute_engine/engine.rs | 190 ++------- .../src/precompute_engine/ingest_source.rs | 193 ++------- .../src/precompute_engine/mod.rs | 7 +- .../src/precompute_engine/pipeline.rs | 220 ++++++++++ .../src/precompute_engine/series_router.rs | 34 +- .../src/precompute_engine/worker.rs | 285 +++---------- 8 files changed, 1031 insertions(+), 569 deletions(-) create mode 100644 asap-query-engine/src/precompute_engine/aggregation_spec.rs create mode 100644 asap-query-engine/src/precompute_engine/build_spec.rs create mode 100644 asap-query-engine/src/precompute_engine/pipeline.rs diff --git a/asap-query-engine/src/precompute_engine/aggregation_spec.rs b/asap-query-engine/src/precompute_engine/aggregation_spec.rs new file mode 100644 index 00000000..47754bfd --- /dev/null +++ b/asap-query-engine/src/precompute_engine/aggregation_spec.rs @@ -0,0 +1,397 @@ +//! The `AggregationConfig`-based build specification: each `AggregationConfig` +//! is one windowed build, and `RoutingConfigSet` routes series to them by +//! metric name and spatial filter. + +use crate::data_model::{AggregateCore, AggregationType, KeyByLabelValues}; +use crate::precompute_engine::accumulator_factory::{ + create_accumulator_updater, AccumulatorUpdater, +}; +use crate::precompute_engine::build_spec::{SeriesRouting, WindowedBuild}; +use crate::precompute_engine::worker::{ + extract_metric_name, parse_labels_from_series_key, PipelineWorker, +}; +use crate::precompute_operators::delta_set_aggregator_accumulator::DeltaSetAggregatorAccumulator; +use asap_types::aggregation_config::AggregationConfig; +use asap_types::streaming_config::StreamingConfig; +use promql_parser::label::Matcher; +use promql_parser::parser::{parse, Expr}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use tracing::warn; + +/// A worker running `AggregationConfig` builds. An alias rather than a +/// default type parameter so `Worker::new` infers without annotations. +pub type Worker = PipelineWorker; + +impl WindowedBuild for AggregationConfig { + /// Key population of the previous non-empty DeltaSetAggregator window. + /// DeltaSetAggregator outputs are differences between consecutive window + /// populations, so this state lives at group scope rather than inside a + /// single pane updater. + type CrossWindowState = HashSet; + + fn window_size_ms(&self) -> u64 { + self.window_size_ms + } + + fn slide_interval_ms(&self) -> u64 { + self.slide_interval_ms + } + + fn new_pane( + &self, + ) -> Result, Box> { + Ok(create_accumulator_updater(self)?) + } + + fn apply_sample( + &self, + pane: &mut dyn AccumulatorUpdater, + series_key: &str, + value: f64, + timestamp_ms: i64, + ) { + apply_sample(pane, series_key, value, timestamp_ms, self); + } + + /// DeltaSetAggregator windows are stateful key deltas, so a late sample + /// cannot be written as a standalone state. + fn forwards_late_samples(&self) -> bool { + self.aggregation_type != AggregationType::DeltaSetAggregator + } + + fn finalize_window( + &self, + merged: Box, + state: &mut Self::CrossWindowState, + ) -> Result, Box> { + finalize_closed_accumulator(merged, self, state) + } +} + +/// Extract grouping label values from a series key string based on the +/// aggregation config's `grouping_labels`. +/// +/// The series key format is: `metric_name{label1="val1",label2="val2",...}` +pub fn extract_key_from_series(series_key: &str, config: &AggregationConfig) -> KeyByLabelValues { + let labels = parse_labels_from_series_key(series_key); + let mut values = Vec::new(); + + for label_name in &config.grouping_labels.labels { + if let Some(val) = labels.get(label_name.as_str()) { + values.push(val.to_string()); + } else { + values.push(String::new()); + } + } + + KeyByLabelValues::new_with_labels(values) +} + +/// Route a single sample to `updater`, dispatching keyed vs. non-keyed based on config. +/// +/// For keyed accumulators (MultipleSum, CMS, HydraKLL), the key is extracted +/// from the series' **aggregated_labels** — these are the labels that become +/// the key dimension *inside* the sketch (e.g., which bucket in a CMS, which +/// entry in a MultipleSumAccumulator's HashMap). This matches the Arroyo SQL +/// pattern: `udf(concat_ws(';', aggregated_labels), value)`. +fn apply_sample( + updater: &mut dyn AccumulatorUpdater, + series_key: &str, + val: f64, + ts: i64, + config: &AggregationConfig, +) { + // Parse the series labels at most once and share them across value resolution + // and key extraction — both walk the same label string. Skip parsing entirely + // when neither path needs labels (non-keyed accumulator with no value_column), + // which is the common SUM/quantile case on the per-sample ingest hot path. + let keyed = updater.is_keyed(); + let labels = if keyed || config.value_column.is_some() { + parse_labels_from_series_key(series_key) + } else { + HashMap::new() + }; + + let value = resolve_sample_value(&labels, val, config); + if keyed { + let key = extract_aggregated_key_from_series(&labels, config); + updater.update_keyed(&key, value, ts); + } else { + updater.update_single(value, ts); + } +} + +/// Resolve which scalar to aggregate for a sample. +/// +/// The wire format collapses each sample to a single scalar (`wire_val`) plus a +/// set of labels carried in `series_key`. `wire_val` is whatever the source +/// considered the default value column (e.g. `pkt_len` for the netflow dataset). +/// But an aggregation may target a *different* column via `config.value_column` +/// — most importantly `COUNT(DISTINCT dstip)`, where the HLL sketch must hash +/// `dstip`, not the wire `pkt_len`. +/// +/// Rule (general, self-correcting): if `config.value_column` names a column that +/// is present among the series labels, aggregate that label's value; otherwise +/// fall back to `wire_val`. Numeric value columns such as `pkt_len` are never +/// sent as labels, so SUM / quantile / top-k transparently keep using the wire +/// scalar, while label-present distinct targets such as `dstip` get substituted. +/// +/// `labels` is the already-parsed label map for the sample's series key (parsed +/// once by `apply_sample` and shared with key extraction), so this is allocation- +/// free on the hot path. +/// +/// The label value is parsed as `f64`. This is lossless for the netflow IPv4 +/// `u32` columns (≤ 2^32 < 2^53) and consistent with the replay's int→f64 +/// convention; cardinality only requires distinct inputs to map to distinct +/// hashes, so the exact hash need not match the baseline engine. +/// +/// # Panics +/// Panics if `value_column` names a label whose value is not numeric. Non-numeric +/// distinct targets (e.g. `proto`) are not yet supported; this is a temporary +/// guard until the path is refactored to return a `Result` (see follow-up for a +/// byte/string hashing path). +pub(crate) fn resolve_sample_value( + labels: &HashMap<&str, &str>, + wire_val: f64, + config: &AggregationConfig, +) -> f64 { + let Some(col) = config.value_column.as_deref() else { + return wire_val; + }; + + let Some(raw) = labels.get(col) else { + return wire_val; + }; + + match raw.parse::() { + Ok(v) => v, + // Non-numeric distinct targets (e.g. COUNT(DISTINCT proto)) are not yet + // supported: silently falling back to the wire value would produce an + // INCORRECT aggregate, so fail loudly instead. This panic is a temporary + // measure — the longer-term fix is to make this path return a `Result` + // and propagate the error up to the caller. + Err(_) => panic!( + "value_column '{col}' label value {raw:?} is not numeric; non-numeric distinct \ + targets (e.g. COUNT(DISTINCT proto)) are not yet supported" + ), + } +} + +/// Extract aggregated label values from a series key string. +/// These are the labels that form the key dimension *inside* keyed accumulators +/// (MultipleSum, CMS, HydraKLL), matching Arroyo's `agg_columns`. +fn extract_aggregated_key_from_series( + labels: &HashMap<&str, &str>, + config: &AggregationConfig, +) -> KeyByLabelValues { + let mut values = Vec::new(); + + for label_name in &config.aggregated_labels.labels { + if let Some(val) = labels.get(label_name.as_str()) { + values.push(val.to_string()); + } else { + values.push(String::new()); + } + } + + KeyByLabelValues::new_with_labels(values) +} + +/// Convert a closed DeltaSetAggregator population into the stateful delta +/// format used by the Arroyo implementation: keys newly present in this +/// window go in `added`, and keys absent from this window go in `removed`. +/// +/// The updater can only collect the current window's observed keys. The +/// previous population therefore belongs to the group's cross-window state, +/// which survives the per-pane updater lifecycle and is isolated for each +/// `(agg_id, group_key)`. +fn finalize_closed_accumulator( + accumulator: Box, + config: &AggregationConfig, + previous_delta_set_keys: &mut HashSet, +) -> Result, Box> { + if config.aggregation_type != AggregationType::DeltaSetAggregator { + return Ok(accumulator); + } + + let delta = accumulator + .as_any() + .downcast_ref::() + .ok_or_else(|| { + format!( + "DeltaSetAggregator config produced {} instead of DeltaSetAggregatorAccumulator", + accumulator.type_name() + ) + })?; + let current_keys: HashSet = delta + .get_keys() + .ok_or("DeltaSetAggregator accumulator could not resolve its current keys")? + .into_iter() + .collect(); + + let added = current_keys + .difference(previous_delta_set_keys) + .cloned() + .collect(); + let removed = previous_delta_set_keys + .difference(¤t_keys) + .cloned() + .collect(); + *previous_delta_set_keys = current_keys; + + Ok(Box::new(DeltaSetAggregatorAccumulator::new_with_sets( + added, removed, + ))) +} + +/// Aggregation configuration enriched with its precompiled spatial filter. +#[derive(Clone)] +pub(crate) struct RoutingAggregationConfig { + pub(crate) config: Arc, + spatial_matchers: Vec, +} + +impl RoutingAggregationConfig { + fn matches_spatial_filter(&self, labels: &HashMap<&str, &str>) -> bool { + self.spatial_matchers.iter().all(|matcher| { + let value = labels.get(matcher.name.as_str()).copied().unwrap_or(""); + matcher.is_match(value) + }) + } +} + +/// The complete, atomically swappable routing configuration for ingest. +/// The default routes nothing. +#[derive(Default)] +pub struct RoutingConfigSet { + configs: Vec, +} + +impl RoutingConfigSet { + pub(crate) fn from_streaming_config(config: &StreamingConfig) -> Result { + Self::from_aggregation_configs(config.get_all_aggregation_configs().values().cloned()) + } + + pub(crate) fn from_aggregation_configs( + configs: impl IntoIterator, + ) -> Result { + let configs = configs + .into_iter() + .map(|config| { + let spatial_matchers = compile_spatial_filter(&config)?; + Ok(RoutingAggregationConfig { + config: Arc::new(config), + spatial_matchers, + }) + }) + .collect::, String>>()?; + Ok(Self { configs }) + } + + pub(crate) fn configs(&self) -> &[RoutingAggregationConfig] { + &self.configs + } +} + +impl SeriesRouting for RoutingConfigSet { + type Build = AggregationConfig; + + fn route_series(&self, series_key: &str, mut emit: F) { + let metric_name = extract_metric_name(series_key); + let labels = parse_labels_from_series_key(series_key); + for routing_config in &self.configs { + let config = &routing_config.config; + if (config.metric != metric_name && config.table_name.as_deref() != Some(metric_name)) + || !routing_config.matches_spatial_filter(&labels) + { + continue; + } + emit(config.aggregation_id, extract_group_key(&labels, config)); + } + } + + fn log_routing_diagnostic(&self, series_key: &str) { + let sample_metric = extract_metric_name(series_key); + warn!( + sample_metric, + sample_labels = %series_key, + num_agg_configs = self.configs.len(), + "routing: first batch diagnostic" + ); + for routing_config in &self.configs { + let cfg = &routing_config.config; + warn!( + agg_id = cfg.aggregation_id, + config_metric = %cfg.metric, + config_spatial_filter = %cfg.spatial_filter, + table_name = ?cfg.table_name, + "routing: agg config metric" + ); + } + } +} + +fn compile_spatial_filter(config: &AggregationConfig) -> Result, String> { + // SQL aggregation configs do not use PromQL label selectors. + if config.table_name.is_some() || config.spatial_filter.trim().is_empty() { + return Ok(Vec::new()); + } + + let filter = config.spatial_filter.trim(); + let selector_body = if filter.starts_with('{') || filter.ends_with('}') { + if !filter.starts_with('{') || !filter.ends_with('}') { + return Err(format!( + "aggregation_id {} has invalid spatialFilter {:?}: unmatched selector braces", + config.aggregation_id, config.spatial_filter + )); + } + filter.to_string() + } else { + format!("{{{filter}}}") + }; + let selector = format!("{}{}", config.metric, selector_body); + let Expr::VectorSelector(vector_selector) = parse(&selector).map_err(|error| { + format!( + "aggregation_id {} has invalid spatialFilter {:?}: {error}", + config.aggregation_id, config.spatial_filter + ) + })? + else { + return Err(format!( + "aggregation_id {} has invalid spatialFilter {:?}: expected a vector selector", + config.aggregation_id, config.spatial_filter + )); + }; + + let matchers = vector_selector.matchers; + if !matchers.or_matchers.is_empty() { + return Err(format!( + "aggregation_id {} spatialFilter must not use selector-level or", + config.aggregation_id + )); + } + let matchers = matchers.matchers; + if matchers.iter().any(|matcher| matcher.name == "__name__") { + return Err(format!( + "aggregation_id {} spatialFilter must not match __name__; use metric instead", + config.aggregation_id + )); + } + Ok(matchers) +} + +pub(crate) fn extract_group_key( + labels: &HashMap<&str, &str>, + config: &AggregationConfig, +) -> String { + let mut values = Vec::new(); + for label_name in &config.grouping_labels.labels { + if let Some(val) = labels.get(label_name.as_str()) { + values.push(*val); + } else { + values.push(""); + } + } + values.join(";") +} diff --git a/asap-query-engine/src/precompute_engine/build_spec.rs b/asap-query-engine/src/precompute_engine/build_spec.rs new file mode 100644 index 00000000..5a9fea85 --- /dev/null +++ b/asap-query-engine/src/precompute_engine/build_spec.rs @@ -0,0 +1,274 @@ +//! The build specification a [`PrecomputePipeline`] is given: which builds +//! each ingested series feeds, and how each build turns samples into +//! windowed state. The pipeline owns routing to workers, windows, watermarks, +//! late data and backpressure; it writes every closed window to its +//! `OutputSink`. +//! +//! [`PrecomputePipeline`]: crate::precompute_engine::pipeline::PrecomputePipeline + +use crate::data_model::AggregateCore; +use crate::precompute_engine::accumulator_factory::AccumulatorUpdater; +use std::collections::HashMap; +use std::sync::Arc; + +/// One windowed build, run per `(build id, group key)`: window geometry, +/// pane updaters, and how a closed window becomes the state written out. +pub trait WindowedBuild: Send + Sync + 'static { + /// State a group carries from one closed window to the next. + type CrossWindowState: Default + Send; + + fn window_size_ms(&self) -> u64; + + fn slide_interval_ms(&self) -> u64; + + /// A fresh updater for one pane. + fn new_pane( + &self, + ) -> Result, Box>; + + /// Feed one sample of series `series_key` into `pane`. + fn apply_sample( + &self, + pane: &mut dyn AccumulatorUpdater, + series_key: &str, + value: f64, + timestamp_ms: i64, + ); + + /// Whether `LateDataPolicy::ForwardToStore` may write a late sample as a + /// standalone state for its already-closed window. + fn forwards_late_samples(&self) -> bool; + + /// Turn the merged panes of a closed window into the state to write. + fn finalize_window( + &self, + merged: Box, + state: &mut Self::CrossWindowState, + ) -> Result, Box>; +} + +/// Decides which builds an ingested series feeds and its group key in each. +/// +/// Group keys are grouping label values joined by `;`; the pipeline splits +/// them back into the written key. `Default` must route nothing: the +/// pipeline holds it until `run` installs the first spec. +pub trait SeriesRouting: Default + Send + Sync + 'static { + type Build: WindowedBuild; + + /// Call `emit(build_id, group_key)` once per build `series_key` feeds. + fn route_series(&self, series_key: &str, emit: F); + + /// Log how this routing sees `series_key`; called once, on the first + /// ingested batch, to diagnose routing mismatches. + fn log_routing_diagnostic(&self, series_key: &str); +} + +/// What the pipeline builds: the ingest-side routing plus the builds workers +/// run, keyed by build id. +pub struct BuildSpec { + pub routing: R, + pub builds: HashMap>, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::drivers::ingest::prometheus_remote_write::DecodedSample; + use crate::precompute_engine::accumulator_factory::SumAccumulatorUpdater; + use crate::precompute_engine::config::LateDataPolicy; + use crate::precompute_engine::ingest_source::{route_decoded_samples, IngestContext}; + use crate::precompute_engine::output_sink::CapturingOutputSink; + use crate::precompute_engine::series_router::{SeriesRouter, WorkerMessage}; + use crate::precompute_engine::worker::{PipelineWorker, WorkerRuntimeConfig}; + use crate::precompute_operators::sum_accumulator::SumAccumulator; + use arc_swap::ArcSwap; + use std::sync::atomic::{AtomicI64, AtomicUsize}; + use std::time::Instant; + + const WINDOW_MS: u64 = 1_000; + + /// Emits the running total of every window closed so far, so each output + /// depends on the cross-window state. + struct RunningTotalBuild; + + impl WindowedBuild for RunningTotalBuild { + type CrossWindowState = f64; + + fn window_size_ms(&self) -> u64 { + WINDOW_MS + } + + fn slide_interval_ms(&self) -> u64 { + WINDOW_MS + } + + fn new_pane( + &self, + ) -> Result, Box> { + Ok(Box::new(SumAccumulatorUpdater::new())) + } + + fn apply_sample( + &self, + pane: &mut dyn AccumulatorUpdater, + _series_key: &str, + value: f64, + timestamp_ms: i64, + ) { + pane.update_single(value, timestamp_ms); + } + + fn forwards_late_samples(&self) -> bool { + false + } + + fn finalize_window( + &self, + merged: Box, + running_total: &mut f64, + ) -> Result, Box> { + let window = merged + .as_any() + .downcast_ref::() + .ok_or("pane is not a SumAccumulator")?; + *running_total += window.sum; + Ok(Box::new(SumAccumulator::with_sum(*running_total))) + } + } + + /// Routes every series to builds 1 and 2, grouped by the whole series key. + #[derive(Default)] + struct EveryBuildRouting; + + impl SeriesRouting for EveryBuildRouting { + type Build = RunningTotalBuild; + + fn route_series(&self, series_key: &str, mut emit: F) { + emit(1, series_key.to_string()); + emit(2, series_key.to_string()); + } + + fn log_routing_diagnostic(&self, _series_key: &str) {} + } + + fn running_total_worker( + sink: Arc, + allowed_lateness_ms: i64, + late_data_policy: LateDataPolicy, + ) -> PipelineWorker { + let (_tx, rx) = tokio::sync::mpsc::channel(1); + let watermark = Arc::new(AtomicI64::new(i64::MIN)); + PipelineWorker::new( + 0, + rx, + sink, + HashMap::from([(7, Arc::new(RunningTotalBuild))]), + WorkerRuntimeConfig { + max_buffer_per_series: 10_000, + allowed_lateness_ms, + pass_raw_samples: false, + raw_mode_aggregation_id: 0, + late_data_policy, + wall_clock_grace_period_ms: 0, + }, + Arc::new(AtomicUsize::new(0)), + watermark.clone(), + vec![watermark], + ) + } + + fn sample(timestamp_ms: i64, value: f64) -> Vec<(String, i64, f64)> { + vec![("cpu".to_string(), timestamp_ms, value)] + } + + #[test] + fn worker_carries_cross_window_state_of_a_non_aggregation_build() { + let sink = Arc::new(CapturingOutputSink::new()); + let mut worker = running_total_worker(sink.clone(), 0, LateDataPolicy::Drop); + + worker + .process_group_samples(7, "g", sample(100, 1.0)) + .unwrap(); + worker + .process_group_samples(7, "g", sample(1_500, 2.0)) + .unwrap(); + worker + .process_group_samples(7, "g", sample(2_500, 4.0)) + .unwrap(); + + let mut captured = sink.drain(); + captured.sort_by_key(|(output, _)| output.start_timestamp); + let windows: Vec<(u64, u64, f64)> = captured + .iter() + .map(|(output, state)| { + assert_eq!(output.aggregation_id, 7); + let sum = state + .as_any() + .downcast_ref::() + .expect("finalized state is a SumAccumulator") + .sum; + (output.start_timestamp, output.end_timestamp, sum) + }) + .collect(); + assert_eq!(windows, vec![(0, 1_000, 1.0), (1_000, 2_000, 3.0)]); + } + + #[test] + fn forward_to_store_drops_late_samples_for_builds_that_do_not_forward() { + let sink = Arc::new(CapturingOutputSink::new()); + let mut worker = running_total_worker(sink.clone(), 5_000, LateDataPolicy::ForwardToStore); + + worker + .process_group_samples(7, "g", sample(100, 1.0)) + .unwrap(); + worker + .process_group_samples(7, "g", sample(2_500, 2.0)) + .unwrap(); + assert_eq!(sink.drain().len(), 1, "window (0, 1000] closes"); + + // Within lateness, but its pane was already evicted. + worker + .process_group_samples(7, "g", sample(200, 8.0)) + .unwrap(); + assert!(sink.is_empty(), "late sample must not be forwarded"); + } + + #[tokio::test] + async fn ingest_routes_through_a_non_aggregation_routing() { + let (sender, mut receiver) = tokio::sync::mpsc::channel(4); + let ctx = IngestContext { + router: SeriesRouter::new(vec![sender]), + routing_configs: Arc::new(ArcSwap::from_pointee(EveryBuildRouting)), + pass_raw_samples: false, + }; + + let samples = vec![DecodedSample { + labels: "cpu{host=\"a\"}".to_string(), + timestamp_ms: 1_000, + value: 1.0, + }]; + route_decoded_samples(&ctx, samples, Instant::now()) + .await + .unwrap(); + drop(ctx); + + let mut routed = Vec::new(); + while let Some(message) = receiver.recv().await { + let WorkerMessage::GroupSamples { + agg_id, group_key, .. + } = message + else { + panic!("routing should produce GroupSamples"); + }; + routed.push((agg_id, group_key)); + } + routed.sort(); + assert_eq!( + routed, + vec![ + (1, "cpu{host=\"a\"}".to_string()), + (2, "cpu{host=\"a\"}".to_string()), + ] + ); + } +} diff --git a/asap-query-engine/src/precompute_engine/engine.rs b/asap-query-engine/src/precompute_engine/engine.rs index 4fd67cc7..762640a4 100644 --- a/asap-query-engine/src/precompute_engine/engine.rs +++ b/asap-query-engine/src/precompute_engine/engine.rs @@ -1,23 +1,17 @@ use crate::data_model::{AggregationType, StreamingConfig}; use crate::precompute_engine::accumulator_factory::create_accumulator_updater; +use crate::precompute_engine::aggregation_spec::RoutingConfigSet; +use crate::precompute_engine::build_spec::BuildSpec; use crate::precompute_engine::config::PrecomputeEngineConfig; -use crate::precompute_engine::ingest_source::{IngestContext, IngestSource, RoutingConfigSet}; +use crate::precompute_engine::ingest_source::IngestSource; use crate::precompute_engine::output_sink::OutputSink; -use crate::precompute_engine::series_router::{SeriesRouter, WorkerMessage}; -use crate::precompute_engine::worker::{Worker, WorkerRuntimeConfig}; -use arc_swap::ArcSwap; +use crate::precompute_engine::pipeline::{ + PipelineHandle, PrecomputePipeline, PrecomputeWorkerDiagnostics, +}; use asap_types::aggregation_config::AggregationConfig; use std::collections::HashMap; -use std::sync::atomic::{AtomicI64, AtomicUsize}; use std::sync::Arc; -use tokio::sync::mpsc; -use tracing::{info, warn}; - -/// Shared diagnostic counters readable from outside the engine. -pub struct PrecomputeWorkerDiagnostics { - pub worker_group_counts: Vec>, - pub worker_watermarks: Vec>, -} +use tracing::info; /// A cloneable handle for applying runtime config updates to a running engine. /// @@ -25,8 +19,7 @@ pub struct PrecomputeWorkerDiagnostics { /// Calling `update_streaming_config` swaps the ingest handler's routing configs /// atomically (lock-free via ArcSwap) and broadcasts the new map to all workers. pub struct PrecomputeEngineHandle { - router: SeriesRouter, - ingest_routing_configs: Arc>, + pipeline: PipelineHandle, } impl PrecomputeEngineHandle { @@ -51,9 +44,11 @@ impl PrecomputeEngineHandle { }) .collect(); - self.ingest_routing_configs.store(Arc::new(routing_configs)); - self.router - .broadcast_update_agg_configs(agg_configs_map) + self.pipeline + .update_spec(BuildSpec { + routing: routing_configs, + builds: agg_configs_map, + }) .await?; info!( @@ -64,26 +59,14 @@ impl PrecomputeEngineHandle { } } -/// The top-level precompute engine orchestrator. +/// The precompute engine: a `PrecomputePipeline` given an +/// `AggregationConfig`-based build specification from a `StreamingConfig`. /// -/// Creates worker threads and drives all registered ingest sources. /// Call `handle()` before `run()` to obtain a `PrecomputeEngineHandle` for /// applying runtime config updates while the engine is running. pub struct PrecomputeEngine { - config: PrecomputeEngineConfig, + pipeline: PrecomputePipeline, streaming_config: Arc, - output_sink: Arc, - diagnostics: Arc, - sources: Vec>, - /// Channels created at construction so handle() can be extracted before run(). - senders: Vec>, - receivers: Option>>, - /// Shared ingest routing configs, swappable at runtime. - ingest_routing_configs: Arc>, - /// Test-support wall-clock override, applied to every spawned worker. - /// See `with_now_ms_fn`. `None` in production — each worker keeps its - /// default `SystemTime::now`-backed clock. - now_ms_fn: Option i64 + Send + Sync>>, } impl PrecomputeEngine { @@ -93,44 +76,15 @@ impl PrecomputeEngine { output_sink: Arc, sources: Vec>, ) -> Self { - let worker_group_counts = (0..config.num_workers) - .map(|_| Arc::new(AtomicUsize::new(0))) - .collect(); - let worker_watermarks = (0..config.num_workers) - .map(|_| Arc::new(AtomicI64::new(i64::MIN))) - .collect(); - let diagnostics = Arc::new(PrecomputeWorkerDiagnostics { - worker_group_counts, - worker_watermarks, - }); - - let channel_size = config.channel_buffer_size; - let mut senders = Vec::with_capacity(config.num_workers); - let mut receivers = Vec::with_capacity(config.num_workers); - for _ in 0..config.num_workers { - let (tx, rx) = mpsc::channel::(channel_size); - senders.push(tx); - receivers.push(rx); - } - - let ingest_routing_configs = Arc::new(ArcSwap::from_pointee(RoutingConfigSet::empty())); - Self { - config, + pipeline: PrecomputePipeline::new(config, output_sink, sources), streaming_config, - output_sink, - diagnostics, - sources, - senders, - receivers: Some(receivers), - ingest_routing_configs, - now_ms_fn: None, } } /// Get a handle to worker diagnostics, readable even after `run()` starts. pub fn diagnostics(&self) -> Arc { - self.diagnostics.clone() + self.pipeline.diagnostics() } /// Test-support builder: override the wall-clock source used by every @@ -138,37 +92,27 @@ impl PrecomputeEngine { /// drive the fallback deterministically through the real ingest pipeline /// instead of racing a real clock with `tokio::time::sleep`. Must be /// called before `run()`. Production code never calls this. - pub fn with_now_ms_fn(mut self, f: impl Fn() -> i64 + Send + Sync + 'static) -> Self { - self.now_ms_fn = Some(Arc::new(f)); - self + pub fn with_now_ms_fn(self, f: impl Fn() -> i64 + Send + Sync + 'static) -> Self { + Self { + pipeline: self.pipeline.with_now_ms_fn(f), + streaming_config: self.streaming_config, + } } /// Return a handle for applying runtime config updates to this engine. /// Must be called before `run()`. pub fn handle(&self) -> PrecomputeEngineHandle { PrecomputeEngineHandle { - router: SeriesRouter::new(self.senders.clone()), - ingest_routing_configs: self.ingest_routing_configs.clone(), + pipeline: self.pipeline.handle(), } } /// Start the precompute engine. This spawns worker tasks and all registered /// ingest sources, then blocks until shutdown. - pub async fn run(mut self) -> Result<(), Box> { + pub async fn run(self) -> Result<(), Box> { validate_startup_aggregation_configs(&self.streaming_config)?; let routing_configs = RoutingConfigSet::from_streaming_config(&self.streaming_config) .map_err(|error| -> Box { error.into() })?; - self.ingest_routing_configs.store(Arc::new(routing_configs)); - - let num_workers = self.config.num_workers; - - let receivers = self - .receivers - .take() - .expect("PrecomputeEngine::run() called twice"); - - // Build the router from the pre-created senders. - let router = SeriesRouter::new(self.senders.clone()); // Build aggregation config map from streaming config for workers. let agg_configs: HashMap> = self @@ -178,84 +122,12 @@ impl PrecomputeEngine { .map(|(&id, cfg)| (id, Arc::new(cfg.clone()))) .collect(); - // Spawn workers - let mut worker_handles = Vec::with_capacity(num_workers); - for (id, rx) in receivers.into_iter().enumerate() { - let mut worker = Worker::new( - id, - rx, - self.output_sink.clone(), - agg_configs.clone(), - WorkerRuntimeConfig { - max_buffer_per_series: self.config.max_buffer_per_series, - allowed_lateness_ms: self.config.allowed_lateness_ms, - pass_raw_samples: self.config.pass_raw_samples, - raw_mode_aggregation_id: self.config.raw_mode_aggregation_id, - late_data_policy: self.config.late_data_policy, - wall_clock_grace_period_ms: self.config.wall_clock_grace_period_ms, - }, - self.diagnostics.worker_group_counts[id].clone(), - self.diagnostics.worker_watermarks[id].clone(), - self.diagnostics.worker_watermarks.to_vec(), - ); - if let Some(now_ms_fn) = &self.now_ms_fn { - let now_ms_fn = now_ms_fn.clone(); - worker.set_now_ms_fn(Box::new(move || now_ms_fn())); - } - let handle = tokio::spawn(async move { - worker.run().await; - }); - worker_handles.push(handle); - } - - info!("PrecomputeEngine started with {} workers", num_workers); - - // Build the ingest context shared by all sources. - // The ArcSwap pointer is the same one held by PrecomputeEngineHandle, so - // handle.update_streaming_config() is immediately visible to every source. - let ctx = IngestContext { - router: router.clone(), - routing_configs: self.ingest_routing_configs.clone(), - pass_raw_samples: self.config.pass_raw_samples, - }; - - // Flush timer: periodically signal workers to close idle windows. - let flush_router = router.clone(); - let flush_interval_ms = self.config.flush_interval_ms; - tokio::spawn(async move { - let mut interval = - tokio::time::interval(tokio::time::Duration::from_millis(flush_interval_ms)); - loop { - interval.tick().await; - if let Err(e) = flush_router.broadcast_flush().await { - warn!("Flush broadcast error: {}", e); - break; - } - } - }); - - // Spawn each ingest source. - let mut source_handles = Vec::with_capacity(self.sources.len()); - for source in self.sources { - let ctx = ctx.clone(); - let handle = tokio::spawn(async move { - if let Err(e) = source.run(ctx).await { - warn!("Ingest source error: {}", e); - } - }); - source_handles.push(handle); - } - - // Block until all sources finish (normally only on shutdown). - for handle in source_handles { - let _ = handle.await; - } - - for handle in worker_handles { - let _ = handle.await; - } - - Ok(()) + self.pipeline + .run(BuildSpec { + routing: routing_configs, + builds: agg_configs, + }) + .await } } diff --git a/asap-query-engine/src/precompute_engine/ingest_source.rs b/asap-query-engine/src/precompute_engine/ingest_source.rs index 4e2977ff..8c49d005 100644 --- a/asap-query-engine/src/precompute_engine/ingest_source.rs +++ b/asap-query-engine/src/precompute_engine/ingest_source.rs @@ -1,129 +1,34 @@ use crate::drivers::ingest::prometheus_remote_write::DecodedSample; +use crate::precompute_engine::aggregation_spec::RoutingConfigSet; +use crate::precompute_engine::build_spec::SeriesRouting; use crate::precompute_engine::series_router::{SeriesRouter, WorkerMessage}; -use crate::precompute_engine::worker::{extract_metric_name, parse_labels_from_series_key}; use arc_swap::ArcSwap; -use asap_types::aggregation_config::AggregationConfig; -use asap_types::streaming_config::StreamingConfig; -use promql_parser::label::Matcher; -use promql_parser::parser::{parse, Expr}; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Instant; -use tracing::{debug, warn}; +use tracing::debug; /// Everything a source needs to push decoded samples into the worker pool. -#[derive(Clone)] -pub struct IngestContext { - pub(crate) router: SeriesRouter, - /// Aggregation configs and their compiled spatial filters. - /// Shared with `PrecomputeEngineHandle`, whose swaps are immediately visible +pub struct IngestContext { + pub(crate) router: SeriesRouter, + /// Which builds each series feeds. + /// Shared with the pipeline handle, whose swaps are immediately visible /// on this lock-free read path. - pub(crate) routing_configs: Arc>, + pub(crate) routing_configs: Arc>, /// When true, skip group-key extraction and pass raw samples through. pub(crate) pass_raw_samples: bool, } -/// Aggregation configuration enriched with its precompiled spatial filter. -#[derive(Clone)] -pub(crate) struct RoutingAggregationConfig { - pub(crate) config: Arc, - spatial_matchers: Vec, -} - -impl RoutingAggregationConfig { - fn matches_spatial_filter(&self, labels: &HashMap<&str, &str>) -> bool { - self.spatial_matchers.iter().all(|matcher| { - let value = labels.get(matcher.name.as_str()).copied().unwrap_or(""); - matcher.is_match(value) - }) - } -} - -/// The complete, atomically swappable routing configuration for ingest. -pub(crate) struct RoutingConfigSet { - configs: Vec, -} - -impl RoutingConfigSet { - pub(crate) fn empty() -> Self { +// Manual impl: cloning the shared handles must not require `R: Clone`. +impl Clone for IngestContext { + fn clone(&self) -> Self { Self { - configs: Vec::new(), - } - } - - pub(crate) fn from_streaming_config(config: &StreamingConfig) -> Result { - Self::from_aggregation_configs(config.get_all_aggregation_configs().values().cloned()) - } - - pub(crate) fn from_aggregation_configs( - configs: impl IntoIterator, - ) -> Result { - let configs = configs - .into_iter() - .map(|config| { - let spatial_matchers = compile_spatial_filter(&config)?; - Ok(RoutingAggregationConfig { - config: Arc::new(config), - spatial_matchers, - }) - }) - .collect::, String>>()?; - Ok(Self { configs }) - } - - pub(crate) fn configs(&self) -> &[RoutingAggregationConfig] { - &self.configs - } -} - -fn compile_spatial_filter(config: &AggregationConfig) -> Result, String> { - // SQL aggregation configs do not use PromQL label selectors. - if config.table_name.is_some() || config.spatial_filter.trim().is_empty() { - return Ok(Vec::new()); - } - - let filter = config.spatial_filter.trim(); - let selector_body = if filter.starts_with('{') || filter.ends_with('}') { - if !filter.starts_with('{') || !filter.ends_with('}') { - return Err(format!( - "aggregation_id {} has invalid spatialFilter {:?}: unmatched selector braces", - config.aggregation_id, config.spatial_filter - )); + router: self.router.clone(), + routing_configs: self.routing_configs.clone(), + pass_raw_samples: self.pass_raw_samples, } - filter.to_string() - } else { - format!("{{{filter}}}") - }; - let selector = format!("{}{}", config.metric, selector_body); - let Expr::VectorSelector(vector_selector) = parse(&selector).map_err(|error| { - format!( - "aggregation_id {} has invalid spatialFilter {:?}: {error}", - config.aggregation_id, config.spatial_filter - ) - })? - else { - return Err(format!( - "aggregation_id {} has invalid spatialFilter {:?}: expected a vector selector", - config.aggregation_id, config.spatial_filter - )); - }; - - let matchers = vector_selector.matchers; - if !matchers.or_matchers.is_empty() { - return Err(format!( - "aggregation_id {} spatialFilter must not use selector-level or", - config.aggregation_id - )); - } - let matchers = matchers.matchers; - if matchers.iter().any(|matcher| matcher.name == "__name__") { - return Err(format!( - "aggregation_id {} spatialFilter must not match __name__; use metric instead", - config.aggregation_id - )); } - Ok(matchers) } /// An ingest source for the precompute engine. @@ -132,33 +37,18 @@ fn compile_spatial_filter(config: &AggregationConfig) -> Result, St /// into the engine via [`route_decoded_samples`]. #[allow(clippy::double_must_use)] #[async_trait::async_trait] -pub trait IngestSource: Send + Sync { +pub trait IngestSource: Send + Sync { async fn run( self: Box, - ctx: IngestContext, + ctx: IngestContext, ) -> Result<(), Box>; } -pub(crate) fn extract_group_key( - labels: &HashMap<&str, &str>, - config: &AggregationConfig, -) -> String { - let mut values = Vec::new(); - for label_name in &config.grouping_labels.labels { - if let Some(val) = labels.get(label_name.as_str()) { - values.push(*val); - } else { - values.push(""); - } - } - values.join(";") -} - /// Group decoded samples by (agg_id, group_key) and route them to workers. /// /// Returns an error if the router fails to deliver any message. -pub(crate) async fn route_decoded_samples( - ctx: &IngestContext, +pub(crate) async fn route_decoded_samples( + ctx: &IngestContext, samples: Vec, ingest_received_at: Instant, ) -> Result<(), Box> { @@ -174,7 +64,7 @@ pub(crate) async fn route_decoded_samples( .or_default() .push((s.timestamp_ms, s.value)); } - let messages: Vec = by_series + let messages: Vec> = by_series .into_iter() .map(|(k, v)| WorkerMessage::RawSamples { series_key: k.to_string(), @@ -199,48 +89,24 @@ pub(crate) async fn route_decoded_samples( // Load routing configs once per request (lock-free ArcSwap read). let routing_configs = ctx.routing_configs.load(); - // On first batch: log config metrics vs sample metric to diagnose mismatches. + // On first batch: log routing vs sample metric to diagnose mismatches. static FIRST_BATCH_LOGGED: AtomicBool = AtomicBool::new(false); if !FIRST_BATCH_LOGGED.swap(true, Ordering::Relaxed) { if let Some(first) = samples.first() { - let sample_metric = extract_metric_name(&first.labels); - warn!( - sample_metric, - sample_labels = %first.labels, - num_agg_configs = routing_configs.configs().len(), - "routing: first batch diagnostic" - ); - for routing_config in routing_configs.configs() { - let cfg = &routing_config.config; - warn!( - agg_id = cfg.aggregation_id, - config_metric = %cfg.metric, - config_spatial_filter = %cfg.spatial_filter, - table_name = ?cfg.table_name, - "routing: agg config metric" - ); - } + routing_configs.log_routing_diagnostic(&first.labels); } } let mut matched_samples: usize = 0; for s in &samples { - let metric_name = extract_metric_name(&s.labels); - let labels = parse_labels_from_series_key(&s.labels); - for routing_config in routing_configs.configs() { - let config = &routing_config.config; - if (config.metric != metric_name && config.table_name.as_deref() != Some(metric_name)) - || !routing_config.matches_spatial_filter(&labels) - { - continue; - } + routing_configs.route_series(&s.labels, |agg_id, group_key| { matched_samples += 1; - let group_key = extract_group_key(&labels, config); - by_group - .entry((config.aggregation_id, group_key)) - .or_default() - .push((s.labels.clone(), s.timestamp_ms, s.value)); - } + by_group.entry((agg_id, group_key)).or_default().push(( + s.labels.clone(), + s.timestamp_ms, + s.value, + )); + }); } debug!( @@ -250,7 +116,7 @@ pub(crate) async fn route_decoded_samples( "routing: batch match summary" ); - let messages: Vec = by_group + let messages: Vec> = by_group .into_iter() .map( |((agg_id, group_key), samples)| WorkerMessage::GroupSamples { @@ -271,6 +137,7 @@ pub(crate) async fn route_decoded_samples( #[cfg(test)] mod tests { use super::*; + use asap_types::aggregation_config::AggregationConfig; use asap_types::enums::{AggregationType, WindowType}; use promql_utilities::data_model::key_by_label_names::KeyByLabelNames; use tokio::sync::mpsc::error::TryRecvError; diff --git a/asap-query-engine/src/precompute_engine/mod.rs b/asap-query-engine/src/precompute_engine/mod.rs index 702ed8e7..21cf65d6 100644 --- a/asap-query-engine/src/precompute_engine/mod.rs +++ b/asap-query-engine/src/precompute_engine/mod.rs @@ -1,4 +1,6 @@ pub mod accumulator_factory; +pub mod aggregation_spec; +pub mod build_spec; pub mod config; pub mod csv_ingest; mod engine; @@ -6,13 +8,16 @@ mod ingest_handler; pub mod ingest_source; pub mod json_ingest; pub mod output_sink; +pub mod pipeline; pub mod series_buffer; pub mod series_router; pub mod window_manager; pub mod worker; +pub use build_spec::{BuildSpec, SeriesRouting, WindowedBuild}; pub use csv_ingest::{CsvFileIngestConfig, CsvFileIngestSource}; -pub use engine::{PrecomputeEngine, PrecomputeEngineHandle, PrecomputeWorkerDiagnostics}; +pub use engine::{PrecomputeEngine, PrecomputeEngineHandle}; pub use ingest_handler::{HttpIngestConfig, HttpIngestSource}; pub use ingest_source::{IngestContext, IngestSource}; pub use json_ingest::{JsonFileIngestConfig, JsonFileIngestSource, TimestampUnit}; +pub use pipeline::{PipelineHandle, PrecomputePipeline, PrecomputeWorkerDiagnostics}; diff --git a/asap-query-engine/src/precompute_engine/pipeline.rs b/asap-query-engine/src/precompute_engine/pipeline.rs new file mode 100644 index 00000000..1959952e --- /dev/null +++ b/asap-query-engine/src/precompute_engine/pipeline.rs @@ -0,0 +1,220 @@ +use crate::precompute_engine::build_spec::{BuildSpec, SeriesRouting}; +use crate::precompute_engine::config::PrecomputeEngineConfig; +use crate::precompute_engine::ingest_source::{IngestContext, IngestSource}; +use crate::precompute_engine::output_sink::OutputSink; +use crate::precompute_engine::series_router::{SeriesRouter, WorkerMessage}; +use crate::precompute_engine::worker::{PipelineWorker, WorkerRuntimeConfig}; +use arc_swap::ArcSwap; +use std::sync::atomic::{AtomicI64, AtomicUsize}; +use std::sync::Arc; +use tokio::sync::mpsc; +use tracing::{info, warn}; + +/// Shared diagnostic counters readable from outside the engine. +pub struct PrecomputeWorkerDiagnostics { + pub worker_group_counts: Vec>, + pub worker_watermarks: Vec>, +} + +/// A cloneable handle for swapping the build specification of a running +/// pipeline. +/// +/// Obtained via `PrecomputePipeline::handle()` before calling `run()`. +pub struct PipelineHandle { + router: SeriesRouter, + routing: Arc>, +} + +impl PipelineHandle { + /// Swap the ingest routing atomically (lock-free via ArcSwap), then + /// broadcast the new builds to all workers via their message channels. + pub async fn update_spec( + &self, + spec: BuildSpec, + ) -> Result<(), Box> { + self.routing.store(Arc::new(spec.routing)); + self.router.broadcast_update_agg_configs(spec.builds).await + } +} + +/// The precompute pipeline: routes series to workers, runs each build's +/// windows, watermarks and late-data policy per group, and writes closed +/// windows to the output sink. What it builds comes from the `BuildSpec` +/// given to `run`. +pub struct PrecomputePipeline { + config: PrecomputeEngineConfig, + output_sink: Arc, + diagnostics: Arc, + sources: Vec>>, + /// Channels created at construction so handle() can be extracted before run(). + senders: Vec>>, + receivers: Option>>>, + /// Shared ingest routing, swappable at runtime. + routing: Arc>, + /// Test-support wall-clock override, applied to every spawned worker. + /// See `with_now_ms_fn`. `None` in production — each worker keeps its + /// default `SystemTime::now`-backed clock. + now_ms_fn: Option i64 + Send + Sync>>, +} + +impl PrecomputePipeline { + pub fn new( + config: PrecomputeEngineConfig, + output_sink: Arc, + sources: Vec>>, + ) -> Self { + let worker_group_counts = (0..config.num_workers) + .map(|_| Arc::new(AtomicUsize::new(0))) + .collect(); + let worker_watermarks = (0..config.num_workers) + .map(|_| Arc::new(AtomicI64::new(i64::MIN))) + .collect(); + let diagnostics = Arc::new(PrecomputeWorkerDiagnostics { + worker_group_counts, + worker_watermarks, + }); + + let channel_size = config.channel_buffer_size; + let mut senders = Vec::with_capacity(config.num_workers); + let mut receivers = Vec::with_capacity(config.num_workers); + for _ in 0..config.num_workers { + let (tx, rx) = mpsc::channel::>(channel_size); + senders.push(tx); + receivers.push(rx); + } + + let routing = Arc::new(ArcSwap::from_pointee(R::default())); + + Self { + config, + output_sink, + diagnostics, + sources, + senders, + receivers: Some(receivers), + routing, + now_ms_fn: None, + } + } + + /// Get a handle to worker diagnostics, readable even after `run()` starts. + pub fn diagnostics(&self) -> Arc { + self.diagnostics.clone() + } + + /// Test-support builder: override the wall-clock source used by every + /// worker's wall-clock fallback (`flush_all`). Must be called before + /// `run()`. Production code never calls this. + pub fn with_now_ms_fn(mut self, f: impl Fn() -> i64 + Send + Sync + 'static) -> Self { + self.now_ms_fn = Some(Arc::new(f)); + self + } + + /// Return a handle for swapping the build specification of this + /// pipeline. Must be called before `run()`. + pub fn handle(&self) -> PipelineHandle { + PipelineHandle { + router: SeriesRouter::new(self.senders.clone()), + routing: self.routing.clone(), + } + } + + /// Install `spec`, spawn worker tasks and all registered ingest sources, + /// then block until shutdown. + pub async fn run( + mut self, + spec: BuildSpec, + ) -> Result<(), Box> { + let BuildSpec { routing, builds } = spec; + self.routing.store(Arc::new(routing)); + + let num_workers = self.config.num_workers; + + let receivers = self + .receivers + .take() + .expect("PrecomputeEngine::run() called twice"); + + // Build the router from the pre-created senders. + let router = SeriesRouter::new(self.senders.clone()); + + // Spawn workers + let mut worker_handles = Vec::with_capacity(num_workers); + for (id, rx) in receivers.into_iter().enumerate() { + let mut worker = PipelineWorker::new( + id, + rx, + self.output_sink.clone(), + builds.clone(), + WorkerRuntimeConfig { + max_buffer_per_series: self.config.max_buffer_per_series, + allowed_lateness_ms: self.config.allowed_lateness_ms, + pass_raw_samples: self.config.pass_raw_samples, + raw_mode_aggregation_id: self.config.raw_mode_aggregation_id, + late_data_policy: self.config.late_data_policy, + wall_clock_grace_period_ms: self.config.wall_clock_grace_period_ms, + }, + self.diagnostics.worker_group_counts[id].clone(), + self.diagnostics.worker_watermarks[id].clone(), + self.diagnostics.worker_watermarks.to_vec(), + ); + if let Some(now_ms_fn) = &self.now_ms_fn { + let now_ms_fn = now_ms_fn.clone(); + worker.set_now_ms_fn(Box::new(move || now_ms_fn())); + } + let handle = tokio::spawn(async move { + worker.run().await; + }); + worker_handles.push(handle); + } + + info!("PrecomputeEngine started with {} workers", num_workers); + + // Build the ingest context shared by all sources. + // The ArcSwap pointer is the same one held by PipelineHandle, so + // handle.update_spec() is immediately visible to every source. + let ctx = IngestContext { + router: router.clone(), + routing_configs: self.routing.clone(), + pass_raw_samples: self.config.pass_raw_samples, + }; + + // Flush timer: periodically signal workers to close idle windows. + let flush_router = router.clone(); + let flush_interval_ms = self.config.flush_interval_ms; + tokio::spawn(async move { + let mut interval = + tokio::time::interval(tokio::time::Duration::from_millis(flush_interval_ms)); + loop { + interval.tick().await; + if let Err(e) = flush_router.broadcast_flush().await { + warn!("Flush broadcast error: {}", e); + break; + } + } + }); + + // Spawn each ingest source. + let mut source_handles = Vec::with_capacity(self.sources.len()); + for source in self.sources { + let ctx = ctx.clone(); + let handle = tokio::spawn(async move { + if let Err(e) = source.run(ctx).await { + warn!("Ingest source error: {}", e); + } + }); + source_handles.push(handle); + } + + // Block until all sources finish (normally only on shutdown). + for handle in source_handles { + let _ = handle.await; + } + + for handle in worker_handles { + let _ = handle.await; + } + + Ok(()) + } +} diff --git a/asap-query-engine/src/precompute_engine/series_router.rs b/asap-query-engine/src/precompute_engine/series_router.rs index 33b92e28..2e841d27 100644 --- a/asap-query-engine/src/precompute_engine/series_router.rs +++ b/asap-query-engine/src/precompute_engine/series_router.rs @@ -6,9 +6,10 @@ use std::time::Instant; use tokio::sync::mpsc; use xxhash_rust::xxh64::xxh64; -/// A message sent from the router to a worker. +/// A message sent from the router to a worker. `B` is the build type the +/// workers run (see `WindowedBuild`); an "aggregation" here is one build. #[derive(Debug)] -pub enum WorkerMessage { +pub enum WorkerMessage { /// A batch of samples for the same series, routed by series key. /// Used in `pass_raw_samples` mode where no aggregation is needed. RawSamples { @@ -34,21 +35,30 @@ pub enum WorkerMessage { Flush, /// Graceful shutdown. Shutdown, - /// Push a new set of aggregation configs to this worker. + /// Push a new set of aggregation builds to this worker. /// Workers replace their local map on receipt; new agg_ids are picked up /// lazily the next time a matching sample arrives. - UpdateAggConfigs(HashMap>), + UpdateAggConfigs(HashMap>), } /// Routes incoming samples to one of N workers based on a consistent hash. -#[derive(Clone)] -pub struct SeriesRouter { - senders: Vec>, +pub struct SeriesRouter { + senders: Vec>>, num_workers: usize, } -impl SeriesRouter { - pub fn new(senders: Vec>) -> Self { +// Manual impl: cloning the senders must not require `B: Clone`. +impl Clone for SeriesRouter { + fn clone(&self) -> Self { + Self { + senders: self.senders.clone(), + num_workers: self.num_workers, + } + } +} + +impl SeriesRouter { + pub fn new(senders: Vec>>) -> Self { let num_workers = senders.len(); Self { senders, @@ -62,11 +72,11 @@ impl SeriesRouter { /// Messages within a single worker are sent sequentially to preserve ordering. pub async fn route_group_batch( &self, - messages: Vec, + messages: Vec>, _ingest_received_at: Instant, ) -> Result<(), Box> { // Group messages by target worker index - let mut per_worker: HashMap> = HashMap::new(); + let mut per_worker: HashMap>> = HashMap::new(); for msg in messages { let worker_idx = match &msg { WorkerMessage::GroupSamples { @@ -113,7 +123,7 @@ impl SeriesRouter { /// Broadcast updated aggregation configs to all workers. pub async fn broadcast_update_agg_configs( &self, - agg_configs: HashMap>, + agg_configs: HashMap>, ) -> Result<(), Box> { for (i, sender) in self.senders.iter().enumerate() { sender diff --git a/asap-query-engine/src/precompute_engine/worker.rs b/asap-query-engine/src/precompute_engine/worker.rs index c98f1a97..67dcd400 100644 --- a/asap-query-engine/src/precompute_engine/worker.rs +++ b/asap-query-engine/src/precompute_engine/worker.rs @@ -1,15 +1,12 @@ -use crate::data_model::{AggregateCore, AggregationType, KeyByLabelValues, PrecomputedOutput}; -use crate::precompute_engine::accumulator_factory::{ - create_accumulator_updater, AccumulatorUpdater, -}; +use crate::data_model::{AggregateCore, KeyByLabelValues, PrecomputedOutput}; +use crate::precompute_engine::accumulator_factory::AccumulatorUpdater; +use crate::precompute_engine::build_spec::WindowedBuild; use crate::precompute_engine::config::LateDataPolicy; use crate::precompute_engine::output_sink::OutputSink; use crate::precompute_engine::series_router::WorkerMessage; use crate::precompute_engine::window_manager::{WindowBoundary, WindowManager, WindowManagerError}; -use crate::precompute_operators::delta_set_aggregator_accumulator::DeltaSetAggregatorAccumulator; use crate::precompute_operators::sum_accumulator::SumAccumulator; -use asap_types::aggregation_config::AggregationConfig; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap}; use std::sync::atomic::{AtomicI64, AtomicUsize, Ordering}; use std::sync::Arc; use tokio::sync::mpsc; @@ -21,16 +18,13 @@ use tracing::{debug, debug_span, info, warn}; /// All raw series sharing the same grouping label values feed into the same /// accumulator, producing one output per (group_key, window) — exactly like /// Arroyo's `GROUP BY window, key`. -struct GroupState { - config: Arc, +struct GroupState { + config: Arc, window_manager: WindowManager, /// Active panes keyed by pane_start_ms. active_panes: BTreeMap>, - /// Key population emitted by the previous non-empty DeltaSetAggregator - /// window for this (aggregation_id, group_key). DeltaSetAggregator outputs - /// are differences between consecutive window populations, so this state - /// must live at group scope rather than inside a single pane updater. - delta_set_previous_keys: HashSet, + /// The build's state carried between this group's closed windows. + cross_window_state: B::CrossWindowState, /// Per-group watermark: tracks the maximum timestamp seen across all /// series in this group on this worker. previous_watermark_ms: i64, @@ -55,7 +49,7 @@ struct GroupState { pane_wall_clock_last_touch_ms: BTreeMap, } -impl GroupState { +impl GroupState { /// Drop wall-clock-last-touch entries whose pane no longer exists in /// `active_panes`. Called after window-close cycles in /// `process_group_samples` and `flush_all` so the bookkeeping doesn't @@ -82,22 +76,22 @@ pub struct WorkerRuntimeConfig { /// Worker that processes samples for a shard of the group space. /// -/// Unlike the old per-series design, this worker maintains accumulators -/// keyed by `(agg_id, group_key)`. Multiple raw series with the same +/// This worker maintains accumulators keyed by `(agg_id, group_key)`, where +/// `agg_id` names one build `B`. Multiple raw series with the same /// grouping label values share a single accumulator, producing one merged /// output per window — matching Arroyo's `GROUP BY` semantics. -pub struct Worker { +pub struct PipelineWorker { id: usize, - receiver: mpsc::Receiver, + receiver: mpsc::Receiver>, output_sink: Arc, /// Map from (agg_id, group_key) to per-group state. /// Per-group state, keyed by `agg_id` then by an interned `Arc` /// group key. Nesting lets the per-sample hot path look up by `&str` /// (no allocation); the group-key string is allocated once, on first /// sight of the group, and shared via the `Arc`. - group_states: HashMap, GroupState>>, - /// Aggregation configs, keyed by aggregation_id. - agg_configs: HashMap>, + group_states: HashMap, GroupState>>, + /// Builds, keyed by agg_id. + agg_configs: HashMap>, /// Allowed lateness in ms. allowed_lateness_ms: i64, /// When true, skip aggregation and pass raw samples through. @@ -123,13 +117,13 @@ pub struct Worker { now_ms_fn: Box i64 + Send + Sync>, } -impl Worker { +impl PipelineWorker { #[allow(clippy::too_many_arguments)] pub fn new( id: usize, - receiver: mpsc::Receiver, + receiver: mpsc::Receiver>, output_sink: Arc, - agg_configs: HashMap>, + agg_configs: HashMap>, runtime_config: WorkerRuntimeConfig, group_count: Arc, worker_watermark: Arc, @@ -298,15 +292,14 @@ impl Worker { if let Some(accumulator) = merge_panes_for_window(&mut active_panes, &pane_starts) { - let accumulator = match finalize_closed_accumulator( + let accumulator = match state.config.finalize_window( accumulator, - &state.config, - &mut state.delta_set_previous_keys, + &mut state.cross_window_state, ) { Ok(accumulator) => accumulator, Err(e) => { warn!( - "Worker {}: failed to finalize DeltaSetAggregator \ + "Worker {}: failed to finalize window \ for removed agg_id={}: {}", self.id, agg_id, e ); @@ -376,7 +369,7 @@ impl Worker { &mut self, agg_id: u64, group_key: &str, - ) -> Result, WindowManagerError> { + ) -> Result>, WindowManagerError> { // Fast path: group already exists — borrow-based lookup, no allocation. let exists = self .group_states @@ -389,13 +382,13 @@ impl Worker { }; let gs = GroupState { window_manager: WindowManager::new( - config.window_size_ms, - config.slide_interval_ms, + config.window_size_ms(), + config.slide_interval_ms(), WindowBoundary::OpenClosed, )?, config, active_panes: BTreeMap::new(), - delta_set_previous_keys: HashSet::new(), + cross_window_state: B::CrossWindowState::default(), previous_watermark_ms: i64::MIN, pane_wall_clock_last_touch_ms: BTreeMap::new(), }; @@ -497,19 +490,20 @@ impl Worker { ); continue; } - LateDataPolicy::ForwardToStore - if state.config.aggregation_type == AggregationType::DeltaSetAggregator => - { + LateDataPolicy::ForwardToStore if !state.config.forwards_late_samples() => { warn!( - "Dropping late DeltaSetAggregator sample for evicted pane ({}, {}]: ForwardToStore is unsupported for stateful key deltas", + "Dropping late sample for evicted pane ({}, {}]: ForwardToStore is unsupported for agg_id={}", pane_start, - pane_end + pane_end, + agg_id ); continue; } LateDataPolicy::ForwardToStore => { - let mut updater = create_accumulator_updater(&state.config)?; - apply_sample(&mut *updater, series_key, *val, *ts, &state.config); + let mut updater = state.config.new_pane()?; + state + .config + .apply_sample(&mut *updater, series_key, *val, *ts); let key = build_group_key_label_values(group_key); let output = PrecomputedOutput::new( window_start as u64, @@ -539,12 +533,12 @@ impl Worker { .insert(pane_start, now_ms); let updater = match state.active_panes.entry(pane_start) { std::collections::btree_map::Entry::Occupied(e) => e.into_mut(), - std::collections::btree_map::Entry::Vacant(e) => { - e.insert(create_accumulator_updater(&state.config)?) - } + std::collections::btree_map::Entry::Vacant(e) => e.insert(state.config.new_pane()?), }; - apply_sample(&mut **updater, series_key, *val, *ts, &state.config); + state + .config + .apply_sample(&mut **updater, series_key, *val, *ts); } // Check for closed windows @@ -558,11 +552,9 @@ impl Worker { if let Some(accumulator) = merge_panes_for_window(&mut state.active_panes, &pane_starts) { - let accumulator = finalize_closed_accumulator( - accumulator, - &state.config, - &mut state.delta_set_previous_keys, - )?; + let accumulator = state + .config + .finalize_window(accumulator, &mut state.cross_window_state)?; let key = build_group_key_label_values(group_key); let output = PrecomputedOutput::new( *window_start as u64, @@ -711,11 +703,9 @@ impl Worker { if let Some(accumulator) = merge_panes_for_window(&mut state.active_panes, &pane_starts) { - let accumulator = finalize_closed_accumulator( - accumulator, - &state.config, - &mut state.delta_set_previous_keys, - )?; + let accumulator = state + .config + .finalize_window(accumulator, &mut state.cross_window_state)?; let key = build_group_key_label_values(group_key); let output = PrecomputedOutput::new( *window_start as u64, @@ -802,11 +792,9 @@ impl Worker { if let Some(accumulator) = merge_panes_for_window(&mut state.active_panes, &pane_starts) { - let accumulator = finalize_closed_accumulator( - accumulator, - &state.config, - &mut state.delta_set_previous_keys, - )?; + let accumulator = state + .config + .finalize_window(accumulator, &mut state.cross_window_state)?; let key = build_group_key_label_values(group_key); let output = PrecomputedOutput::new( *window_start as u64, @@ -887,25 +875,6 @@ pub fn extract_metric_name(series_key: &str) -> &str { } } -/// Extract grouping label values from a series key string based on the -/// aggregation config's `grouping_labels`. -/// -/// The series key format is: `metric_name{label1="val1",label2="val2",...}` -pub fn extract_key_from_series(series_key: &str, config: &AggregationConfig) -> KeyByLabelValues { - let labels = parse_labels_from_series_key(series_key); - let mut values = Vec::new(); - - for label_name in &config.grouping_labels.labels { - if let Some(val) = labels.get(label_name.as_str()) { - values.push(val.to_string()); - } else { - values.push(String::new()); - } - } - - KeyByLabelValues::new_with_labels(values) -} - /// Parse label key-value pairs from a series key string. /// `"metric{a=\"b\",c=\"d\"}"` → `{("a", "b"), ("c", "d")}` pub fn parse_labels_from_series_key(series_key: &str) -> HashMap<&str, &str> { @@ -959,116 +928,6 @@ pub fn parse_labels_from_series_key(series_key: &str) -> HashMap<&str, &str> { labels } -/// Route a single sample to `updater`, dispatching keyed vs. non-keyed based on config. -/// -/// For keyed accumulators (MultipleSum, CMS, HydraKLL), the key is extracted -/// from the series' **aggregated_labels** — these are the labels that become -/// the key dimension *inside* the sketch (e.g., which bucket in a CMS, which -/// entry in a MultipleSumAccumulator's HashMap). This matches the Arroyo SQL -/// pattern: `udf(concat_ws(';', aggregated_labels), value)`. -fn apply_sample( - updater: &mut dyn AccumulatorUpdater, - series_key: &str, - val: f64, - ts: i64, - config: &AggregationConfig, -) { - // Parse the series labels at most once and share them across value resolution - // and key extraction — both walk the same label string. Skip parsing entirely - // when neither path needs labels (non-keyed accumulator with no value_column), - // which is the common SUM/quantile case on the per-sample ingest hot path. - let keyed = updater.is_keyed(); - let labels = if keyed || config.value_column.is_some() { - parse_labels_from_series_key(series_key) - } else { - HashMap::new() - }; - - let value = resolve_sample_value(&labels, val, config); - if keyed { - let key = extract_aggregated_key_from_series(&labels, config); - updater.update_keyed(&key, value, ts); - } else { - updater.update_single(value, ts); - } -} - -/// Resolve which scalar to aggregate for a sample. -/// -/// The wire format collapses each sample to a single scalar (`wire_val`) plus a -/// set of labels carried in `series_key`. `wire_val` is whatever the source -/// considered the default value column (e.g. `pkt_len` for the netflow dataset). -/// But an aggregation may target a *different* column via `config.value_column` -/// — most importantly `COUNT(DISTINCT dstip)`, where the HLL sketch must hash -/// `dstip`, not the wire `pkt_len`. -/// -/// Rule (general, self-correcting): if `config.value_column` names a column that -/// is present among the series labels, aggregate that label's value; otherwise -/// fall back to `wire_val`. Numeric value columns such as `pkt_len` are never -/// sent as labels, so SUM / quantile / top-k transparently keep using the wire -/// scalar, while label-present distinct targets such as `dstip` get substituted. -/// -/// `labels` is the already-parsed label map for the sample's series key (parsed -/// once by `apply_sample` and shared with key extraction), so this is allocation- -/// free on the hot path. -/// -/// The label value is parsed as `f64`. This is lossless for the netflow IPv4 -/// `u32` columns (≤ 2^32 < 2^53) and consistent with the replay's int→f64 -/// convention; cardinality only requires distinct inputs to map to distinct -/// hashes, so the exact hash need not match the baseline engine. -/// -/// # Panics -/// Panics if `value_column` names a label whose value is not numeric. Non-numeric -/// distinct targets (e.g. `proto`) are not yet supported; this is a temporary -/// guard until the path is refactored to return a `Result` (see follow-up for a -/// byte/string hashing path). -fn resolve_sample_value( - labels: &HashMap<&str, &str>, - wire_val: f64, - config: &AggregationConfig, -) -> f64 { - let Some(col) = config.value_column.as_deref() else { - return wire_val; - }; - - let Some(raw) = labels.get(col) else { - return wire_val; - }; - - match raw.parse::() { - Ok(v) => v, - // Non-numeric distinct targets (e.g. COUNT(DISTINCT proto)) are not yet - // supported: silently falling back to the wire value would produce an - // INCORRECT aggregate, so fail loudly instead. This panic is a temporary - // measure — the longer-term fix is to make this path return a `Result` - // and propagate the error up to the caller. - Err(_) => panic!( - "value_column '{col}' label value {raw:?} is not numeric; non-numeric distinct \ - targets (e.g. COUNT(DISTINCT proto)) are not yet supported" - ), - } -} - -/// Extract aggregated label values from a series key string. -/// These are the labels that form the key dimension *inside* keyed accumulators -/// (MultipleSum, CMS, HydraKLL), matching Arroyo's `agg_columns`. -fn extract_aggregated_key_from_series( - labels: &HashMap<&str, &str>, - config: &AggregationConfig, -) -> KeyByLabelValues { - let mut values = Vec::new(); - - for label_name in &config.aggregated_labels.labels { - if let Some(val) = labels.get(label_name.as_str()) { - values.push(val.to_string()); - } else { - values.push(String::new()); - } - } - - KeyByLabelValues::new_with_labels(values) -} - /// Merge the pane accumulators that constitute a closed window. /// /// The oldest pane (index 0) is taken destructively from `active_panes` @@ -1115,55 +974,13 @@ fn merge_panes_for_window( merged } -/// Convert a closed DeltaSetAggregator population into the stateful delta -/// format used by the Arroyo implementation: keys newly present in this -/// window go in `added`, and keys absent from this window go in `removed`. -/// -/// The updater can only collect the current window's observed keys. The -/// previous population therefore belongs to `GroupState`, which survives the -/// per-pane updater lifecycle and is isolated for each `(agg_id, group_key)`. -fn finalize_closed_accumulator( - accumulator: Box, - config: &AggregationConfig, - previous_delta_set_keys: &mut HashSet, -) -> Result, Box> { - if config.aggregation_type != AggregationType::DeltaSetAggregator { - return Ok(accumulator); - } - - let delta = accumulator - .as_any() - .downcast_ref::() - .ok_or_else(|| { - format!( - "DeltaSetAggregator config produced {} instead of DeltaSetAggregatorAccumulator", - accumulator.type_name() - ) - })?; - let current_keys: HashSet = delta - .get_keys() - .ok_or("DeltaSetAggregator accumulator could not resolve its current keys")? - .into_iter() - .collect(); - - let added = current_keys - .difference(previous_delta_set_keys) - .cloned() - .collect(); - let removed = previous_delta_set_keys - .difference(¤t_keys) - .cloned() - .collect(); - *previous_delta_set_keys = current_keys; - - Ok(Box::new(DeltaSetAggregatorAccumulator::new_with_sets( - added, removed, - ))) -} - #[cfg(test)] mod tests { use super::*; + use crate::precompute_engine::aggregation_spec::{ + extract_key_from_series, resolve_sample_value, Worker, + }; + use asap_types::aggregation_config::AggregationConfig; #[test] fn test_extract_metric_name() { From a842a371cb974e680fe6f1c4aa232c912b893ea4 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 24 Nov 2026 10:53:44 -0500 Subject: [PATCH 2/2] docs(query-engine): describe the precompute pipeline and build specification Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014qhwq4jq8TFcKGchhF7Hfb --- .../precompute_engine_design_doc.md | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/asap-query-engine/src/precompute_engine/precompute_engine_design_doc.md b/asap-query-engine/src/precompute_engine/precompute_engine_design_doc.md index 5231e04b..9158221a 100644 --- a/asap-query-engine/src/precompute_engine/precompute_engine_design_doc.md +++ b/asap-query-engine/src/precompute_engine/precompute_engine_design_doc.md @@ -169,9 +169,26 @@ prevents a cold worker from blocking the entire system. ## 3. Components -### 3.1 PrecomputeEngine (`mod.rs`) +### 3.1 PrecomputeEngine, pipeline and build specification -Top-level orchestrator. On `run()`: +The engine is split in two: + +- **`PrecomputePipeline`** (`pipeline.rs`) owns series + routing to workers, workers, windows, watermarks, late-data policy and + backpressure. It writes every closed window to its `OutputSink`. +- **`BuildSpec`** (`build_spec.rs`), given to `run()` and swapped through + `PipelineHandle::update_spec`, says what to build: `R: SeriesRouting` + decides which builds (by id) and group key each series feeds, and each + build is a `WindowedBuild` (window geometry, pane updaters, how a closed + window becomes the written state, per-group state carried across windows, + whether late samples may be forwarded). + +`PrecomputeEngine` (`engine.rs`) is the pipeline given the +`AggregationConfig`-based spec (`aggregation_spec.rs`): `RoutingConfigSet` +routes by metric and spatial filter, and each `AggregationConfig` is a +`WindowedBuild`. + +`PrecomputePipeline::run()`: 1. Creates one `mpsc::channel` per worker. 2. Constructs a `SeriesRouter` with the sender halves. @@ -182,9 +199,8 @@ Top-level orchestrator. On `run()`: ```rust pub struct PrecomputeEngine { - config: PrecomputeEngineConfig, + pipeline: PrecomputePipeline, streaming_config: Arc, - output_sink: Arc, } ``` @@ -1250,9 +1266,12 @@ A lighter alternative: **periodic pane snapshots** written to disk at each flush | File | Purpose | |------|---------| -| `precompute_engine/mod.rs` | Orchestrator, HTTP ingest handler | +| `precompute_engine/engine.rs` | `PrecomputeEngine`: pipeline + `AggregationConfig` spec from a `StreamingConfig` | +| `precompute_engine/pipeline.rs` | `PrecomputePipeline`: workers, flush timer, ingest sources | +| `precompute_engine/build_spec.rs` | `BuildSpec`, `SeriesRouting`, `WindowedBuild` (the pipeline/spec seam) | +| `precompute_engine/aggregation_spec.rs` | `AggregationConfig` as `WindowedBuild`, `RoutingConfigSet` as `SeriesRouting` | | `precompute_engine/config.rs` | `PrecomputeEngineConfig`, `LateDataPolicy` | -| `precompute_engine/worker.rs` | Per-shard processing, aggregation, window management | +| `precompute_engine/worker.rs` | Per-shard processing, window management, watermarks, late data | | `precompute_engine/series_router.rs` | Hash-based series → worker routing | | `precompute_engine/series_buffer.rs` | Per-series BTreeMap sample buffer | | `precompute_engine/window_manager.rs` | Tumbling/sliding window logic |