diff --git a/src/promql/AGENTS.md b/src/promql/AGENTS.md index 891fe19f269..fbd6a6e9139 100644 --- a/src/promql/AGENTS.md +++ b/src/promql/AGENTS.md @@ -69,6 +69,13 @@ scan per selector, each carrying a `RawSeriesSource` that answers explicit-label The frame schema is compared exactly at the merge scan, so its declaration and the region's output change together. +A `RawSeriesSource` over a metric-engine physical table merges stored series +that share a label set (`SeriesRouting::RawLabelSet`). The flag is not +serialized, and standalone hands the region the logical plan unserialized, so the +dist planner clears it (`RawSeriesSource::for_regions`) in the plan it gives +`MergeScanExec` and puts the router above the merge scan. Without a dist planner +(e.g. flownode), `plan_raw_series_source` puts the router above the region scan. + ## Comments and tests Docs on public items state the contract: inputs, guarantees, errors. Private diff --git a/src/promql/src/extension_plan/planner.rs b/src/promql/src/extension_plan/planner.rs index 192d6a0bdc8..39961c25757 100644 --- a/src/promql/src/extension_plan/planner.rs +++ b/src/promql/src/extension_plan/planner.rs @@ -217,7 +217,7 @@ fn plan_raw_series_source( source.fields(), target_partitions, )?; - source.to_per_series_execution_plan(series_scan) + source.merged_by_label_set(source.to_per_series_execution_plan(series_scan)?) } /// The raw-series leaf of a region scan bound to one metric. diff --git a/src/promql/src/extension_plan/raw_series_source.rs b/src/promql/src/extension_plan/raw_series_source.rs index ac3129b9e47..76936c47627 100644 --- a/src/promql/src/extension_plan/raw_series_source.rs +++ b/src/promql/src/extension_plan/raw_series_source.rs @@ -67,6 +67,7 @@ use table::table::scan::SeriesScanExec; use crate::extension_plan::series_execution::{ HandedSeriesChunk, SendableSeriesStream, SeriesChunk, SeriesExecutionPlan, }; +use crate::extension_plan::series_repartition::{SeriesRepartitionExec, SeriesRouting}; use crate::source::materialize_raw_labels; /// The ordering every frame of this node declares. @@ -86,6 +87,14 @@ pub struct RawSeriesSource { tags: Vec, /// The field columns each frame carries, in the order the tree reading them was compiled with. fields: Vec, + /// Whether stored series that share a label set are answered as one series; see + /// [`Self::with_label_set_merge`]. + /// + /// Not part of the wire binding. A distributed planner hands regions the source without it + /// ([`Self::for_regions`]) and merges above its merge scan, where every region's answer + /// arrives; standalone passes the logical plan to the region without serializing it, so the + /// flag would otherwise reach the region too. + merges_label_sets: bool, input: LogicalPlan, schema: DFSchemaRef, } @@ -106,11 +115,56 @@ impl RawSeriesSource { metric_name, tags, fields, + merges_label_sets: false, input, schema, }) } + /// Answers every stored series that shares a label set as one series, samples chained by + /// timestamp, for a table whose storage keys carry identity its labels do not. A metric-engine + /// physical table is that table: each logical table keys its series by `__table_id` and + /// `__tsid`, so two logical tables with equal labels store two series Prometheus would see as + /// one. + pub fn with_label_set_merge(mut self) -> Self { + self.merges_label_sets = true; + self + } + + pub fn merges_label_sets(&self) -> bool { + self.merges_label_sets + } + + /// This source as a region runs it: the region answers its own stored series, and the label-set + /// merge stays with the planner above the regions. + pub fn for_regions(&self) -> Self { + Self { + metric_name: Arc::clone(&self.metric_name), + tags: self.tags.clone(), + fields: self.fields.clone(), + merges_label_sets: false, + input: self.input.clone(), + schema: Arc::clone(&self.schema), + } + } + + /// `frames` - the physical plan delivering this source's frames from every region it reads - + /// with the label-set merge this source asks for above it. + pub fn merged_by_label_set( + &self, + frames: Arc, + ) -> DataFusionResult> { + if !self.merges_label_sets { + return Ok(frames); + } + let outputs = frames.properties().partitioning.partition_count().max(1); + Ok(Arc::new(SeriesRepartitionExec::try_new_with_routing( + frames, + outputs, + SeriesRouting::RawLabelSet, + )?)) + } + pub fn metric_name(&self) -> &str { &self.metric_name } @@ -195,8 +249,18 @@ fn frame_schema(fields: &[String]) -> DataFusionResult { impl PartialOrd for RawSeriesSource { fn partial_cmp(&self, other: &Self) -> Option { // The schema is derived from the fields, so it adds nothing to the order. - (&self.metric_name, &self.tags, &self.fields) - .partial_cmp(&(&other.metric_name, &other.tags, &other.fields)) + ( + &self.metric_name, + &self.tags, + &self.fields, + self.merges_label_sets, + ) + .partial_cmp(&( + &other.metric_name, + &other.tags, + &other.fields, + other.merges_label_sets, + )) .and_then(|ordering| match ordering { std::cmp::Ordering::Equal => self.input.partial_cmp(&other.input), ordering => Some(ordering), @@ -228,7 +292,11 @@ impl UserDefinedLogicalNodeCore for RawSeriesSource { self.metric_name, self.tags.join(", "), self.fields.join(", ") - ) + )?; + if self.merges_label_sets { + write!(f, ", identity=label_set")?; + } + Ok(()) } fn with_exprs_and_inputs( @@ -245,6 +313,7 @@ impl UserDefinedLogicalNodeCore for RawSeriesSource { metric_name: Arc::clone(&self.metric_name), tags: self.tags.clone(), fields: self.fields.clone(), + merges_label_sets: self.merges_label_sets, input: inputs.swap_remove(0), schema: Arc::clone(&self.schema), }) diff --git a/src/promql/src/extension_plan/series_repartition.rs b/src/promql/src/extension_plan/series_repartition.rs index 4cb10b39445..c9334db02a7 100644 --- a/src/promql/src/extension_plan/series_repartition.rs +++ b/src/promql/src/extension_plan/series_repartition.rs @@ -158,10 +158,10 @@ use crate::extension_plan::series_execution::{ HandedSeriesChunk, SendableSeriesStream, SeriesCharge, SeriesChunk, SeriesExecutionPlan, checked_series_stream, series_execution_plan, }; -use crate::grid_series::{label_set, merge_same_labelset}; +use crate::grid_series::{LabelSet, label_set, merge_same_labelset}; use crate::native::execute::{field_segments, merge_workspace_bytes, operand_chunk_bytes}; use crate::native::state::{StateChunk, state_bytes, state_row_of}; -use crate::source::merge_raw_identity_charging; +use crate::source::{merge_raw_identity_charging, merge_raw_label_set_charging}; use datatypes::series::samples::DenseSamplesRef; /// Selects the key used to route a series to an output partition. @@ -175,6 +175,14 @@ pub enum SeriesRouting { Matching(crate::vector_match::MatchingLabels), /// Route raw frames by their complete stored primary key. RawPrimaryKey, + /// Route raw frames by their Prometheus label set and merge every stored series that shares + /// one into a single series, as Prometheus does with series of identical labels. Used where + /// stored keys carry identity the labels do not: a metric-engine physical table keys each + /// logical table's series by `__table_id` and `__tsid`, neither of which is a label. + /// + /// A label set can recur on any input until every input ends, so an owner publishes nothing + /// before every input's EOF. + RawLabelSet, } /// The seed behind every routing decision. @@ -542,9 +550,12 @@ impl SeriesRepartitionExec { })?; let content = declaration.content(); match (content, &routing_policy) { - (FrameContent::Evaluated, SeriesRouting::RawPrimaryKey) => { + ( + FrameContent::Evaluated, + SeriesRouting::RawPrimaryKey | SeriesRouting::RawLabelSet, + ) => { return Err(DataFusionError::Plan( - "SeriesRepartition evaluated frames cannot use RawPrimaryKey routing".into(), + "SeriesRepartition evaluated frames cannot use raw routing".into(), )); } ( @@ -557,7 +568,9 @@ impl SeriesRepartitionExec { } ( FrameContent::AggregateState, - SeriesRouting::RawPrimaryKey | SeriesRouting::Matching(_), + SeriesRouting::RawPrimaryKey + | SeriesRouting::RawLabelSet + | SeriesRouting::Matching(_), ) => { return Err(DataFusionError::Plan( "SeriesRepartition aggregate-state frames require canonical-label routing" @@ -573,14 +586,17 @@ impl SeriesRepartitionExec { SeriesOrdering::Contiguous }; if content == FrameContent::Raw - && ordering == SeriesOrdering::Interleaved + && (ordering == SeriesOrdering::Interleaved + || routing_policy == SeriesRouting::RawLabelSet) && identity_completion == IdentityCompletion::CompleteDisjoint { return Err(DataFusionError::Plan( "SeriesRepartition cannot use CompleteDisjoint with interleaved raw input".into(), )); } - let output_ordering = if ordering == SeriesOrdering::Interleaved { + let output_ordering = if ordering == SeriesOrdering::Interleaved + || routing_policy == SeriesRouting::RawLabelSet + { SeriesOrdering::Contiguous } else { ordering @@ -620,6 +636,13 @@ impl SeriesRepartitionExec { .to_string(), )); } + // Whatever order the child keeps per stored key, one label set may span several keys + // anywhere in it, which is exactly what an interleaved owner waits out. + let ordering = if routing_policy == SeriesRouting::RawLabelSet { + SeriesOrdering::Interleaved + } else { + ordering + }; let properties = PlanProperties::new( EquivalenceProperties::new(declared), Partitioning::UnknownPartitioning(outputs), @@ -734,6 +757,7 @@ impl SeriesRepartitionExec { self.input.properties().partitioning.partition_count(), self.ordering, self.identity_completion, + self.routing_policy == SeriesRouting::RawLabelSet, ) } @@ -793,7 +817,11 @@ impl DisplayAs for SeriesRepartitionExec { "SeriesRepartitionExec: outputs={}, input_partitions={}", self.outputs(), self.input.properties().partitioning.partition_count() - ) + )?; + if self.routing_policy == SeriesRouting::RawLabelSet { + write!(f, ", identity=label_set")?; + } + Ok(()) } } @@ -2315,10 +2343,10 @@ async fn read_raw_chains( Some(output) => output, None => { let output = match &routing.policy { - SeriesRouting::Matching(_) => { + SeriesRouting::Matching(_) | SeriesRouting::RawLabelSet => { let Some(labels) = chunk.metric.as_ref() else { return Stop::Failed(Arc::new(DataFusionError::Execution( - "a matching-routed raw chain carries no labels".into(), + "a label-routed raw chain carries no labels".into(), ))); }; routing.output_labels(labels) @@ -2637,10 +2665,25 @@ impl RawSeriesStream for RawOutputStream { enum OwnerKey { Evaluated(ExactIdentity), Raw(Vec), + /// The Prometheus label set every stored series of one [`SeriesRouting::RawLabelSet`] owner + /// shares. + RawLabelSet(LabelSet), } -fn raw_identity(chunk: &RawSeriesChunk) -> OwnerKey { - OwnerKey::Raw(chunk.primary_key.as_slice().to_vec()) +impl OwnerKey { + fn is_raw(&self) -> bool { + matches!(self, OwnerKey::Raw(_) | OwnerKey::RawLabelSet(_)) + } +} + +fn raw_identity(chunk: &RawSeriesChunk, by_label_set: bool) -> DataFusionResult { + if by_label_set { + let labels = chunk.metric.as_ref().ok_or_else(|| { + DataFusionError::Execution("a label-routed raw chain carries no labels".into()) + })?; + return Ok(OwnerKey::RawLabelSet(label_set(labels))); + } + Ok(OwnerKey::Raw(chunk.primary_key.as_slice().to_vec())) } /// The raw identity of one chunk: its complete stored primary key and nothing else. @@ -2729,7 +2772,7 @@ fn group_ready( completion: IdentityCompletion, key: &OwnerKey, ) -> bool { - if ordering == SeriesOrdering::Interleaved && matches!(key, OwnerKey::Raw(_)) { + if ordering == SeriesOrdering::Interleaved && key.is_raw() { return eof.iter().all(|eof| *eof); } if ordering == SeriesOrdering::KeyThenTime { @@ -2876,6 +2919,9 @@ struct RepartitionStream { /// The input's ordering and identity completion guarantee. ordering: SeriesOrdering, identity_completion: IdentityCompletion, + /// Whether raw chains are grouped by label set ([`SeriesRouting::RawLabelSet`]) rather than + /// by stored key. + by_label_set: bool, groups: BTreeMap, eof: Vec, last_key_from: Vec>>, @@ -2943,6 +2989,7 @@ impl Stream for PackedHandoffStream { } impl RepartitionStream { + #[allow(clippy::too_many_arguments)] fn new( receiver: mpsc::UnboundedReceiver, lease: OutputLease, @@ -2951,6 +2998,7 @@ impl RepartitionStream { inputs: usize, ordering: SeriesOrdering, identity_completion: IdentityCompletion, + by_label_set: bool, ) -> Self { Self { receiver, @@ -2958,6 +3006,7 @@ impl RepartitionStream { schema, ordering, identity_completion, + by_label_set, pool: Arc::clone(pool), groups: BTreeMap::new(), eof: Vec::new(), @@ -2991,8 +3040,10 @@ impl RepartitionStream { let Some(group) = self.groups.remove(key) else { return Ok(()); }; - if matches!(key, OwnerKey::Raw(_)) { - return self.finish_raw_group(group); + match key { + OwnerKey::Raw(_) => return self.finish_raw_group(group), + OwnerKey::RawLabelSet(_) => return self.finish_raw_label_set(group), + OwnerKey::Evaluated(_) => {} } let workspace = if group.fragments.len() > 1 { let rows = group.fragments.iter().fold(0usize, |rows, series| { @@ -3088,6 +3139,35 @@ impl RepartitionStream { }); Ok(()) } + + /// Publishes the stored series of one label set as one series; see + /// [`merge_raw_label_set_charging`] for which sample a shared timestamp keeps. + fn finish_raw_label_set(&mut self, mut group: PendingGroup) -> DataFusionResult<()> { + if group.raw_chunks.len() == 1 { + return self.finish_raw_group(group); + } + let workspace = MemoryConsumer::new("SeriesRepartitionRawOwner").register(&self.pool); + let mut reserve = |bytes: usize| workspace.try_grow(bytes); + let mut shrink = |bytes: usize| { + let result = workspace.try_shrink(bytes); + debug_assert!( + result.is_ok(), + "raw merge workspace shrink failed: {result:?}" + ); + let _ = result; + }; + let chunk = merge_raw_label_set_charging( + &self.schema, + &mut group.raw_chunks, + &mut reserve, + &mut shrink, + )?; + self.output.push_back(ReadySeries { + series: ReadyOutput::Raw(chunk), + charge: SeriesCharge::new(group.charges, group.metadata, Some(workspace)), + }); + Ok(()) + } } impl Stream for RepartitionStream { @@ -3247,7 +3327,13 @@ impl Stream for RepartitionStream { let Some(first) = chain.first() else { continue; }; - let key = raw_identity(&first.0); + let key = match raw_identity(&first.0, this.by_label_set) { + Ok(key) => key, + Err(error) => { + this.lease.fail(Arc::new(error)); + continue; + } + }; if let OwnerKey::Raw(raw_key) = &key && this.ordering == SeriesOrdering::KeyThenTime { @@ -3281,6 +3367,15 @@ impl Stream for RepartitionStream { ) } OwnerKey::Raw(key) => key.capacity(), + OwnerKey::RawLabelSet(labels) => labels + .capacity() + .saturating_mul(std::mem::size_of::<(Arc, Arc)>()) + .saturating_add( + labels + .iter() + .map(|(n, v)| n.len().saturating_add(v.len())) + .sum::(), + ), }; let bytes = std::mem::size_of::() .saturating_add(std::mem::size_of::()) @@ -3316,7 +3411,7 @@ impl Stream for RepartitionStream { if input >= entry.get().received.len() || (entry.get().received[input] && !(this.ordering == SeriesOrdering::Interleaved - && matches!(entry.key(), OwnerKey::Raw(_)))) + && entry.key().is_raw())) { this.lease.fail(Arc::new(DataFusionError::Execution( "input repeated an exact series identity".into(), @@ -3454,7 +3549,9 @@ impl Routing { fn output_labels(&self, metric: &SeriesLabels) -> usize { let mut hasher = XxHash64::with_seed(self.seed); match &self.policy { - SeriesRouting::CanonicalLabels => label_set(metric).hash(&mut hasher), + SeriesRouting::CanonicalLabels | SeriesRouting::RawLabelSet => { + label_set(metric).hash(&mut hasher) + } SeriesRouting::CanonicalLabelsExcept(excluded) => { let mut labels = label_set(metric); labels.retain(|(name, _)| !excluded.contains(name)); diff --git a/src/promql/src/extension_plan/series_repartition/tests.rs b/src/promql/src/extension_plan/series_repartition/tests.rs index 701ed44a6b9..097d70133f2 100644 --- a/src/promql/src/extension_plan/series_repartition/tests.rs +++ b/src/promql/src/extension_plan/series_repartition/tests.rs @@ -3837,6 +3837,7 @@ async fn eof_readies_two_groups_but_poll_merges_one_at_a_time() { 1, SeriesOrdering::Contiguous, super::IdentityCompletion::MergeInputs, + false, ); wait_until("both identities and EOF are queued", || { producer_stopped(&shared) @@ -5874,6 +5875,7 @@ async fn a_recorded_failure_reaches_every_output_once() { 2, SeriesOrdering::Contiguous, super::IdentityCompletion::MergeInputs, + false, ))), }) as SendableEvaluatedSeriesStream); } @@ -6211,6 +6213,7 @@ async fn dropping_unpolled_route_future_ends_outputs_and_cancels_peer() { 2, SeriesOrdering::Contiguous, super::IdentityCompletion::MergeInputs, + false, ))), }), Arc::clone(&series_schema), @@ -6323,6 +6326,7 @@ async fn unpolled_route_drop_preserves_an_already_elected_failure() { 2, SeriesOrdering::Contiguous, super::IdentityCompletion::MergeInputs, + false, ))), }), Arc::clone(&schema()), @@ -6485,6 +6489,7 @@ async fn sibling_failure_aborts_budget_yielded_route_and_releases_prefix() { 1, SeriesOrdering::Contiguous, super::IdentityCompletion::MergeInputs, + false, ))), }); let future = route_partition( @@ -7067,6 +7072,7 @@ async fn internal_stream_releases_each_chunk_charge_only_when_polled() { 1, SeriesOrdering::Contiguous, super::IdentityCompletion::MergeInputs, + false, ); wait_until("internal producer finishes", || producer_stopped(&shared)).await; // Queue, EOF, and identity-group metadata are charged alongside the retained chunks, so the @@ -7374,6 +7380,7 @@ async fn histogram_chain_slices_fit_a_budget_below_the_full_table_charge() { 1, SeriesOrdering::Contiguous, super::IdentityCompletion::MergeInputs, + false, ); wait_until("histogram producer queues the whole chain", || { producer_stopped(&shared) diff --git a/src/promql/src/source.rs b/src/promql/src/source.rs index 39cfd2352db..db3c222f6de 100644 --- a/src/promql/src/source.rs +++ b/src/promql/src/source.rs @@ -16,7 +16,7 @@ mod merge; #[cfg(test)] mod tests; -pub(crate) use merge::merge_raw_identity_charging; +pub(crate) use merge::{merge_raw_identity_charging, merge_raw_label_set_charging}; use std::pin::Pin; use std::sync::Arc; diff --git a/src/promql/src/source/merge.rs b/src/promql/src/source/merge.rs index 0cee3695a1a..98d1e35a899 100644 --- a/src/promql/src/source/merge.rs +++ b/src/promql/src/source/merge.rs @@ -15,7 +15,8 @@ #[cfg(test)] mod tests; -use datafusion::arrow::buffer::ScalarBuffer; +use common_query::prometheus::is_prometheus_stale_nan; +use datafusion::arrow::buffer::{Buffer, ScalarBuffer}; use datafusion_common::DataFusionError; use datatypes::error::InvalidSeriesSnafu; use datatypes::series::SeriesLabels; @@ -34,20 +35,9 @@ pub(crate) fn merge_raw_identity_charging( reserve: &mut dyn FnMut(usize) -> std::result::Result<(), DataFusionError>, shrink: &mut dyn FnMut(usize), ) -> std::result::Result { - let invalid = |reason: &str| { - DataFusionError::External(Box::new( - InvalidSeriesSnafu { - reason: reason.to_string(), - } - .build(), - )) - }; let Some(first) = chunks.first() else { return Err(invalid("cannot merge an empty raw identity")); }; - if schema.eval_grid.is_some() { - return Err(invalid("raw series schema cannot have an evaluation grid")); - } let key = first.primary_key.clone(); let labels = first .metric @@ -63,6 +53,81 @@ pub(crate) fn merge_raw_identity_charging( "raw identity chunks have different or missing labels", )); } + } + merge_raw_chunks(schema, chunks, key, labels, reserve, shrink) +} + +/// Rebuilds one series from the pieces of every stored series whose labels make the same +/// Prometheus label set, the way Prometheus chains series with identical labels +/// (`storage.ChainedSeriesMerge`): samples in timestamp order, one per timestamp. +/// +/// Prometheus keeps an arbitrary one of the samples several series hold at one timestamp. Here the +/// first sample that is not a stale marker wins, in the order of the stored primary keys, so the +/// answer does not depend on which region or partition delivered a piece first, and one series +/// going stale does not hide a live sample of another; only a timestamp every series marks stale +/// keeps the marker. The merged series is published under the smallest key and that series' +/// labels. Pieces of one stored series still have to agree at a shared timestamp, exactly as +/// [`merge_raw_identity_charging`] requires. +pub(crate) fn merge_raw_label_set_charging( + schema: &SeriesSchema, + chunks: &mut [RawSeriesChunk], + reserve: &mut dyn FnMut(usize) -> std::result::Result<(), DataFusionError>, + shrink: &mut dyn FnMut(usize), +) -> std::result::Result { + // Stable, so the pieces of one stored series keep the order they arrived in. + chunks.sort_by(|left, right| { + left.primary_key + .as_slice() + .cmp(right.primary_key.as_slice()) + }); + let Some(first) = chunks.first() else { + return Err(invalid("cannot merge an empty raw label set")); + }; + let key = first.primary_key.clone(); + let labels = first + .metric + .as_ref() + .ok_or_else(|| invalid("raw label set chunk has no explicit labels"))? + .clone(); + let expected = label_set(&labels); + for chunk in chunks.iter() { + if chunk + .metric + .as_ref() + .is_none_or(|metric| label_set(metric) != expected) + { + return Err(invalid( + "raw label set chunks have different or missing labels", + )); + } + } + merge_raw_chunks(schema, chunks, key, labels, reserve, shrink) +} + +fn invalid(reason: &str) -> DataFusionError { + DataFusionError::External(Box::new( + InvalidSeriesSnafu { + reason: reason.to_string(), + } + .build(), + )) +} + +/// Chains `chunks` by timestamp. At a timestamp several chunks hold, the earliest chunk in `chunks` +/// whose row is not a stale marker wins, or the earliest one if every row is. Chunks of one +/// primary key have to be adjacent in `chunks` and hold the same sample there. +fn merge_raw_chunks( + schema: &SeriesSchema, + chunks: &[RawSeriesChunk], + key: Buffer, + labels: SeriesLabels, + reserve: &mut dyn FnMut(usize) -> std::result::Result<(), DataFusionError>, + shrink: &mut dyn FnMut(usize), +) -> std::result::Result { + if schema.eval_grid.is_some() { + return Err(invalid("raw series schema cannot have an evaluation grid")); + } + for chunk in chunks { if chunk.fields.len() != schema.fields.len() || chunk .fields @@ -137,25 +202,32 @@ pub(crate) fn merge_raw_identity_charging( while end < rows.len() && rows[end].0 == rows[index].0 { end += 1; } - for duplicate in &rows[index + 1..end] { + // `chunks` is ordered by primary key, so the rows of one key are adjacent here. + let mut key_first = index; + for current in index + 1..end { + if chunks[rows[current].1].primary_key != chunks[rows[key_first].1].primary_key { + key_first = current; + continue; + } for field_index in 0..schema.fields.len() { if !samples_equal( - chunks[rows[index].1] - .fields - .get(field_index) - .ok_or_else(|| invalid("field index out of bounds"))? - .sample(rows[index].2), - chunks[duplicate.1] - .fields - .get(field_index) - .ok_or_else(|| invalid("field index out of bounds"))? - .sample(duplicate.2), + field_sample(chunks, rows[key_first], field_index)?, + field_sample(chunks, rows[current], field_index)?, ) { return Err(invalid(&conflicting_samples(&labels, rows[index].0))); } } } - selected.push(rows[index]); + let mut winner = rows[index]; + if end - index > 1 { + for &row in &rows[index..end] { + if !row_is_stale(chunks, row, schema.fields.len())? { + winner = row; + break; + } + } + } + selected.push(winner); index = end; } @@ -224,6 +296,37 @@ fn conflicting_samples(labels: &SeriesLabels, timestamp: i64) -> String { ) } +fn field_sample( + chunks: &[RawSeriesChunk], + (_, chunk_index, row_index): (i64, usize, usize), + field_index: usize, +) -> std::result::Result, DataFusionError> { + Ok(chunks[chunk_index] + .fields + .get(field_index) + .ok_or_else(|| invalid("field index out of bounds"))? + .sample(row_index)) +} + +/// Matches the range and instant evaluators: a stale marker in any field makes the row stale. +fn row_is_stale( + chunks: &[RawSeriesChunk], + row: (i64, usize, usize), + field_count: usize, +) -> std::result::Result { + for field_index in 0..field_count { + let stale = match field_sample(chunks, row, field_index)? { + SampleRef::Float(value) => is_prometheus_stale_nan(value), + SampleRef::Histogram(histogram) => is_prometheus_stale_nan(histogram.sum), + SampleRef::Missing => false, + }; + if stale { + return Ok(true); + } + } + Ok(false) +} + fn samples_equal(left: SampleRef<'_>, right: SampleRef<'_>) -> bool { match (left, right) { (SampleRef::Missing, SampleRef::Missing) => true, diff --git a/src/promql/src/source/merge/tests.rs b/src/promql/src/source/merge/tests.rs index cfba60c14db..a1ddddb6257 100644 --- a/src/promql/src/source/merge/tests.rs +++ b/src/promql/src/source/merge/tests.rs @@ -14,6 +14,7 @@ use std::sync::Arc; +use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS; use datafusion::arrow::array::{Float64Array, UInt32Array}; use datafusion::arrow::buffer::Buffer; use datatypes::series::histogram::{BucketSideView, CounterResetHint, HistogramBatchBuilder}; @@ -21,7 +22,7 @@ use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{Samples, SeriesFields, SeriesSchema}; use datatypes::series::{Label, SeriesLabels}; -use super::merge_raw_identity_charging; +use super::{merge_raw_identity_charging, merge_raw_label_set_charging}; /// The same merge, with accounting the tests do not measure. fn merge_raw_identity( @@ -631,3 +632,106 @@ fn merge_releases_transient_row_workspace() { assert!(retained < reserved); assert!(retained >= result.time.len() * std::mem::size_of::()); } + +/// Stored series of one label set chain into one series; a timestamp several of them hold keeps +/// the sample of the smallest key whatever order the pieces arrived in, while two pieces of any one +/// key still have to agree. +#[test] +fn label_set_merge_keeps_the_smallest_key_at_a_shared_timestamp() { + let schema = schema(1); + let merge = |chunks: &mut Vec| { + merge_raw_label_set_charging(&schema, chunks, &mut |_| Ok(()), &mut |_| {}) + }; + let pieces = || { + vec![ + chunk( + b"b", + "x", + vec![1, 3, 4], + vec![vec![Some(20.0), Some(40.0), Some(50.0)]], + ), + chunk(b"a", "x", vec![1, 2], vec![vec![Some(1.0), Some(2.0)]]), + ] + }; + for mut chunks in [pieces(), pieces().into_iter().rev().collect()] { + let merged = merge(&mut chunks).unwrap(); + assert_eq!(merged.primary_key.as_slice(), b"a"); + assert_eq!(merged.time.as_buffer().as_ref(), &[1, 2, 3, 4]); + assert_eq!( + merged + .fields + .get(0) + .unwrap() + .iter() + .map(|s| match s { + datatypes::series::samples::SampleRef::Float(v) => v, + _ => f64::NAN, + }) + .collect::>(), + vec![1., 2., 40., 50.] + ); + } + + let mut conflicting = vec![ + chunk(b"a", "x", vec![1], vec![vec![Some(1.0)]]), + chunk(b"b", "x", vec![1], vec![vec![Some(9.0)]]), + chunk(b"a", "x", vec![1], vec![vec![Some(2.0)]]), + ]; + assert!(merge(&mut conflicting).is_err()); + + // The pieces of a key that does not win still have to agree. + let mut conflicting_loser = vec![ + chunk(b"a", "x", vec![1], vec![vec![Some(1.0)]]), + chunk(b"b", "x", vec![1], vec![vec![Some(9.0)]]), + chunk(b"b", "x", vec![1], vec![vec![Some(8.0)]]), + ]; + assert!(merge(&mut conflicting_loser).is_err()); + + let mut other_labels = vec![ + chunk(b"a", "x", vec![1], vec![vec![Some(1.0)]]), + chunk(b"b", "y", vec![2], vec![vec![Some(2.0)]]), + ]; + assert!(merge(&mut other_labels).is_err()); +} + +/// A stale marker of one stored series does not hide another series' sample at the same +/// timestamp, as the legacy range path filters stale markers before collapsing timestamps; a +/// timestamp every series marks stale stays stale. +#[test] +fn label_set_merge_prefers_a_live_sample_over_a_stale_marker() { + let stale = f64::from_bits(PROMETHEUS_STALE_NAN_BITS); + let schema = schema(2); + let mut chunks = vec![ + chunk( + b"a", + "x", + vec![1, 2], + vec![vec![Some(1.0), Some(stale)], vec![Some(stale), Some(2.0)]], + ), + chunk( + b"b", + "x", + vec![1, 2], + vec![vec![Some(10.0), Some(stale)], vec![Some(11.0), Some(stale)]], + ), + ]; + let merged = + merge_raw_label_set_charging(&schema, &mut chunks, &mut |_| Ok(()), &mut |_| {}).unwrap(); + assert_eq!(merged.primary_key.as_slice(), b"a"); + let bits = |field: usize| { + merged + .fields + .get(field) + .unwrap() + .iter() + .map(|s| match s { + datatypes::series::samples::SampleRef::Float(v) => v.to_bits(), + _ => 0, + }) + .collect::>() + }; + // At 1 `a`'s row is stale through its second field, so `b`'s row wins; at 2 both are stale + // and `a`'s marker is kept. + assert_eq!(bits(0), vec![10f64.to_bits(), PROMETHEUS_STALE_NAN_BITS]); + assert_eq!(bits(1), vec![11f64.to_bits(), 2f64.to_bits()]); +} diff --git a/src/query/src/dist_plan/planner.rs b/src/query/src/dist_plan/planner.rs index e095ea72a8e..b4ca977cbd8 100644 --- a/src/query/src/dist_plan/planner.rs +++ b/src/query/src/dist_plan/planner.rs @@ -31,7 +31,7 @@ use datafusion::physical_plan::ExecutionPlan; use datafusion::physical_planner::{ExtensionPlanner, PhysicalPlanner}; use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion, TreeNodeVisitor}; use datafusion_common::{DataFusionError, TableReference}; -use datafusion_expr::{LogicalPlan, UserDefinedLogicalNode}; +use datafusion_expr::{Extension, LogicalPlan, UserDefinedLogicalNode}; use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr}; use datatypes::prelude::ConcreteDataType; use datatypes::value::Value; @@ -235,11 +235,28 @@ impl ExtensionPlanner for DistExtensionPlanner { .config() .get_extension() .unwrap_or_else(QueryContext::arc); + // A source that merges label sets does so above this merge scan, where every region's + // answer arrives; a region running that merge too would buffer its whole answer and + // resolve a shared timestamp from its own share of the keys. + let label_set_source = match input_plan { + LogicalPlan::Extension(extension) => extension + .node + .as_any() + .downcast_ref::() + .filter(|source| source.merges_label_sets()), + _ => None, + }; + let region_plan = match label_set_source { + Some(source) => LogicalPlan::Extension(Extension { + node: Arc::new(source.for_regions()), + }), + None => input_plan.clone(), + }; let merge_scan_plan = MergeScanExec::new( session_state, table_name, regions, - input_plan.clone(), + region_plan, schema, self.region_query_handler.clone(), query_ctx, @@ -248,7 +265,11 @@ impl ExtensionPlanner for DistExtensionPlanner { self.enable_per_region_metrics, )? .with_raw_series_disjoint(series_disjoint)?; - Ok(Some(Arc::new(merge_scan_plan) as _)) + let merge_scan_plan = Arc::new(merge_scan_plan) as Arc; + match label_set_source { + Some(source) => source.merged_by_label_set(merge_scan_plan).map(Some), + None => Ok(Some(merge_scan_plan)), + } } } diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index f88191d1863..e9c898efb6c 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -74,7 +74,9 @@ use promql_parser::parser::{ }; use session::context::{MetricDiscoveryScope, QueryContextRef}; use snafu::{OptionExt, ResultExt, ensure}; -use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME}; +use store_api::metric_engine_consts::{ + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY, +}; use store_api::region_engine::RawLabelSource; use crate::parser::AliasExpr; @@ -369,11 +371,25 @@ impl PromPlanner { ); // Checked here because a physical-planning refusal is an error, not a fallback. A // file-engine table reads through a `RowSeriesSource`, which sorts its rows into series; a - // metric-engine selector needs its verified logical rewrite. + // metric-engine selector needs its verified logical rewrite or names the physical table. + // + // A physical table keys series by `__table_id` and `__tsid`, which are not labels, so two + // logical tables with equal labels store two series under one label set. Prometheus answers + // one series per label set, so such a selector reads through a source that merges them. A + // logical selector's scan is already rewritten to the physical table, so only a scan + // without that rewrite names it. let reads_rows = table_meta.engine == FILE_ENGINE; + let physical_metric_table = !has_verified_metric_rewrite + && table_meta.engine == METRIC_ENGINE_NAME + && table_meta + .options + .extra_options + .contains_key(PHYSICAL_TABLE_METADATA_KEY); if !reads_rows && (!supports_native_raw_series(&table_meta.engine) - || (table_meta.engine == METRIC_ENGINE_NAME && !has_verified_metric_rewrite)) + || (table_meta.engine == METRIC_ENGINE_NAME + && !has_verified_metric_rewrite + && !physical_metric_table)) { return Ok(declined("engine_without_raw_series_scanner")); } @@ -472,6 +488,19 @@ impl PromPlanner { if let LogicalPlan::TableScan(table_scan) = &mut input { table_scan.filters.append(&mut filters); } + if physical_metric_table { + let source = RawSeriesSource::try_new( + Arc::from(metric.as_str()), + tags.clone(), + fields.clone(), + input, + ) + .context(DataFusionPlanningSnafu)? + .with_label_set_merge(); + input = LogicalPlan::Extension(Extension { + node: Arc::new(source), + }); + } } // A row source reads every key column as a label value with no null, so two rows that differ // only by `NULL` against `''` are already one series there. diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 5f7d85cb7de..6420103ea83 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -4978,6 +4978,58 @@ async fn native_fused_metric_table_without_logical_metadata_falls_back() { ); } +/// A selector naming a metric-engine physical table runs natively, reading the table through a +/// source that answers each label set once: the logical tables on it key their series by +/// `__table_id` and `__tsid`, which are not labels. +#[tokio::test] +async fn native_physical_metric_table_reads_through_a_label_set_merge() { + use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion}; + + for query in ["phy", "rate(phy[5m])", "sum by (tag_0) (phy)"] { + let plan = build_native_fused_plan_with_provider( + query, + true, + metric_discovery_provider(&["a", "b"]).await, + ) + .await; + assert_eq!(None, take_reported_decline(), "{query}: {plan}"); + assert!(find_fused_series(&plan).is_some(), "{query}: {plan}"); + // Every read of the table, including the partial half of a split aggregate, goes through + // the merging source: a bare scan would hand the node one stored series per logical table. + let mut sources = Vec::new(); + plan.apply(|node| { + if let LogicalPlan::Extension(extension) = node + && let Some(source) = extension.node.as_any().downcast_ref::() + { + sources.push(source.merges_label_sets()); + } + if let LogicalPlan::Extension(extension) = node + && let Some(fused) = extension.node.as_any().downcast_ref::() + { + assert!( + !fused + .inputs() + .iter() + .any(|input| matches!(input, LogicalPlan::TableScan(_))), + "{query}: {plan}" + ); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + assert_eq!(sources, vec![true], "{query}: {plan}"); + } + // A logical table on the same physical table keeps its own scan: its series are unique per + // label set already. + let plan = build_native_fused_plan_with_provider( + "rate(a[5m])", + true, + metric_discovery_provider(&["a", "b"]).await, + ) + .await; + assert!(find_metric_physical_scan(&plan).is_some(), "{plan}"); +} + /// A file-engine table has no raw-series scanner, so each selector reads it through a /// `RowSeriesSource`, which sorts the table's rows into series. /// diff --git a/tests-integration/src/tests/promql_test.rs b/tests-integration/src/tests/promql_test.rs index 43aea3e6e6e..e8a9d730742 100644 --- a/tests-integration/src/tests/promql_test.rs +++ b/tests-integration/src/tests/promql_test.rs @@ -2531,6 +2531,149 @@ async fn native_promql_clamp_aggregates_execute_on_native_segments() { } } +/// Logical tables `{prefix}_a`, `{prefix}_b` and `{prefix}_c` on the physical table `{prefix}`. +/// `a` and `b` both store `{host="x"}`, and both hold a sample at `0` and at `30s`, where `a`'s is a +/// stale marker; `c` stores `{host="x"}` under one more label. +async fn physical_table_fixture(instance: &Arc, prefix: &str, partition: &str) { + let sql = format!( + "CREATE TABLE {prefix} (ts TIMESTAMP TIME INDEX, val DOUBLE) {partition} \ + ENGINE=metric WITH ('physical_metric_table' = 'true'); \ + CREATE TABLE {prefix}_a (host STRING NULL, ts TIMESTAMP NOT NULL, val DOUBLE NULL, \ + TIME INDEX (ts), PRIMARY KEY (host)) ENGINE=metric WITH (on_physical_table = '{prefix}'); \ + CREATE TABLE {prefix}_b (host STRING NULL, ts TIMESTAMP NOT NULL, val DOUBLE NULL, \ + TIME INDEX (ts), PRIMARY KEY (host)) ENGINE=metric WITH (on_physical_table = '{prefix}'); \ + CREATE TABLE {prefix}_c (host STRING NULL, job STRING NULL, ts TIMESTAMP NOT NULL, \ + val DOUBLE NULL, TIME INDEX (ts), PRIMARY KEY (host, job)) \ + ENGINE=metric WITH (on_physical_table = '{prefix}'); \ + INSERT INTO {prefix}_a (host, ts, val) VALUES ('x', 0, 1), ('x', 60000, 2), \ + ('x', 120000, 3), ('y', 0, 10); \ + INSERT INTO {prefix}_b (host, ts, val) VALUES ('x', 0, 50), ('x', 30000, 7), \ + ('x', 180000, 4), ('x', 240000, 5); \ + INSERT INTO {prefix}_c (host, job, ts, val) VALUES ('x', 'j', 0, 100)" + ); + execute_all(instance, &sql, QueryContext::arc()).await; + let column = |name: &str, datatype: ColumnDataType, semantic_type: SemanticType| ColumnSchema { + column_name: name.into(), + datatype: datatype as i32, + semantic_type: semantic_type as i32, + ..Default::default() + }; + instance + .handle_row_inserts( + RowInsertRequests { + inserts: vec![RowInsertRequest { + table_name: format!("{prefix}_a"), + rows: Some(Rows { + schema: vec![ + column("host", ColumnDataType::String, SemanticType::Tag), + column( + "ts", + ColumnDataType::TimestampMillisecond, + SemanticType::Timestamp, + ), + column("val", ColumnDataType::Float64, SemanticType::Field), + ], + rows: vec![Row { + values: vec![ + ValueData::StringValue("x".into()).into(), + ValueData::TimestampMillisecondValue(30_000).into(), + ValueData::F64Value(f64::from_bits(PROMETHEUS_STALE_NAN_BITS)) + .into(), + ], + }], + }), + }], + }, + QueryContext::arc(), + false, + false, + ) + .await + .unwrap(); +} + +/// What Prometheus answers over [`physical_table_fixture`] on `TQL EVAL (0, 240, '60s')`. +/// +/// Prometheus reads series with identical labels as one series, samples chained by timestamp and +/// one sample per timestamp, so `a` and `b` are one `{host="x"}`. Both hold a sample at `0`; `a`'s +/// stored key sorts first (its `__table_id` is smaller), so its `1` is the one kept. At `30s` +/// `a`'s stale marker does not hide `b`'s `7`. +fn physical_table_expected(query: &str) -> Vec<(i64, String, f64)> { + let x = [1.0, 2.0, 3.0, 4.0, 5.0]; + let mut rows = Vec::new(); + for (step, time) in (0..=240_000).step_by(60_000).enumerate() { + let mut add = |labels: &str, value: f64| rows.push((time, labels.to_string(), value)); + if query == "sum(PHY)" { + add("", x[step] + 10.0 + 100.0); + } else if query == "sum by (host) (PHY)" { + add("host=x", x[step] + 100.0); + add("host=y", 10.0); + } else { + let (x, xj, y) = match query { + "PHY + 0" => (x[step], 100.0, 10.0), + // The window `(t - 5m, t]` holds every merged sample up to `t`: the two at `0` are + // one, and from `60s` on it holds `b`'s `7` at `30s` too. + "count_over_time(PHY[5m])" => ((step + 1 + usize::from(step > 0)) as f64, 1.0, 1.0), + _ => unreachable!("{query}"), + }; + add("host=x", x); + add("host=x,job=j", xj); + add("host=y", y); + } + } + rows.sort_by(|left, right| (left.0, &left.1).cmp(&(right.0, &right.1))); + rows +} + +const PHYSICAL_TABLE_QUERIES: [&str; 4] = [ + "PHY + 0", + "count_over_time(PHY[5m])", + "sum(PHY)", + "sum by (host) (PHY)", +]; + +/// A selector naming a metric-engine physical table answers one series per label set, as +/// Prometheus does, although every logical table on it stores its own series. The existing plan +/// answers the same, including which sample the shared timestamp keeps. +#[tokio::test(flavor = "multi_thread")] +async fn native_promql_physical_table_merges_equal_label_sets() { + common_telemetry::init_default_ut_logging(); + let (standalone, observer) = native_test_instance(GreptimeDbStandaloneBuilder::new( + "native_promql_physical_table", + )) + .await; + let instance = standalone.fe_instance().clone(); + physical_table_fixture(&instance, "native_phy", "").await; + for query in PHYSICAL_TABLE_QUERIES { + let expression = query.replace("PHY", "native_phy"); + let sql = format!("TQL EVAL (0, 240, '60s') {expression}"); + observer.clear(); + let native = native_rows(native_tql_output(&instance, &sql, true).await, None).await; + assert_native_rows_plan(&observer); + // The merge runs once, above the region: a region merging too would buffer its whole + // answer a second time. + let display = |plan: &Arc| { + datafusion::physical_plan::displayable(plan.as_ref()) + .indent(true) + .to_string() + }; + let root = display(&observer.root_plan()); + assert!(root.contains("identity=label_set"), "{expression}: {root}"); + let regions = observer.region_plans(); + assert!(!regions.is_empty(), "{expression}: {root}"); + for region in ®ions { + let region = display(region); + assert!( + !region.contains("identity=label_set"), + "{expression}: {region}" + ); + } + assert_eq!(physical_table_expected(query), native, "{expression}"); + let legacy = native_rows(native_tql_output(&instance, &sql, false).await, None).await; + assert_eq!(legacy, native, "{expression}"); + } +} + /// TQL answers a selector that names no metric as the Prometheus handler does, with no scope /// supplied by the caller: authorizing the statement prepares it. #[tokio::test(flavor = "multi_thread")] @@ -4669,6 +4812,58 @@ fn cross_region_fixture_inserts(prefix: &str) -> String { ) } +/// [`native_promql_physical_table_merges_equal_label_sets`] over a physical table split by time +/// across two datanodes, so the stored series of one label set arrive from several regions and +/// the merge has to run above all of them. +#[tokio::test(flavor = "multi_thread")] +async fn distributed_native_promql_physical_table_merges_label_sets_across_regions() { + common_telemetry::init_default_ut_logging(); + let cluster = GreptimeDbClusterBuilder::new("distributed_native_promql_physical_table") + .await + .with_datanodes(2) + .with_real_datanode_grpc_addr(true) + .with_frontend_real_datanode_grpc(true) + .with_query_options(QueryOptions { + experimental_native_promql: true, + ..Default::default() + }) + .build(false) + .await; + let instance = cluster.fe_instance().clone(); + physical_table_fixture( + &instance, + "dist_phy", + "PARTITION ON COLUMNS (ts) (ts < '1970-01-01 00:01:00', \ + ts >= '1970-01-01 00:01:00' AND ts < '1970-01-01 00:03:00', \ + ts >= '1970-01-01 00:03:00')", + ) + .await; + for query in PHYSICAL_TABLE_QUERIES { + let expression = query.replace("PHY", "dist_phy"); + let output = instance + .do_query( + &format!("TQL EVAL (0, 240, '60s') {expression}"), + native_query_context(true, 2), + ) + .await + .remove(0) + .unwrap(); + let plan = output.meta.plan.clone().expect("frontend physical plan"); + let display = datafusion::physical_plan::displayable(plan.as_ref()) + .indent(true) + .to_string(); + assert_eq!( + physical_table_expected(query), + native_rows(output, None).await, + "{expression}: {display}" + ); + assert!( + display.contains("identity=label_set") && display.contains("MergeScanExec"), + "{expression}: {display}" + ); + } +} + /// Real two-datanode TCP acceptance for raw series fragmented by time. Ratios alone can hide /// history dropped on both sides, so an absolute increase is checked separately as well. #[tokio::test(flavor = "multi_thread")]