From 69e98308929fd354d757865f8d5c95eb5ee33797 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 17:58:24 +0000 Subject: [PATCH 1/3] test(store): label predicate pushdown for raw reads (tests first, stubs) Tests for selecting series by a Scan's label predicates (label = 'v', IN, OR of = on one label) in raw reads: recognition and its negative cases, the label index, per-chunk selection and skipping, shared conversions kept apart by selection, series partition composition, and an end-to-end intent round answering the same with and without pushdown while reading only the bound host's rows. Stubs keep today's behaviour; RawData::read returns RawRead with rows in the time range. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/engine.rs | 5 + data_plane/src/label_selection.rs | 286 +++++++++++++++++++++++++++ data_plane/src/lib.rs | 1 + data_plane/src/metrics.rs | 4 + data_plane/src/push.rs | 1 + data_plane/src/series_ids.rs | 38 ++++ data_plane/src/store.rs | 273 ++++++++++++++++++++++++- data_plane/tests/intent_sil_modes.rs | 96 +++++++++ 8 files changed, 699 insertions(+), 5 deletions(-) create mode 100644 data_plane/src/label_selection.rs diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index 1bde8f09a..e5a308205 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -132,6 +132,10 @@ 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 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 +219,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, diff --git a/data_plane/src/label_selection.rs b/data_plane/src/label_selection.rs new file mode 100644 index 000000000..438e95740 --- /dev/null +++ b/data_plane/src/label_selection.rs @@ -0,0 +1,286 @@ +//! 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::ScalarExpr; +use asap_executor::planner::ir::schema::Schema; + +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 { + pub fn new(values_by_label: BTreeMap>) -> Self { + Self { values_by_label } + } + + /// 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 { + // Stub until the implementation: nothing recognized. + None + } + + pub fn values_by_label(&self) -> &BTreeMap> { + &self.values_by_label + } + + /// Whether `series` holds one of the values of every restricted label. + pub fn holds(&self, _series: &Series) -> bool { + // Stub until the implementation: every series. + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + use asap_executor::planner::ir::scalar::expr_ir::{CompareOpKind, ScalarValue}; + use asap_executor::planner::ir::scalar::ExprSemantics; + use asap_executor::planner::ir::schema::{DataType, Field, PROMQL_SERIES_IDENTITY}; + + 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::new( + 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(&[predicate.clone()]), 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/metrics.rs b/data_plane/src/metrics.rs index e5e646ecf..9baff07cc 100644 --- a/data_plane/src/metrics.rs +++ b/data_plane/src/metrics.rs @@ -324,6 +324,9 @@ 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, } impl Metrics { @@ -365,6 +368,7 @@ 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(), } } 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/series_ids.rs b/data_plane/src/series_ids.rs index ab7c0ae84..3d6b2a0c2 100644 --- a/data_plane/src/series_ids.rs +++ b/data_plane/src/series_ids.rs @@ -207,3 +207,41 @@ pub fn labels_of_identity(identity: &str) -> Option None => result_labels(identity).ok(), } } + +/// The ids of the interned series of `metric` whose `label` is `value`, +/// ascending: the label index the interner keeps, a series entered once +/// for each label (`__name__` excluded) when it is interned. A raw read +/// selecting series by label values ([`crate::label_selection`]) takes +/// the union over a label's values and the intersection over labels. +pub fn series_with_label(_metric: &str, _label: &str, _value: &str) -> Vec { + // Stub until the implementation: no index. + Vec::new() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The label index holds every series interned so far, those interned + /// after an earlier lookup included, and only the metric's own. + #[test] + fn label_index_follows_interning() { + let a1 = intern_pairs(&[("__name__", "m_label_index"), ("host", "a"), ("user", "1")]); + let b1 = intern_pairs(&[("__name__", "m_label_index"), ("host", "b"), ("user", "1")]); + intern_pairs(&[("__name__", "m_label_index_other"), ("host", "a")]); + assert_eq!(series_with_label("m_label_index", "host", "a"), vec![a1.id]); + assert_eq!( + series_with_label("m_label_index", "user", "1"), + vec![a1.id, b1.id] + ); + let a2 = intern_pairs(&[("__name__", "m_label_index"), ("host", "a"), ("user", "2")]); + // Interning an existing label set again adds nothing. + intern_pairs(&[("user", "1"), ("host", "a"), ("__name__", "m_label_index")]); + assert_eq!( + series_with_label("m_label_index", "host", "a"), + vec![a1.id, a2.id] + ); + assert!(series_with_label("m_label_index", "host", "c").is_empty()); + assert!(series_with_label("m_label_index", "__name__", "m_label_index").is_empty()); + } +} diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 58ddb848e..3d56bcb2c 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -361,10 +361,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 +377,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`. @@ -386,6 +386,7 @@ impl RawData { Bound::Excluded(end.saturating_add(self.pane_width_ms)), )); 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,6 +398,7 @@ impl RawData { }) else { continue; }; + rows_in_time_range += chunk.len() as u64; let convert = || -> Result { let columns = columns .iter() @@ -412,10 +414,34 @@ impl RawData { }; batches.push(batch); } - Ok(batches) + Ok(RawRead { + batches, + rows_in_time_range, + }) } } +/// 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, + #[allow(dead_code)] // Read by RunStore after the implementation. + 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)] @@ -578,6 +604,13 @@ 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. + #[allow(dead_code)] // Stub until the implementation. + label_pushdown: bool, + /// Where the run counts its raw reads' rows. + #[allow(dead_code)] // Stub until the implementation. + raw_read_counts: Option>, } impl RunStore { @@ -600,9 +633,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, @@ -647,7 +695,10 @@ impl DataStore for RunStore { self.raw_reads.as_deref(), self.partition.as_ref(), ); - batches.extend(read.inspect_err(|error| self.record_missing(error))?); + batches.extend( + read.inspect_err(|error| self.record_missing(error))? + .batches, + ); } Ok(stream::iter(batches) .map(move |batch| { @@ -1641,6 +1692,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 +1804,7 @@ mod tests { }; raw.read("m_store_test", &request, reads, None) .unwrap() + .batches .iter() .flat_map(Batch::to_rows) .collect() @@ -1801,6 +1855,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: usize = shared.shards.iter().map(|s| s.lock().unwrap().len()).sum(); + 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" + ); + } +} From ac2be997860e0060bcfa05b3dfd614439c35d564 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 18:20:05 +0000 Subject: [PATCH 2/3] feat(store): raw reads return only the series a Scan's label predicates select A raw read recognizes, among its Scan's predicates, label = 'v', label IN (...) and an OR of = on one label, on label columns (a SQL table's text columns, a metric's labels), and returns only the rows of the series they select; everything else is still applied by the executor, so the answers do not change. Per read, each series is judged once (a verdict by dense series id); per chunk, its distinct series are checked, a chunk with none selected is skipped without touching its rows, and the selected rows are copied in one pass (Chunk::select, which Chunk::in_partition now uses). A selected cut of a stored chunk is converted once per range request and selection, apart from the whole chunk's conversion. /metrics counts the query runs' raw reads, their rows in the time range and the rows returned (asap_query_raw_read_*_total). --no-label-pushdown (EngineOptions::label_pushdown) reads every series, for comparison. No global label index: the per-chunk check walks each chunk's series list either way (rows are in arrival order). Co-Authored-By: Claude Opus 5.5 --- data_plane/src/engine.rs | 1 + data_plane/src/label_selection.rs | 135 ++++++++++++++++++---- data_plane/src/main.rs | 5 + data_plane/src/metrics.rs | 23 ++++ data_plane/src/query.rs | 53 ++++++--- data_plane/src/series_ids.rs | 38 ------- data_plane/src/store.rs | 181 +++++++++++++++++++++++++----- 7 files changed, 336 insertions(+), 100 deletions(-) diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index e5a308205..03742112c 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -472,6 +472,7 @@ 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()); if let Some(tier) = &tier { let _ = metrics.view_tier.set(tier.clone()); } diff --git a/data_plane/src/label_selection.rs b/data_plane/src/label_selection.rs index 438e95740..34d89b35f 100644 --- a/data_plane/src/label_selection.rs +++ b/data_plane/src/label_selection.rs @@ -22,8 +22,9 @@ 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::Schema; +use asap_executor::planner::ir::schema::{DataType, FieldDataType, Schema, PROMQL_SERIES_IDENTITY}; use crate::series_ids::Series; @@ -35,34 +36,124 @@ pub struct LabelSelection { } impl LabelSelection { - pub fn new(values_by_label: BTreeMap>) -> Self { - Self { values_by_label } - } - /// 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 { - // Stub until the implementation: nothing recognized. - None + 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 }) } - pub fn values_by_label(&self) -> &BTreeMap> { - &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)) + }) } +} - /// Whether `series` holds one of the values of every restricted label. - pub fn holds(&self, _series: &Series) -> bool { - // Stub until the implementation: every series. - true +/// 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::expr_ir::{CompareOpKind, ScalarValue}; use asap_executor::planner::ir::scalar::ExprSemantics; - use asap_executor::planner::ir::schema::{DataType, Field, PROMQL_SERIES_IDENTITY}; + use asap_executor::planner::ir::schema::Field; use crate::series_ids::intern_pairs; @@ -123,8 +214,8 @@ mod tests { } fn selection(pairs: &[(&str, &[&str])]) -> LabelSelection { - LabelSelection::new( - pairs + LabelSelection { + values_by_label: pairs .iter() .map(|(label, values)| { ( @@ -133,7 +224,7 @@ mod tests { ) }) .collect(), - ) + } } fn select(predicates: &[Expr]) -> Option { @@ -261,7 +352,11 @@ mod tests { in_list(HOST, &["a", ""], false), ]; for predicate in ignored { - assert_eq!(select(&[predicate.clone()]), None, "{predicate:?}"); + assert_eq!( + select(std::slice::from_ref(&predicate)), + None, + "{predicate:?}" + ); } assert_eq!(select(&[]), None); } diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index c04a9c238..675ea92cc 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -128,6 +128,10 @@ 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, 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 +240,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 9baff07cc..754f73f51 100644 --- a/data_plane/src/metrics.rs +++ b/data_plane/src/metrics.rs @@ -576,6 +576,29 @@ pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { "Raw-data panes held, over every metric.", load(&metrics.raw_data_panes), ); + for (name, help, value) in [ + ( + "asap_query_raw_reads_total", + "Raw reads of the query runs.", + &metrics.query_raw_reads.reads, + ), + ( + "asap_query_raw_read_rows_in_time_range_total", + "Rows of the series read in the query runs' raw reads' time ranges, before label predicate pushdown.", + &metrics.query_raw_reads.rows_in_time_range, + ), + ( + "asap_query_raw_read_rows_returned_total", + "Rows the query runs' raw reads returned, after label predicate pushdown.", + &metrics.query_raw_reads.rows_returned, + ), + ] { + let _ = writeln!( + out, + "# HELP {name} {help}\n# TYPE {name} counter\n{name} {}", + load(value) + ); + } gauge( &mut out, "asap_view_bytes", 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/series_ids.rs b/data_plane/src/series_ids.rs index 3d6b2a0c2..ab7c0ae84 100644 --- a/data_plane/src/series_ids.rs +++ b/data_plane/src/series_ids.rs @@ -207,41 +207,3 @@ pub fn labels_of_identity(identity: &str) -> Option None => result_labels(identity).ok(), } } - -/// The ids of the interned series of `metric` whose `label` is `value`, -/// ascending: the label index the interner keeps, a series entered once -/// for each label (`__name__` excluded) when it is interned. A raw read -/// selecting series by label values ([`crate::label_selection`]) takes -/// the union over a label's values and the intersection over labels. -pub fn series_with_label(_metric: &str, _label: &str, _value: &str) -> Vec { - // Stub until the implementation: no index. - Vec::new() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The label index holds every series interned so far, those interned - /// after an earlier lookup included, and only the metric's own. - #[test] - fn label_index_follows_interning() { - let a1 = intern_pairs(&[("__name__", "m_label_index"), ("host", "a"), ("user", "1")]); - let b1 = intern_pairs(&[("__name__", "m_label_index"), ("host", "b"), ("user", "1")]); - intern_pairs(&[("__name__", "m_label_index_other"), ("host", "a")]); - assert_eq!(series_with_label("m_label_index", "host", "a"), vec![a1.id]); - assert_eq!( - series_with_label("m_label_index", "user", "1"), - vec![a1.id, b1.id] - ); - let a2 = intern_pairs(&[("__name__", "m_label_index"), ("host", "a"), ("user", "2")]); - // Interning an existing label set again adds nothing. - intern_pairs(&[("user", "1"), ("host", "a"), ("__name__", "m_label_index")]); - assert_eq!( - series_with_label("m_label_index", "host", "a"), - vec![a1.id, a2.id] - ); - assert!(series_with_label("m_label_index", "host", "c").is_empty()); - assert!(series_with_label("m_label_index", "__name__", "m_label_index").is_empty()); - } -} diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 3d56bcb2c..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); } @@ -385,6 +394,25 @@ 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) { @@ -399,20 +427,28 @@ impl RawData { continue; }; rows_in_time_range += chunk.len() as u64; - 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)? + 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, @@ -421,6 +457,35 @@ impl RawData { } } +/// 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); + } + 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 @@ -428,7 +493,6 @@ impl RawData { #[derive(Debug, Default)] pub(crate) struct RawRead { pub batches: Vec, - #[allow(dead_code)] // Read by RunStore after the implementation. pub rows_in_time_range: u64, } @@ -497,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, @@ -606,10 +709,8 @@ pub struct RunStore { missing_rows: Mutex>, /// Whether raw reads select series by the `Scan`'s label predicates /// ([`crate::label_selection`]); `false` reads every series. - #[allow(dead_code)] // Stub until the implementation. label_pushdown: bool, /// Where the run counts its raw reads' rows. - #[allow(dead_code)] // Stub until the implementation. raw_read_counts: Option>, } @@ -687,18 +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))? - .batches, - ); + 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| { @@ -2033,7 +2156,7 @@ mod tests { }) .count() }; - let converted: usize = shared.shards.iter().map(|s| s.lock().unwrap().len()).sum(); + let converted = shared.conversions.load(Ordering::Relaxed) as usize; assert_eq!(converted, raw.chunks().count() + cut_by("a") + cut_by("b")); } From d3a36c5dc0919423fcf1c83d2f23480a858e7e8b Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 23:18:48 +0000 Subject: [PATCH 3/3] feat(data_plane): tables stored by series key; other columns as per-chunk dictionary fields A table may declare its series key (--table-layouts): a row's series is its key labels, its other labels are fields stored as dictionary-coded columns of the chunk. Sealed keyed panes are sorted by series then time; key-label columns are dictionaries over the chunk's series codes and are built once per chunk (cached across rounds); label pushdown applies key restrictions to series and field restrictions to dictionary entries. Metrics and tables without a layout keep one series per label set. N1 5-min (synthetic x1, 6.6 M rows): round 12.5 s -> 0.56 s, series 5.07 M -> 520, peak RSS 7.8 GB -> 1.9 GB, answers identical. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- data_plane/examples/packets_bench.rs | 321 ++++++++ data_plane/src/engine.rs | 6 + data_plane/src/label_selection.rs | 5 + data_plane/src/lib.rs | 11 +- data_plane/src/main.rs | 11 + data_plane/src/metrics.rs | 6 + data_plane/src/remote_write.rs | 181 ++++- data_plane/src/series_ids.rs | 33 + data_plane/src/store.rs | 821 ++++++++++++++++++--- data_plane/src/table_layout.rs | 157 ++++ data_plane/tests/intent_sil_modes.rs | 143 +++- data_plane/tests/remote_write_reference.rs | 1 + 12 files changed, 1578 insertions(+), 118 deletions(-) create mode 100644 data_plane/examples/packets_bench.rs create mode 100644 data_plane/src/table_layout.rs diff --git a/data_plane/examples/packets_bench.rs b/data_plane/examples/packets_bench.rs new file mode 100644 index 000000000..2640ee211 --- /dev/null +++ b/data_plane/examples/packets_bench.rs @@ -0,0 +1,321 @@ +//! Packet table bench, in process: the network eval's `packets` table fed +//! as Remote Write rows (one sample per packet, as the eval's feeder sends +//! them: labels `dst_ip, dst_port, proto, src_ip, src_p16, src_p24`, value +//! = bytes), then an intent's rounds. Measures what the table layout +//! changes: ingest CPU and wall time per row, raw bytes, series interned, +//! peak RSS, and each query's latency per round. Writes every round's +//! answers to `ANSWERS_OUT` (JSON lines) so two layouts can be compared. +//! +//! `ROWS` is a `net_dump` file: 24-byte little-endian records in time +//! order (ts_ms i64 since the stream epoch, src u32, dst u32, sport u16, +//! dport u16, proto u8, pad u8, bytes u16). Rows of `[0, FEED_S)` are fed +//! unpaced in 250 ms requests (encoded on their own thread, `encoder`, +//! not counted as engine CPU), the windows closed by a barrier at +//! `FEED_S`, then `ROUNDS` rounds 10 s apart ending at `FEED_S`. +//! +//! Environment: `TABLE_LAYOUTS=path.json` declares the tables' series keys +//! (`--table-layouts`); `INGEST_THREADS`, `QUERY_THREADS`; `ANSWERS_OUT`. +//! +//! `cargo run --release -p data_plane --example packets_bench -- INTENT_PLAN INTENT_NAME ROWS FEED_S [ROUNDS]` + +#[global_allocator] +static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; + +use std::io::Write as _; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use data_plane::engine::EngineOptions; +use data_plane::intent::{BindMode, IntentLoop, IntentPlan, IntentSchedule}; +use data_plane::metrics::thread_cpu_seconds; +use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; +use data_plane::{router, DataPlane}; +use tower::ServiceExt; + +/// Event time of the stream's epoch: 2023-11-14, a multiple of 10 s, in +/// the past (the data plane drops samples from the future). +const EPOCH_MS: i64 = 1_700_000_000_000; +const REQUEST_MS: i64 = 250; +const ROUND_MS: i64 = 10_000; + +struct Packet { + ts_ms: i64, + src: u32, + dst: u32, + dport: u16, + proto: u8, + bytes: u16, +} + +fn packets(path: &str, feed_ms: i64) -> Vec { + let data = std::fs::read(path).unwrap(); + data.chunks_exact(24) + .map(|r| Packet { + ts_ms: i64::from_le_bytes(r[0..8].try_into().unwrap()), + src: u32::from_le_bytes(r[8..12].try_into().unwrap()), + dst: u32::from_le_bytes(r[12..16].try_into().unwrap()), + dport: u16::from_le_bytes(r[18..20].try_into().unwrap()), + proto: r[20], + bytes: u16::from_le_bytes(r[22..24].try_into().unwrap()), + }) + .take_while(|p| p.ts_ms < feed_ms) + .collect() +} + +/// One Remote Write request per 250 ms of rows, each row its own +/// `TimeSeries` (labels sorted by name, as the eval's feeder sends them). +fn encode_requests(rows: &[Packet], out: std::sync::mpsc::SyncSender<(usize, Vec)>) { + let mut start = 0; + while start < rows.len() { + let request_end = (rows[start].ts_ms / REQUEST_MS + 1) * REQUEST_MS; + let end = start + rows[start..].partition_point(|p| p.ts_ms < request_end); + let timeseries = rows[start..end] + .iter() + .map(|p| { + let labels = [ + ("__name__", "packets".to_string()), + ("dst_ip", p.dst.to_string()), + ("dst_port", p.dport.to_string()), + ("proto", p.proto.to_string()), + ("src_ip", p.src.to_string()), + ("src_p16", (p.src / 65536).to_string()), + ("src_p24", (p.src / 256).to_string()), + ] + .into_iter() + .map(|(name, value)| Label { + name: name.into(), + value, + }) + .collect(); + TimeSeries { + labels, + samples: vec![Sample { + timestamp: EPOCH_MS + p.ts_ms, + value: p.bytes as f64, + }], + } + }) + .collect(); + if out + .send((end - start, encode(&WriteRequest { timeseries }))) + .is_err() + { + return; + } + start = end; + } +} + +/// Peak and current resident set, in MiB. +fn rss_mib() -> (f64, f64) { + let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); + let field = |name: &str| { + status + .lines() + .find_map(|l| l.strip_prefix(name)) + .and_then(|v| v.trim().trim_end_matches(" kB").trim().parse::().ok()) + .map_or(0.0, |kb| kb / 1024.0) + }; + (field("VmHWM:"), field("VmRSS:")) +} + +fn metric(text: &str, name: &str) -> f64 { + text.lines() + .find_map(|l| l.strip_prefix(name).and_then(|v| v.trim().parse().ok())) + .unwrap_or(f64::NAN) +} + +#[tokio::main(flavor = "multi_thread")] +async fn main() { + let args: Vec = std::env::args().collect(); + let plan: IntentPlan = + serde_json::from_str(&std::fs::read_to_string(&args[1]).unwrap()).unwrap(); + let intent_name = &args[2]; + let feed_ms = args[4].parse::().unwrap() * 1000; + let rounds: i64 = args.get(5).map_or(3, |a| a.parse().unwrap()); + let env_usize = |name: &str| { + std::env::var(name) + .ok() + .map(|v| v.parse::().unwrap()) + }; + + let loaded = Instant::now(); + let rows = Arc::new(packets(&args[3], feed_ms)); + println!( + "rows {} of [0, {} s) loaded in {:.1} s", + rows.len(), + feed_ms / 1000, + loaded.elapsed().as_secs_f64() + ); + + let mut options = EngineOptions { + no_forward: true, + ..EngineOptions::default() + }; + if let Some(threads) = env_usize("INGEST_THREADS") { + options.ingest_threads = threads; + } + if let Some(threads) = env_usize("QUERY_THREADS") { + options.query_threads = threads; + } + if let Ok(path) = std::env::var("TABLE_LAYOUTS") { + options.table_layouts = data_plane::table_layout::TableLayouts::from_json( + &std::fs::read_to_string(path).unwrap(), + ) + .unwrap(); + } + let state = Arc::new( + DataPlane::with_options( + serde_json::to_string(&plan.plan).unwrap(), + "http://127.0.0.1:1".into(), + options, + ) + .unwrap(), + ); + let app = router(state.clone()); + + // Ingest: unpaced, the bodies encoded ahead on their own thread. + let (sender, bodies) = std::sync::mpsc::sync_channel(64); + let encoder_rows = rows.clone(); + std::thread::Builder::new() + .name("encoder".into()) + .spawn(move || encode_requests(&encoder_rows, sender)) + .unwrap(); + let cpu_before = thread_cpu_seconds(); + let started = Instant::now(); + let (mut sent, mut retries, mut in_write) = (0usize, 0u64, Duration::ZERO); + while let Ok((count, body)) = bodies.recv() { + let body = axum::body::Bytes::from(body); + loop { + let call = Instant::now(); + let response = app + .clone() + .oneshot( + Request::post("/api/v1/write") + .body(Body::from(body.clone())) + .unwrap(), + ) + .await + .unwrap(); + in_write += call.elapsed(); + match response.status() { + StatusCode::NO_CONTENT => break, + StatusCode::SERVICE_UNAVAILABLE => { + retries += 1; + tokio::time::sleep(Duration::from_millis(1)).await; + } + status => panic!("Remote Write answered {status}"), + } + } + sent += count; + } + let acknowledged = started.elapsed().as_secs_f64(); + while state.engine.queued_samples() > 0 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + let appended = started.elapsed().as_secs_f64(); + let barrier = app + .clone() + .oneshot( + Request::post(format!( + "/api/v1/precompute/watermark?time_ms={}", + EPOCH_MS + feed_ms + )) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(barrier.status(), StatusCode::OK); + let refreshed = started.elapsed().as_secs_f64(); + let cpu_after = thread_cpu_seconds(); + let text = state.engine.render_metrics(); + let (peak_mib, rss_mib_now) = rss_mib(); + println!( + "ingest: {sent} rows; acknowledged {acknowledged:.2} s ({:.0} rows/s), appended {appended:.2} s, \ + refreshed {refreshed:.2} s; in write handler {:.2} s; 503 retries {retries}", + sent as f64 / acknowledged, + in_write.as_secs_f64() + ); + let mut engine_cpu = 0.0; + for (name, after) in &cpu_after { + let cpu = after - cpu_before.get(name).copied().unwrap_or(0.0); + if name != "encoder" { + engine_cpu += cpu; + } + if cpu > 0.05 { + println!(" cpu {name:<24} {cpu:8.2} s"); + } + } + println!( + " engine cpu {engine_cpu:.2} s = {:.2} us/row; raw bytes {:.1} MiB ({:.1} B/row); \ + raw samples {}; series interned {}; RSS peak {peak_mib:.0} MiB, now {rss_mib_now:.0} MiB \ + (includes the bench's rows: {:.0} MiB)", + engine_cpu * 1e6 / sent.max(1) as f64, + metric(&text, "asap_raw_data_bytes") / 1048576.0, + metric(&text, "asap_raw_data_bytes") / sent.max(1) as f64, + metric(&text, "asap_raw_data_samples"), + data_plane::series_ids::interned_count(), + (rows.len() * std::mem::size_of::()) as f64 / 1048576.0, + ); + + // Rounds, 10 s apart, the last at the barrier. + let schedule = IntentSchedule::per_clock_from_intent_plan(&plan, intent_name) + .unwrap() + .remove(0); + let intent = + IntentLoop::new(schedule, BindMode::ParameterSlot, Duration::from_secs(600)).unwrap(); + let mut answers = std::env::var("ANSWERS_OUT") + .ok() + .map(|path| std::fs::File::create(path).unwrap()); + for round in 0..rounds { + let time_ms = EPOCH_MS + feed_ms - (rounds - 1 - round) * ROUND_MS; + let cpu_before = thread_cpu_seconds(); + let record = intent.run_round(&state.engine, round as u64, time_ms).await; + let cpu_after = thread_cpu_seconds(); + let cpu: f64 = cpu_after + .iter() + .map(|(name, after)| after - cpu_before.get(name).copied().unwrap_or(0.0)) + .sum(); + let latencies: Vec = record + .queries + .iter() + .map(|q| { + format!( + "{} {:?} {} rows {}", + q.query_id, + q.status, + q.latency_ms.map_or("-".into(), |l| format!("{l:.1} ms")), + q.answer.len() + ) + }) + .collect(); + println!( + "round {round} at +{} s: {:.1} ms, cpu {cpu:.2} s; {}", + (time_ms - EPOCH_MS) / 1000, + record.duration_ms, + latencies.join("; ") + ); + if let Some(file) = answers.as_mut() { + for q in &record.queries { + let mut rows: Vec = q + .answer + .iter() + .map(|r| format!("{:?} {:?}", r.labels, r.value)) + .collect(); + rows.sort(); + let line = serde_json::json!({ + "round": round, "time_ms": time_ms, "query": q.query_id, + "status": format!("{:?}", q.status), "bindings": format!("{:?}", q.bindings), + "rows": rows, + }); + writeln!(file, "{line}").unwrap(); + } + } + } + let (peak_mib, _) = rss_mib(); + println!("RSS peak after rounds {peak_mib:.0} MiB"); + state.engine.stop(); +} diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index 03742112c..eaddf5049 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -136,6 +136,10 @@ pub struct EngineOptions { /// select ([`crate::label_selection`]); `false` reads every series in /// the time range (for comparison). The answers are the same. pub label_pushdown: bool, + /// The series key of each SQL table that declares one + /// (`--table-layouts`, [`crate::table_layout`]); other tables and + /// metrics keep one series per label set. + pub table_layouts: crate::table_layout::TableLayouts, /// 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, @@ -220,6 +224,7 @@ impl Default for EngineOptions { query_threads: std::thread::available_parallelism().map_or(1, usize::from), share_one_evaluation_results: true, label_pushdown: true, + table_layouts: Default::default(), query_time_results_retention_ms: 60_000, query_time_results_max_bytes: 1 << 30, result_cache: true, @@ -2741,6 +2746,7 @@ mod tests { labels: series, timestamp_ms: 15_000, value: 1.0, + fields: Box::default(), }; let routed = ingestion.routing().route(vec![sample], 25_000); assert_eq!(routed.accepted.len(), 1, "{:?}", routed.stats); diff --git a/data_plane/src/label_selection.rs b/data_plane/src/label_selection.rs index 34d89b35f..01a4d8086 100644 --- a/data_plane/src/label_selection.rs +++ b/data_plane/src/label_selection.rs @@ -59,6 +59,11 @@ impl LabelSelection { (!values_by_label.is_empty()).then_some(Self { values_by_label }) } + /// The values each restricted label may take. + pub fn restrictions(&self) -> &BTreeMap> { + &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)| { diff --git a/data_plane/src/lib.rs b/data_plane/src/lib.rs index e3644ab66..09f7b0910 100644 --- a/data_plane/src/lib.rs +++ b/data_plane/src/lib.rs @@ -32,6 +32,7 @@ pub mod segment; pub mod series_ids; mod state_codec; pub mod store; +pub mod table_layout; pub mod window_cache; use std::sync::atomic::Ordering; @@ -95,13 +96,21 @@ impl DataPlane { options: EngineOptions, ) -> anyhow::Result { let no_forward = options.no_forward; + let table_layouts = options.table_layouts.clone(); + // Push pipelines fold samples without their fields. + if options.precompute_mode == engine::PrecomputeMode::Push && !table_layouts.is_empty() { + anyhow::bail!("--table-layouts is not supported with push precompute mode"); + } let (engine, queries) = EngineHandle::spawn(plan_json, options)?; Ok(Self { no_forward, queries, engine, prometheus_url: prometheus_url.trim_end_matches('/').to_string(), - limits: remote_write::Limits::default(), + limits: remote_write::Limits { + table_layouts: std::sync::Arc::new(table_layouts), + ..remote_write::Limits::default() + }, client: forward_client(DEFAULT_FORWARD_TIMEOUT), raw_forward: None, }) diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index 675ea92cc..73e3f40a6 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -132,6 +132,11 @@ struct Args { /// label predicates (for comparison; the answers are the same). #[arg(long)] no_label_pushdown: bool, + /// A JSON file naming each SQL table's series key columns + /// (`{"packets": {"series_key": ["src_p16"]}}`): a table's other columns + /// are stored as columns of its series' rows, not as labels. + #[arg(long)] + table_layouts: Option, /// 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, @@ -241,6 +246,12 @@ async fn main() -> anyhow::Result<()> { query_threads: args.query_threads, share_one_evaluation_results: !args.no_shared_results, label_pushdown: !args.no_label_pushdown, + table_layouts: match &args.table_layouts { + Some(path) => data_plane::table_layout::TableLayouts::from_json( + &std::fs::read_to_string(path)?, + )?, + None => Default::default(), + }, 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 754f73f51..64bd0b65d 100644 --- a/data_plane/src/metrics.rs +++ b/data_plane/src/metrics.rs @@ -564,6 +564,12 @@ pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { "Bytes of raw samples held.", load(&metrics.raw_data_bytes), ); + gauge( + &mut out, + "asap_series_interned", + "Series interned so far (a table with a series key: one per key value).", + crate::series_ids::interned_count() as f64, + ); gauge( &mut out, "asap_raw_data_samples", diff --git a/data_plane/src/remote_write.rs b/data_plane/src/remote_write.rs index d3a385ca4..ce84f247a 100644 --- a/data_plane/src/remote_write.rs +++ b/data_plane/src/remote_write.rs @@ -3,7 +3,7 @@ use prost::Message; use crate::series_ids::Series; -use crate::store::RawSample; +use crate::store::{RawSample, RowFields}; #[derive(Clone, PartialEq, Message)] pub struct WriteRequest { @@ -41,6 +41,9 @@ pub struct Limits { pub max_compressed_bytes: usize, pub max_decompressed_bytes: usize, pub max_samples: usize, + /// The tables whose rows are stored by series key: a row of one is + /// interned by its key labels, its other labels kept as its fields. + pub table_layouts: std::sync::Arc, } impl Default for Limits { @@ -49,6 +52,7 @@ impl Default for Limits { max_compressed_bytes: 32 * 1024 * 1024, max_decompressed_bytes: 128 * 1024 * 1024, max_samples: 1_000_000, + table_layouts: Default::default(), } } } @@ -185,11 +189,11 @@ fn decode_series( } let labels = match (labels_start, contiguous) { (Some(start), true) => { - let labels = cached_series(&series[start..labels_end])?; + let (labels, fields) = row_series(&series[start..labels_end], limits)?; // Second pass: the samples, in the fields before and after the // labels (both whole fields, as the first pass found). - push_samples(&series[..start], labels, samples, limits)?; - return push_samples(&series[labels_end..], labels, samples, limits); + push_samples(&series[..start], labels, &fields, samples, limits)?; + return push_samples(&series[labels_end..], labels, &fields, samples, limits); } (None, _) => return Err(RemoteWriteError::MissingMetricName), (Some(_), false) => { @@ -202,10 +206,46 @@ fn decode_series( key.extend_from_slice(&series[reader.field_start..reader.position]); } } - cached_series(&key)? + row_series(&key, limits)? } }; - push_samples(series, labels, samples, limits) + push_samples(series, labels.0, &labels.1, samples, limits) +} + +/// The series of the encoded labels `key` and the row's fields: for a +/// table with a series key ([`crate::table_layout`]), the series of its key +/// labels and its other labels as fields, sorted by name; otherwise the +/// series of every label (cached by `key`) and no fields. A keyed table's +/// rows are not cached by their label bytes, which rarely repeat. +fn row_series( + key: &[u8], + limits: &Limits, +) -> Result<(&'static Series, RowFields), RemoteWriteError> { + let layouts = &limits.table_layouts; + if layouts.is_empty() { + return Ok((cached_series(key)?, RowFields::default())); + } + if let Some(series) = SERIES_CACHE.with(|cache| cache.borrow_mut().get(key)) { + return Ok((series, RowFields::default())); + } + let pairs = parse_pairs(key)?; + let metric = pairs + .iter() + .find(|(name, _)| *name == "__name__") + .map_or("", |(_, value)| *value); + if layouts.get(metric).is_none() { + let series = crate::series_ids::intern_pairs(&pairs); + SERIES_CACHE.with(|cache| cache.borrow_mut().insert(key, series)); + return Ok((series, RowFields::default())); + } + let (key_pairs, field_pairs) = layouts.split(&pairs); + let series = crate::series_ids::intern_pairs(&key_pairs); + let mut fields: Vec<(&'static str, Box)> = field_pairs + .iter() + .map(|(name, value)| (crate::series_ids::intern_name(name), Box::from(*value))) + .collect(); + fields.sort_unstable_by(|a, b| a.0.cmp(b.0)); + Ok((series, fields.into())) } /// The end of the `Label` field (tag `0x0a`) at `start` of `series`, when @@ -230,12 +270,13 @@ fn short_label_end(series: &[u8], start: usize) -> Option { /// `fields` to `samples`, each with series `labels`. #[inline] fn push_samples( - fields: &[u8], + encoded: &[u8], labels: &'static Series, + fields: &RowFields, samples: &mut Vec, limits: &Limits, ) -> Result<(), RemoteWriteError> { - let mut reader = Reader::new(fields); + let mut reader = Reader::new(encoded); while let Some((field, value)) = reader.field()? { let (2, Value::Bytes(sample)) = (field, value) else { continue; @@ -251,6 +292,7 @@ fn push_samples( labels, timestamp_ms, value, + fields: fields.clone(), }); } Ok(()) @@ -293,17 +335,19 @@ fn sample_generic(sample: &[u8]) -> Result<(i64, f64), RemoteWriteError> { Ok((timestamp_ms, value)) } +thread_local! { + /// This thread's series by the bytes of their encoded labels. + static SERIES_CACHE: std::cell::RefCell = std::cell::RefCell::default(); +} + /// The series of the encoded labels `key` (a run of `TimeSeries` field-1 /// entries): from this thread's cache, or parsed, validated and interned. fn cached_series(key: &[u8]) -> Result<&'static Series, RemoteWriteError> { - thread_local! { - static CACHE: std::cell::RefCell = std::cell::RefCell::default(); - } - if let Some(series) = CACHE.with(|cache| cache.borrow_mut().get(key)) { + if let Some(series) = SERIES_CACHE.with(|cache| cache.borrow_mut().get(key)) { return Ok(series); } let series = parse_labels(key)?; - CACHE.with(|cache| cache.borrow_mut().insert(key, series)); + SERIES_CACHE.with(|cache| cache.borrow_mut().insert(key, series)); Ok(series) } @@ -377,6 +421,12 @@ impl SeriesCache { /// Parses, validates and interns the labels encoded in `key`. fn parse_labels(key: &[u8]) -> Result<&'static Series, RemoteWriteError> { + Ok(crate::series_ids::intern_pairs(&parse_pairs(key)?)) +} + +/// The label pairs of the encoded labels `key`, checked: each name once, +/// `__name__` among them. +fn parse_pairs(key: &[u8]) -> Result, RemoteWriteError> { let mut pairs: Vec<(&str, &str)> = Vec::new(); let mut reader = Reader::new(key); while let Some((_, value)) = reader.field()? { @@ -404,7 +454,7 @@ fn parse_labels(key: &[u8]) -> Result<&'static Series, RemoteWriteError> { if !names.contains(&"__name__") { return Err(RemoteWriteError::MissingMetricName); } - Ok(crate::series_ids::intern_pairs(&pairs)) + Ok(pairs) } /// One protobuf field value. @@ -569,6 +619,109 @@ mod tests { Ok(request) } + /// Limits applying `layouts` (`--table-layouts`). + fn with_layouts(layouts: &str) -> Limits { + Limits { + table_layouts: std::sync::Arc::new( + crate::table_layout::TableLayouts::from_json(layouts).unwrap(), + ), + ..Limits::default() + } + } + + /// A row of a table keyed by `src_p16` is interned by its key labels + /// only: 100 rows from 100 hosts in two /16s make two series, each + /// sample carrying its other labels as fields (sorted by name); a + /// metric's samples, sent alongside and also carrying `src_p16`, keep + /// one series per label set and no fields. + #[test] + fn keyed_table_rows_intern_one_series_per_key_and_carry_their_other_labels() { + let limits = with_layouts(r#"{"t_rw_keyed": {"series_key": ["src_p16"]}}"#); + let mut timeseries = Vec::new(); + for host in 0..100u32 { + let src_ip = (host % 2) * 65_536 + host; + let (dst_ip, src_p16) = ((host * 3).to_string(), (src_ip / 65_536).to_string()); + let src_ip = src_ip.to_string(); + timeseries.push(series( + &[ + ("__name__", "t_rw_keyed"), + ("dst_ip", dst_ip.as_str()), + ("src_ip", src_ip.as_str()), + ("src_p16", src_p16.as_str()), + ], + &[(1_000 + host as i64, host as f64)], + )); + } + for instance in ["a", "b", "c"] { + timeseries.push(series( + &[ + ("__name__", "m_rw_up"), + ("instance", instance), + ("src_p16", "1"), + ], + &[(1_000, 1.0)], + )); + } + let samples = decode_samples(&encode(&WriteRequest { timeseries }), &limits).unwrap(); + assert_eq!(samples.len(), 103); + let (rows, metric): (Vec<_>, Vec<_>) = samples + .iter() + .partition(|s| &*s.labels.metric == "t_rw_keyed"); + let keys: std::collections::BTreeSet = rows.iter().map(|s| s.labels.id).collect(); + assert_eq!(keys.len(), 2, "one series per src_p16"); + for (host, sample) in rows.iter().enumerate() { + let src_ip = (host as u32 % 2) * 65_536 + host as u32; + let key: BTreeMap = [ + ("__name__".to_string(), "t_rw_keyed".to_string()), + ("src_p16".to_string(), (src_ip / 65_536).to_string()), + ] + .into(); + assert_eq!(**sample.labels, key); + let fields: Vec<(&str, &str)> = sample.fields.iter().map(|(n, v)| (*n, &**v)).collect(); + let (dst_ip, src_ip) = ((host * 3).to_string(), src_ip.to_string()); + assert_eq!( + fields, + [("dst_ip", dst_ip.as_str()), ("src_ip", src_ip.as_str())] + ); + assert_eq!(sample.value, host as f64); + } + let metric_series: std::collections::BTreeSet = + metric.iter().map(|s| s.labels.id).collect(); + assert_eq!(metric_series.len(), 3); + assert!(metric + .iter() + .all(|s| s.fields.is_empty() && s.labels.len() == 3)); + } + + /// A keyed table's row lacking a key label is the series of the key + /// labels it has (here only `__name__`); its other labels are fields. + #[test] + fn a_keyed_row_missing_a_key_label_is_the_series_of_the_key_labels_it_has() { + let limits = with_layouts(r#"{"t_rw_keyed2": {"series_key": ["src_p16", "proto"]}}"#); + let timeseries = vec![ + series(&[("__name__", "t_rw_keyed2"), ("src_ip", "1")], &[(1, 1.0)]), + series(&[("__name__", "t_rw_keyed2"), ("src_ip", "2")], &[(2, 2.0)]), + series( + &[("__name__", "t_rw_keyed2"), ("proto", "6"), ("src_ip", "3")], + &[(3, 3.0)], + ), + ]; + let samples = decode_samples(&encode(&WriteRequest { timeseries }), &limits).unwrap(); + assert_eq!(samples[0].labels.id, samples[1].labels.id); + assert_eq!(samples[0].labels.len(), 1); + assert_ne!(samples[2].labels.id, samples[0].labels.id); + assert_eq!( + samples[2].labels.get("proto").map(String::as_str), + Some("6") + ); + for (sample, src_ip) in samples.iter().zip(["1", "2", "3"]) { + assert_eq!( + sample.fields.to_vec(), + vec![("src_ip", Box::::from(src_ip))] + ); + } + } + fn series(labels: &[(&str, &str)], samples: &[(i64, f64)]) -> TimeSeries { TimeSeries { labels: labels diff --git a/data_plane/src/series_ids.rs b/data_plane/src/series_ids.rs index ab7c0ae84..f3767d10d 100644 --- a/data_plane/src/series_ids.rs +++ b/data_plane/src/series_ids.rs @@ -175,6 +175,39 @@ pub fn by_identity(identity: &str) -> Option<&'static Series> { Some(interner.series[id as usize]) } +/// The number of series interned so far, over every metric. +pub fn interned_count() -> usize { + interner().read().expect("interner lock").series.len() +} + +/// The number of series of `metric` interned so far (a scan of every +/// series: for tests and benches). +pub fn interned_count_of(metric: &str) -> usize { + let interner = interner().read().expect("interner lock"); + interner + .series + .iter() + .filter(|series| &*series.metric == metric) + .count() +} + +/// `name` as a `&'static str`, one copy per distinct name: a table row's +/// field names ([`crate::store::RawSample::fields`]). Never forgets a name. +pub fn intern_name(name: &str) -> &'static str { + static NAMES: OnceLock>> = OnceLock::new(); + let names = NAMES.get_or_init(RwLock::default); + if let Some(&known) = names.read().expect("names lock").get(name) { + return known; + } + let mut names = names.write().expect("names lock"); + if let Some(&known) = names.get(name) { + return known; + } + let leaked: &'static str = Box::leak(name.into()); + names.insert(leaked); + leaked +} + /// A series' label set, shared by every row and answer that carries it. pub type Labels = Arc>; diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 7917de062..eeea33685 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -57,17 +57,25 @@ use crate::series_ids::Series; use crate::window_cache::{WindowCache, WindowKey}; /// One raw sample: its series (interned: its id and full label set, -/// `__name__` included), time and value. +/// `__name__` included), time and value. A row of a table with a series +/// key ([`crate::table_layout`]) also carries its fields: the labels not in +/// its key, by name, sorted by name; empty for every other sample. #[derive(Debug, Clone, PartialEq)] pub struct RawSample { pub labels: &'static Series, pub timestamp_ms: i64, pub value: f64, + pub fields: RowFields, } +/// A row's fields: `(column name, text)`, sorted by name. +pub type RowFields = Box<[(&'static str, Box)]>; + /// Raw samples of one metric, columnar and immutable: one Remote Write /// request's samples of a pane, or a closed pane's samples compacted into -/// one chunk. Rows keep arrival order. +/// one chunk. Rows keep arrival order, except in a compacted chunk with +/// fields (a table stored by series key), whose rows are sorted by series, +/// then time (ties in arrival order). #[derive(Debug)] struct Chunk { time: TimestampMillisecondArray, @@ -76,18 +84,72 @@ struct Chunk { codes: UInt32Array, /// The chunk's distinct series, in order of their first row. series: Vec<&'static Series>, - /// Each series' identity text, by code: the dictionary of the series - /// identity column, built by the first read that needs it and shared by - /// every later one. - identities: std::sync::OnceLock, + /// A keyed table's fields (its labels outside the series key), sorted + /// by name: each row's text, dictionary-coded over the chunk's + /// distinct values (`''` for a row without the field). + fields: Vec<(&'static str, TextColumn)>, + /// Rows sorted by series, then time. + sorted: bool, + /// The columns built from the series' labels (each a dictionary whose + /// keys are `codes`: one entry per series, no work per row), built by + /// the first read that needs one and shared by every later read, for + /// the chunk's life. + built: Mutex>, /// The oldest and newest sample time. time_bounds_ms: (i64, i64), } +/// A text column: `u32` codes over its distinct values. +type TextColumn = DictionaryArray; + +/// Builds a [`TextColumn`]: one code per distinct text, in order of first +/// appearance. +#[derive(Default)] +struct TextBuilder<'a> { + code_of: ahash::HashMap<&'a str, u32>, + texts: Vec<&'a str>, + keys: Vec, +} + +impl<'a> TextBuilder<'a> { + fn push(&mut self, text: &'a str) { + let code = *self.code_of.entry(text).or_insert_with(|| { + self.texts.push(text); + self.texts.len() as u32 - 1 + }); + self.keys.push(code); + } + + fn finish(self) -> TextColumn { + DictionaryArray::new( + UInt32Array::from(self.keys), + Arc::new(StringArray::from(self.texts)), + ) + } +} + +/// The text of `column` at `row`. +fn text_at(column: &TextColumn, row: usize) -> &str { + let texts = column + .values() + .as_any() + .downcast_ref::() + .expect("text columns are dictionaries over strings"); + texts.value(column.keys().value(row) as usize) +} + +/// The field `name` of a row's fields (sorted by name); `''` without it. +fn field_text<'a>(fields: &'a RowFields, name: &str) -> &'a str { + match fields.binary_search_by(|(n, _)| (*n).cmp(name)) { + Ok(index) => &fields[index].1, + Err(_) => "", + } +} + impl Chunk { /// `rows` (series, time, value), in order; `None` when there is none. fn new(rows: impl Iterator) -> Option { - let mut code_of: HashMap = HashMap::new(); + let mut code_of: ahash::HashMap = ahash::HashMap::default(); let mut series: Vec<&'static Series> = Vec::new(); let (mut times, mut values, mut codes) = (Vec::new(), Vec::new(), Vec::new()); for (row_series, time, value) in rows { @@ -99,17 +161,95 @@ impl Chunk { values.push(value); codes.push(code); } + Self::from_parts(times, values, codes, series, Vec::new(), false) + } + + fn from_parts( + times: Vec, + values: Vec, + codes: Vec, + series: Vec<&'static Series>, + fields: Vec<(&'static str, TextColumn)>, + sorted: bool, + ) -> Option { let time_bounds_ms = (*times.iter().min()?, *times.iter().max()?); Some(Self { time: TimestampMillisecondArray::from(times), value: Float64Array::from(values), codes: UInt32Array::from(codes), series, - identities: std::sync::OnceLock::new(), + fields, + sorted, + built: Mutex::default(), time_bounds_ms, }) } + /// `samples`, in order, with their fields; `None` when there is none. + fn from_samples(samples: &[&RawSample]) -> Option { + let names: BTreeSet<&'static str> = samples + .iter() + .flat_map(|s| s.fields.iter().map(|(name, _)| *name)) + .collect(); + let mut chunk = Self::new(samples.iter().map(|s| (s.labels, s.timestamp_ms, s.value)))?; + chunk.fields = names + .into_iter() + .map(|name| { + let mut column = TextBuilder::default(); + for sample in samples { + column.push(field_text(&sample.fields, name)); + } + (name, column.finish()) + }) + .collect(); + Some(chunk) + } + + /// The chunks' rows as one chunk: in order for chunks without fields; + /// with fields, sorted by series (id), then time, ties in order, each + /// field's dictionary rebuilt over the rows' values. + fn compacted(chunks: &[Arc]) -> Option { + if chunks.iter().all(|chunk| chunk.fields.is_empty()) { + return Self::new(chunks.iter().flat_map(|chunk| chunk.rows())); + } + let mut rows: Vec<(u32, u32)> = chunks + .iter() + .enumerate() + .flat_map(|(c, chunk)| (0..chunk.len() as u32).map(move |r| (c as u32, r))) + .collect(); + let series_of = |&(c, r): &(u32, u32)| { + let chunk = &chunks[c as usize]; + chunk.series[chunk.codes.value(r as usize) as usize] + }; + let time_of = |&(c, r): &(u32, u32)| chunks[c as usize].time.value(r as usize); + rows.sort_by_key(|row| (series_of(row).id, time_of(row))); + let mut chunk = Self::new(rows.iter().map(|row| { + ( + series_of(row), + time_of(row), + chunks[row.0 as usize].value.value(row.1 as usize), + ) + }))?; + let names: BTreeSet<&'static str> = chunks + .iter() + .flat_map(|chunk| chunk.fields.iter().map(|(name, _)| *name)) + .collect(); + chunk.fields = names + .into_iter() + .map(|name| { + let sources: Vec> = + chunks.iter().map(|chunk| chunk.field(name)).collect(); + let mut column = TextBuilder::default(); + for &(c, r) in &rows { + column.push(sources[c as usize].map_or("", |f| text_at(f, r as usize))); + } + (name, column.finish()) + }) + .collect(); + chunk.sorted = true; + Some(chunk) + } + fn rows(&self) -> impl Iterator + '_ { self.codes .values() @@ -123,26 +263,73 @@ impl Chunk { self.time.len() } - /// Each series' identity text, by code. - fn identities(&self) -> &ArrayRef { - self.identities.get_or_init(|| { - Arc::new(StringArray::from_iter_values( - self.series.iter().map(|s| &*s.identity), - )) - }) + fn field(&self, name: &str) -> Option<&TextColumn> { + self.fields + .iter() + .find(|(field, _)| *field == name) + .map(|(_, column)| column) } fn bytes(&self) -> usize { + let built: usize = self + .built + .lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .map( + |column| match column.as_any().downcast_ref::() { + // The keys are `codes`, counted once. + Some(dictionary) => dictionary.values().get_array_memory_size(), + None => column.get_array_memory_size(), + }, + ) + .sum(); self.time.get_array_memory_size() + self.value.get_array_memory_size() + self.codes.get_array_memory_size() + self - .identities - .get() - .map_or(0, |identities| identities.get_array_memory_size()) + .fields + .iter() + .map(|(_, column)| column.get_array_memory_size()) + .sum::() + + built + self.series.len() * std::mem::size_of::<&Series>() } + /// The rows `rows` (ascending), as a chunk; `None` for none. Fields + /// keep their dictionaries. + fn take(&self, rows: &[u32]) -> Option { + const DROPPED: u32 = u32::MAX; + let mut new_code = vec![DROPPED; self.series.len()]; + let mut series = Vec::new(); + let (mut times, mut values, mut codes) = ( + Vec::with_capacity(rows.len()), + Vec::with_capacity(rows.len()), + Vec::with_capacity(rows.len()), + ); + for &row in rows { + let row = row as usize; + let old = self.codes.value(row) as usize; + if new_code[old] == DROPPED { + new_code[old] = series.len() as u32; + series.push(self.series[old]); + } + codes.push(new_code[old]); + times.push(self.time.value(row)); + values.push(self.value.value(row)); + } + let fields = self + .fields + .iter() + .map(|(name, column)| { + let keys = column.keys().values(); + let taken = UInt32Array::from_iter_values(rows.iter().map(|&r| keys[r as usize])); + (*name, DictionaryArray::new(taken, column.values().clone())) + }) + .collect(); + Self::from_parts(times, values, codes, series, fields, self.sorted) + } + /// The rows in `(start, end]`; the chunk itself when all are. fn in_range(self: &Arc, (start, end): (i64, i64)) -> Option> { let (oldest, newest) = self.time_bounds_ms; @@ -152,7 +339,13 @@ impl Chunk { if newest <= start || end < oldest { return None; } - Self::new(self.rows().filter(|(_, t, _)| start < *t && *t <= end)).map(Arc::new) + let rows: Vec = (0..self.len() as u32) + .filter(|&r| { + let t = self.time.value(r as usize); + start < t && t <= end + }) + .collect(); + self.take(&rows).map(Arc::new) } /// The rows of the series in `partition`, in order: the chunk itself @@ -163,83 +356,113 @@ impl Chunk { /// 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. + /// none. `keep` is asked once per series of the chunk. 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 keep(one) { - new_code[code] = series.len() as u32; - series.push(*one); + let kept: Vec = self.series.iter().map(|series| keep(series)).collect(); + self.cut(&kept, &[]) + } + + /// The rows a label selection keeps: of the series it selects by their + /// labels (`verdicts`), and, for a restricted label that is a field of + /// this chunk, whose field value it allows (the allowed dictionary + /// entries found once per chunk; a chunk allowing none is skipped + /// without touching its rows). + fn select_by(self: &Arc, verdicts: &SeriesVerdicts) -> Option> { + let mut allowed_entries: Vec<(usize, Vec)> = Vec::new(); + for (label, values) in verdicts.selection.restrictions() { + let Some(index) = self + .fields + .iter() + .position(|(name, _)| *name == label.as_str()) + else { + continue; + }; + let texts = self.fields[index] + .1 + .values() + .as_any() + .downcast_ref::() + .expect("text columns are dictionaries over strings"); + let allowed: Vec = (0..texts.len()) + .map(|entry| values.contains(texts.value(entry))) + .collect(); + if !allowed.iter().any(|&a| a) { + return None; } + allowed_entries.push((index, allowed)); } - if series.len() == self.series.len() { - return Some(self.clone()); - } - if series.is_empty() { + let is_field = |label: &str| self.field(label).is_some(); + let kept: Vec = self + .series + .iter() + .map(|series| verdicts.keeps(series, is_field)) + .collect(); + self.cut(&kept, &allowed_entries) + } + + /// The rows of the series `kept` keeps (by code) whose fields hold an + /// allowed entry in each of `allowed_entries` (field index, allowed + /// dictionary entries): the chunk itself when that is every row. + fn cut( + self: &Arc, + kept: &[bool], + allowed_entries: &[(usize, Vec)], + ) -> Option> { + if !kept.iter().any(|&k| k) { return None; } - let (mut times, mut values, mut codes) = (Vec::new(), Vec::new(), Vec::new()); - let rows = self - .codes - .values() + if allowed_entries.is_empty() && kept.iter().all(|&k| k) { + return Some(self.clone()); + } + let codes = self.codes.values(); + let field_keys: Vec<(&[u32], &[bool])> = allowed_entries .iter() - .zip(self.time.values().iter()) - .zip(self.value.values().iter()); - for ((&code, &time), &value) in rows { - let code = new_code[code as usize]; - if code != DROPPED { - times.push(time); - values.push(value); - codes.push(code); - } + .map(|(index, allowed)| (&self.fields[*index].1.keys().values()[..], &allowed[..])) + .collect(); + let rows: Vec = (0..self.len()) + .filter(|&r| { + kept[codes[r] as usize] + && field_keys + .iter() + .all(|(keys, allowed)| allowed[keys[r] as usize]) + }) + .map(|r| r as u32) + .collect(); + if rows.len() == self.len() { + return Some(self.clone()); } - let time_bounds_ms = (*times.iter().min()?, *times.iter().max()?); - Some(Arc::new(Self { - time: TimestampMillisecondArray::from(times), - value: Float64Array::from(values), - codes: UInt32Array::from(codes), - series, - identities: std::sync::OnceLock::new(), - time_bounds_ms, - })) + self.take(&rows).map(Arc::new) } fn column(&self, kind: &ColumnKind) -> Result { - Ok(match kind { - ColumnKind::Time => Arc::new(self.time.clone()), - ColumnKind::Value => Arc::new(self.value.clone()), - ColumnKind::SeriesIdentity => Arc::new( - DictionaryArray::try_new(self.codes.clone(), self.identities().clone()) - .map_err(|e| Error::Invalid(e.to_string()))?, - ), - ColumnKind::Label(name) => { - // Series sharing a label value share its dictionary entry. - let mut code_of_text: HashMap<&str, u32> = HashMap::new(); - let mut texts: Vec<&str> = Vec::new(); - let label_code: Vec = self - .series + let label = match kind { + ColumnKind::Time => return Ok(Arc::new(self.time.clone())), + ColumnKind::Value => return Ok(Arc::new(self.value.clone())), + ColumnKind::Label(name) => match self.field(name) { + Some(field) => return Ok(Arc::new(field.clone())), + None => Some(name), + }, + ColumnKind::SeriesIdentity => None, + }; + let mut built = self.built.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(column) = built.get(kind) { + return Ok(column.clone()); + } + // One entry per series: series sharing a value repeat it. + let texts: StringArray = match label { + Some(name) => StringArray::from_iter_values( + self.series .iter() - .map(|series| { - let text = series.get(name).map_or("", String::as_str); - *code_of_text.entry(text).or_insert_with(|| { - texts.push(text); - texts.len() as u32 - 1 - }) - }) - .collect(); - let keys = UInt32Array::from_iter_values( - self.codes.values().iter().map(|&c| label_code[c as usize]), - ); - Arc::new( - DictionaryArray::try_new(keys, Arc::new(StringArray::from(texts))) - .map_err(|e| Error::Invalid(e.to_string()))?, - ) - } - }) + .map(|series| series.get(name).map_or("", String::as_str)), + ), + None => StringArray::from_iter_values(self.series.iter().map(|s| &*s.identity)), + }; + let column: ArrayRef = Arc::new( + DictionaryArray::try_new(self.codes.clone(), Arc::new(texts)) + .map_err(|e| Error::Invalid(e.to_string()))?, + ); + built.insert(kind.clone(), column.clone()); + Ok(column) } } @@ -302,7 +525,7 @@ impl RawData { let Some(metric) = self.by_metric.get_mut(metric) else { continue; }; - let chunk = Chunk::new(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))); + let chunk = Chunk::from_samples(&rows); metric .panes .entry(pane_end) @@ -317,8 +540,9 @@ impl RawData { pub fn seal_through(&mut self, watermark_ms: i64) { for metric in self.by_metric.values_mut() { for (_, pane) in metric.panes.range_mut(..=watermark_ms) { - if pane.len() > 1 { - let compacted = Chunk::new(pane.iter().flat_map(|chunk| chunk.rows())); + let unsorted = |chunk: &Arc| !chunk.fields.is_empty() && !chunk.sorted; + if pane.len() > 1 || pane.iter().any(unsorted) { + let compacted = Chunk::compacted(pane); *pane = compacted.map(Arc::new).into_iter().collect(); } } @@ -435,14 +659,14 @@ impl RawData { // `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)) { + match stored.select_by(verdicts) { None => Ok(None), Some(cut) if Arc::ptr_eq(&cut, stored) => whole(stored).map(Some), Some(cut) => convert(&cut).map(Some), } })? } - (Some(verdicts), _) => match chunk.select(|series| verdicts.keeps(series)) { + (Some(verdicts), _) => match chunk.select_by(verdicts) { None => None, Some(cut) if Arc::ptr_eq(&cut, stored) => Some(whole(stored)?), Some(cut) => Some(convert(&cut)?), @@ -473,16 +697,39 @@ impl SeriesVerdicts { } } - fn keeps(&self, series: &Series) -> bool { + /// Whether `series` holds one of the allowed values of every + /// restricted label, a label it lacks passing when `is_field` says the + /// chunk holds it as a field (its rows are then judged by value). + fn keeps(&self, series: &Series, is_field: impl Fn(&str) -> bool) -> 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); } if by_id[id] == 0 { - by_id[id] = if self.selection.holds(series) { 1 } else { 2 }; + let mut lacks = false; + let mut holds = true; + for (label, values) in self.selection.restrictions() { + match series.get(label) { + Some(value) => holds &= values.contains(value), + None => lacks = true, + } + } + by_id[id] = match (holds, lacks) { + (false, _) => 2, + (true, false) => 1, + (true, true) => 3, + }; + } + match by_id[id] { + 1 => true, + 2 => false, + _ => self + .selection + .restrictions() + .keys() + .all(|label| series.get(label).is_some() || is_field(label)), } - by_id[id] == 1 } } @@ -527,7 +774,7 @@ pub(crate) struct PartitionReads { partition: SeriesPartition, /// By chunk address; each entry holds the chunk, so its address is not /// reused while it is kept. - chunks: Mutex>, + chunks: Mutex>, } /// A stored chunk and its rows of one part of the series (`None`: none). @@ -569,10 +816,10 @@ pub struct RawReads { conversions: AtomicU64, } -type ConvertedChunks = HashMap<(usize, usize), (Arc, SchemaRef, Batch)>; +type ConvertedChunks = ahash::HashMap<(usize, usize), (Arc, SchemaRef, Batch)>; type SelectedChunks = - HashMap<(usize, usize, Arc), (Arc, SchemaRef, Option)>; + ahash::HashMap<(usize, usize, Arc), (Arc, SchemaRef, Option)>; impl Default for RawReads { fn default() -> Self { @@ -650,13 +897,14 @@ pub(crate) fn stored_series(source: &Source) -> &str { } /// What one column of a time series table holds. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] enum ColumnKind { Time, Value, /// The canonical JSON of every label, `__name__` included. SeriesIdentity, - /// One label's value, empty when the series lacks it. + /// One label's value, empty when the series lacks it; a keyed + /// table's field when the chunk holds one of that name. Label(String), } @@ -1897,6 +2145,7 @@ mod tests { labels: series, timestamp_ms: t + index as i64, value: (t / 100 + index as i64) as f64, + fields: Box::default(), }); } } @@ -1904,6 +2153,7 @@ mod tests { labels: series[0], timestamp_ms: 4_242, value: -1.0, + fields: Box::default(), }]); requests } @@ -2100,6 +2350,7 @@ mod tests { labels, timestamp_ms, value: 1.0, + fields: Box::default(), }; 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. @@ -2187,6 +2438,380 @@ mod tests { } } + // --- Tables stored by series key (`crate::table_layout`) --- + + const TABLE: &str = "t_store_rows"; + + /// `(ts, job, instance, value)`: a table read. + fn table_schema() -> Arc { + Arc::new(Schema::with_time_index( + vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain("job", DataType::Utf8, false), + Field::plain("instance", DataType::Utf8, false), + Field::plain("value", DataType::Float64, false), + ], + 0, + vec![], + )) + } + + /// One table row: job, instance, time, value. + type TableRow = (&'static str, String, i64, f64); + + /// Rows of [`TABLE`] every 300 ms over 30 s, in requests of 2 s: job + /// `a` with instances i0..i2 and job `b` with i3, i4, plus i5 (job b) + /// from 20 s on only; rows of one request interleave jobs, and times + /// repeat across jobs. + fn table_rows() -> Vec> { + let mut requests: Vec> = Vec::new(); + for t in (0..30_000).step_by(300) { + if t % 2_000 < 300 { + requests.push(Vec::new()); + } + for i in 0..6 { + if i == 5 && t < 20_000 { + continue; + } + let job = if i < 3 { "a" } else { "b" }; + requests.last_mut().unwrap().push(( + job, + format!("i{i}"), + t + (5 - i) * 7, + (t / 300 * 10 + i) as f64, + )); + } + } + requests + } + + /// `rows` as samples of the label layout: each `(job, instance)` its + /// own series. + fn label_layout(rows: &[TableRow]) -> Vec { + rows.iter() + .map(|(job, instance, t, v)| RawSample { + labels: intern_pairs(&[ + ("__name__", TABLE), + ("instance", instance.as_str()), + ("job", *job), + ]), + timestamp_ms: *t, + value: *v, + fields: Box::default(), + }) + .collect() + } + + /// `rows` as samples of the table keyed by `job`: one series per job, + /// `instance` a field. + fn keyed_layout(rows: &[TableRow]) -> Vec { + rows.iter() + .map(|(job, instance, t, v)| RawSample { + labels: intern_pairs(&[("__name__", TABLE), ("job", *job)]), + timestamp_ms: *t, + value: *v, + fields: Box::new([("instance", instance.clone().into_boxed_str())]), + }) + .collect() + } + + /// The table's rows in `range`, as a read of [`table_schema`] returns + /// them. + fn table_read(rows: &[TableRow], range: Option<(i64, i64)>) -> Vec> { + rows.iter() + .filter(|(_, _, t, _)| range.is_none_or(|(start, end)| start < *t && *t <= end)) + .map(|(job, instance, t, v)| { + vec![ + Value::Timestamp(*t), + Value::Utf8((*job).into()), + Value::Utf8(instance.as_str().into()), + Value::Float64(*v), + ] + }) + .collect() + } + + fn table_data(requests: &[Vec]) -> RawData { + let mut raw = RawData::for_metrics(&[TABLE.to_string()], 5_000); + for request in requests { + raw.append(request); + } + raw + } + + /// A read of [`TABLE`] with `predicates`: its batches and rows in the + /// time range. + fn table_read_with( + raw: &RawData, + range: Option<(i64, i64)>, + predicates: &[ScalarExpr<()>], + reads: Option<&RawReads>, + ) -> (Vec, u64) { + let schema = table_schema(); + let request = RawDataRequest { + time_range_ms: range, + schema: &schema, + predicates, + }; + let read = raw.read(TABLE, &request, reads, None).unwrap(); + (read.batches, read.rows_in_time_range) + } + + fn rows_of(batches: &[Batch]) -> Vec> { + batches.iter().flat_map(Batch::to_rows).collect() + } + + /// `column = 'v'` (`in_list`: `column IN (..)`) on [`table_schema`]. + fn text_is(column: usize, values: &[&str]) -> ScalarExpr<()> { + let literal = |v: &str| ScalarExpr::Literal(ScalarValue::Utf8(v.into())); + match values { + [one] => ScalarExpr::Compare { + left: Box::new(ScalarExpr::Column(column)), + op: CompareOpKind::Eq, + right: Box::new(literal(one)), + semantics: ExprSemantics::Sql, + }, + many => ScalarExpr::InList { + expr: Box::new(ScalarExpr::Column(column)), + list: many.iter().map(|v| literal(v)).collect(), + negated: false, + }, + } + } + + /// A table keyed by `job` reads the same rows as the label layout + /// (each `(job, instance)` its own series), for ranges in one pane, + /// across panes and unbounded, before and after compaction, with and + /// without shared conversions: a field column reads each row's own + /// value. + #[test] + fn keyed_table_reads_the_label_layout_rows() { + let requests = table_rows(); + let rows: Vec = requests.iter().flatten().cloned().collect(); + let mut labels = table_data(&requests.iter().map(|r| label_layout(r)).collect::>()); + let mut keyed = table_data(&requests.iter().map(|r| keyed_layout(r)).collect::>()); + 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 { + labels.seal_through(20_000); + keyed.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 expected = sorted(table_read(&rows, range)); + let (batches, _) = table_read_with(&labels, range, &[], reads); + assert_eq!(sorted(rows_of(&batches)), expected, "label layout, {what}"); + let (batches, _) = table_read_with(&keyed, range, &[], reads); + assert_eq!(sorted(rows_of(&batches)), expected, "keyed, {what}"); + } + } + } + } + + /// A sealed pane of a keyed table holds each series' rows together, in + /// time order (ties in arrival order): the pane's batch lists each job + /// in one run, its times ascending. + #[test] + fn sealed_keyed_panes_hold_each_series_rows_together_in_time_order() { + let requests = table_rows(); + let mut keyed = table_data(&requests.iter().map(|r| keyed_layout(r)).collect::>()); + keyed.seal_through(30_000); + for pane_end in [5_000, 10_000, 30_000] { + let (batches, _) = + table_read_with(&keyed, Some((pane_end - 5_000, pane_end)), &[], None); + assert_eq!(batches.len(), 1, "pane {pane_end}: one chunk"); + // (job, time) of each row, in batch order. + let rows: Vec<(String, i64)> = rows_of(&batches) + .into_iter() + .map(|row| match (&row[1], &row[0]) { + (Value::Utf8(job), Value::Timestamp(t)) => (job.to_string(), *t), + other => panic!("{other:?}"), + }) + .collect(); + for pair in rows.windows(2) { + if pair[0].0 == pair[1].0 { + assert!( + pair[0].1 <= pair[1].1, + "pane {pane_end}: time order in {pair:?}" + ); + } + } + let mut runs: Vec<&str> = Vec::new(); + for (job, _) in &rows { + if runs.last() != Some(&job.as_str()) { + runs.push(job); + } + } + assert_eq!(runs.len(), 2, "pane {pane_end}: one run per job: {runs:?}"); + } + } + + /// In a keyed chunk's batch, a key column's dictionary has one entry per + /// series of the chunk (its keys are the rows' series codes), and a + /// field column's dictionary one entry per distinct value. + #[test] + fn key_columns_have_an_entry_per_series_and_fields_per_value() { + let requests = table_rows(); + let mut keyed = table_data(&requests.iter().map(|r| keyed_layout(r)).collect::>()); + keyed.seal_through(30_000); + let dictionary_len = |batch: &Batch, column: usize| { + batch + .column(column) + .as_any() + .downcast_ref::>() + .expect("text columns are dictionaries") + .values() + .len() + }; + for (pane_end, instances) in [(5_000, 5), (30_000, 6)] { + let (batches, _) = + table_read_with(&keyed, Some((pane_end - 5_000, pane_end)), &[], None); + assert_eq!(dictionary_len(&batches[0], 1), 2, "pane {pane_end}: job"); + assert_eq!( + dictionary_len(&batches[0], 2), + instances, + "pane {pane_end}: instance" + ); + } + } + + /// A sealed chunk's columns are built once and shared by every later + /// read, whatever run makes it (no shared conversions between them): + /// the second read's columns are the first's arrays. + #[test] + fn sealed_chunk_columns_are_built_once_across_runs() { + let requests = table_rows(); + for keyed_rows in [false, true] { + let samples: Vec> = requests + .iter() + .map(|r| { + if keyed_rows { + keyed_layout(r) + } else { + label_layout(r) + } + }) + .collect(); + let mut raw = table_data(&samples); + raw.seal_through(30_000); + let range = Some((5_000, 10_000)); + let (first, _) = table_read_with(&raw, range, &[], None); + let (second, _) = table_read_with(&raw, range, &[], Some(&RawReads::default())); + for column in 0..4 { + let buffer = |batches: &[Batch]| { + batches[0].column(column).to_data().buffers()[0].as_ptr() as usize + }; + assert_eq!( + buffer(&first), + buffer(&second), + "keyed {keyed_rows}, column {column}: built again" + ); + } + } + } + + /// The columns a read builds count in the raw data's bytes; a pane + /// compacted after a read reads its new rows (no column of a replaced + /// chunk is served), and eviction frees the cached columns with their + /// chunks. + #[test] + fn cached_columns_are_counted_and_follow_compaction_and_eviction() { + let requests = table_rows(); + let rows: Vec = requests.iter().flatten().cloned().collect(); + let (early, late) = requests.split_at(requests.len() / 2); + let mut keyed = table_data(&early.iter().map(|r| keyed_layout(r)).collect::>()); + keyed.seal_through(10_000); + let before = keyed.bytes(); + table_read_with(&keyed, None, &[], None); + assert!( + keyed.bytes() > before, + "built columns are counted: {before} -> {}", + keyed.bytes() + ); + for request in late { + keyed.append(&keyed_layout(request)); + } + table_read_with(&keyed, None, &[], None); + keyed.seal_through(30_000); + let (batches, _) = table_read_with(&keyed, None, &[], None); + assert_eq!(sorted(rows_of(&batches)), sorted(table_read(&rows, None))); + keyed.evict_through(TABLE, 30_000); + assert_eq!(keyed.bytes(), 0); + } + + /// Pushdown on a key column selects series: `job = 'a'` returns job + /// a's rows only (with their own instances), the rows in the time range + /// counting every job's; a pane without job a's series yields no batch. + #[test] + fn pushdown_on_a_key_column_selects_series() { + let requests = table_rows(); + let rows: Vec = requests.iter().flatten().cloned().collect(); + let job_a: Vec = rows.iter().filter(|r| r.0 == "a").cloned().collect(); + let mut keyed = table_data(&requests.iter().map(|r| keyed_layout(r)).collect::>()); + for sealed in [false, true] { + if sealed { + keyed.seal_through(20_000); + } + for range in [None, Some((2_100, 27_001))] { + let (batches, in_range) = + table_read_with(&keyed, range, &[text_is(1, &["a"])], None); + assert_eq!( + sorted(rows_of(&batches)), + sorted(table_read(&job_a, range)), + "sealed {sealed}, {range:?}" + ); + assert_eq!(in_range as usize, table_read(&rows, range).len()); + } + } + let mut only_b = table_data(&[keyed_layout(&[("b", "i3".into(), 1_000, 1.0)])]); + only_b.seal_through(5_000); + let (batches, in_range) = table_read_with(&only_b, None, &[text_is(1, &["a"])], None); + assert_eq!((batches.len(), in_range), (0, 1)); + } + + /// Pushdown on a field column: a chunk whose dictionary holds none of + /// the values yields no batch, and a chunk holding one returns only the + /// rows with those values (the executor's filter would keep no other); + /// it composes with a key column's selection. + #[test] + fn pushdown_on_a_field_column_skips_chunks_and_rows_without_the_values() { + let requests = table_rows(); + let rows: Vec = requests.iter().flatten().cloned().collect(); + let mut keyed = table_data(&requests.iter().map(|r| keyed_layout(r)).collect::>()); + keyed.seal_through(30_000); + // i5 appears from 20 s on only: panes 25 000 and 30 000. + let i5: Vec = rows.iter().filter(|r| r.1 == "i5").cloned().collect(); + let (batches, in_range) = table_read_with(&keyed, None, &[text_is(2, &["i5"])], None); + assert_eq!(sorted(rows_of(&batches)), sorted(table_read(&i5, None))); + assert_eq!(batches.len(), 2, "only the chunks holding i5"); + assert_eq!(in_range as usize, rows.len()); + // Field and key restrictions together. + let selected: Vec = rows + .iter() + .filter(|r| r.0 == "a" && (r.1 == "i1" || r.1 == "i4")) + .cloned() + .collect(); + let predicates = [text_is(1, &["a"]), text_is(2, &["i1", "i4"])]; + let (batches, _) = table_read_with(&keyed, None, &predicates, Some(&RawReads::default())); + assert_eq!( + sorted(rows_of(&batches)), + sorted(table_read(&selected, None)) + ); + // A value no chunk holds: nothing read. + let (batches, _) = table_read_with(&keyed, None, &[text_is(2, &["i9"])], None); + assert!(batches.is_empty()); + } + /// 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/src/table_layout.rs b/data_plane/src/table_layout.rs new file mode 100644 index 000000000..c95f568f4 --- /dev/null +++ b/data_plane/src/table_layout.rs @@ -0,0 +1,157 @@ +//! How a SQL table's rows are stored (deployment configuration, +//! `--table-layouts`): which of its columns form its **series key**. +//! +//! A table's rows arrive as Remote Write samples, one per row: the +//! series `{__name__=, =, ..}` with the row's `value`. +//! Without a layout every label is part of the series, so a table whose +//! rows each carry a distinct label value (a packet's `src_ip`) becomes one +//! series per row. With a layout, only the key columns' labels (and +//! `__name__`) form the series; every other label is a **field** of the +//! row, stored as a column inside the series' chunks ([`crate::store`]). +//! +//! ```json +//! {"packets": {"series_key": ["src_p16"]}} +//! ``` +//! +//! Metrics, and tables without a layout, keep one series per label set. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::Deserialize; + +/// The series key of each table that declares one. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +#[serde(transparent)] +pub struct TableLayouts { + by_table: BTreeMap, +} + +/// One table's layout. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TableLayout { + /// The columns whose values form a row's series; may be empty (the + /// whole table is one series). + pub series_key: Vec, +} + +impl TableLayouts { + /// Parses and checks a layouts file: a key column is never `__name__` + /// or `value`, nor named twice. + pub fn from_json(text: &str) -> anyhow::Result { + let layouts: Self = serde_json::from_str(text)?; + for (table, layout) in &layouts.by_table { + let mut seen = BTreeSet::new(); + for column in &layout.series_key { + anyhow::ensure!( + column != "__name__" && column != "value", + "table {table}: `{column}` cannot be a series key column" + ); + anyhow::ensure!( + seen.insert(column.as_str()), + "table {table}: series key column `{column}` named twice" + ); + } + } + Ok(layouts) + } + + pub fn get(&self, table: &str) -> Option<&TableLayout> { + self.by_table.get(table) + } + + pub fn is_empty(&self) -> bool { + self.by_table.is_empty() + } + + /// A row's Remote Write label pairs split into its series key + /// (`__name__` and the key columns' labels) and its fields (every other + /// label), each in the order given. A metric, or a table without a + /// layout: every pair is in the key. + pub fn split<'a>( + &self, + pairs: &[(&'a str, &'a str)], + ) -> (Vec<(&'a str, &'a str)>, Vec<(&'a str, &'a str)>) { + let metric = pairs + .iter() + .find(|(name, _)| *name == "__name__") + .map(|(_, value)| *value); + let Some(layout) = metric.and_then(|metric| self.by_table.get(metric)) else { + return (pairs.to_vec(), Vec::new()); + }; + pairs.iter().partition(|(name, _)| { + *name == "__name__" || layout.series_key.iter().any(|key| key == name) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A layouts file names each table's series key columns, in order; an + /// empty key is allowed. + #[test] + fn parses_each_tables_series_key() { + let layouts = TableLayouts::from_json( + r#"{"packets": {"series_key": ["src_p16", "proto"]}, "auth": {"series_key": []}}"#, + ) + .unwrap(); + assert_eq!( + layouts.get("packets").unwrap().series_key, + ["src_p16", "proto"] + ); + assert!(layouts.get("auth").unwrap().series_key.is_empty()); + assert!(layouts.get("flows").is_none()); + } + + /// `__name__`, `value`, a column named twice and an unknown setting are + /// refused. + #[test] + fn refuses_bad_layouts() { + for text in [ + r#"{"t": {"series_key": ["__name__"]}}"#, + r#"{"t": {"series_key": ["value"]}}"#, + r#"{"t": {"series_key": ["a", "a"]}}"#, + r#"{"t": {"series_key": ["a"], "sort": "a"}}"#, + r#"{"t": ["a"]}"#, + ] { + assert!(TableLayouts::from_json(text).is_err(), "{text}"); + } + } + + /// A declared table's row: `__name__` and the key labels form its + /// series, the other labels are fields (a missing key label is simply + /// absent); a metric's labels and an undeclared table's all stay in + /// the key. + #[test] + fn splits_a_rows_labels_into_series_key_and_fields() { + let layouts = + TableLayouts::from_json(r#"{"packets": {"series_key": ["src_p16"]}}"#).unwrap(); + let row = [ + ("__name__", "packets"), + ("dst_ip", "3"), + ("src_ip", "65538"), + ("src_p16", "1"), + ]; + assert_eq!( + layouts.split(&row), + ( + vec![("__name__", "packets"), ("src_p16", "1")], + vec![("dst_ip", "3"), ("src_ip", "65538")] + ) + ); + let no_key = [("__name__", "packets"), ("src_ip", "7")]; + assert_eq!( + layouts.split(&no_key), + (vec![("__name__", "packets")], vec![("src_ip", "7")]) + ); + for other in [ + vec![("__name__", "up"), ("instance", "a"), ("src_p16", "1")], + vec![("__name__", "flows"), ("host", "h"), ("user", "u")], + vec![("job", "j")], + ] { + assert_eq!(layouts.split(&other), (other.clone(), vec![])); + } + } +} diff --git a/data_plane/tests/intent_sil_modes.rs b/data_plane/tests/intent_sil_modes.rs index 5255be694..bbbba0166 100644 --- a/data_plane/tests/intent_sil_modes.rs +++ b/data_plane/tests/intent_sil_modes.rs @@ -167,12 +167,18 @@ async fn planned(mode: IntentPlanningMode) -> IntentPlan { /// The planner's plan of the SIL program `text` in `mode`. async fn planned_text(text: &str, mode: IntentPlanningMode) -> IntentPlan { - let catalog = SqlCatalog::new().with_table("flows", table_schema()); + planned_on("flows", text, mode).await +} + +/// The planner's plan of `text` with its table `flows` named `table`. +async fn planned_on(table: &str, text: &str, mode: IntentPlanningMode) -> IntentPlan { + let text = text.replace("FROM flows", &format!("FROM {table}")); + let catalog = SqlCatalog::new().with_table(table, table_schema()); // Declared at production scale, so that keeping state pays off. let data = serde_json::from_value(serde_json::json!({ "arrival": {"ingesting": {"rows_per_second": 100_000.0}}, "sources": { - "flows": {"distinct_values_per_label": {"host": 300, "user": 1000}, "rows_held": 1_000_000_000u64}, + table: {"distinct_values_per_label": {"host": 300, "user": 1000}, "rows_held": 1_000_000_000u64}, }, })) .unwrap(); @@ -180,7 +186,7 @@ async fn planned_text(text: &str, mode: IntentPlanningMode) -> IntentPlan { let models = PlanningModels::builtin() .with_deployment_capabilities(&inputs.deployment_capabilities) .with_cost_inputs(&inputs.cost_inputs); - let intents = asap_frontend_sil::parse_intents(text).unwrap(); + let intents = asap_frontend_sil::parse_intents(&text).unwrap(); let options = IntentPlanningOptions { mode, ..IntentPlanningOptions::default() @@ -203,6 +209,23 @@ async fn install_with( plan: &IntentPlan, tables: &BTreeMap<&str, Vec>, label_pushdown: bool, +) -> Arc { + install_options( + plan, + tables, + EngineOptions { + label_pushdown, + ..EngineOptions::default() + }, + ) + .await +} + +/// [`install`] with `options` (never forwarding). +async fn install_options( + plan: &IntentPlan, + tables: &BTreeMap<&str, Vec>, + options: EngineOptions, ) -> Arc { let state = Arc::new( DataPlane::with_options( @@ -210,8 +233,7 @@ async fn install_with( "http://127.0.0.1:1".into(), EngineOptions { no_forward: true, - label_pushdown, - ..EngineOptions::default() + ..options }, ) .unwrap(), @@ -478,3 +500,114 @@ async fn label_pushdown_reads_the_bound_series_only_and_answers_the_same() { ); } } + +/// Two rounds' answers of the plan installed on `state` and q2's answer +/// bound to `h0`, each sorted, and the raw rows q2's bound call read: +/// (in its time ranges, returned). +async fn rounds_and_bound_q2( + plan: &IntentPlan, + state: &DataPlane, +) -> (Vec<(i64, String, Vec)>, (u64, u64)) { + 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 intent = + IntentLoop::new(schedule, 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.to_string(), 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(); + let mut rows: Vec = answer + .iter() + .map(|s| format!("{:?} {:?}", s.labels, s.value)) + .collect(); + rows.sort(); + answers.push((EVALUATION_MS, "q2 bound to h0".into(), rows)); + let (in_range_after, returned_after) = raw_read_rows(state); + ( + answers, + ( + in_range_after - in_range_before, + returned_after - returned_before, + ), + ) +} + +/// A table stored by series key answers every query as the label layout +/// does (each `(host, user)` its own series), in each planning mode and +/// for keys the queries group or filter by (`host`), both columns (q1's +/// `host` dictionary then repeats values across series), or neither of +/// the filtered column (`user`: `host` is a field). It interns one series +/// per key value (4 hosts, 12 pairs, 3 users, against 12 label sets), and +/// q2 bound to one host of four still reads a quarter of the rows in its +/// time range, by series (key `host`) or by the field's values (key +/// `user`). +#[tokio::test(flavor = "multi_thread")] +async fn keyed_table_answers_equal_the_label_layout_and_exact() { + let rows = tables().remove("flows").unwrap(); + for mode in [ + IntentPlanningMode::QueryAtATime, + IntentPlanningMode::IntentOnDemandHoles, + IntentPlanningMode::IntentFull, + ] { + let plan = planned(mode).await; + let state = install(&plan, &tables()).await; + let (expected, _) = rounds_and_bound_q2(&plan, &state).await; + state.engine.stop(); + // The label layout's answers are exact (q1's top two hosts are h1, h3). + assert_eq!(expected[0].2.len(), 2, "{mode:?}: {:?}", expected[0]); + assert!(expected[0].2[0].contains("h1") && expected[0].2[1].contains("h3")); + for (key, series) in [ + (vec!["host"], 4), + (vec!["host", "user"], 12), + (vec!["user"], 3), + ] { + let table = format!("flows_by_{}_{mode:?}", key.join("_")).to_lowercase(); + let what = format!("{mode:?}, key {key:?}"); + let plan = planned_on(&table, INTENT, mode).await; + let layouts = serde_json::json!({ &table: {"series_key": key} }).to_string(); + let tables = BTreeMap::from([(table.as_str(), rows.clone())]); + let state = install_options( + &plan, + &tables, + EngineOptions { + table_layouts: data_plane::table_layout::TableLayouts::from_json(&layouts) + .unwrap(), + ..EngineOptions::default() + }, + ) + .await; + let (answers, (in_range, returned)) = rounds_and_bound_q2(&plan, &state).await; + assert_eq!(answers, expected, "{what}: answers"); + assert_eq!( + data_plane::series_ids::interned_count_of(&table), + series, + "{what}: series interned" + ); + assert!(in_range > 0, "{what}: q2 read no raw rows"); + assert_eq!(returned * 4, in_range, "{what}: rows returned"); + state.engine.stop(); + } + } +} diff --git a/data_plane/tests/remote_write_reference.rs b/data_plane/tests/remote_write_reference.rs index 0d9d5f745..7cffee2e7 100644 --- a/data_plane/tests/remote_write_reference.rs +++ b/data_plane/tests/remote_write_reference.rs @@ -108,6 +108,7 @@ mod reference { labels, timestamp_ms, value, + fields: Box::default(), }); } Ok(())