mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
Merge branch 'narthex' into feat/narthex-native-exec-sparse
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
+262
-169
@@ -31,13 +31,15 @@ use common_recordbatch::{RecordBatchStreamWrapper, SendableRecordBatchStream};
|
||||
use common_telemetry::tracing::{self, Instrument};
|
||||
use common_telemetry::{debug, warn};
|
||||
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
|
||||
use datafusion::physical_plan::{DisplayAs, DisplayFormatType};
|
||||
use datafusion::physical_plan::{DisplayAs, DisplayFormatType, PhysicalExpr};
|
||||
use datafusion_common::tree_node::TreeNode;
|
||||
use datafusion_expr::{Expr, Volatility};
|
||||
use datatypes::arrow::array::BinaryArray;
|
||||
use datatypes::arrow::datatypes::DataType as ArrowDataType;
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::SchemaRef;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use datatypes::types::TimestampType;
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
@@ -79,6 +81,49 @@ const SEND_TIMEOUT: Duration = Duration::from_micros(100);
|
||||
/// Maximum number of candidate series retained before distributing assignments.
|
||||
const CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD: usize = 1_000_000;
|
||||
|
||||
/// Test-only override of [`CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD`], where `0` means "use the
|
||||
/// production constant".
|
||||
///
|
||||
/// The production build compiles this static, the setter below and the private accessor out, so
|
||||
/// the shipped threshold is always the constant above.
|
||||
#[cfg(test)]
|
||||
static CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// Test-only number of candidate assignment rounds sent since the override was last set.
|
||||
///
|
||||
/// A round is one `send_assignments` call, so a partition that received more than one assignment
|
||||
/// sees `>= 2` rounds here. Increments are compiled out of production builds.
|
||||
#[cfg(test)]
|
||||
static CANDIDATE_ASSIGNMENT_ROUNDS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// Returns the candidate-series assignment threshold, honouring the test-only override.
|
||||
fn candidate_series_assignment_threshold() -> usize {
|
||||
#[cfg(test)]
|
||||
{
|
||||
let threshold = CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE.load(Ordering::Relaxed);
|
||||
if threshold > 0 {
|
||||
return threshold;
|
||||
}
|
||||
}
|
||||
CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD
|
||||
}
|
||||
|
||||
/// Test-only: overrides the candidate-series assignment threshold and resets the round counter.
|
||||
///
|
||||
/// Pass `0` to restore the production threshold. Tests must reset the override before they
|
||||
/// return; a scope guard in `engine::scan_test` does that even on panic.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn set_candidate_series_assignment_threshold(threshold: usize) {
|
||||
CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE.store(threshold, Ordering::Relaxed);
|
||||
CANDIDATE_ASSIGNMENT_ROUNDS.store(0, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Test-only: returns the number of assignment rounds sent since the override was last set.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn candidate_assignment_rounds() -> usize {
|
||||
CANDIDATE_ASSIGNMENT_ROUNDS.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Legacy data receivers for output partitions.
|
||||
type LegacyReceiverList = Vec<Option<Receiver<Result<SeriesBatch>>>>;
|
||||
|
||||
@@ -88,6 +133,12 @@ type CandidateReceiverList = Vec<Option<CandidateReceiver>>;
|
||||
/// Candidate assignment senders for output partitions.
|
||||
type CandidateSenderList = Vec<Option<mpsc::UnboundedSender<Result<SeriesReaderInput>>>>;
|
||||
|
||||
struct RawScanPreparation {
|
||||
schema: Arc<SeriesSchema>,
|
||||
fields: Vec<(usize, ConcreteDataType)>,
|
||||
predicates: Vec<Arc<dyn PhysicalExpr>>,
|
||||
}
|
||||
|
||||
struct CandidateReceiver {
|
||||
receiver: mpsc::UnboundedReceiver<Result<SeriesReaderInput>>,
|
||||
active_receivers: Arc<AtomicUsize>,
|
||||
@@ -194,6 +245,189 @@ impl SeriesScan {
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_raw_scan(
|
||||
&self,
|
||||
label_source: &RawLabelSource,
|
||||
) -> Result<Option<RawScanPreparation>, BoxedError> {
|
||||
let input = &self.stream_ctx.input;
|
||||
let metadata = input.mapper.metadata();
|
||||
match label_source {
|
||||
RawLabelSource::PrimaryKey {
|
||||
physical_metadata,
|
||||
logical_tags,
|
||||
..
|
||||
} => {
|
||||
if !Arc::ptr_eq(metadata, physical_metadata) {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected metadata snapshot: region_id={}, physical_region_id={}, schema_version={}, physical_schema_version={}",
|
||||
metadata.region_id,
|
||||
physical_metadata.region_id,
|
||||
metadata.schema_version,
|
||||
physical_metadata.schema_version,
|
||||
);
|
||||
return Err(BoxedError::new(
|
||||
InvalidRecordBatchSnafu {
|
||||
reason: "raw label source metadata does not match scanner snapshot"
|
||||
.to_string(),
|
||||
}
|
||||
.build(),
|
||||
));
|
||||
}
|
||||
let mut ids = HashSet::new();
|
||||
let mut names = HashSet::new();
|
||||
for tag in logical_tags.iter() {
|
||||
let column = metadata.column_by_id(tag.column_id).filter(|column| {
|
||||
column.semantic_type == SemanticType::Tag
|
||||
&& metadata.primary_key.contains(&tag.column_id)
|
||||
});
|
||||
let valid = column.is_some_and(|column| {
|
||||
column.column_schema.name == tag.name.as_ref()
|
||||
&& tag.name.as_ref() != "__name__"
|
||||
&& !is_internal_column(tag.name.as_ref())
|
||||
&& !is_metric_engine_internal_column(tag.name.as_ref())
|
||||
&& !ReservedColumnId::is_reserved(tag.column_id)
|
||||
});
|
||||
let unique_id = valid && ids.insert(tag.column_id);
|
||||
let unique_name = unique_id && names.insert(tag.name.as_ref());
|
||||
if !valid || !unique_id || !unique_name {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected label binding: region_id={}, column_id={}, binding_valid={}, unique_id={}, unique_name={}",
|
||||
metadata.region_id, tag.column_id, valid, unique_id, unique_name,
|
||||
);
|
||||
return Err(BoxedError::new(
|
||||
InvalidRecordBatchSnafu {
|
||||
reason: "invalid raw label binding".to_string(),
|
||||
}
|
||||
.build(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
RawLabelSource::Explicit => {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected explicit labels: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let selected = input.mapper.output_schema();
|
||||
let mut fields = Vec::new();
|
||||
let mut specs = Vec::new();
|
||||
for output in selected.column_schemas() {
|
||||
let Some(column) = metadata.column_metadatas.iter().find(|column| {
|
||||
column.column_schema.name == output.name
|
||||
&& column.semantic_type == SemanticType::Field
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let Some((index, (_, data_type))) = input
|
||||
.mapper
|
||||
.batch_schema()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, (id, _))| *id == column.column_id)
|
||||
else {
|
||||
debug!(
|
||||
"Raw series scan preflight missing mapper field: region_id={}, column_id={}",
|
||||
metadata.region_id, column.column_id,
|
||||
);
|
||||
return Err(BoxedError::new(
|
||||
InvalidRecordBatchSnafu {
|
||||
reason: format!(
|
||||
"selected field {} is missing from mapper batch schema",
|
||||
output.name
|
||||
),
|
||||
}
|
||||
.build(),
|
||||
));
|
||||
};
|
||||
if !data_type.is_numeric() && !is_native_histogram_value_type(data_type) {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected field type: region_id={}, column_id={}",
|
||||
metadata.region_id, column.column_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
fields.push((index, data_type.clone()));
|
||||
specs.push(FieldSpec {
|
||||
name: Arc::from(output.name.as_str()),
|
||||
});
|
||||
}
|
||||
let time_is_millis = matches!(metadata.time_index_type(), TimestampType::Millisecond(_));
|
||||
if fields.is_empty()
|
||||
|| input.append_mode
|
||||
|| input.series_row_selector.is_some()
|
||||
|| !time_is_millis
|
||||
{
|
||||
debug!(
|
||||
"Raw series scan preflight rejected scan options: region_id={}, selected_fields={}, append_mode={}, row_selector={}, time_is_millis={}",
|
||||
metadata.region_id,
|
||||
fields.len(),
|
||||
input.append_mode,
|
||||
input.series_row_selector.is_some(),
|
||||
time_is_millis,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: specs.into(),
|
||||
eval_grid: None,
|
||||
});
|
||||
let typed_schema = input.mapper.input_arrow_schema(false);
|
||||
let mut predicates = Vec::new();
|
||||
if let Some(predicate) = input.predicate_group().predicate_without_region() {
|
||||
if !predicate.dyn_filters().is_empty() {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected dynamic predicate filters: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
for expr in predicate.exprs() {
|
||||
// Fresh execution properties cannot preserve Stable or query-dependent semantics.
|
||||
if expr
|
||||
.exists(|node| {
|
||||
Ok(matches!(node, Expr::ScalarFunction(function)
|
||||
if function.func.signature().volatility != Volatility::Immutable)
|
||||
|| matches!(node, Expr::ScalarVariable(..)))
|
||||
})
|
||||
.unwrap_or(true)
|
||||
{
|
||||
debug!(
|
||||
"Raw series scan preflight rejected predicate volatility or variable: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
// Evaluate residuals with original types before raw conversion to Float64.
|
||||
let Ok(physical) = Predicate::to_physical_expr(expr, &typed_schema) else {
|
||||
debug!(
|
||||
"Raw series scan preflight failed predicate compilation: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
};
|
||||
if !matches!(
|
||||
physical.data_type(&typed_schema),
|
||||
Ok(ArrowDataType::Boolean | ArrowDataType::Null)
|
||||
) {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected predicate type: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
predicates.push(physical);
|
||||
}
|
||||
}
|
||||
Ok(Some(RawScanPreparation {
|
||||
schema,
|
||||
fields,
|
||||
predicates,
|
||||
}))
|
||||
}
|
||||
|
||||
fn supports_two_phase(input: &ScanInput) -> bool {
|
||||
if !is_sparse_metric_metadata(input.region_metadata()) {
|
||||
return false;
|
||||
@@ -578,6 +812,22 @@ impl RegionScanner for SeriesScan {
|
||||
.map_err(BoxedError::new)
|
||||
}
|
||||
|
||||
fn raw_series_ordering(&self) -> SeriesOrdering {
|
||||
match self.mode {
|
||||
SeriesScanMode::Legacy => SeriesOrdering::KeyThenTime,
|
||||
SeriesScanMode::TwoPhase => SeriesOrdering::Contiguous,
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_series_schema(
|
||||
&self,
|
||||
label_source: &RawLabelSource,
|
||||
) -> Result<Option<Arc<SeriesSchema>>, BoxedError> {
|
||||
Ok(self
|
||||
.prepare_raw_scan(label_source)?
|
||||
.map(|preparation| preparation.schema))
|
||||
}
|
||||
|
||||
fn scan_series_partition(
|
||||
&self,
|
||||
ctx: &QueryScanContext,
|
||||
@@ -585,171 +835,9 @@ impl RegionScanner for SeriesScan {
|
||||
partition: usize,
|
||||
label_source: &RawLabelSource,
|
||||
) -> Result<Option<SendableRawSeriesStream>, BoxedError> {
|
||||
let input = &self.stream_ctx.input;
|
||||
let metadata = input.mapper.metadata();
|
||||
match label_source {
|
||||
RawLabelSource::PrimaryKey {
|
||||
physical_metadata,
|
||||
logical_tags,
|
||||
..
|
||||
} => {
|
||||
if !Arc::ptr_eq(metadata, physical_metadata) {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected metadata snapshot: region_id={}, physical_region_id={}, schema_version={}, physical_schema_version={}",
|
||||
metadata.region_id,
|
||||
physical_metadata.region_id,
|
||||
metadata.schema_version,
|
||||
physical_metadata.schema_version,
|
||||
);
|
||||
return Err(BoxedError::new(
|
||||
InvalidRecordBatchSnafu {
|
||||
reason: "raw label source metadata does not match scanner snapshot"
|
||||
.to_string(),
|
||||
}
|
||||
.build(),
|
||||
));
|
||||
}
|
||||
let mut ids = HashSet::new();
|
||||
let mut names = HashSet::new();
|
||||
for tag in logical_tags.iter() {
|
||||
let column = metadata.column_by_id(tag.column_id).filter(|column| {
|
||||
column.semantic_type == SemanticType::Tag
|
||||
&& metadata.primary_key.contains(&tag.column_id)
|
||||
});
|
||||
let valid = column.is_some_and(|column| {
|
||||
column.column_schema.name == tag.name.as_ref()
|
||||
&& tag.name.as_ref() != "__name__"
|
||||
&& !is_internal_column(tag.name.as_ref())
|
||||
&& !is_metric_engine_internal_column(tag.name.as_ref())
|
||||
&& !ReservedColumnId::is_reserved(tag.column_id)
|
||||
});
|
||||
let unique_id = valid && ids.insert(tag.column_id);
|
||||
let unique_name = unique_id && names.insert(tag.name.as_ref());
|
||||
if !valid || !unique_id || !unique_name {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected label binding: region_id={}, column_id={}, binding_valid={}, unique_id={}, unique_name={}",
|
||||
metadata.region_id, tag.column_id, valid, unique_id, unique_name,
|
||||
);
|
||||
return Err(BoxedError::new(
|
||||
InvalidRecordBatchSnafu {
|
||||
reason: "invalid raw label binding".to_string(),
|
||||
}
|
||||
.build(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
RawLabelSource::Explicit => {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected explicit labels: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let selected = input.mapper.output_schema();
|
||||
let mut fields = Vec::new();
|
||||
let mut specs = Vec::new();
|
||||
for output in selected.column_schemas() {
|
||||
let Some(column) = metadata.column_metadatas.iter().find(|column| {
|
||||
column.column_schema.name == output.name
|
||||
&& column.semantic_type == SemanticType::Field
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let Some((index, (_, data_type))) = input
|
||||
.mapper
|
||||
.batch_schema()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, (id, _))| *id == column.column_id)
|
||||
else {
|
||||
debug!(
|
||||
"Raw series scan preflight missing mapper field: region_id={}, column_id={}",
|
||||
metadata.region_id, column.column_id,
|
||||
);
|
||||
return Err(BoxedError::new(
|
||||
InvalidRecordBatchSnafu {
|
||||
reason: format!(
|
||||
"selected field {} is missing from mapper batch schema",
|
||||
output.name
|
||||
),
|
||||
}
|
||||
.build(),
|
||||
));
|
||||
};
|
||||
if !data_type.is_numeric() && !is_native_histogram_value_type(data_type) {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected field type: region_id={}, column_id={}",
|
||||
metadata.region_id, column.column_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
fields.push((index, data_type.clone()));
|
||||
specs.push(FieldSpec {
|
||||
name: Arc::from(output.name.as_str()),
|
||||
});
|
||||
}
|
||||
let time_is_millis = matches!(metadata.time_index_type(), TimestampType::Millisecond(_));
|
||||
if fields.is_empty()
|
||||
|| input.append_mode
|
||||
|| input.series_row_selector.is_some()
|
||||
|| !time_is_millis
|
||||
{
|
||||
debug!(
|
||||
"Raw series scan preflight rejected scan options: region_id={}, selected_fields={}, append_mode={}, row_selector={}, time_is_millis={}",
|
||||
metadata.region_id,
|
||||
fields.len(),
|
||||
input.append_mode,
|
||||
input.series_row_selector.is_some(),
|
||||
time_is_millis,
|
||||
);
|
||||
let Some(preparation) = self.prepare_raw_scan(label_source)? else {
|
||||
return Ok(None);
|
||||
}
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: specs.into(),
|
||||
eval_grid: None,
|
||||
});
|
||||
let typed_schema = input.mapper.input_arrow_schema(false);
|
||||
let mut predicates = Vec::new();
|
||||
if let Some(predicate) = input.predicate_group().predicate_without_region() {
|
||||
for expr in predicate.exprs() {
|
||||
// Fresh execution properties cannot preserve Stable or query-dependent semantics.
|
||||
if expr
|
||||
.exists(|node| {
|
||||
Ok(matches!(node, Expr::ScalarFunction(function)
|
||||
if function.func.signature().volatility != Volatility::Immutable)
|
||||
|| matches!(node, Expr::ScalarVariable(..)))
|
||||
})
|
||||
.unwrap_or(true)
|
||||
{
|
||||
debug!(
|
||||
"Raw series scan preflight rejected predicate volatility or variable: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
// Evaluate residuals with original types before raw conversion to Float64.
|
||||
let Ok(physical) = Predicate::to_physical_expr(expr, &typed_schema) else {
|
||||
debug!(
|
||||
"Raw series scan preflight failed predicate compilation: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
};
|
||||
if !matches!(
|
||||
physical.data_type(&typed_schema),
|
||||
Ok(ArrowDataType::Boolean | ArrowDataType::Null)
|
||||
) {
|
||||
debug!(
|
||||
"Raw series scan preflight rejected predicate type: region_id={}",
|
||||
metadata.region_id,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
predicates.push(physical);
|
||||
}
|
||||
}
|
||||
};
|
||||
let metrics = new_partition_metrics(
|
||||
&self.stream_ctx,
|
||||
ctx.explain_verbose,
|
||||
@@ -760,13 +848,15 @@ impl RegionScanner for SeriesScan {
|
||||
let batches = self
|
||||
.scan_batch_in_partition(ctx, partition, metrics.clone(), metrics_set)
|
||||
.map_err(BoxedError::new)?;
|
||||
let ordering = self.raw_series_ordering();
|
||||
Ok(Some(raw::make_stream(
|
||||
batches,
|
||||
schema,
|
||||
preparation.schema,
|
||||
label_source.clone(),
|
||||
fields,
|
||||
preparation.fields,
|
||||
metrics,
|
||||
predicates,
|
||||
preparation.predicates,
|
||||
ordering,
|
||||
)))
|
||||
}
|
||||
|
||||
@@ -1096,7 +1186,7 @@ impl SeriesCandidateDistributor {
|
||||
return Ok(());
|
||||
}
|
||||
collector.push(batch);
|
||||
if collector.len() >= CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD {
|
||||
if collector.len() >= candidate_series_assignment_threshold() {
|
||||
chunked = true;
|
||||
self.send_assignments(collector.finish(false), &partition_pruner);
|
||||
if !self.should_fetch_candidates() {
|
||||
@@ -1120,6 +1210,9 @@ impl SeriesCandidateDistributor {
|
||||
assignments: Vec<AssignedSeriesBatch>,
|
||||
partition_pruner: &Arc<PartitionPruner>,
|
||||
) {
|
||||
// One round of candidate collection; a partition that receives two assignments sees two.
|
||||
#[cfg(test)]
|
||||
CANDIDATE_ASSIGNMENT_ROUNDS.fetch_add(1, Ordering::Relaxed);
|
||||
for (partition, assigned_series) in assignments.into_iter().enumerate() {
|
||||
if assigned_series.series().is_empty() {
|
||||
continue;
|
||||
|
||||
@@ -128,6 +128,7 @@ fn chunk(
|
||||
struct RawStream {
|
||||
schema: Arc<SeriesSchema>,
|
||||
label_source: RawLabelSource,
|
||||
ordering: SeriesOrdering,
|
||||
inner: BoxStream<'static, Result<RawSeriesChunk, BoxedError>>,
|
||||
}
|
||||
|
||||
@@ -146,7 +147,7 @@ impl RawSeriesStream for RawStream {
|
||||
&self.label_source
|
||||
}
|
||||
fn ordering(&self) -> SeriesOrdering {
|
||||
SeriesOrdering::Contiguous
|
||||
self.ordering
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,15 +158,16 @@ pub(crate) fn make_stream(
|
||||
fields: Vec<(usize, ConcreteDataType)>,
|
||||
metrics: PartitionMetrics,
|
||||
predicates: Vec<Arc<dyn PhysicalExpr>>,
|
||||
ordering: SeriesOrdering,
|
||||
) -> SendableRawSeriesStream {
|
||||
let output_schema = schema.clone();
|
||||
let stream = async_stream::stream! {
|
||||
let mut input = inner;
|
||||
let mut pending: Option<RawSeriesChunk> = None;
|
||||
while let Some(item) = input.next().await {
|
||||
let (records, is_legacy) = match item {
|
||||
Ok(ScanBatch::Series(SeriesBatch::Flat(flat))) => (flat.batches.into_vec(), true),
|
||||
Ok(ScanBatch::RecordBatch(batch)) => (vec![batch], false),
|
||||
let records = match item {
|
||||
Ok(ScanBatch::Series(SeriesBatch::Flat(flat))) => flat.batches.into_vec(),
|
||||
Ok(ScanBatch::RecordBatch(batch)) => vec![batch],
|
||||
Err(error) => { yield Err(BoxedError::new(error)); return; }
|
||||
};
|
||||
for record in records {
|
||||
@@ -238,7 +240,7 @@ pub(crate) fn make_stream(
|
||||
};
|
||||
metrics.inc_convert_batch_cost(begun.elapsed());
|
||||
if let Some(old) = pending.as_ref()
|
||||
&& is_legacy
|
||||
&& ordering == SeriesOrdering::KeyThenTime
|
||||
&& old.primary_key.as_slice() != current.primary_key.as_slice()
|
||||
&& current.primary_key.as_slice() <= old.primary_key.as_slice()
|
||||
{
|
||||
@@ -265,6 +267,7 @@ pub(crate) fn make_stream(
|
||||
Box::pin(RawStream {
|
||||
schema,
|
||||
label_source,
|
||||
ordering,
|
||||
inner: Box::pin(stream),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ use datatypes::arrow::record_batch::RecordBatch;
|
||||
use datatypes::data_type::DataType as _;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::ColumnSchema;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::raw::RawSeriesChunk;
|
||||
use datatypes::series::samples::{FieldSpec, SampleRef, SeriesSchema};
|
||||
use futures::{Stream, StreamExt, stream};
|
||||
@@ -239,6 +240,7 @@ fn convert_with_source(
|
||||
schema: Arc<SeriesSchema>,
|
||||
source: RawLabelSource,
|
||||
field_type: ConcreteDataType,
|
||||
ordering: SeriesOrdering,
|
||||
) -> SendableRawSeriesStream {
|
||||
make_stream(
|
||||
inner,
|
||||
@@ -247,6 +249,7 @@ fn convert_with_source(
|
||||
vec![(0, field_type)],
|
||||
metrics(),
|
||||
vec![],
|
||||
ordering,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -267,6 +270,17 @@ fn convert(inner: ScanBatchStream, schema: Arc<SeriesSchema>) -> SendableRawSeri
|
||||
schema,
|
||||
primary_key_source(metadata()),
|
||||
ConcreteDataType::int64_datatype(),
|
||||
SeriesOrdering::Contiguous,
|
||||
)
|
||||
}
|
||||
|
||||
fn convert_ordered(inner: ScanBatchStream, schema: Arc<SeriesSchema>) -> SendableRawSeriesStream {
|
||||
convert_with_source(
|
||||
inner,
|
||||
schema,
|
||||
primary_key_source(metadata()),
|
||||
ConcreteDataType::int64_datatype(),
|
||||
SeriesOrdering::KeyThenTime,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -370,6 +384,59 @@ async fn chunks_preserve_keys_values_times_and_final_flags_for_both_input_shapes
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_stream_reports_and_enforces_declared_ordering() {
|
||||
let stream = convert(input(vec![]), schema());
|
||||
assert_eq!(stream.ordering(), SeriesOrdering::Contiguous);
|
||||
drop(stream);
|
||||
let stream = convert_ordered(input(vec![]), schema());
|
||||
assert_eq!(stream.ordering(), SeriesOrdering::KeyThenTime);
|
||||
drop(stream);
|
||||
|
||||
let mut output = convert_ordered(
|
||||
input(vec![
|
||||
Ok(ScanBatch::RecordBatch(dictionary_batch(
|
||||
&[b"z"],
|
||||
&[1],
|
||||
&[Some(1)],
|
||||
))),
|
||||
Ok(ScanBatch::RecordBatch(dictionary_batch(
|
||||
&[b"a"],
|
||||
&[1],
|
||||
&[Some(2)],
|
||||
))),
|
||||
]),
|
||||
schema(),
|
||||
);
|
||||
assert!(output.next().await.unwrap().is_err());
|
||||
assert!(output.next().await.is_none());
|
||||
|
||||
let mut output = convert(
|
||||
input(vec![
|
||||
Ok(ScanBatch::RecordBatch(dictionary_batch(
|
||||
&[b"z"],
|
||||
&[1],
|
||||
&[Some(1)],
|
||||
))),
|
||||
Ok(ScanBatch::RecordBatch(dictionary_batch(
|
||||
&[b"a"],
|
||||
&[1],
|
||||
&[Some(2)],
|
||||
))),
|
||||
]),
|
||||
schema(),
|
||||
);
|
||||
assert_eq!(
|
||||
output.next().await.unwrap().unwrap().primary_key.as_slice(),
|
||||
b"z"
|
||||
);
|
||||
assert_eq!(
|
||||
output.next().await.unwrap().unwrap().primary_key.as_slice(),
|
||||
b"a"
|
||||
);
|
||||
assert!(output.next().await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn typed_predicate_filters_before_numeric_samples_are_cast() {
|
||||
let threshold = 1_i64 << 53;
|
||||
@@ -395,6 +462,7 @@ async fn typed_predicate_filters_before_numeric_samples_are_cast() {
|
||||
vec![(0, ConcreteDataType::int64_datatype())],
|
||||
metrics(),
|
||||
vec![predicate],
|
||||
SeriesOrdering::Contiguous,
|
||||
);
|
||||
let chunk = output.next().await.unwrap().unwrap();
|
||||
assert!(chunk.is_last);
|
||||
@@ -424,6 +492,7 @@ async fn predicate_error_is_terminal() {
|
||||
vec![(0, ConcreteDataType::int64_datatype())],
|
||||
metrics(),
|
||||
vec![predicate],
|
||||
SeriesOrdering::Contiguous,
|
||||
);
|
||||
assert!(output.next().await.unwrap().is_err());
|
||||
assert!(output.next().await.is_none());
|
||||
@@ -515,7 +584,7 @@ async fn legacy_series_requires_increasing_keys_but_record_batches_do_not() {
|
||||
let mut batches = smallvec::SmallVec::new();
|
||||
batches.push(dictionary_batch(&[b"b"], &[1], &[Some(1)]));
|
||||
batches.push(dictionary_batch(&[b"a"], &[2], &[Some(2)]));
|
||||
let mut output = convert(
|
||||
let mut output = convert_ordered(
|
||||
input(vec![Ok(ScanBatch::Series(SeriesBatch::Flat(
|
||||
FlatSeriesBatch { batches },
|
||||
)))]),
|
||||
@@ -528,7 +597,7 @@ async fn legacy_series_requires_increasing_keys_but_record_batches_do_not() {
|
||||
batches.push(dictionary_batch(&[b"a"], &[1], &[Some(1)]));
|
||||
batches.push(dictionary_batch(&[b"b"], &[1], &[Some(2)]));
|
||||
batches.push(dictionary_batch(&[b"a"], &[2], &[Some(3)]));
|
||||
let mut output = convert(
|
||||
let mut output = convert_ordered(
|
||||
input(vec![Ok(ScanBatch::Series(SeriesBatch::Flat(
|
||||
FlatSeriesBatch { batches },
|
||||
)))]),
|
||||
@@ -545,7 +614,7 @@ async fn legacy_series_requires_increasing_keys_but_record_batches_do_not() {
|
||||
let mut batches = smallvec::SmallVec::new();
|
||||
batches.push(dictionary_batch(&[b"a"], &[1], &[Some(1)]));
|
||||
batches.push(dictionary_batch(&[b"b"], &[1], &[Some(2)]));
|
||||
let mut output = convert(
|
||||
let mut output = convert_ordered(
|
||||
input(vec![Ok(ScanBatch::Series(SeriesBatch::Flat(
|
||||
FlatSeriesBatch { batches },
|
||||
)))]),
|
||||
@@ -636,6 +705,7 @@ async fn native_histogram_adapter_preserves_complete_payload() {
|
||||
native_histogram_value_type().clone(),
|
||||
)),
|
||||
native_histogram_value_type().clone(),
|
||||
SeriesOrdering::Contiguous,
|
||||
);
|
||||
assert!(matches!(
|
||||
raw.label_source(),
|
||||
|
||||
@@ -28,6 +28,7 @@ prost.workspace = true
|
||||
regex.workspace = true
|
||||
snafu.workspace = true
|
||||
store-api.workspace = true
|
||||
twox-hash.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
api.workspace = true
|
||||
|
||||
@@ -88,6 +88,17 @@ pub(crate) enum GridSample {
|
||||
|
||||
const _: () = assert!(std::mem::size_of::<Option<GridSample>>() == 16);
|
||||
|
||||
/// `sample` as an owned value; `None` when missing.
|
||||
pub(crate) fn owned(sample: SampleRef<'_>) -> Result<Option<GridSample>> {
|
||||
Ok(match sample {
|
||||
SampleRef::Missing => None,
|
||||
SampleRef::Float(value) => Some(GridSample::Float(value)),
|
||||
SampleRef::Histogram(view) => Some(GridSample::Histogram(Box::new(
|
||||
FloatHistogram::try_from_view(&view)?,
|
||||
))),
|
||||
})
|
||||
}
|
||||
|
||||
impl GridSeriesBuilder {
|
||||
/// Creates a builder for series of `schema`, which must have an evaluation grid.
|
||||
pub fn try_new(schema: Arc<SeriesSchema>) -> Result<Self> {
|
||||
|
||||
@@ -32,7 +32,7 @@ use crate::native::plan::{
|
||||
NativeType,
|
||||
};
|
||||
use crate::range_eval::RangeFunction;
|
||||
use crate::vector_match::{BinaryOp, Cardinality, MatchingLabels};
|
||||
use crate::vector_match::{BinaryOp, Cardinality, FillValues, MatchingLabels};
|
||||
|
||||
/// The header line of every tree.
|
||||
const HEADER: &str = "NativeTree";
|
||||
@@ -121,7 +121,7 @@ fn describe(node: &NativeNode) -> String {
|
||||
}
|
||||
),
|
||||
NativeExpr::Binary { matching, .. } => format!(
|
||||
"{}{} {} {}",
|
||||
"{}{} {} {}{}",
|
||||
binary_op(matching.op),
|
||||
if matching.return_bool { " bool" } else { "" },
|
||||
match &matching.labels {
|
||||
@@ -132,11 +132,25 @@ fn describe(node: &NativeNode) -> String {
|
||||
Cardinality::OneToOne => "one-to-one".to_string(),
|
||||
Cardinality::ManyToOne(labels) => format!("many-to-one [{}]", label_list(labels)),
|
||||
Cardinality::OneToMany(labels) => format!("one-to-many [{}]", label_list(labels)),
|
||||
}
|
||||
},
|
||||
fill(matching.fill)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn fill(values: FillValues) -> String {
|
||||
let side = |name: &str, value: Option<f64>| {
|
||||
value
|
||||
.map(|value| format!(" {name} {value}"))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
format!(
|
||||
"{}{}",
|
||||
side("fill_left", values.lhs),
|
||||
side("fill_right", values.rhs)
|
||||
)
|
||||
}
|
||||
|
||||
/// A window: what it runs, over which range, and where it lands.
|
||||
fn window(op: &BoundWindow) -> String {
|
||||
format!(
|
||||
|
||||
@@ -24,7 +24,7 @@ use super::super::plan::{
|
||||
};
|
||||
use crate::map::MathOp;
|
||||
use crate::range_eval::{RangeFunction, RangeWindow};
|
||||
use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels};
|
||||
use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels};
|
||||
|
||||
fn grid(start: i64, step: i64, len: u64) -> Arc<EvalGrid> {
|
||||
Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap())
|
||||
@@ -324,11 +324,12 @@ fn an_aggregate_and_a_binary_name_their_binding() {
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
},
|
||||
},
|
||||
output: evaluated(out),
|
||||
};
|
||||
let tree = NativeTree::try_new(binary).unwrap();
|
||||
let tree = NativeTree::try_new(binary.clone()).unwrap();
|
||||
assert_eq!(
|
||||
tree.to_string(),
|
||||
shown(&[
|
||||
@@ -339,6 +340,21 @@ fn an_aggregate_and_a_binary_name_their_binding() {
|
||||
" input Input raw samples",
|
||||
])
|
||||
);
|
||||
|
||||
// Fill values change the result, so a set one is part of the binding shown.
|
||||
let mut filled = binary;
|
||||
let NativeExpr::Binary { matching, .. } = &mut filled.expr else {
|
||||
unreachable!()
|
||||
};
|
||||
matching.fill.rhs = Some(0.5);
|
||||
assert_eq!(
|
||||
NativeTree::try_new(filled)
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.lines()
|
||||
.nth(1),
|
||||
Some(" root Binary + ignoring [] one-to-one fill_right 0.5")
|
||||
);
|
||||
}
|
||||
|
||||
/// A `without` grouping reads as `without [...]`, not as `by [...]`.
|
||||
|
||||
@@ -452,6 +452,7 @@ mod tests {
|
||||
return_bool: false,
|
||||
labels: crate::vector_match::MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: crate::vector_match::Cardinality::OneToOne,
|
||||
fill: crate::vector_match::FillValues::default(),
|
||||
},
|
||||
},
|
||||
output: {
|
||||
|
||||
@@ -24,7 +24,7 @@ use super::{
|
||||
};
|
||||
use crate::map::MathOp;
|
||||
use crate::range_eval::{RangeFunction, RangeWindow};
|
||||
use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels};
|
||||
use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels};
|
||||
|
||||
fn grid(start: i64, step: i64, len: u64) -> Arc<EvalGrid> {
|
||||
Arc::new(EvalGrid::try_new(GridSpec::try_new(start, step, len).unwrap()).unwrap())
|
||||
@@ -218,6 +218,7 @@ fn add() -> BinaryMatching {
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+162
-18
@@ -13,9 +13,9 @@
|
||||
// limitations under the License.
|
||||
|
||||
//! Operators that depend on the whole set of evaluated series at each grid point: `topk`,
|
||||
//! `bottomk`, `scalar`, `absent` and the instant-result sorts.
|
||||
//! `bottomk`, `limitk`, `limit_ratio`, `scalar`, `absent` and the instant-result sorts.
|
||||
//!
|
||||
//! Semantics follow Prometheus (`aggregationK`, `funcScalar`, `funcAbsent`,
|
||||
//! Semantics follow Prometheus (`aggregationK`, `HashRatioSampler`, `funcScalar`, `funcAbsent`,
|
||||
//! `createLabelsForAbsentFunction`, `funcSort*`). A scalar is a grid series without labels that
|
||||
//! has a value at every point, so `vector(s)` is `s` itself and has no kernel.
|
||||
|
||||
@@ -29,7 +29,7 @@ use datatypes::series::time::union_positions;
|
||||
use datatypes::series::{Label, MetricName};
|
||||
|
||||
use crate::go_sort;
|
||||
use crate::grid_series::{GridSeriesBuilder, external};
|
||||
use crate::grid_series::{GridSeriesBuilder, external, owned};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -73,22 +73,9 @@ pub fn topk(
|
||||
// Validates the series against the schema and its grid; the walk below visits the carried
|
||||
// positions, not the whole grid.
|
||||
grid_points(schema, series)?;
|
||||
// Prometheus returns nothing for k below 1, rejects NaN and values out of int64, then
|
||||
// truncates k and caps it at the number of input series.
|
||||
if k < 1.0 {
|
||||
let Some(k) = k_param(k, series.len())? else {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if k.is_nan() {
|
||||
return Err(DataFusionError::Execution("Parameter value is NaN".into()));
|
||||
}
|
||||
// Prometheus' `maxInt64`, the largest float64 below 2^63.
|
||||
if k >= 9_223_372_036_854_774_784.0 {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"Scalar value {k} overflows int64"
|
||||
)));
|
||||
}
|
||||
let k = k.trunc().min(series.len() as f64) as usize;
|
||||
|
||||
};
|
||||
let mut order: Vec<usize> = (0..series.len()).collect();
|
||||
order.sort_by(|&a, &b| compare_labels(&series[a].metric, &series[b].metric));
|
||||
let mut groups: HashMap<GroupKey, Vec<usize>> = HashMap::new();
|
||||
@@ -149,6 +136,144 @@ pub fn topk(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// `limitk(k, ...)` with a constant `k`.
|
||||
///
|
||||
/// At every point each group keeps the first `k` series in input order that hold a sample there,
|
||||
/// float or histogram, with their labels and values. Prometheus takes them in the order its
|
||||
/// storage returns series: label order once a query reads several queriers (the head and a
|
||||
/// block), creation order when the TSDB head alone answers it. A caller that wants Prometheus'
|
||||
/// result over persisted data passes the series in label order.
|
||||
pub fn limitk(
|
||||
k: f64,
|
||||
grouping: &Grouping,
|
||||
schema: &SeriesSchema,
|
||||
series: &[Series],
|
||||
) -> Result<Vec<Series>> {
|
||||
single_field(schema, "limitk")?;
|
||||
grid_points(schema, series)?;
|
||||
let Some(k) = k_param(k, series.len())? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut groups: HashMap<GroupKey, Vec<usize>> = HashMap::new();
|
||||
for (index, item) in series.iter().enumerate() {
|
||||
groups
|
||||
.entry(group_key(&item.metric, grouping))
|
||||
.or_default()
|
||||
.push(index);
|
||||
}
|
||||
let mut selected: Vec<Vec<(usize, usize)>> = vec![Vec::new(); series.len()];
|
||||
for members in groups.values() {
|
||||
let mut cursors: Vec<RowCursor<'_>> = members
|
||||
.iter()
|
||||
.map(|&member| series[member].fields.as_slice()[0].cursor())
|
||||
.collect();
|
||||
for point in union_positions(members.iter().map(|&member| &series[member].time)) {
|
||||
let mut taken = 0;
|
||||
for (slot, &member) in members.iter().enumerate() {
|
||||
if taken == k {
|
||||
break;
|
||||
}
|
||||
let Some(row) = series[member].time.row_of(point) else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(
|
||||
cursors[slot]
|
||||
.at(row)
|
||||
.expect("the axis and the fields are aligned"),
|
||||
SampleRef::Missing
|
||||
) {
|
||||
selected[member].push((point, row));
|
||||
taken += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
|
||||
let mut result = Vec::new();
|
||||
for (index, points) in selected.into_iter().enumerate() {
|
||||
if points.is_empty() {
|
||||
continue;
|
||||
}
|
||||
builder.begin_series();
|
||||
// A series belongs to one group, whose points are visited in order.
|
||||
let mut cursor = series[index].fields.as_slice()[0].cursor();
|
||||
for (point, row) in points {
|
||||
let sample = cursor.at(row).expect("the axis and the fields are aligned");
|
||||
builder.push_samples(point, &[owned(sample)?])?;
|
||||
}
|
||||
result.extend(builder.finish(series[index].metric.clone())?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// `limit_ratio(r, ...)` with a constant `r`.
|
||||
///
|
||||
/// Keeps whole series: Prometheus derives an offset in `[0, 1)` from the hash of a series' labels
|
||||
/// and keeps the series when the offset is below `r`, or, for a negative `r`, at least `1 + r`.
|
||||
/// Which series are kept does not depend on the grouping, so it is not a parameter. The hash is
|
||||
/// the one of Prometheus' default `stringlabels` build; the other label builds hash differently.
|
||||
pub fn limit_ratio(ratio: f64, schema: &SeriesSchema, series: &[Series]) -> Result<Vec<Series>> {
|
||||
grid_points(schema, series)?;
|
||||
if ratio.is_nan() {
|
||||
return Err(DataFusionError::Execution("Ratio value is NaN".into()));
|
||||
}
|
||||
let ratio = ratio.clamp(-1.0, 1.0);
|
||||
let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
|
||||
let mut result = Vec::new();
|
||||
let mut row = Vec::with_capacity(schema.fields.len());
|
||||
for item in series {
|
||||
let offset = sample_offset(&item.metric);
|
||||
let kept = if ratio >= 0.0 {
|
||||
offset < ratio
|
||||
} else {
|
||||
offset >= 1.0 + ratio
|
||||
};
|
||||
if !kept {
|
||||
continue;
|
||||
}
|
||||
// Rebuilt rather than cloned: an input may carry rows without a value, a result may not.
|
||||
builder.begin_series();
|
||||
let mut cursors: Vec<RowCursor<'_>> =
|
||||
item.fields.iter().map(|field| field.cursor()).collect();
|
||||
for (point, index) in item.time.positions() {
|
||||
row.clear();
|
||||
for cursor in &mut cursors {
|
||||
row.push(owned(
|
||||
cursor
|
||||
.at(index)
|
||||
.expect("the axis and the fields are aligned"),
|
||||
)?);
|
||||
}
|
||||
builder.push_samples(point, &row)?;
|
||||
}
|
||||
result.extend(builder.finish(item.metric.clone())?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Prometheus `HashRatioSampler.SampleOffset`: the xxHash64 of the labels as `stringlabels`
|
||||
/// encodes them, each name and value prefixed by its length, over `u64::MAX`.
|
||||
fn sample_offset(metric: &MetricName) -> f64 {
|
||||
let mut data = Vec::new();
|
||||
for (name, value) in labels_with_name(metric) {
|
||||
// Prometheus label sets hold no empty value.
|
||||
if value.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for text in [&name, &value] {
|
||||
let len = text.len();
|
||||
if len < 255 {
|
||||
data.push(len as u8);
|
||||
} else {
|
||||
data.extend([255, len as u8, (len >> 8) as u8, (len >> 16) as u8]);
|
||||
}
|
||||
data.extend_from_slice(text.as_bytes());
|
||||
}
|
||||
}
|
||||
twox_hash::XxHash64::oneshot(0, &data) as f64 / u64::MAX as f64
|
||||
}
|
||||
|
||||
/// `scalar(v)`: the value of the only series present at each point, NaN otherwise.
|
||||
pub fn scalar(schema: &SeriesSchema, series: &[Series]) -> Result<Series> {
|
||||
single_field(schema, "scalar")?;
|
||||
@@ -361,6 +486,25 @@ fn rank(a: f64, b: f64, top: bool) -> Ordering {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `k` of `topk`, `bottomk` and `limitk` as Prometheus reads it: nothing for `k` below 1, an
|
||||
/// error for NaN or a value out of int64, otherwise `k` truncated and capped at the number of
|
||||
/// input series.
|
||||
fn k_param(k: f64, series: usize) -> Result<Option<usize>> {
|
||||
if k < 1.0 {
|
||||
return Ok(None);
|
||||
}
|
||||
if k.is_nan() {
|
||||
return Err(DataFusionError::Execution("Parameter value is NaN".into()));
|
||||
}
|
||||
// Prometheus' `maxInt64`, the largest float64 below 2^63.
|
||||
if k >= 9_223_372_036_854_774_784.0 {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"Scalar value {k} overflows int64"
|
||||
)));
|
||||
}
|
||||
Ok(Some(k.trunc().min(series as f64) as usize))
|
||||
}
|
||||
|
||||
/// Label pairs identifying a group; empty values are absent, as in Prometheus.
|
||||
type GroupKey = Vec<(Arc<str>, Arc<str>)>;
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+164
-40
@@ -24,14 +24,16 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis};
|
||||
use datatypes::series::{Label, MetricName};
|
||||
|
||||
use super::{
|
||||
Grouping, LabelMatcher, MatchOp, SortOrder, absent, absent_labels, natural_less, scalar,
|
||||
sort_instant, topk,
|
||||
Grouping, LabelMatcher, MatchOp, SortOrder, absent, absent_labels, limit_ratio, limitk,
|
||||
natural_less, sample_offset, scalar, sort_instant, topk,
|
||||
};
|
||||
use crate::golden::fold_pieces;
|
||||
use crate::grid_series::reference::{
|
||||
Dense, Labels, Points, assert_pieces_eq, assert_result_eq, piece_ranges, run_ranges,
|
||||
sparse_series,
|
||||
Dense, Labels, OwnedHistogram, Points, assert_pieces_eq, assert_result_eq, piece_ranges,
|
||||
run_ranges, sparse_series,
|
||||
};
|
||||
use crate::grid_series::{GridSample, GridSeriesBuilder};
|
||||
use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
|
||||
fn schema(points: u64, fields: usize) -> SeriesSchema {
|
||||
SeriesSchema {
|
||||
@@ -117,42 +119,20 @@ fn names(list: &str) -> Vec<Arc<str>> {
|
||||
/// header of `prometheus_cases.txt`.
|
||||
#[test]
|
||||
fn select_operators_match_prometheus() {
|
||||
let text = include_str!("prometheus_cases.txt");
|
||||
let mut checked = 0;
|
||||
for case in text.split("end\n").filter(|case| case.contains("case ")) {
|
||||
let lines: Vec<&str> = case.lines().filter(|line| !line.starts_with('#')).collect();
|
||||
let spec: Vec<&str> = lines[0].split_whitespace().skip(1).collect();
|
||||
let points: usize = lines[1].split_whitespace().nth(3).unwrap().parse().unwrap();
|
||||
let schema = schema(points as u64, 1);
|
||||
let mut inputs = Vec::new();
|
||||
let mut expected: BTreeMap<String, Dense> = BTreeMap::new();
|
||||
for line in &lines[2..] {
|
||||
let (kind, rest) = line.split_once(' ').unwrap();
|
||||
let (labels, values) = rest.split_once(" ;").unwrap();
|
||||
match kind {
|
||||
"series" => inputs.push((metric(labels), dense(points, values))),
|
||||
"result" => {
|
||||
expected.insert(labels.to_string(), dense(points, values));
|
||||
}
|
||||
other => panic!("unexpected line {other} in {case}"),
|
||||
}
|
||||
}
|
||||
let series: Vec<Series> = inputs
|
||||
.iter()
|
||||
.filter_map(|(metric, dense)| build(&schema, metric.clone(), dense))
|
||||
.collect();
|
||||
|
||||
let actual: Vec<Series> = match spec[0] {
|
||||
let checked = check_cases(
|
||||
include_str!("prometheus_cases.txt"),
|
||||
|spec, schema, series| match spec[0] {
|
||||
"topk" => {
|
||||
let grouping = match spec[3] {
|
||||
"without" => Grouping::Without(names(spec[4])),
|
||||
"by" => Grouping::By(names(spec[4])),
|
||||
_ => Grouping::By(Vec::new()),
|
||||
};
|
||||
let k: f64 = spec[2].parse().unwrap();
|
||||
topk(k, spec[1] == "topk", &grouping, &schema, &series).unwrap()
|
||||
topk(
|
||||
k,
|
||||
spec[1] == "topk",
|
||||
&grouping(spec[3], spec[4]),
|
||||
schema,
|
||||
series,
|
||||
)
|
||||
}
|
||||
"scalar" => vec![scalar(&schema, &series).unwrap()],
|
||||
"scalar" => Ok(vec![scalar(schema, series).unwrap()]),
|
||||
"absent" => {
|
||||
let matchers: Vec<LabelMatcher> = spec
|
||||
.get(1)
|
||||
@@ -189,12 +169,156 @@ fn select_operators_match_prometheus() {
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
absent(&schema, &selected, absent_labels(&matchers).unwrap())
|
||||
Ok(absent(schema, &selected, absent_labels(&matchers).unwrap())
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.collect()
|
||||
.collect())
|
||||
}
|
||||
other => panic!("unknown case {other}"),
|
||||
},
|
||||
);
|
||||
assert!(checked > 200, "{checked} result series checked");
|
||||
}
|
||||
|
||||
/// `limitk` and `limit_ratio` evaluated by the Prometheus v3.15.0 engine; see the header of
|
||||
/// `limit_cases.txt`.
|
||||
#[test]
|
||||
fn limit_operators_match_prometheus() {
|
||||
let checked = check_cases(include_str!("limit_cases.txt"), |spec, schema, series| {
|
||||
let param: f64 = spec[2].parse().unwrap();
|
||||
match spec[1] {
|
||||
"limitk" => limitk(param, &grouping(spec[3], spec[4]), schema, series),
|
||||
_ => limit_ratio(param, schema, series),
|
||||
}
|
||||
});
|
||||
assert!(checked > 200, "{checked} result series checked");
|
||||
}
|
||||
|
||||
/// The labels of the fixtures are short; these need the long length prefix of `stringlabels`.
|
||||
/// Prometheus' offsets were computed with promql-compat `cmd/narthex-golden-labelhash`.
|
||||
#[test]
|
||||
fn sample_offset_hashes_labels_like_prometheus() {
|
||||
let cases = [
|
||||
("__name__=a,job=x".to_string(), 0x3fe1c2f8b3f15aa8),
|
||||
(
|
||||
format!("__name__=a,long={}", "v".repeat(300)),
|
||||
0x3fca51ed01e04434,
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"__name__=a,{}={},zone={}",
|
||||
"n".repeat(254),
|
||||
"v".repeat(255),
|
||||
"z".repeat(70000)
|
||||
),
|
||||
0x3fc3bf72b8300ba3,
|
||||
),
|
||||
// A Prometheus label set has no empty value, so an empty label is no label.
|
||||
("__name__=a,empty=,job=x".to_string(), 0x3fe1c2f8b3f15aa8),
|
||||
];
|
||||
for (labels, offset) in cases {
|
||||
assert_eq!(sample_offset(&metric(&labels)).to_bits(), offset);
|
||||
}
|
||||
}
|
||||
|
||||
/// `limitk` and `limit_ratio` select series, so histogram samples pass through, and
|
||||
/// `limit_ratio` keeps every field of the series it keeps.
|
||||
#[test]
|
||||
fn limit_operators_keep_histogram_samples() {
|
||||
let histogram =
|
||||
OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///");
|
||||
let sample = || {
|
||||
GridSample::Histogram(Box::new(
|
||||
FloatHistogram::try_from_view(&histogram.view()).unwrap(),
|
||||
))
|
||||
};
|
||||
let kinds = |series: &Series, field: usize| -> Vec<(usize, &str)> {
|
||||
let samples = &series.fields.as_slice()[field];
|
||||
series
|
||||
.time
|
||||
.positions()
|
||||
.map(|(point, row)| {
|
||||
let kind = match samples.sample(row) {
|
||||
SampleRef::Missing => "missing",
|
||||
SampleRef::Float(_) => "float",
|
||||
SampleRef::Histogram(_) => "histogram",
|
||||
};
|
||||
(point, kind)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
let two_fields = schema(3, 2);
|
||||
let mut builder = GridSeriesBuilder::try_new(Arc::new(two_fields.clone())).unwrap();
|
||||
builder
|
||||
.push_samples(0, &[Some(GridSample::Float(1.0)), Some(sample())])
|
||||
.unwrap();
|
||||
builder.push_samples(2, &[None, Some(sample())]).unwrap();
|
||||
let series = builder.finish(metric("__name__=a")).unwrap().unwrap();
|
||||
let kept = limit_ratio(1.0, &two_fields, std::slice::from_ref(&series)).unwrap();
|
||||
assert_eq!(kept.len(), 1);
|
||||
assert_eq!(kinds(&kept[0], 0), [(0, "float"), (2, "missing")]);
|
||||
assert_eq!(kinds(&kept[0], 1), [(0, "histogram"), (2, "histogram")]);
|
||||
|
||||
let one_field = schema(3, 1);
|
||||
let mut builder = GridSeriesBuilder::try_new(Arc::new(one_field.clone())).unwrap();
|
||||
builder.push_samples(1, &[Some(sample())]).unwrap();
|
||||
let series = builder.finish(metric("__name__=a")).unwrap().unwrap();
|
||||
let kept = limitk(1.0, &Grouping::By(Vec::new()), &one_field, &[series]).unwrap();
|
||||
assert_eq!(kept.len(), 1);
|
||||
assert_eq!(kinds(&kept[0], 0), [(1, "histogram")]);
|
||||
}
|
||||
|
||||
fn grouping(kind: &str, labels: &str) -> Grouping {
|
||||
match kind {
|
||||
"without" => Grouping::Without(names(labels)),
|
||||
"by" => Grouping::By(names(labels)),
|
||||
_ => Grouping::By(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates each case of a fixture with `eval` and returns how many result series matched; a
|
||||
/// case with an `error` line must fail with that message.
|
||||
fn check_cases(
|
||||
text: &str,
|
||||
eval: impl Fn(&[&str], &SeriesSchema, &[Series]) -> Result<Vec<Series>, DataFusionError>,
|
||||
) -> usize {
|
||||
let mut checked = 0;
|
||||
for case in text.split("end\n").filter(|case| case.contains("case ")) {
|
||||
let lines: Vec<&str> = case.lines().filter(|line| !line.starts_with('#')).collect();
|
||||
let spec: Vec<&str> = lines[0].split_whitespace().skip(1).collect();
|
||||
let points: usize = lines[1].split_whitespace().nth(3).unwrap().parse().unwrap();
|
||||
let schema = schema(points as u64, 1);
|
||||
let mut inputs = Vec::new();
|
||||
let mut expected: BTreeMap<String, Dense> = BTreeMap::new();
|
||||
let mut error = None;
|
||||
for line in &lines[2..] {
|
||||
if let Some(message) = line.strip_prefix("error ") {
|
||||
error = Some(message);
|
||||
continue;
|
||||
}
|
||||
let (kind, rest) = line.split_once(' ').unwrap();
|
||||
let (labels, values) = rest.split_once(" ;").unwrap();
|
||||
match kind {
|
||||
"series" => inputs.push((metric(labels), dense(points, values))),
|
||||
"result" => {
|
||||
expected.insert(labels.to_string(), dense(points, values));
|
||||
}
|
||||
other => panic!("unexpected line {other} in {case}"),
|
||||
}
|
||||
}
|
||||
let series: Vec<Series> = inputs
|
||||
.iter()
|
||||
.filter_map(|(metric, dense)| build(&schema, metric.clone(), dense))
|
||||
.collect();
|
||||
|
||||
let actual = match (eval(&spec, &schema, &series), error) {
|
||||
(Ok(actual), None) => actual,
|
||||
(Err(actual), Some(expected)) => {
|
||||
assert_eq!(actual.message(), expected, "{case}");
|
||||
continue;
|
||||
}
|
||||
(actual, expected) => panic!("{case}\ngot {actual:?}, expected error {expected:?}"),
|
||||
};
|
||||
|
||||
// A result arrives as one series over the runs of valued positions; the fixtures pin the
|
||||
@@ -213,7 +337,7 @@ fn select_operators_match_prometheus() {
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked > 200, "{checked} result series checked");
|
||||
checked
|
||||
}
|
||||
|
||||
/// The fixture's label rendering: `name=value` pairs in name order, `-` when empty.
|
||||
|
||||
@@ -23,6 +23,7 @@ use std::task::{Context, Poll, Waker};
|
||||
use api::v1::SemanticType;
|
||||
use common_error::ext::{BoxedError, ErrorExt, PlainError};
|
||||
use common_error::status_code::StatusCode;
|
||||
use common_query::series_frame::{pack_raw_series, raw_series_frame_ordering, unpack_raw_series};
|
||||
use datatypes::arrow::array::Float64Array;
|
||||
use datatypes::arrow::buffer::{Buffer, ScalarBuffer};
|
||||
use datatypes::data_type::ConcreteDataType;
|
||||
@@ -431,6 +432,67 @@ async fn merges_full_encoded_keys_and_interleaved_chunks_with_global_finality()
|
||||
assert!(series[2].3.last().unwrap());
|
||||
}
|
||||
|
||||
/// Two inputs that each went through the frame codec merge like plain streams: unpacking keeps
|
||||
/// the declared ordering, and the merge restores global key order and per-key finality across
|
||||
/// the unpacked frames.
|
||||
#[tokio::test]
|
||||
async fn merges_two_unpacked_frames_through_the_frame_codec() {
|
||||
let rack_a_sensor_1 = read_key("rack-a", "sensor-1");
|
||||
let rack_b_sensor_1 = read_key("rack-b", "sensor-1");
|
||||
let framed = |labels: RawLabelSource, chunks: Vec<RawSeriesChunk>| {
|
||||
let (stream, _, _) = stream(
|
||||
labels,
|
||||
SeriesOrdering::KeyThenTime,
|
||||
chunks.into_iter().map(ready),
|
||||
);
|
||||
let schema = Arc::clone(stream.schema());
|
||||
let binding = stream.label_source().clone();
|
||||
let packed = pack_raw_series(stream).unwrap();
|
||||
let ordering = raw_series_frame_ordering(packed.schema().as_ref()).unwrap();
|
||||
assert_eq!(SeriesOrdering::KeyThenTime, ordering);
|
||||
unpack_raw_series(packed, schema, binding, ordering).unwrap()
|
||||
};
|
||||
let left = framed(
|
||||
label_source(1),
|
||||
vec![
|
||||
chunk(rack_a_sensor_1.clone(), &[10, 30], &[1.0, 3.0], true),
|
||||
chunk(rack_b_sensor_1.clone(), &[5], &[5.0], true),
|
||||
],
|
||||
);
|
||||
let right = framed(
|
||||
label_source(2),
|
||||
vec![chunk(rack_a_sensor_1.clone(), &[20, 40], &[2.0, 4.0], true)],
|
||||
);
|
||||
|
||||
let mut merged = merge_ordered_raw_series(vec![left, right]).unwrap();
|
||||
assert_eq!(SeriesOrdering::KeyThenTime, merged.ordering());
|
||||
let mut series = Vec::<(Buffer, Vec<i64>, Vec<bool>)>::new();
|
||||
while let Some(item) = merged.next().await {
|
||||
let item = item.unwrap();
|
||||
if series
|
||||
.last()
|
||||
.is_none_or(|current| current.0 != item.primary_key)
|
||||
{
|
||||
series.push((item.primary_key.clone(), Vec::new(), Vec::new()));
|
||||
}
|
||||
let current = series.last_mut().unwrap();
|
||||
current.1.extend(item.time.as_buffer().to_vec());
|
||||
current.2.push(item.is_last);
|
||||
}
|
||||
assert_eq!(2, series.len());
|
||||
assert_eq!(rack_a_sensor_1, series[0].0);
|
||||
assert_eq!(vec![10, 20, 30, 40], series[0].1);
|
||||
assert!(*series[0].2.last().unwrap());
|
||||
assert!(
|
||||
series[0].2[..series[0].2.len() - 1]
|
||||
.iter()
|
||||
.all(|last| !last)
|
||||
);
|
||||
assert_eq!(rack_b_sensor_1, series[1].0);
|
||||
assert_eq!(vec![5], series[1].1);
|
||||
assert!(*series[1].2.last().unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_equal_timestamp_from_separate_heads() {
|
||||
let key = read_key("rack-a", "sensor-1");
|
||||
|
||||
+187
-59
@@ -25,12 +25,12 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::error::{DataFusionError, Result};
|
||||
use datatypes::series::MetricName;
|
||||
use datatypes::series::histogram::{CounterResetHint, HistogramView};
|
||||
use datatypes::series::samples::{RowCursor, SampleRef, Series, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridRunPair, TimeAxis};
|
||||
use datatypes::series::{Label, MetricName};
|
||||
|
||||
use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS};
|
||||
use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS, external, owned};
|
||||
use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -110,8 +110,30 @@ pub struct BinaryMatching {
|
||||
pub return_bool: bool,
|
||||
pub labels: MatchingLabels,
|
||||
pub cardinality: Cardinality,
|
||||
pub fill: FillValues,
|
||||
}
|
||||
|
||||
/// The values of `fill`, `fill_left` and `fill_right`, which stand in for a sample that has no
|
||||
/// match on the other side.
|
||||
///
|
||||
/// Prometheus applies them after it swaps the operands of `group_right`, so there `fill_left`
|
||||
/// stands in for a missing right-hand sample and `fill_right` for a missing left-hand one.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct FillValues {
|
||||
pub lhs: Option<f64>,
|
||||
pub rhs: Option<f64>,
|
||||
}
|
||||
|
||||
// Compared by bits: a NaN fill equals itself, and `fill(-0)` differs from `fill(0)` (`1 / fill`).
|
||||
impl PartialEq for FillValues {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let bits = |value: Option<f64>| value.map(f64::to_bits);
|
||||
bits(self.lhs) == bits(other.lhs) && bits(self.rhs) == bits(other.rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for FillValues {}
|
||||
|
||||
/// A PromQL set operator between two instant vectors.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SetOp {
|
||||
@@ -135,7 +157,8 @@ pub fn binary_output_schema(lhs: &SeriesSchema, rhs: &SeriesSchema) -> Result<Ar
|
||||
/// Fields are paired by position. Arithmetic and `bool` comparisons drop `__name__`, `__type__`
|
||||
/// and `__unit__`; comparisons without `bool` keep the left value where they hold. Native
|
||||
/// histograms support `+`, `-`, `==` and `!=` with each other, `*` with a float on either side
|
||||
/// and `/` by a float; Prometheus skips any other pairing of a histogram.
|
||||
/// and `/` by a float; Prometheus skips any other pairing of a histogram. A fill value pairs a
|
||||
/// sample that has no match with a float sample labelled with its match group.
|
||||
pub fn binary_vectors(
|
||||
matching: &BinaryMatching,
|
||||
lhs_schema: &SeriesSchema,
|
||||
@@ -174,18 +197,21 @@ fn binary_field(
|
||||
Cardinality::OneToMany(include) => (rhs, lhs, &include[..], true),
|
||||
};
|
||||
let points = grid.timestamps().len();
|
||||
// Prometheus short-circuits a point where either side is empty, before any check.
|
||||
let both_present: Vec<bool> = lhs
|
||||
let fill = matching.fill;
|
||||
// Prometheus short-circuits a point where either side is empty, before any check; with a fill
|
||||
// value only a point where both are empty.
|
||||
let filling = fill.lhs.is_some() || fill.rhs.is_some();
|
||||
let evaluated: Vec<bool> = lhs
|
||||
.presence(points)
|
||||
.into_iter()
|
||||
.zip(rhs.presence(points))
|
||||
.map(|(lhs, rhs)| lhs && rhs)
|
||||
.map(|(lhs, rhs)| if filling { lhs || rhs } else { lhs && rhs })
|
||||
.collect();
|
||||
|
||||
let one_groups = group(one, &matching.labels);
|
||||
let mut one_duplicate: Option<(usize, &GroupKey)> = None;
|
||||
for (key, members) in &one_groups {
|
||||
if let Some(point) = overlap(one, members, |point| both_present[point])
|
||||
if let Some(point) = overlap(one, members, |point| evaluated[point])
|
||||
&& one_duplicate.is_none_or(|(first, _)| point < first)
|
||||
{
|
||||
one_duplicate = Some((point, key));
|
||||
@@ -193,23 +219,23 @@ fn binary_field(
|
||||
}
|
||||
|
||||
let drop_name = !matching.op.is_comparison() || matching.return_bool;
|
||||
let mut results = Results::default();
|
||||
let group_keys: Vec<&GroupKey> = one_groups.keys().collect();
|
||||
let group_ids: HashMap<&GroupKey, usize> = group_keys
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, key)| (*key, id))
|
||||
.collect();
|
||||
// One-to-one: a match group may be matched once per point; Prometheus counts a filtered
|
||||
// comparison as a match too, but not an operation that failed.
|
||||
let mut matched: HashSet<(usize, usize)> = HashSet::new();
|
||||
let mut implicit_many_to_one: Option<(usize, &GroupKey)> = None;
|
||||
let mut pairs = Pairs {
|
||||
matching,
|
||||
one_is_left,
|
||||
results: Results::default(),
|
||||
group_keys: Vec::new(),
|
||||
group_ids: HashMap::new(),
|
||||
matched: (matching.cardinality == Cardinality::OneToOne || fill.lhs.is_some())
|
||||
.then(HashSet::new),
|
||||
implicit_many_to_one: None,
|
||||
};
|
||||
for (many_index, many_series) in many.series.iter().enumerate() {
|
||||
let key = group_key(&many_series.metric, &matching.labels);
|
||||
let Some(candidates) = one_groups.get(&key) else {
|
||||
let candidates = one_groups.get(&key).map_or(&[][..], Vec::as_slice);
|
||||
if candidates.is_empty() && fill.rhs.is_none() {
|
||||
continue;
|
||||
};
|
||||
let group_id = group_ids[&key];
|
||||
}
|
||||
let group = pairs.group_id(&key);
|
||||
for &one_index in candidates {
|
||||
let metric = result_metric(
|
||||
&many_series.metric,
|
||||
@@ -237,36 +263,65 @@ fn binary_field(
|
||||
.at(pair.other_row + offset)
|
||||
.expect("a row never goes back"),
|
||||
);
|
||||
if matches!(many_value, SampleRef::Missing)
|
||||
|| matches!(one_value, SampleRef::Missing)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (lhs_value, rhs_value) = if one_is_left {
|
||||
(one_value, many_value)
|
||||
} else {
|
||||
(many_value, one_value)
|
||||
};
|
||||
let Some((result, keep)) = elem_binop(matching.op, lhs_value, rhs_value)?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if matching.cardinality == Cardinality::OneToOne
|
||||
&& !matched.insert((group_id, point))
|
||||
&& implicit_many_to_one.is_none_or(|(first, _)| point < first)
|
||||
{
|
||||
implicit_many_to_one = Some((point, group_keys[group_id]));
|
||||
}
|
||||
let value = if matching.return_bool {
|
||||
Some(GridSample::Float(if keep { 1.0 } else { 0.0 }))
|
||||
} else {
|
||||
keep.then_some(result)
|
||||
};
|
||||
results.insert(&metric, group_id, point, value);
|
||||
pairs.apply(group, &metric, point, many_value, one_value)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(value) = fill.rhs {
|
||||
let metric = result_metric(
|
||||
&many_series.metric,
|
||||
&metric_of(&key)?,
|
||||
matching,
|
||||
include,
|
||||
drop_name,
|
||||
)?;
|
||||
let mut cursor = many.cursor(many_index);
|
||||
let mut candidate_cursors: Vec<RowCursor<'_>> =
|
||||
candidates.iter().map(|&index| one.cursor(index)).collect();
|
||||
for (point, row) in many.positions(many_index) {
|
||||
let sample = cursor.at(row).expect("a row never goes back");
|
||||
let matched = candidates
|
||||
.iter()
|
||||
.zip(&mut candidate_cursors)
|
||||
.any(|(&index, cursor)| one.present(index, point, cursor));
|
||||
if !matched {
|
||||
pairs.apply(group, &metric, point, sample, SampleRef::Float(value))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Prometheus fills the many side after every match of the step, for the samples of the one
|
||||
// side that no operation matched.
|
||||
if let Some(value) = fill.lhs {
|
||||
for (one_index, one_series) in one.series.iter().enumerate() {
|
||||
let key = group_key(&one_series.metric, &matching.labels);
|
||||
let group = pairs.group_id(&key);
|
||||
let metric = result_metric(
|
||||
&metric_of(&key)?,
|
||||
&one_series.metric,
|
||||
matching,
|
||||
include,
|
||||
drop_name,
|
||||
)?;
|
||||
let mut cursor = one.cursor(one_index);
|
||||
for (point, row) in one.positions(one_index) {
|
||||
if !pairs
|
||||
.matched
|
||||
.as_ref()
|
||||
.is_some_and(|matched| matched.contains(&(group, point)))
|
||||
{
|
||||
let sample = cursor.at(row).expect("a row never goes back");
|
||||
pairs.apply(group, &metric, point, SampleRef::Float(value), sample)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Pairs {
|
||||
mut results,
|
||||
group_keys,
|
||||
implicit_many_to_one,
|
||||
..
|
||||
} = pairs;
|
||||
// Prometheus fails at the first failing step. Within a step it checks the one side, then
|
||||
// matches, and only after the operator checks that result label sets are unique.
|
||||
if let Some((point, key)) = one_duplicate {
|
||||
@@ -283,7 +338,8 @@ fn binary_field(
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Some((point, key)) = implicit_many_to_one {
|
||||
if let Some((point, group)) = implicit_many_to_one {
|
||||
let key = &group_keys[group];
|
||||
errors.push((
|
||||
point,
|
||||
1,
|
||||
@@ -319,6 +375,89 @@ fn binary_field(
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// The matched pairs of one field and the state Prometheus checks them against.
|
||||
struct Pairs<'a> {
|
||||
matching: &'a BinaryMatching,
|
||||
one_is_left: bool,
|
||||
results: Results,
|
||||
group_keys: Vec<GroupKey>,
|
||||
group_ids: HashMap<GroupKey, usize>,
|
||||
/// The match groups an operation matched at a point, kept where Prometheus consults them:
|
||||
/// one-to-one matching, and filling the many side. A filtered comparison counts as a match,
|
||||
/// an operation that failed does not.
|
||||
matched: Option<HashSet<(usize, usize)>>,
|
||||
implicit_many_to_one: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl Pairs<'_> {
|
||||
/// The id of the match group `key`, which stands for it in `matched` and in the results.
|
||||
fn group_id(&mut self, key: &GroupKey) -> usize {
|
||||
if let Some(&id) = self.group_ids.get(key) {
|
||||
return id;
|
||||
}
|
||||
let id = self.group_keys.len();
|
||||
self.group_keys.push(key.clone());
|
||||
self.group_ids.insert(key.clone(), id);
|
||||
id
|
||||
}
|
||||
|
||||
/// Applies the operator to a sample of each side at `point`; a missing sample is no pair.
|
||||
fn apply(
|
||||
&mut self,
|
||||
group: usize,
|
||||
metric: &MetricName,
|
||||
point: usize,
|
||||
many_value: SampleRef<'_>,
|
||||
one_value: SampleRef<'_>,
|
||||
) -> Result<()> {
|
||||
if matches!(many_value, SampleRef::Missing) || matches!(one_value, SampleRef::Missing) {
|
||||
return Ok(());
|
||||
}
|
||||
let (lhs_value, rhs_value) = if self.one_is_left {
|
||||
(one_value, many_value)
|
||||
} else {
|
||||
(many_value, one_value)
|
||||
};
|
||||
let Some((result, keep)) = elem_binop(self.matching.op, lhs_value, rhs_value)? else {
|
||||
return Ok(());
|
||||
};
|
||||
// One-to-one: a match group may be matched once per point.
|
||||
if let Some(matched) = &mut self.matched
|
||||
&& !matched.insert((group, point))
|
||||
&& self.matching.cardinality == Cardinality::OneToOne
|
||||
&& self
|
||||
.implicit_many_to_one
|
||||
.is_none_or(|(first, _)| point < first)
|
||||
{
|
||||
self.implicit_many_to_one = Some((point, group));
|
||||
}
|
||||
let value = if self.matching.return_bool {
|
||||
Some(GridSample::Float(if keep { 1.0 } else { 0.0 }))
|
||||
} else {
|
||||
keep.then_some(result)
|
||||
};
|
||||
self.results.insert(metric, group, point, value);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The labels Prometheus gives a fill sample: the match group of the sample it pairs with.
|
||||
fn metric_of(key: &GroupKey) -> Result<MetricName> {
|
||||
let mut name = None;
|
||||
let mut labels = Vec::with_capacity(key.len());
|
||||
for (label, value) in key {
|
||||
if &**label == "__name__" {
|
||||
name = Some(value.clone());
|
||||
} else {
|
||||
labels.push(Label {
|
||||
name: label.clone(),
|
||||
value: value.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
MetricName::try_new(name, labels).map_err(external)
|
||||
}
|
||||
|
||||
fn earliest_error(errors: Vec<(usize, u8, String)>) -> Result<()> {
|
||||
match errors
|
||||
.into_iter()
|
||||
@@ -687,17 +826,6 @@ impl<'a> Operand<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `sample` as an owned value; `None` when missing.
|
||||
fn owned(sample: SampleRef<'_>) -> Result<Option<GridSample>> {
|
||||
Ok(match sample {
|
||||
SampleRef::Missing => None,
|
||||
SampleRef::Float(value) => Some(GridSample::Float(value)),
|
||||
SampleRef::Histogram(view) => Some(GridSample::Histogram(Box::new(
|
||||
FloatHistogram::try_from_view(&view)?,
|
||||
))),
|
||||
})
|
||||
}
|
||||
|
||||
/// Prometheus `vectorElemBinop` over present samples: the value and whether to keep it, or
|
||||
/// `None` when Prometheus reports the pair as an annotation and skips it without counting the
|
||||
/// match: an operator the sample types do not support, or an addition or subtraction of
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -23,7 +23,8 @@ use rand::rngs::StdRng;
|
||||
use rand::{Rng, SeedableRng};
|
||||
|
||||
use super::{
|
||||
BinaryMatching, BinaryOp, Cardinality, MatchingLabels, SetOp, binary_vectors, set_vectors,
|
||||
BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp, binary_vectors,
|
||||
set_vectors,
|
||||
};
|
||||
use crate::grid_series::GridSeriesBuilder;
|
||||
use crate::grid_series::reference::{
|
||||
@@ -481,6 +482,7 @@ fn binary_vectors_match_prometheus_reference() {
|
||||
return_bool,
|
||||
labels,
|
||||
cardinality,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let fields = lhs_fields.min(rhs_fields);
|
||||
let points = grid.timestamps().len();
|
||||
@@ -555,6 +557,7 @@ fn rejects_operands_on_other_grids_and_unpaired_or_fields() {
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
assert!(binary_vectors(&matching, &lhs.schema, &lhs.series, &schema(1, &other), &[]).is_err());
|
||||
assert!(matches!(
|
||||
@@ -614,6 +617,7 @@ fn reports_the_earliest_failing_point() {
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::On(vec![Arc::from("job")]),
|
||||
cardinality: Cardinality::ManyToOne(Vec::new()),
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let error = binary_vectors(&matching, &schema, &lhs, &schema, &rhs)
|
||||
.unwrap_err()
|
||||
@@ -655,6 +659,26 @@ fn canonical_bits(value: f64) -> u64 {
|
||||
/// `prometheus_cases.txt`.
|
||||
#[test]
|
||||
fn vector_operations_match_prometheus() {
|
||||
let (matched, failed) = check_cases(include_str!("prometheus_cases.txt"));
|
||||
assert!(
|
||||
matched > 100 && failed > 20,
|
||||
"{matched} matched, {failed} failed"
|
||||
);
|
||||
}
|
||||
|
||||
/// Binary operations with fill modifiers, evaluated by the Prometheus v3.15.0 engine; see the
|
||||
/// header of `fill_cases.txt`.
|
||||
#[test]
|
||||
fn fill_modifiers_match_prometheus() {
|
||||
let (matched, failed) = check_cases(include_str!("fill_cases.txt"));
|
||||
assert!(
|
||||
matched > 100 && failed > 20,
|
||||
"{matched} matched, {failed} failed"
|
||||
);
|
||||
}
|
||||
|
||||
/// Checks each case of a fixture and returns how many matched results and how many failed.
|
||||
fn check_cases(text: &str) -> (usize, usize) {
|
||||
let parse_labels = |labels: &str| -> Labels {
|
||||
labels
|
||||
.split(',')
|
||||
@@ -672,7 +696,6 @@ fn vector_operations_match_prometheus() {
|
||||
.collect()
|
||||
};
|
||||
let (mut matched, mut failed) = (0, 0);
|
||||
let text = include_str!("prometheus_cases.txt");
|
||||
for case in text.split("end\n").filter(|case| case.contains("case ")) {
|
||||
let lines: Vec<&str> = case.lines().filter(|line| !line.starts_with('#')).collect();
|
||||
let spec: Vec<&str> = lines[0].split_whitespace().skip(1).collect();
|
||||
@@ -729,6 +752,10 @@ fn vector_operations_match_prometheus() {
|
||||
other => panic!("unexpected line {other}"),
|
||||
}
|
||||
}
|
||||
let fill = |value: Option<&&str>| match value {
|
||||
None | Some(&"-") => None,
|
||||
Some(value) => Some(value.parse::<f64>().unwrap()),
|
||||
};
|
||||
let labels = |kind: &str, list: &str| match kind {
|
||||
"on" => MatchingLabels::On(names(list)),
|
||||
_ => MatchingLabels::Ignoring(names(list)),
|
||||
@@ -760,6 +787,10 @@ fn vector_operations_match_prometheus() {
|
||||
"right" => Cardinality::OneToMany(names(spec[6])),
|
||||
_ => Cardinality::OneToOne,
|
||||
},
|
||||
fill: FillValues {
|
||||
lhs: fill(spec.get(7)),
|
||||
rhs: fill(spec.get(8)),
|
||||
},
|
||||
};
|
||||
binary_vectors(&matching, &schema, &lhs, &schema, &rhs)
|
||||
}
|
||||
@@ -806,10 +837,7 @@ fn vector_operations_match_prometheus() {
|
||||
(actual, expected) => panic!("{case}\ngot {actual:?}, expected error {expected:?}"),
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
matched > 100 && failed > 20,
|
||||
"{matched} matched, {failed} failed"
|
||||
);
|
||||
(matched, failed)
|
||||
}
|
||||
|
||||
/// Results that share a label set once `__type__` is dropped fail as a grouping violation within
|
||||
@@ -858,6 +886,7 @@ fn colliding_results_fail_by_where_they_collide() {
|
||||
return_bool: false,
|
||||
labels,
|
||||
cardinality: Cardinality::ManyToOne(Vec::new()),
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let error = binary_vectors(&matching, &schema, &lhs, &schema, rhs)
|
||||
.unwrap_err()
|
||||
@@ -1002,6 +1031,7 @@ fn histogram_operators_match_prometheus() {
|
||||
"right" => Cardinality::OneToMany(Vec::new()),
|
||||
_ => Cardinality::OneToOne,
|
||||
},
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
binary_vectors(&matching, &schema, &lhs, &schema, &rhs)
|
||||
}
|
||||
@@ -1127,12 +1157,66 @@ fn colliding_reset_hints_skip_the_pair() {
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::On(vec![Arc::from("job")]),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(&matching, &schema, &lhs, &schema, &rhs).unwrap();
|
||||
assert_eq!(result.len(), 1, "{op:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A pair whose operation fails is not a match, so `fill_left` still fills for the right-hand
|
||||
/// sample of that pair; the fixtures hold floats only.
|
||||
#[test]
|
||||
fn a_failed_pair_leaves_its_sample_to_the_fill() {
|
||||
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 10_000, 1).unwrap()).unwrap());
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: vec![FieldSpec {
|
||||
name: Arc::from("value"),
|
||||
}]
|
||||
.into(),
|
||||
eval_grid: Some(grid),
|
||||
});
|
||||
let labels = |pairs: &[(&str, &str)]| -> Labels {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(name, value)| (name.to_string(), value.to_string()))
|
||||
.collect()
|
||||
};
|
||||
let histogram = "0/0/0/4014000000000000/4014000000000000/0/0_1/4014000000000000///";
|
||||
let lhs = [mixed_series(
|
||||
&schema,
|
||||
&labels(&[("__name__", "a"), ("job", "x")]),
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::from([(0, histogram.to_string())]),
|
||||
)
|
||||
.unwrap()];
|
||||
let rhs = [mixed_series(
|
||||
&schema,
|
||||
&labels(&[("__name__", "b"), ("job", "x")]),
|
||||
&BTreeMap::from([(0, 2.0f64.to_bits())]),
|
||||
&BTreeMap::new(),
|
||||
)
|
||||
.unwrap()];
|
||||
// A histogram plus a float is skipped, so `b` is unmatched: 10 + 2 under the match labels.
|
||||
let matching = BinaryMatching {
|
||||
op: BinaryOp::Add,
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::On(vec![Arc::from("job")]),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues {
|
||||
lhs: Some(10.0),
|
||||
rhs: None,
|
||||
},
|
||||
};
|
||||
let result = binary_vectors(&matching, &schema, &lhs, &schema, &rhs).unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(labels_of(&result[0].metric), labels(&[("job", "x")]));
|
||||
assert!(matches!(
|
||||
result[0].fields.as_slice()[0].sample(0),
|
||||
SampleRef::Float(value) if value == 12.0
|
||||
));
|
||||
}
|
||||
|
||||
/// A binary pairing walks two operands of many single-position runs and still reports every
|
||||
/// position exactly once.
|
||||
///
|
||||
@@ -1170,6 +1254,7 @@ fn a_pairing_reads_many_single_position_runs_once() {
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::On(vec![Arc::from("job")]),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(
|
||||
&matching,
|
||||
@@ -1218,6 +1303,7 @@ fn a_binary_pairing_of_sparse_operands_keeps_the_shared_positions() {
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(
|
||||
&matching,
|
||||
@@ -1249,6 +1335,7 @@ fn a_binary_pairing_of_sparse_operands_keeps_the_shared_positions() {
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(
|
||||
&filtered,
|
||||
@@ -1278,6 +1365,7 @@ fn a_binary_pairing_of_sparse_operands_keeps_the_shared_positions() {
|
||||
return_bool: true,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(
|
||||
&booled,
|
||||
|
||||
Reference in New Issue
Block a user