diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index 1bde8f09a..3255bbf35 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -132,6 +132,11 @@ pub struct EngineOptions { /// once per evaluation time, as the plan says; `false` computes it in /// every query's run (for comparison). pub share_one_evaluation_results: bool, + /// Raw reads (of query and ingestion runs) return only the series a + /// `Scan`'s label predicates select ([`crate::label_selection`]); + /// `false` reads every series in the time range (for comparison). The + /// answers are the same. + pub label_pushdown: bool, /// How long a query-time result is kept after its evaluation time, /// counted back from the newest evaluation time computed. pub query_time_results_retention_ms: u64, @@ -215,6 +220,7 @@ impl Default for EngineOptions { run_memory_limit_bytes: 4 << 30, query_threads: std::thread::available_parallelism().map_or(1, usize::from), share_one_evaluation_results: true, + label_pushdown: true, query_time_results_retention_ms: 60_000, query_time_results_max_bytes: 1 << 30, result_cache: true, @@ -403,7 +409,12 @@ impl EngineHandle { /// invalid or the data plane cannot execute it. pub fn spawn(plan_json: String, options: EngineOptions) -> anyhow::Result<(Self, Vec)> { let (mut ingestion, precompute, query, query_texts) = install(&plan_json, &options)?; - let precompute = Arc::new(precompute); + // The ingestion runs' raw reads follow the same pushdown switch as + // the query runs', counted apart. + let ingestion_raw_reads = Arc::new(crate::store::RawReadCounts::default()); + let precompute = Arc::new( + precompute.with_raw_reads(options.label_pushdown, ingestion_raw_reads.clone()), + ); // Push mode: the groups the shards build by push. let push_groups: Vec> = match options.precompute_mode { PrecomputeMode::Window => vec![None; precompute.groups().len()], @@ -467,6 +478,8 @@ impl EngineHandle { .map(|(width_ms, views)| (width_ms, views.iter().map(ToString::to_string).collect())) .collect(); let mut metrics = Metrics::new(&groups, &query_texts); + let query = query.with_raw_reads(options.label_pushdown, metrics.query_raw_reads.clone()); + metrics.ingestion_raw_reads = ingestion_raw_reads; if let Some(tier) = &tier { let _ = metrics.view_tier.set(tier.clone()); } diff --git a/data_plane/src/ingestion.rs b/data_plane/src/ingestion.rs index f9b476a13..eb9114e97 100644 --- a/data_plane/src/ingestion.rs +++ b/data_plane/src/ingestion.rs @@ -43,7 +43,9 @@ use asap_executor::values::{Batch, SchemaRef}; use futures::executor::block_on; use crate::prometheus::MAX_TIME_MS; -use crate::store::{RawData, RawSample, RawShards, RunStore, SeriesPartition, ViewStore}; +use crate::store::{ + RawData, RawReadCounts, RawSample, RawShards, RunStore, SeriesPartition, ViewStore, +}; /// How ingestion treats sample times. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -365,6 +367,8 @@ impl Ingestion { runs, tasks, limits, + label_pushdown: true, + raw_read_counts: None, }, )) } @@ -923,9 +927,22 @@ pub struct Precompute { runs: Vec, tasks: RefreshTaskGraph, limits: Limits, + /// Whether the runs' raw reads select series by the `Scan`'s label + /// predicates ([`crate::label_selection`]); default true. + label_pushdown: bool, + /// Where the runs count their raw reads' rows; `None`: not counted. + raw_read_counts: Option>, } impl Precompute { + /// 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 { + self.label_pushdown = label_pushdown; + self.raw_read_counts = Some(counts); + self + } + /// Runs `window`'s group's views in one ingestion run over /// `(end - W, end]`, reading `raw_data` (as it was when the window /// closed) and `views`, and appends each view's rows to `views`. A view @@ -972,7 +989,14 @@ impl Precompute { return Ok(Computed::AlreadyStored); } let outputs = { - let store = Arc::new(RunStore::for_partition(raw_data, views, partition)); + let mut store = RunStore::for_partition(raw_data, views, 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 context = RunContext::new( Scope::Ingestion { diff --git a/data_plane/src/label_selection.rs b/data_plane/src/label_selection.rs new file mode 100644 index 000000000..34d89b35f --- /dev/null +++ b/data_plane/src/label_selection.rs @@ -0,0 +1,381 @@ +//! The series a raw read needs, from its `Scan`'s predicates: label +//! predicate pushdown. A raw read returns every series' rows in its time +//! range; the executor re-applies the `Scan`'s predicates to them +//! (`asap_executor::sources::DataStore::read_raw_data`: the predicates are +//! a hint). A read whose predicates restrict a label to a few values +//! returns the rows of the series holding one of them only, so the +//! executor converts and filters those rather than every series' rows. +//! +//! Recognized, per conjunct of the predicates (a `BoolAnd` is flattened), +//! on a label column of the read's schema (a `Utf8` column other than the +//! series identity) compared with `Utf8` literals: +//! - `label = 'v'` (either side), +//! - `label IN ('v1', .., 'vn')`, +//! - `label = 'v1' OR .. OR label = 'vn'` on one label (the planner's +//! rollup compensation form), an `IN` among the disjuncts included. +//! +//! Every other conjunct (`NOT IN`, `!=`, regular expressions, `LIKE`, +//! ranges, functions of a label, other columns, an `OR` over several +//! labels) is ignored: the executor applies it. A conjunct allowing the +//! empty value is ignored too, as a series lacking the label reads it as +//! `''`. Conjuncts on one label intersect. + +use std::collections::{BTreeMap, BTreeSet}; + +use asap_executor::planner::ir::scalar::expr_ir::{CompareOpKind, ScalarValue}; +use asap_executor::planner::ir::scalar::ScalarExpr; +use asap_executor::planner::ir::schema::{DataType, FieldDataType, Schema, PROMQL_SERIES_IDENTITY}; + +use crate::series_ids::Series; + +/// The values each restricted label may take; a series is selected when +/// every restricted label holds one of its values. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct LabelSelection { + values_by_label: BTreeMap>, +} + +impl LabelSelection { + /// The selection `predicates` (over `schema`) imply; `None` when no + /// conjunct is recognized (every series is read). + pub fn from_predicates(schema: &Schema, predicates: &[ScalarExpr<()>]) -> Option { + let mut values_by_label: BTreeMap> = BTreeMap::new(); + let mut conjuncts: Vec<&ScalarExpr<()>> = predicates.iter().collect(); + while let Some(conjunct) = conjuncts.pop() { + if let ScalarExpr::BoolAnd(nested) = conjunct { + conjuncts.extend(nested); + continue; + } + let Some((label, values)) = label_values(schema, conjunct) else { + continue; + }; + match values_by_label.get_mut(label) { + Some(kept) => kept.retain(|value| values.contains(value)), + None => { + values_by_label.insert(label.to_string(), values); + } + } + } + (!values_by_label.is_empty()).then_some(Self { values_by_label }) + } + + /// Whether `series` holds one of the values of every restricted label. + pub fn holds(&self, series: &Series) -> bool { + self.values_by_label.iter().all(|(label, values)| { + series + .get(label) + .is_some_and(|value| values.contains(value)) + }) + } +} + +/// The label `conjunct` restricts and the values it allows, when it is +/// one of the recognized forms and allows no empty value. +fn label_values<'a>( + schema: &'a Schema, + conjunct: &ScalarExpr<()>, +) -> Option<(&'a str, BTreeSet)> { + let (label, values) = match conjunct { + ScalarExpr::BoolOr(disjuncts) => { + let mut label = None; + let mut values = BTreeSet::new(); + for disjunct in disjuncts { + let (one_label, one_values) = equality_or_in(schema, disjunct)?; + if label.is_some_and(|label| label != one_label) { + return None; + } + label = Some(one_label); + values.extend(one_values); + } + (label?, values) + } + other => equality_or_in(schema, other)?, + }; + (!values.contains("")).then_some((label, values)) +} + +/// `label = 'v'` (either side) or `label IN ('v1', ..)`. +fn equality_or_in<'a>( + schema: &'a Schema, + expr: &ScalarExpr<()>, +) -> Option<(&'a str, BTreeSet)> { + match expr { + ScalarExpr::Compare { + left, + op: CompareOpKind::Eq, + right, + .. + } => { + let (column, literal) = match (&**left, &**right) { + (ScalarExpr::Column(column), literal) | (literal, ScalarExpr::Column(column)) => { + (*column, literal) + } + _ => return None, + }; + Some(( + label_column(schema, column)?, + BTreeSet::from([text(literal)?]), + )) + } + ScalarExpr::InList { + expr, + list, + negated: false, + } => { + let ScalarExpr::Column(column) = &**expr else { + return None; + }; + let values = list.iter().map(text).collect::>>()?; + Some((label_column(schema, *column)?, values)) + } + _ => None, + } +} + +/// The name of `schema`'s column `index` when it holds a label: text, +/// neither the time column nor the series identity. +fn label_column(schema: &Schema, index: usize) -> Option<&str> { + let field = schema.fields.get(index)?; + (Some(index) != schema.time_index + && field.name != PROMQL_SERIES_IDENTITY + && field.dtype == FieldDataType::Plain(DataType::Utf8)) + .then_some(field.name.as_str()) +} + +fn text(literal: &ScalarExpr<()>) -> Option { + match literal { + ScalarExpr::Literal(ScalarValue::Utf8(value)) => Some(value.clone()), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use asap_executor::planner::ir::scalar::ExprSemantics; + use asap_executor::planner::ir::schema::Field; + + use crate::series_ids::intern_pairs; + + /// `(ts, host, user, value, series identity)`: a SQL table stored as + /// series, as `auth` is in E6. + fn schema() -> Schema { + Schema::with_time_index( + vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain("host", DataType::Utf8, false), + Field::plain("user", DataType::Utf8, false), + Field::plain("value", DataType::Float64, false), + Field::plain(PROMQL_SERIES_IDENTITY, DataType::Utf8, false), + ], + 0, + vec![], + ) + } + + const TS: usize = 0; + const HOST: usize = 1; + const USER: usize = 2; + const VALUE: usize = 3; + const IDENTITY: usize = 4; + + type Expr = ScalarExpr<()>; + + /// No value: a label restricted to nothing. + const NONE: &[&str] = &[]; + + fn col(index: usize) -> Expr { + ScalarExpr::Column(index) + } + + fn text(value: &str) -> Expr { + ScalarExpr::Literal(ScalarValue::Utf8(value.into())) + } + + fn compare(left: Expr, op: CompareOpKind, right: Expr) -> Expr { + ScalarExpr::Compare { + left: Box::new(left), + op, + right: Box::new(right), + semantics: ExprSemantics::Sql, + } + } + + fn eq(column: usize, value: &str) -> Expr { + compare(col(column), CompareOpKind::Eq, text(value)) + } + + fn in_list(column: usize, values: &[&str], negated: bool) -> Expr { + ScalarExpr::InList { + expr: Box::new(col(column)), + list: values.iter().map(|v| text(v)).collect(), + negated, + } + } + + fn selection(pairs: &[(&str, &[&str])]) -> LabelSelection { + LabelSelection { + values_by_label: pairs + .iter() + .map(|(label, values)| { + ( + label.to_string(), + values.iter().map(|v| v.to_string()).collect(), + ) + }) + .collect(), + } + } + + fn select(predicates: &[Expr]) -> Option { + LabelSelection::from_predicates(&schema(), predicates) + } + + /// `host = 'a'`, either side, and `host IN ('a', 'b')`. + #[test] + fn recognizes_equality_and_in_list() { + let a = Some(selection(&[("host", &["a"])])); + assert_eq!(select(&[eq(HOST, "a")]), a); + assert_eq!( + select(&[compare(text("a"), CompareOpKind::Eq, col(HOST))]), + a + ); + assert_eq!( + select(&[in_list(HOST, &["a", "b"], false)]), + Some(selection(&[("host", &["a", "b"])])) + ); + } + + /// The rollup compensation form `host = 'a' OR host = 'b'` (an `IN` + /// among the disjuncts included), and conjuncts nested in a `BoolAnd`. + #[test] + fn recognizes_an_or_of_equalities_on_one_label_and_nested_conjunctions() { + assert_eq!( + select(&[ScalarExpr::BoolOr(vec![eq(HOST, "a"), eq(HOST, "b")])]), + Some(selection(&[("host", &["a", "b"])])) + ); + assert_eq!( + select(&[ScalarExpr::BoolOr(vec![ + eq(HOST, "a"), + in_list(HOST, &["b", "c"], false), + ])]), + Some(selection(&[("host", &["a", "b", "c"])])) + ); + assert_eq!( + select(&[ScalarExpr::BoolAnd(vec![eq(HOST, "a"), eq(USER, "u")])]), + Some(selection(&[("host", &["a"]), ("user", &["u"])])) + ); + } + + /// Conjuncts on several labels are all kept; conjuncts on one label + /// intersect (to nothing, when they share no value: no series is read, + /// and the executor would have kept none). + #[test] + fn conjuncts_on_one_label_intersect() { + assert_eq!( + select(&[in_list(HOST, &["a", "b"], false), eq(USER, "u")]), + Some(selection(&[("host", &["a", "b"]), ("user", &["u"])])) + ); + assert_eq!( + select(&[in_list(HOST, &["a", "b"], false), eq(HOST, "b")]), + Some(selection(&[("host", &["b"])])) + ); + assert_eq!( + select(&[eq(HOST, "a"), eq(HOST, "b")]), + Some(selection(&[("host", NONE)])) + ); + } + + /// Recognized conjuncts are kept beside ignored ones (the time range, + /// a value comparison), which the executor applies. + #[test] + fn keeps_recognized_conjuncts_beside_ignored_ones() { + let time = compare( + col(TS), + CompareOpKind::Gt, + ScalarExpr::Literal(ScalarValue::Timestamp(1_000)), + ); + let value = compare( + col(VALUE), + CompareOpKind::Gt, + ScalarExpr::Literal(ScalarValue::Float64(3.0)), + ); + assert_eq!( + select(&[time, in_list(HOST, &["a"], false), value]), + Some(selection(&[("host", &["a"])])) + ); + } + + /// Nothing is recognized from `NOT IN`, `!=`, `NOT`, regular + /// expressions, `LIKE`, ranges, a function of a label, a label against + /// another column or a non-text literal, the value, time or series + /// identity column, an `OR` over two labels or with another form, or + /// a value the missing label reads as (`''`). + #[test] + fn ignores_every_other_form() { + let ignored = [ + in_list(HOST, &["a"], true), + compare(col(HOST), CompareOpKind::Ne, text("a")), + ScalarExpr::Not(Box::new(eq(HOST, "a"))), + compare(col(HOST), CompareOpKind::Regex, text("a|b")), + compare(col(HOST), CompareOpKind::NotRegex, text("a")), + compare(col(HOST), CompareOpKind::Like, text("a%")), + compare(col(HOST), CompareOpKind::Gt, text("a")), + compare(col(HOST), CompareOpKind::Le, text("z")), + compare( + ScalarExpr::FunctionCall { + name: "lower".into(), + args: vec![col(HOST)], + }, + CompareOpKind::Eq, + text("a"), + ), + compare(col(HOST), CompareOpKind::Eq, col(USER)), + compare( + col(HOST), + CompareOpKind::Eq, + ScalarExpr::Literal(ScalarValue::Int64(1)), + ), + compare( + col(VALUE), + CompareOpKind::Eq, + ScalarExpr::Literal(ScalarValue::Float64(1.0)), + ), + eq(IDENTITY, "{\"host\":\"a\"}"), + ScalarExpr::BoolOr(vec![eq(HOST, "a"), eq(USER, "u")]), + ScalarExpr::BoolOr(vec![ + eq(HOST, "a"), + compare(col(HOST), CompareOpKind::Regex, text("b.*")), + ]), + ScalarExpr::IsNotNull(Box::new(col(HOST))), + eq(HOST, ""), + in_list(HOST, &["a", ""], false), + ]; + for predicate in ignored { + assert_eq!( + select(std::slice::from_ref(&predicate)), + None, + "{predicate:?}" + ); + } + assert_eq!(select(&[]), None); + } + + /// A series is selected when each restricted label holds one of its + /// values; a series lacking a restricted label is not. + #[test] + fn holds_series_matching_every_restricted_label() { + let chosen = selection(&[("host", &["a", "b"]), ("user", &["u"])]); + let series = |pairs: &[(&str, &str)]| { + let mut all = vec![("__name__", "label_selection_test")]; + all.extend_from_slice(pairs); + intern_pairs(&all) + }; + assert!(chosen.holds(series(&[("host", "a"), ("user", "u")]))); + assert!(chosen.holds(series(&[("host", "b"), ("user", "u"), ("x", "1")]))); + assert!(!chosen.holds(series(&[("host", "c"), ("user", "u")]))); + assert!(!chosen.holds(series(&[("host", "a"), ("user", "v")]))); + assert!(!chosen.holds(series(&[("host", "a")]))); + assert!(!selection(&[("host", NONE)]).holds(series(&[("host", "a")]))); + } +} diff --git a/data_plane/src/lib.rs b/data_plane/src/lib.rs index c0eee1f02..e3644ab66 100644 --- a/data_plane/src/lib.rs +++ b/data_plane/src/lib.rs @@ -17,6 +17,7 @@ pub mod engine; pub mod ingestion; pub mod intent; +pub mod label_selection; pub mod memory_budget; pub mod metrics; pub mod persist; diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index c04a9c238..3a594e1af 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -128,6 +128,11 @@ struct Args { /// of once per evaluation time (for comparison). #[arg(long)] no_shared_results: bool, + /// Read every series of a raw read's time range (query and ingestion + /// runs), whatever the `Scan`'s label predicates (for comparison; the + /// answers are the same). + #[arg(long)] + no_label_pushdown: bool, /// How long a query-time result is kept behind the watermark. #[arg(long, default_value_t = EngineOptions::default().query_time_results_retention_ms)] query_time_results_retention_ms: u64, @@ -236,6 +241,7 @@ async fn main() -> anyhow::Result<()> { run_memory_limit_bytes: args.run_memory_limit_bytes, query_threads: args.query_threads, share_one_evaluation_results: !args.no_shared_results, + label_pushdown: !args.no_label_pushdown, query_time_results_retention_ms: args.query_time_results_retention_ms, query_time_results_max_bytes: args.query_time_results_max_bytes, result_cache: !args.no_result_cache, diff --git a/data_plane/src/metrics.rs b/data_plane/src/metrics.rs index e5e646ecf..2feb9c506 100644 --- a/data_plane/src/metrics.rs +++ b/data_plane/src/metrics.rs @@ -324,6 +324,11 @@ pub struct Metrics { pub view_segments_marked_cold: AtomicU64, /// The views' cold tier, when they are persisted. pub view_tier: std::sync::OnceLock>, + /// Rows of the query runs' raw reads: in their time ranges, and + /// returned after label predicate pushdown. + pub query_raw_reads: std::sync::Arc, + /// The same counts for the ingestion runs' raw reads. + pub ingestion_raw_reads: std::sync::Arc, } impl Metrics { @@ -365,6 +370,8 @@ impl Metrics { view_file_bytes: AtomicU64::new(0), view_segments_marked_cold: AtomicU64::new(0), view_tier: std::sync::OnceLock::new(), + query_raw_reads: std::sync::Arc::default(), + ingestion_raw_reads: std::sync::Arc::default(), } } @@ -572,6 +579,34 @@ pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { "Raw-data panes held, over every metric.", load(&metrics.raw_data_panes), ); + for (scope, counts) in [ + ("query", &metrics.query_raw_reads), + ("ingestion", &metrics.ingestion_raw_reads), + ] { + for (name, help, value) in [ + ( + "raw_reads_total", + "Raw reads of the runs.", + &counts.reads, + ), + ( + "raw_read_rows_in_time_range_total", + "Rows of the series read in the runs' raw reads' time ranges, before label predicate pushdown.", + &counts.rows_in_time_range, + ), + ( + "raw_read_rows_returned_total", + "Rows the runs' raw reads returned, after label predicate pushdown.", + &counts.rows_returned, + ), + ] { + let _ = writeln!( + out, + "# HELP asap_{scope}_{name} {help}\n# TYPE asap_{scope}_{name} counter\nasap_{scope}_{name} {}", + load(value) + ); + } + } gauge( &mut out, "asap_view_bytes", diff --git a/data_plane/src/push.rs b/data_plane/src/push.rs index c617104cc..308e0a365 100644 --- a/data_plane/src/push.rs +++ b/data_plane/src/push.rs @@ -80,6 +80,7 @@ impl Morsel { let batches: Vec = self .raw .read(metric, &request, None, None)? + .batches .into_iter() .filter(|b| b.num_rows() > 0) .collect(); diff --git a/data_plane/src/query.rs b/data_plane/src/query.rs index f1a7cac6b..93c429dd3 100644 --- a/data_plane/src/query.rs +++ b/data_plane/src/query.rs @@ -35,7 +35,9 @@ use futures::executor::block_on; use futures::StreamExt; use crate::result_cache::{Answer, ResultCache}; -use crate::store::{PublishedStore, QueryTimeResults, RawReads, RawShards, RunStore, ViewStore}; +use crate::store::{ + PublishedStore, QueryTimeResults, RawReadCounts, RawReads, RawShards, RunStore, ViewStore, +}; /// One series of an instant-query result. #[derive(Debug, Clone, PartialEq)] @@ -106,6 +108,10 @@ pub struct QueryEngine { reads_raw_data: BTreeSet, /// Final answers of the query roots by evaluation time; `None`: off. result_cache: Option, + /// Whether raw reads select series by the `Scan`'s label predicates. + label_pushdown: bool, + /// Where the runs count their raw reads' rows. + raw_read_counts: Option>, } impl QueryEngine { @@ -192,6 +198,8 @@ impl QueryEngine { limits, reads_raw_data, result_cache, + label_pushdown: true, + raw_read_counts: None, }) } @@ -203,6 +211,35 @@ impl QueryEngine { .collect() } + /// 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 { + self.label_pushdown = label_pushdown; + self.raw_read_counts = Some(counts); + self + } + + /// A run's store: `snapshot` and the shared results it reads. + fn run_store( + &self, + snapshot: &Snapshot, + shared: HashMap>>, + ) -> RunStore { + let mut store = RunStore::with_query_time_results( + snapshot.raw_data.clone(), + snapshot.views.clone(), + Some(snapshot.raw_reads.clone()), + shared, + ); + if !self.label_pushdown { + store = store.without_label_pushdown(); + } + match &self.raw_read_counts { + Some(counts) => store.with_raw_read_counts(counts.clone()), + None => store, + } + } + /// The query-time partition of the view store. pub fn query_time_results(&self) -> &QueryTimeResults { &self.results @@ -372,12 +409,7 @@ impl QueryEngine { for &read in &run.reads { shared.insert(read, self.output_bound(read, time_ms, snapshot, bound)?); } - let run_store = Arc::new(RunStore::with_query_time_results( - snapshot.raw_data.clone(), - snapshot.views.clone(), - Some(snapshot.raw_reads.clone()), - shared, - )); + let run_store = Arc::new(self.run_store(snapshot, shared)); run_compiled(&compiled, run_store.clone(), time_ms, &self.limits).map_err(|error| { match run_store.missing_rows() { Some(missing) => Unanswered::MissingRows(missing), @@ -418,12 +450,7 @@ impl QueryEngine { for &read in &run.reads { shared.insert(read, self.output(read, time_ms, snapshot)?); } - let run_store = Arc::new(RunStore::with_query_time_results( - snapshot.raw_data.clone(), - snapshot.views.clone(), - Some(snapshot.raw_reads.clone()), - shared, - )); + let run_store = Arc::new(self.run_store(snapshot, shared)); run_compiled(&run.compiled, run_store.clone(), time_ms, &self.limits).map_err(|error| { match run_store.missing_rows() { Some(missing) => Unanswered::MissingRows(missing), diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 58ddb848e..7917de062 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -50,6 +50,7 @@ use asap_executor::Error; use futures::{stream, StreamExt}; use crate::ingestion::window_end; +use crate::label_selection::LabelSelection; use crate::metrics::{PhaseStats, Timer}; use crate::persist::{ViewRead, WindowLocation}; use crate::series_ids::Series; @@ -155,14 +156,22 @@ impl Chunk { } /// The rows of the series in `partition`, in order: the chunk itself - /// when every series is, `None` when none is. One pass over the rows, - /// with no lookup per row: each series' new code is found once. + /// when every series is, `None` when none is. fn in_partition(self: &Arc, partition: SeriesPartition) -> Option> { + self.select(|series| partition.holds(series.id)) + } + + /// The rows of the series `keep` holds, in order: the chunk itself + /// when it holds every series, `None` (no row touched) when it holds + /// none. `keep` is asked once per series of the chunk, and the rows + /// are copied in one pass with no lookup per row: each series' new + /// code is found once. + fn select(self: &Arc, mut keep: impl FnMut(&Series) -> bool) -> Option> { const DROPPED: u32 = u32::MAX; let mut new_code = vec![DROPPED; self.series.len()]; let mut series = Vec::new(); for (code, one) in self.series.iter().enumerate() { - if partition.holds(one.id) { + if keep(one) { new_code[code] = series.len() as u32; series.push(*one); } @@ -361,10 +370,10 @@ impl RawData { request: &RawDataRequest, reads: Option<&RawReads>, partition: Option<&PartitionReads>, - ) -> Result, Error> { + ) -> Result { let columns = column_kinds(metric, request)?; let Some(metric_data) = self.by_metric.get(metric) else { - return Ok(Vec::new()); + return Ok(RawRead::default()); }; // A range starting before the evicted samples cannot be read whole: // the read fails, as a missing view window does. A read of every @@ -377,7 +386,7 @@ impl RawData { ))); } if start >= end { - return Ok(Vec::new()); + return Ok(RawRead::default()); } // Pane `(e - w, e]` overlaps `(start, end]` when // `start < e < end + w`. @@ -385,7 +394,27 @@ impl RawData { Bound::Excluded(start), Bound::Excluded(end.saturating_add(self.pane_width_ms)), )); + // The series the `Scan`'s label predicates select, each judged once + // per read; `None`: every series. + let selection = LabelSelection::from_predicates(request.schema, request.predicates) + .map(|selection| SeriesVerdicts::new(Arc::new(selection))); + let convert = |chunk: &Chunk| -> Result { + if let Some(reads) = reads { + reads.conversions.fetch_add(1, Ordering::Relaxed); + } + let columns = columns + .iter() + .map(|kind| chunk.column(kind).map(BatchColumn::Plain)) + .collect::, Error>>()?; + Batch::try_from_columns(request.schema.clone(), columns) + }; + // The stored chunk read whole, converted once per `reads`. + let whole = |stored: &Arc| match reads { + Some(reads) => reads.get_or_convert(stored, request.schema, || convert(stored)), + None => convert(stored), + }; let mut batches = Vec::new(); + let mut rows_in_time_range = 0; for stored in panes.flat_map(|(_, pane)| pane) { let Some(chunk) = stored.in_range((start, end)) else { continue; @@ -397,25 +426,86 @@ impl RawData { }) else { continue; }; - let convert = || -> Result { - let columns = columns - .iter() - .map(|kind| chunk.column(kind).map(BatchColumn::Plain)) - .collect::, Error>>()?; - Batch::try_from_columns(request.schema.clone(), columns) - }; - let batch = match reads { - Some(reads) if Arc::ptr_eq(stored, &chunk) => { - reads.get_or_convert(stored, request.schema, convert)? + rows_in_time_range += chunk.len() as u64; + let is_whole = Arc::ptr_eq(stored, &chunk); + let batch = match (&selection, reads) { + (None, _) if is_whole => Some(whole(stored)?), + (None, _) => Some(convert(&chunk)?), + // A stored chunk's selected rows, cut and converted once per + // `reads` and selection. + (Some(verdicts), Some(reads)) if is_whole => { + reads.get_or_select(stored, request.schema, &verdicts.selection, || { + match stored.select(|series| verdicts.keeps(series)) { + None => Ok(None), + Some(cut) if Arc::ptr_eq(&cut, stored) => whole(stored).map(Some), + Some(cut) => convert(&cut).map(Some), + } + })? } - _ => convert()?, + (Some(verdicts), _) => match chunk.select(|series| verdicts.keeps(series)) { + None => None, + Some(cut) if Arc::ptr_eq(&cut, stored) => Some(whole(stored)?), + Some(cut) => Some(convert(&cut)?), + }, }; - batches.push(batch); + batches.extend(batch); + } + Ok(RawRead { + batches, + rows_in_time_range, + }) + } +} + +/// Each series' verdict under one label selection, by series id (dense): +/// a series is judged once per read, however many chunks hold it. +struct SeriesVerdicts { + selection: Arc, + /// By series id: 0 not judged yet, 1 selected, 2 not. + by_id: std::cell::RefCell>, +} + +impl SeriesVerdicts { + fn new(selection: Arc) -> Self { + Self { + selection, + by_id: Default::default(), + } + } + + fn keeps(&self, series: &Series) -> bool { + let mut by_id = self.by_id.borrow_mut(); + let id = series.id as usize; + if by_id.len() <= id { + by_id.resize(id + 1, 0); } - Ok(batches) + if by_id[id] == 0 { + by_id[id] = if self.selection.holds(series) { 1 } else { 2 }; + } + by_id[id] == 1 } } +/// One raw read's batches, and the rows of the read's series in its time +/// range before the `Scan`'s label predicates selected some +/// ([`crate::label_selection`]): without a recognized predicate, the rows +/// returned. +#[derive(Debug, Default)] +pub(crate) struct RawRead { + pub batches: Vec, + pub rows_in_time_range: u64, +} + +/// Rows of the raw reads of some runs (the query runs: `/metrics`): +/// how many were in the reads' time ranges, and how many the reads +/// returned after label predicate pushdown. +#[derive(Debug, Default)] +pub struct RawReadCounts { + pub reads: AtomicU64, + pub rows_in_time_range: AtomicU64, + pub rows_returned: AtomicU64, +} + /// One of `count` disjoint parts of the series, by series id: a window's /// ingestion run split by series reads one part per run. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -471,19 +561,58 @@ pub struct RawReads { /// workers rarely wait for each other; each entry holds the chunk and /// the schema, so their addresses are not reused while it is kept. shards: Vec>, + /// A stored chunk's rows of the series a label selection selects, by + /// chunk, request schema and selection, sharded as `shards`: `None` + /// when it holds none of them. Never mixed with whole conversions. + selected: Vec>, + /// Chunks (whole or cut) converted to batches. + conversions: AtomicU64, } type ConvertedChunks = HashMap<(usize, usize), (Arc, SchemaRef, Batch)>; +type SelectedChunks = + HashMap<(usize, usize, Arc), (Arc, SchemaRef, Option)>; + impl Default for RawReads { fn default() -> Self { Self { shards: (0..64).map(|_| Mutex::default()).collect(), + selected: (0..64).map(|_| Mutex::default()).collect(), + conversions: AtomicU64::new(0), } } } impl RawReads { + /// `chunk`'s rows of the series `selection` selects, converted by + /// `cut` on the first read. + fn get_or_select( + &self, + chunk: &Arc, + schema: &SchemaRef, + selection: &Arc, + cut: impl FnOnce() -> Result, Error>, + ) -> Result, Error> { + let key = ( + Arc::as_ptr(chunk) as usize, + Arc::as_ptr(schema) as usize, + selection.clone(), + ); + let shard = &self.selected[(key.0 >> 4) % self.selected.len()]; + if let Some((_, _, batch)) = shard.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { + return Ok(batch.clone()); + } + let batch = cut()?; + Ok(shard + .lock() + .unwrap_or_else(|e| e.into_inner()) + .entry(key) + .or_insert_with(|| (chunk.clone(), schema.clone(), batch)) + .2 + .clone()) + } + fn get_or_convert( &self, chunk: &Arc, @@ -578,6 +707,11 @@ pub struct RunStore { /// the run's evaluation time before the run starts and held by the run. query_time_results: HashMap>>, missing_rows: Mutex>, + /// Whether raw reads select series by the `Scan`'s label predicates + /// ([`crate::label_selection`]); `false` reads every series. + label_pushdown: bool, + /// Where the run counts its raw reads' rows. + raw_read_counts: Option>, } impl RunStore { @@ -600,9 +734,24 @@ impl RunStore { partition: None, query_time_results, missing_rows: Mutex::new(None), + label_pushdown: true, + raw_read_counts: None, } } + /// The run reads every series, whatever the `Scan`'s label predicates + /// (for comparison). + pub fn without_label_pushdown(mut self) -> Self { + self.label_pushdown = false; + self + } + + /// The run counts its raw reads' rows in `counts`. + pub fn with_raw_read_counts(mut self, counts: Arc) -> Self { + self.raw_read_counts = Some(counts); + self + } + /// A run reading the raw samples of `partition`'s series only. pub fn for_partition( raw_data: RawShards, @@ -639,15 +788,40 @@ impl DataStore for RunStore { context: RunContext, ) -> Result, Error> { let metric = stored_series(source); + // Without pushdown the store reads by the time range only; the + // executor applies every predicate either way. + let unselected = RawDataRequest { + predicates: &[], + ..*request + }; + let request = if self.label_pushdown { + request + } else { + &unselected + }; let mut batches = Vec::new(); + let mut rows_in_time_range = 0; for shard in self.raw_data.iter() { - let read = shard.read( - metric, - request, - self.raw_reads.as_deref(), - self.partition.as_ref(), - ); - batches.extend(read.inspect_err(|error| self.record_missing(error))?); + let read = shard + .read( + metric, + request, + self.raw_reads.as_deref(), + self.partition.as_ref(), + ) + .inspect_err(|error| self.record_missing(error))?; + rows_in_time_range += read.rows_in_time_range; + batches.extend(read.batches); + } + if let Some(counts) = &self.raw_read_counts { + let returned: usize = batches.iter().map(Batch::num_rows).sum(); + counts.reads.fetch_add(1, Ordering::Relaxed); + counts + .rows_in_time_range + .fetch_add(rows_in_time_range, Ordering::Relaxed); + counts + .rows_returned + .fetch_add(returned as u64, Ordering::Relaxed); } Ok(stream::iter(batches) .map(move |batch| { @@ -1641,6 +1815,8 @@ pub fn scanned_metrics<'a>( #[cfg(test)] mod tests { use super::*; + use asap_executor::planner::ir::scalar::expr_ir::{CompareOpKind, ScalarValue}; + use asap_executor::planner::ir::scalar::{ExprSemantics, ScalarExpr}; use asap_executor::planner::ir::schema::{Field, Schema}; use asap_executor::values::Value; @@ -1751,6 +1927,7 @@ mod tests { }; raw.read("m_store_test", &request, reads, None) .unwrap() + .batches .iter() .flat_map(Batch::to_rows) .collect() @@ -1801,6 +1978,215 @@ mod tests { assert!(panes[&25_000].len() > 1); } + /// `job = 'v'` on the test schema's `job` column. + fn job_is(value: &str) -> ScalarExpr<()> { + ScalarExpr::Compare { + left: Box::new(ScalarExpr::Column(3)), + op: CompareOpKind::Eq, + right: Box::new(ScalarExpr::Literal(ScalarValue::Utf8(value.into()))), + semantics: ExprSemantics::Sql, + } + } + + /// A read of `m_store_test` with `predicates`: its rows, batches and + /// rows in the time range. + fn read_with( + raw: &RawData, + schema: &Arc, + range: Option<(i64, i64)>, + predicates: &[ScalarExpr<()>], + reads: Option<&RawReads>, + partition: Option<&PartitionReads>, + ) -> (Vec>, usize, u64) { + let request = RawDataRequest { + time_range_ms: range, + schema, + predicates, + }; + let read = raw + .read("m_store_test", &request, reads, partition) + .unwrap(); + let rows = read.batches.iter().flat_map(Batch::to_rows).collect(); + (rows, read.batches.len(), read.rows_in_time_range) + } + + /// The samples of the series whose `job` is `job`. + fn of_job(samples: &[RawSample], job: &str) -> Vec { + samples + .iter() + .filter(|s| s.labels.get("job").map(String::as_str) == Some(job)) + .cloned() + .collect() + } + + /// A read whose predicates restrict `job` returns the rows of the + /// series holding it only, the rows the executor's filter would keep, + /// for ranges inside one pane, across panes and unbounded, before and + /// after compaction, with and without shared conversions; its rows in + /// the time range are the rows a read without predicates returns. + #[test] + fn label_selected_read_returns_the_selected_series_rows() { + let schema = schema(); + let requests = samples(); + let all: Vec = requests.iter().flatten().cloned().collect(); + let job_a = of_job(&all, "a"); + let mut raw = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + for request in &requests { + raw.append(request); + } + let ranges = [ + None, + Some((5_000, 10_000)), + Some((4_000, 4_242)), + Some((2_100, 27_001)), + ]; + for sealed in [false, true] { + if sealed { + raw.seal_through(20_000); + } + let shared = RawReads::default(); + for range in ranges { + for reads in [None, Some(&shared), Some(&shared)] { + let what = format!( + "range {range:?}, sealed {sealed}, shared {}", + reads.is_some() + ); + let (rows, _, in_range) = + read_with(&raw, &schema, range, &[job_is("a")], reads, None); + assert_eq!( + sorted(rows), + sorted(row_read(&job_a, &schema, range)), + "{what}" + ); + assert_eq!( + in_range as usize, + row_read(&all, &schema, range).len(), + "{what}: rows in the time range" + ); + } + } + } + } + + /// A predicate the store does not recognize (`job != 'a'`) reads every + /// series, as before: the executor applies it. (Passes before the + /// implementation: a guard.) + #[test] + fn unrecognized_predicates_read_every_series() { + let schema = schema(); + let requests = samples(); + let all: Vec = requests.iter().flatten().cloned().collect(); + let mut raw = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + for request in &requests { + raw.append(request); + } + let not_a = ScalarExpr::Compare { + left: Box::new(ScalarExpr::Column(3)), + op: CompareOpKind::Ne, + right: Box::new(ScalarExpr::Literal(ScalarValue::Utf8("a".into()))), + semantics: ExprSemantics::Sql, + }; + let (rows, _, _) = read_with(&raw, &schema, None, &[not_a], None, None); + assert_eq!(sorted(rows), sorted(row_read(&all, &schema, None))); + } + + /// A chunk holding none of the selected series yields no batch. + #[test] + fn chunks_without_a_selected_series_are_skipped() { + let schema = schema(); + let a = intern_pairs(&[("__name__", "m_store_test"), ("job", "a"), ("i", "1")]); + let b = intern_pairs(&[("__name__", "m_store_test"), ("job", "b"), ("i", "3")]); + let sample = |labels, timestamp_ms| RawSample { + labels, + timestamp_ms, + value: 1.0, + }; + let mut raw = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + // Pane 5 000: both series; pane 10 000: `b` only, in two chunks. + raw.append(&[sample(a, 1_000), sample(b, 1_000)]); + raw.append(&[sample(b, 6_000)]); + raw.append(&[sample(b, 7_000)]); + let range = Some((0, 10_000)); + let (rows, batches, in_range) = read_with(&raw, &schema, range, &[job_is("a")], None, None); + assert_eq!((rows.len(), batches, in_range), (1, 1, 4)); + let (rows, batches, in_range) = + read_with(&raw, &schema, range, &[job_is("none")], None, None); + assert_eq!((rows.len(), batches, in_range), (0, 0, 4)); + } + + /// Reads sharing converted chunks keep a selected conversion apart from + /// the whole one and from another selection's, in either order; reads + /// of one selection convert each chunk once. + #[test] + fn shared_conversions_keep_selections_apart() { + let schema = schema(); + let requests = samples(); + let all: Vec = requests.iter().flatten().cloned().collect(); + let mut raw = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + for request in &requests { + raw.append(request); + } + let shared = RawReads::default(); + let whole = sorted(row_read(&all, &schema, None)); + let job_a = sorted(row_read(&of_job(&all, "a"), &schema, None)); + let job_b = sorted(row_read(&of_job(&all, "b"), &schema, None)); + for _ in 0..2 { + for (predicates, expected) in [ + (vec![], &whole), + (vec![job_is("a")], &job_a), + (vec![job_is("b")], &job_b), + (vec![], &whole), + ] { + let (rows, _, _) = read_with(&raw, &schema, None, &predicates, Some(&shared), None); + assert_eq!(&sorted(rows), expected, "{predicates:?}"); + } + } + // Each chunk once whole, and once per selection keeping some but + // not all of its series (one keeping all reads the whole + // conversion; one keeping none converts nothing). + let cut_by = |job: &str| { + raw.chunks() + .filter(|c| { + let kept = c + .series + .iter() + .filter(|s| s.get("job").map(String::as_str) == Some(job)) + .count(); + 0 < kept && kept < c.series.len() + }) + .count() + }; + let converted = shared.conversions.load(Ordering::Relaxed) as usize; + assert_eq!(converted, raw.chunks().count() + cut_by("a") + cut_by("b")); + } + + /// An ingestion run's part of the series and the label selection + /// compose: the rows of the part's series that the predicates select. + #[test] + fn series_partition_and_label_selection_compose() { + let schema = schema(); + let requests = samples(); + let all: Vec = requests.iter().flatten().cloned().collect(); + let mut raw = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + for request in &requests { + raw.append(request); + } + for index in 0..2 { + let partition = SeriesPartition { index, count: 2 }; + let reads = PartitionReads::new(partition); + let expected: Vec = of_job(&all, "a") + .into_iter() + .filter(|s| partition.holds(s.labels.id)) + .collect(); + let (rows, _, _) = read_with(&raw, &schema, None, &[job_is("a")], None, Some(&reads)); + assert_eq!( + sorted(rows), + sorted(row_read(&expected, &schema, None)), + "partition {index}" + ); + } + } + /// Eviction drops the panes ending at or before the cutoff, keeps the /// pane the cutoff falls in, and no read returns a sample at or /// before the cutoff: a read of a range starting before it fails (its diff --git a/data_plane/tests/intent_sil_modes.rs b/data_plane/tests/intent_sil_modes.rs index 1b55e3c24..5255be694 100644 --- a/data_plane/tests/intent_sil_modes.rs +++ b/data_plane/tests/intent_sil_modes.rs @@ -7,6 +7,7 @@ mod common; use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::Ordering; use std::sync::Arc; use std::time::Duration; @@ -194,12 +195,22 @@ async fn planned_text(text: &str, mode: IntentPlanningMode) -> IntentPlan { /// row a sample of the series `{__name__=table, host, user}`) and closed by /// the barrier at `EVALUATION_MS`. async fn install(plan: &IntentPlan, tables: &BTreeMap<&str, Vec>) -> Arc { + install_with(plan, tables, true).await +} + +/// [`install`], with label predicate pushdown on or off. +async fn install_with( + plan: &IntentPlan, + tables: &BTreeMap<&str, Vec>, + label_pushdown: bool, +) -> Arc { let state = Arc::new( DataPlane::with_options( serde_json::to_string(&plan.plan).unwrap(), "http://127.0.0.1:1".into(), EngineOptions { no_forward: true, + label_pushdown, ..EngineOptions::default() }, ) @@ -382,3 +393,88 @@ async fn each_clock_runs_its_queries_exactly() { assert_answers("q3", &rows_of(&slow, "q3"), "user", &exact); state.engine.stop(); } + +/// The query runs' raw read rows so far: in the time ranges, returned. +fn raw_read_rows(state: &DataPlane) -> (u64, u64) { + let counts = &state.engine.metrics().query_raw_reads; + ( + counts.rows_in_time_range.load(Ordering::SeqCst), + counts.rows_returned.load(Ordering::SeqCst), + ) +} + +/// Label predicate pushdown: in each planning mode, the rounds' answers +/// and q2's answer bound to one host are the same with pushdown as +/// without; without it, q2's raw reads return every row in their time +/// range; with it, only the bound host's (one host of four: a quarter). +#[tokio::test(flavor = "multi_thread")] +async fn label_pushdown_reads_the_bound_series_only_and_answers_the_same() { + let tables = tables(); + for mode in [ + IntentPlanningMode::QueryAtATime, + IntentPlanningMode::IntentOnDemandHoles, + IntentPlanningMode::IntentFull, + ] { + let plan = planned(mode).await; + let schedule = IntentSchedule::per_clock_from_intent_plan(&plan, "triage") + .unwrap() + .remove(0); + let q2_text = schedule.queries[1].query.clone(); + let q2_slot = schedule.queries[1].bind_slots[0].clone(); + let mut answers_by_pushdown = Vec::new(); + for label_pushdown in [false, true] { + let what = format!("{mode:?}, pushdown {label_pushdown}"); + let state = install_with(&plan, &tables, label_pushdown).await; + let intent = IntentLoop::new( + schedule.clone(), + BindMode::ParameterSlot, + Duration::from_secs(30), + ) + .unwrap(); + let mut answers = Vec::new(); + for time_ms in [EVALUATION_MS - 10_000, EVALUATION_MS] { + let round = intent.run_round(&state.engine, 0, time_ms).await; + for id in ["q1", "q2", "q3"] { + let mut rows = rows_of(&round, id) + .into_iter() + .map(|(labels, value)| format!("{labels:?} {value:?}")) + .collect::>(); + rows.sort(); + answers.push((time_ms, id, rows)); + } + } + let (in_range_before, returned_before) = raw_read_rows(&state); + let slot = SlotBinding { + position: SlotPosition::InList, + placeholders: q2_slot.placeholder_values.clone(), + values: BTreeSet::from(["h0".to_string()]), + }; + let answer = state + .engine + .answer_bound(&q2_text, EVALUATION_MS, &[slot]) + .await + .unwrap_or_else(|e| panic!("{what}: {e}")); + let mut rows: Vec = answer + .iter() + .map(|s| format!("{:?} {:?}", s.labels, s.value)) + .collect(); + rows.sort(); + answers.push((EVALUATION_MS, "q2 bound to h0", rows)); + let (in_range_after, returned_after) = raw_read_rows(&state); + let in_range = in_range_after - in_range_before; + let returned = returned_after - returned_before; + assert!(in_range > 0, "{what}: q2 read no raw rows"); + if label_pushdown { + assert_eq!(returned * 4, in_range, "{what}: rows returned"); + } else { + assert_eq!(returned, in_range, "{what}: rows returned"); + } + state.engine.stop(); + answers_by_pushdown.push(answers); + } + assert_eq!( + answers_by_pushdown[0], answers_by_pushdown[1], + "{mode:?}: answers with and without pushdown" + ); + } +} diff --git a/data_plane/tests/label_pushdown_ingestion.rs b/data_plane/tests/label_pushdown_ingestion.rs new file mode 100644 index 000000000..aba49425b --- /dev/null +++ b/data_plane/tests/label_pushdown_ingestion.rs @@ -0,0 +1,102 @@ +//! Label predicate pushdown in ingestion runs: a view built at ingestion +//! from a `Scan` with a label matcher reads only the matching series' +//! rows, and `--no-label-pushdown` (`EngineOptions::label_pushdown`) turns +//! it off there too, with the same answers. + +mod common; + +use std::sync::Arc; + +use axum::http::StatusCode; +use axum::Router; +use data_plane::engine::EngineOptions; +use data_plane::remote_write::{Label, Sample, TimeSeries}; +use data_plane::{router, DataPlane}; +use serde_json::{json, Value}; + +/// Four jobs of four series each; the query reads job `a`'s only. +const JOBS: [&str; 4] = ["a", "b", "c", "d"]; +const PER_JOB: usize = 4; +const QUERY: &str = r#"sum by (instance) (sum_over_time(data{job="a"}[1m]))"#; + +fn data_plane(label_pushdown: bool) -> (Router, Arc) { + // No raw data kept: the plan builds its views at ingestion. + let plan = common::one_query_plan_json(QUERY, JOBS.len() * PER_JOB, json!({})); + let options = EngineOptions { + view_dir: None, + label_pushdown, + ..common::no_forward_options() + }; + let state = + Arc::new(DataPlane::with_options(plan, "http://127.0.0.1:1".into(), options).unwrap()); + (router(state.clone()), state) +} + +/// One sample per second in `(0, to_s]` for every series, then a barrier +/// closing every window through `to_s`. +async fn write(app: &Router, to_s: i64) { + let mut timeseries = Vec::new(); + for (j, job) in JOBS.iter().enumerate() { + for i in 0..PER_JOB { + let label = |name: &str, value: String| Label { + name: name.into(), + value, + }; + timeseries.push(TimeSeries { + labels: vec![ + label("__name__", "data".into()), + label("instance", format!("i{i}")), + label("job", job.to_string()), + ], + samples: (1..=to_s) + .map(|s| Sample { + timestamp: s * 1000, + value: ((s * 7 + (j * PER_JOB + i) as i64) % 101) as f64, + }) + .collect(), + }); + } + } + common::remote_write(app, timeseries).await; + common::barrier(app, to_s * 1000).await; +} + +/// The ingestion runs' raw read rows: in the time ranges, returned. +fn ingestion_rows(state: &DataPlane) -> (f64, f64) { + ( + common::metric(state, "asap_ingestion_raw_read_rows_in_time_range_total "), + common::metric(state, "asap_ingestion_raw_read_rows_returned_total "), + ) +} + +/// With pushdown, the ingestion runs return job `a`'s rows only (a quarter +/// of the rows in their time ranges); without it, every row; the answers +/// are the same. +#[tokio::test(flavor = "multi_thread")] +async fn ingestion_runs_follow_the_label_pushdown_switch() { + let mut answers: Vec = Vec::new(); + for label_pushdown in [false, true] { + let (app, state) = data_plane(label_pushdown); + write(&app, 120).await; + let (status, _, body) = common::get(&app, &common::instant_uri(QUERY, 120)).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!( + body["data"]["result"].as_array().unwrap().len(), + PER_JOB, + "{body}" + ); + let (in_range, returned) = ingestion_rows(&state); + assert!( + in_range > 0.0, + "pushdown {label_pushdown}: no ingestion raw reads" + ); + if label_pushdown { + assert_eq!(returned * JOBS.len() as f64, in_range, "rows returned"); + } else { + assert_eq!(returned, in_range, "rows returned"); + } + state.engine.stop(); + answers.push(body["data"]["result"].clone()); + } + assert_eq!(answers[0], answers[1], "answers with and without pushdown"); +}