mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 21:54:08 +00:00
Merge branch 'feat/narthex-native-exec-sparse' into feat/narthex-unified-exec
Bring the instant selection node onto the simplified native executor: keep the parent's coarse accounting, NodeSpec, collecting-window merge and boundary validation, and re-express the instant gather in that shape. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
Generated
+1
@@ -11377,6 +11377,7 @@ dependencies = [
|
||||
"snafu 0.8.6",
|
||||
"store-api",
|
||||
"tokio",
|
||||
"twox-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -278,6 +278,7 @@ tracing = "0.1"
|
||||
tracing-appender = "0.2"
|
||||
tracing-opentelemetry = "0.33.0"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "json", "fmt"] }
|
||||
twox-hash = { version = "2.1", default-features = false, features = ["xxhash64"] }
|
||||
typetag = "0.2"
|
||||
uddsketch-rs = "0.1.0"
|
||||
uuid = { version = "1.17", features = ["serde", "v4", "v7", "fast-rng"] }
|
||||
|
||||
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
|
||||
|
||||
+260
-81
@@ -24,7 +24,7 @@ use datafusion::error::{DataFusionError, Result};
|
||||
use datatypes::series::MetricName;
|
||||
use datatypes::series::histogram::HistogramBatchBuilder;
|
||||
use datatypes::series::samples::{
|
||||
HistogramSamples, RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
|
||||
HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
|
||||
};
|
||||
use datatypes::series::time::{EvalGrid, GridSpan, TimeAxis};
|
||||
|
||||
@@ -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> {
|
||||
@@ -310,6 +321,13 @@ pub(crate) fn label_set(metric: &MetricName) -> LabelSet {
|
||||
|
||||
/// Merges series that share a label set into one, as Prometheus does after a function that
|
||||
/// rewrites labels or drops `__name__`; two of them holding one field at one point fail.
|
||||
///
|
||||
/// The merge rearranges the payloads instead of rewriting them: a merged row takes the value its
|
||||
/// member carries at that position -- a float, a NaN, or a native histogram -- and a field another
|
||||
/// field's row does not fill keeps a null there. The values keep their storage: a run of rows one
|
||||
/// member holds in one dense segment is handed out as a [`Samples::slice`] of that segment, so a
|
||||
/// histogram table is shared rather than copied. The result costs one row per position holding a
|
||||
/// value, plus the rows the other fields fill, and nothing for a position of the grid holding none.
|
||||
pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> Result<Vec<Series>> {
|
||||
let mut groups: HashMap<LabelSet, Vec<usize>> = HashMap::with_capacity(series.len());
|
||||
let mut collided = false;
|
||||
@@ -328,111 +346,272 @@ pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> R
|
||||
return Ok(series);
|
||||
}
|
||||
|
||||
// The merged axis and the fields placed on it are the schema's grid: a member of another grid
|
||||
// would land its rows at positions naming other timestamps.
|
||||
let grid = schema.eval_grid.clone().ok_or_else(|| {
|
||||
DataFusionError::Execution("grid series schema requires an evaluation grid".into())
|
||||
})?;
|
||||
let mut series: Vec<Option<Series>> = series.into_iter().map(Some).collect();
|
||||
let mut output = Vec::with_capacity(groups.len());
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
|
||||
// `(absolute position, member slot, compact row)`, sorted by position before merging. The
|
||||
// slot indexes `members`, so the merge below picks the member's cursor directly instead of
|
||||
// searching for the member per row.
|
||||
// `(absolute position, member slot, compact row)`, sorted by position before merging. The slot
|
||||
// indexes the group's fragments, so a row names its member without a search.
|
||||
let mut rows: Vec<(usize, usize, usize)> = Vec::new();
|
||||
let mut values = vec![None; schema.fields.len()];
|
||||
let mut merged = vec![None; schema.fields.len()];
|
||||
// The position of each merged row, ascending, with the positions several fragments share held
|
||||
// once.
|
||||
let mut positions: Vec<usize> = Vec::new();
|
||||
for (labels, members) in groups {
|
||||
if let [member] = members[..] {
|
||||
output.extend(series[member].take());
|
||||
continue;
|
||||
}
|
||||
builder.begin_series();
|
||||
rows.clear();
|
||||
for (member_slot, &member) in members.iter().enumerate() {
|
||||
let member_series = series[member]
|
||||
.as_ref()
|
||||
.expect("each series is in one group");
|
||||
if member_series.time.grid().is_none() {
|
||||
// Validate every fragment before indexing it: the merge reads its fields and places its
|
||||
// rows on the schema's grid.
|
||||
let mut fragments: Vec<&Series> = Vec::with_capacity(members.len());
|
||||
for &member in &members {
|
||||
let fragment = series[member].as_ref().ok_or_else(|| {
|
||||
DataFusionError::Execution("each series is in exactly one label set".into())
|
||||
})?;
|
||||
let Some(fragment_grid) = fragment.time.grid() else {
|
||||
return Err(DataFusionError::Execution(
|
||||
"merging requires evaluated series".into(),
|
||||
));
|
||||
};
|
||||
if fragment_grid.spec() != grid.spec() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"merging requires one evaluation grid".into(),
|
||||
));
|
||||
}
|
||||
// The axis names the positions this member holds, and one cursor per field reads its
|
||||
// values in the same order, so a member of several runs costs its rows.
|
||||
let mut cursors: Vec<RowCursor<'_>> = member_series
|
||||
if fragment.fields.len() != schema.fields.len() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"merging requires {} fields, a fragment holds {}",
|
||||
schema.fields.len(),
|
||||
fragment.fields.len()
|
||||
)));
|
||||
}
|
||||
// The alignment is checked before a row is read: a field of another length would either
|
||||
// run off the axis or leave values the axis never reaches.
|
||||
let time_len = fragment.time.len();
|
||||
if let Some((field, samples)) = fragment
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.cursor())
|
||||
.collect();
|
||||
for (point, row) in member_series.time.positions() {
|
||||
if read_row(&mut cursors, row, &mut values)? {
|
||||
rows.push((point, member_slot, row));
|
||||
.enumerate()
|
||||
.find(|(_, samples)| samples.len() != time_len)
|
||||
{
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"merging requires every field to hold the {time_len} rows of its axis, field \
|
||||
{field} holds {}",
|
||||
samples.len()
|
||||
)));
|
||||
}
|
||||
fragments.push(fragment);
|
||||
}
|
||||
rows.clear();
|
||||
for (member_slot, fragment) in fragments.iter().enumerate() {
|
||||
// One forward reader per field: the axis names the rows that exist, and a row holding
|
||||
// no value in any field is not a merged row.
|
||||
let mut readers: Vec<FieldReader<'_>> =
|
||||
fragment.fields.iter().map(FieldReader::new).collect();
|
||||
for (position, row) in fragment.time.positions() {
|
||||
let mut present = false;
|
||||
for reader in &mut readers {
|
||||
let (segment, offset) = reader.locate(row)?;
|
||||
present |= !matches!(segment.sample(offset), SampleRef::Missing);
|
||||
}
|
||||
if present {
|
||||
rows.push((position, member_slot, row));
|
||||
}
|
||||
}
|
||||
}
|
||||
// By position, then by member slot: the slots follow the order `members` was built in, so
|
||||
// the merge below still walks each member's rows forward and its cursors never go back.
|
||||
// By position, then by member slot: the slots follow the order the fragments were collected
|
||||
// in, so a member's rows only go forward and its readers never go back.
|
||||
rows.sort_unstable();
|
||||
// One forward cursor per member and field, so re-reading a row costs neither a chunk scan
|
||||
// nor an allocation.
|
||||
let mut cursors: Vec<Vec<RowCursor<'_>>> = members
|
||||
.iter()
|
||||
.map(|&member| {
|
||||
let member_series = series[member]
|
||||
.as_ref()
|
||||
.expect("each series is in one group");
|
||||
member_series
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.cursor())
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let point = rows[start].0;
|
||||
let end = start + rows[start..].partition_point(|&(p, _, _)| p == point);
|
||||
// Rows of one point merge field by field; only a field present twice collides.
|
||||
merged.iter_mut().for_each(|value| *value = None);
|
||||
for &(_, member_slot, row) in &rows[start..end] {
|
||||
read_row(&mut cursors[member_slot], row, &mut values)?;
|
||||
for (slot, value) in merged.iter_mut().zip(&values) {
|
||||
if value.is_some() {
|
||||
if slot.is_some() {
|
||||
let labels: Vec<_> = labels
|
||||
.iter()
|
||||
.map(|(name, value)| format!("{name}=\"{value}\""))
|
||||
.collect();
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"vector cannot contain metrics with the same labelset {{{}}}",
|
||||
labels.join(", ")
|
||||
)));
|
||||
}
|
||||
*slot = *value;
|
||||
}
|
||||
}
|
||||
}
|
||||
builder.push(point, &merged)?;
|
||||
start = end;
|
||||
positions.clear();
|
||||
positions.extend(rows.iter().map(|&(position, _, _)| position));
|
||||
positions.dedup();
|
||||
let mut fields = Vec::with_capacity(schema.fields.len());
|
||||
for field in 0..schema.fields.len() {
|
||||
let mut readers: Vec<FieldReader<'_>> = fragments
|
||||
.iter()
|
||||
.map(|fragment| FieldReader::new(&fragment.fields.as_slice()[field]))
|
||||
.collect();
|
||||
fields.push(merge_field(&mut readers, &rows, &labels)?);
|
||||
}
|
||||
let metric = series[members[0]].as_ref().unwrap().metric.clone();
|
||||
output.extend(builder.finish(metric)?);
|
||||
// The runs are all the axis remembers about the holes, so a sparse merge stores one span
|
||||
// per run and no row for the positions between them.
|
||||
let time =
|
||||
TimeAxis::from_grid_spans(grid.clone(), spans_of(&positions)).map_err(external)?;
|
||||
let fields = SeriesFields::try_from_vec(fields).map_err(external)?;
|
||||
// The first fragment names the output, as it always has: a label set ignores empty values,
|
||||
// so the metric of the first member is the one the merged series keeps.
|
||||
let metric = fragments[0].metric.clone();
|
||||
output.push(Series::try_new(schema, metric, time, fields).map_err(external)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Reads the float fields of `row` through the member's cursors; returns whether any is present.
|
||||
fn read_row(cursors: &mut [RowCursor<'_>], row: usize, values: &mut [Option<f64>]) -> Result<bool> {
|
||||
let mut present = false;
|
||||
for (value, cursor) in values.iter_mut().zip(cursors) {
|
||||
*value = match cursor.at(row).expect("the axis and the fields are aligned") {
|
||||
SampleRef::Missing => None,
|
||||
SampleRef::Float(value) => Some(value),
|
||||
SampleRef::Histogram(_) => {
|
||||
return Err(DataFusionError::NotImplemented(
|
||||
"merging histogram series with the same label set".into(),
|
||||
));
|
||||
/// Builds one field of the merged series, one sample per merged row.
|
||||
///
|
||||
/// The rows are walked in output order. A row holding a value of this field in one member continues
|
||||
/// the run of rows that member holds in one dense segment, and a run is handed out as one
|
||||
/// [`Samples::slice`]; the rows another field fills become one null run, so the field stays aligned
|
||||
/// with the merged axis while sharing the values it carries.
|
||||
fn merge_field(
|
||||
readers: &mut [FieldReader<'_>],
|
||||
rows: &[(usize, usize, usize)],
|
||||
labels: &LabelSet,
|
||||
) -> Result<Samples> {
|
||||
let mut chunks: Vec<Samples> = Vec::new();
|
||||
// The run of values the last merged row continued, if any.
|
||||
let mut run: Option<FieldRun<'_>> = None;
|
||||
// Merged rows this field leaves empty, waiting for the null run that carries them.
|
||||
let mut missing = 0;
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let position = rows[start].0;
|
||||
let mut end = start;
|
||||
// At most one member may hold this field here; the second value is the collision Prometheus
|
||||
// rejects, since the two label sets became one.
|
||||
let mut value: Option<(usize, &Samples, usize)> = None;
|
||||
while end < rows.len() && rows[end].0 == position {
|
||||
let (_, member, row) = rows[end];
|
||||
let (segment, offset) = readers[member].locate(row)?;
|
||||
if !matches!(segment.sample(offset), SampleRef::Missing) {
|
||||
if value.is_some() {
|
||||
let labels: Vec<_> = labels
|
||||
.iter()
|
||||
.map(|(name, value)| format!("{name}=\"{value}\""))
|
||||
.collect();
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"vector cannot contain metrics with the same labelset {{{}}}",
|
||||
labels.join(", ")
|
||||
)));
|
||||
}
|
||||
value = Some((member, segment, offset));
|
||||
}
|
||||
};
|
||||
present |= value.is_some();
|
||||
end += 1;
|
||||
}
|
||||
match value {
|
||||
Some((member, segment, offset)) => {
|
||||
if let Some(run) = &mut run
|
||||
&& run.continues(member, segment, offset)
|
||||
{
|
||||
run.len += 1;
|
||||
} else {
|
||||
if let Some(run) = run.take() {
|
||||
run.push(&mut chunks)?;
|
||||
}
|
||||
push_missing(&mut chunks, &mut missing);
|
||||
run = Some(FieldRun {
|
||||
member,
|
||||
segment,
|
||||
offset,
|
||||
len: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(run) = run.take() {
|
||||
run.push(&mut chunks)?;
|
||||
}
|
||||
missing += 1;
|
||||
}
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
if let Some(run) = run {
|
||||
run.push(&mut chunks)?;
|
||||
}
|
||||
push_missing(&mut chunks, &mut missing);
|
||||
Samples::try_from_chunks(chunks).map_err(external)
|
||||
}
|
||||
|
||||
/// A run of merged rows one member field fills out of one dense segment, without copying values.
|
||||
///
|
||||
/// The run grows only while the next merged row is the same member's next row in the same segment,
|
||||
/// so handing it out is one [`Samples::slice`] of that segment: the payload stays where it is, and
|
||||
/// the rows a hole skipped are not part of the run.
|
||||
struct FieldRun<'a> {
|
||||
/// The member slot the run reads, which indexes the [`FieldReader`]s of the field.
|
||||
member: usize,
|
||||
/// The dense segment holding the run's values.
|
||||
segment: &'a Samples,
|
||||
/// Offset of the run's first row inside `segment`.
|
||||
offset: usize,
|
||||
/// How many rows of `segment` the run covers.
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl FieldRun<'_> {
|
||||
/// Returns whether the value at `offset` of `segment` continues the run: the same member's next
|
||||
/// row in the same dense segment.
|
||||
fn continues(&self, member: usize, segment: &Samples, offset: usize) -> bool {
|
||||
self.member == member
|
||||
&& std::ptr::eq(self.segment, segment)
|
||||
&& self.offset + self.len == offset
|
||||
}
|
||||
|
||||
/// Pushes the run as one slice of its dense segment.
|
||||
fn push(self, chunks: &mut Vec<Samples>) -> Result<()> {
|
||||
chunks.push(
|
||||
self.segment
|
||||
.slice(self.offset, self.len)
|
||||
.map_err(external)?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads one field's rows by locating the dense segment each row sits in.
|
||||
///
|
||||
/// [`Samples::sample`] rescans a chunked field from its first segment on every row, so reading a
|
||||
/// field row by row would cost a scan over the segments before it. The rows a merge reads only go
|
||||
/// forward, so this walks the segments once and returns the segment with the offset of the row
|
||||
/// inside it, which is what a [`FieldRun`] slices.
|
||||
struct FieldReader<'a> {
|
||||
segments: &'a [Samples],
|
||||
/// Index of the segment `start` belongs to.
|
||||
segment: usize,
|
||||
/// Logical row the current segment starts at.
|
||||
start: usize,
|
||||
}
|
||||
|
||||
impl<'a> FieldReader<'a> {
|
||||
/// Creates a reader at the first row of `samples`.
|
||||
fn new(samples: &'a Samples) -> Self {
|
||||
Self {
|
||||
segments: samples.segments(),
|
||||
segment: 0,
|
||||
start: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the dense segment holding `row` and the offset of `row` inside it.
|
||||
///
|
||||
/// Rows must not go backwards. A row past the field is an error rather than a panic: a member is
|
||||
/// only read after its fields are validated to align with its axis.
|
||||
fn locate(&mut self, row: usize) -> Result<(&'a Samples, usize)> {
|
||||
while let Some(segment) = self.segments.get(self.segment) {
|
||||
if let Some(offset) = row
|
||||
.checked_sub(self.start)
|
||||
.filter(|offset| *offset < segment.len())
|
||||
{
|
||||
return Ok((segment, offset));
|
||||
}
|
||||
self.segment += 1;
|
||||
self.start += segment.len();
|
||||
}
|
||||
Err(DataFusionError::Execution(
|
||||
"merging requires each field to be row-aligned with its time axis".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes the merged rows a field leaves empty as one null run.
|
||||
fn push_missing(chunks: &mut Vec<Samples>, missing: &mut usize) {
|
||||
if *missing != 0 {
|
||||
chunks.push(Samples::from_float(Float64Array::new_null(*missing)));
|
||||
*missing = 0;
|
||||
}
|
||||
Ok(present)
|
||||
}
|
||||
|
||||
pub(crate) fn external(error: datatypes::error::Error) -> DataFusionError {
|
||||
|
||||
@@ -15,15 +15,20 @@
|
||||
use std::mem::size_of;
|
||||
use std::sync::Arc;
|
||||
|
||||
use datatypes::series::samples::{DenseSamplesRef, FieldSpec, SampleRef, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridSpec};
|
||||
use datafusion::arrow::array::{Float64Array, UInt32Array};
|
||||
use datatypes::series::histogram::{HistogramBatch, HistogramBatchBuilder};
|
||||
use datatypes::series::samples::{
|
||||
DenseSamplesRef, FieldSpec, HistogramSamples, SampleRef, Samples, Series, SeriesFields,
|
||||
SeriesSchema,
|
||||
};
|
||||
use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis};
|
||||
use datatypes::series::{Label, MetricName};
|
||||
use rand::rngs::StdRng;
|
||||
use rand::{Rng, SeedableRng};
|
||||
|
||||
use super::reference::{
|
||||
Labels, Points, assert_pieces_eq, assert_result_eq, points_of, random_dense, run_ranges,
|
||||
series_of, stitch,
|
||||
Labels, OwnedHistogram, Points, assert_pieces_eq, assert_result_eq, metric_of, points_of,
|
||||
random_dense, run_ranges, series_of, stitch,
|
||||
};
|
||||
use super::{GridSeriesBuilder, merge_same_labelset};
|
||||
|
||||
@@ -479,6 +484,325 @@ fn finish_hands_out_only_the_rows_pushed_after_a_prefix_flush() {
|
||||
assert!(!builder.has_pending());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Merging: one label set handed over in several fragments.
|
||||
//
|
||||
// A runtime hands one label set over as fragments, and the merge is the only place that puts them
|
||||
// back into one series. What these tests pin is that the values move without being rebuilt: the
|
||||
// merged series shares the fragments' payloads, keeps native histograms and NaNs, and still costs
|
||||
// one row per position holding a value.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The start of the float buffer a dense float segment reads, to show a merge shared the buffer
|
||||
/// instead of copying it.
|
||||
fn float_ptr(segment: &Samples) -> *const f64 {
|
||||
match segment.dense() {
|
||||
Some(DenseSamplesRef::Float(values)) => values.values().as_ptr(),
|
||||
_ => panic!("expected a dense float segment"),
|
||||
}
|
||||
}
|
||||
|
||||
type FragmentRow<'a> = (usize, Option<f64>, Option<&'a str>, Option<f64>);
|
||||
|
||||
/// A two-field fragment: field 0 holds a float or a native histogram, field 1 a float.
|
||||
///
|
||||
/// `rows` holds `(position, field 0 float, field 0 histogram, field 1 float)` in ascending position
|
||||
/// order; a row holds a value when some field has one at that position.
|
||||
fn fragment_with_histograms(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
labels: &Labels,
|
||||
rows: &[FragmentRow<'_>],
|
||||
) -> (Series, Arc<HistogramBatch>) {
|
||||
let mut batch = HistogramBatchBuilder::new();
|
||||
let mut spans: Vec<GridSpan> = Vec::new();
|
||||
let mut floats = Vec::with_capacity(rows.len());
|
||||
let mut indices = Vec::with_capacity(rows.len());
|
||||
let mut seconds = Vec::with_capacity(rows.len());
|
||||
for &(position, float, histogram, second) in rows {
|
||||
match spans.last_mut() {
|
||||
Some(span) if span.start() + span.len() == position => {
|
||||
*span = GridSpan::new(span.start(), span.len() + 1);
|
||||
}
|
||||
_ => spans.push(GridSpan::new(position, 1)),
|
||||
}
|
||||
floats.push(float);
|
||||
indices.push(histogram.map(|text| {
|
||||
batch
|
||||
.push(OwnedHistogram::parse(text).view())
|
||||
.expect("the fixture histogram is valid")
|
||||
}));
|
||||
seconds.push(second);
|
||||
}
|
||||
let batch = batch.finish().expect("an empty histogram table is valid");
|
||||
let histograms = HistogramSamples::try_new(UInt32Array::from(indices), batch.clone()).unwrap();
|
||||
let mixed = Samples::try_from_mixed(Float64Array::from(floats), histograms).unwrap();
|
||||
let fields = SeriesFields::try_from_vec(vec![
|
||||
mixed,
|
||||
Samples::from_float(Float64Array::from(seconds)),
|
||||
])
|
||||
.unwrap();
|
||||
let time = TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans).unwrap();
|
||||
(
|
||||
Series::try_new(schema, metric_of(labels), time, fields).unwrap(),
|
||||
batch,
|
||||
)
|
||||
}
|
||||
|
||||
/// Two fragments a boundary kept apart -- the first holding position 0, the second positions 1 and
|
||||
/// 2 -- become one series of one run, each fragment's rows at its own positions.
|
||||
#[test]
|
||||
fn merge_of_adjacent_fragments_is_one_run() {
|
||||
let schema = grid_schema(1, 4);
|
||||
let labels = Labels::from([("job".to_string(), "x".to_string())]);
|
||||
let first = series_of(&schema, &labels, &Points::from([(0, 1f64.to_bits())])).unwrap();
|
||||
let second = series_of(
|
||||
&schema,
|
||||
&labels,
|
||||
&Points::from([(1, 2f64.to_bits()), (2, 3f64.to_bits())]),
|
||||
)
|
||||
.unwrap();
|
||||
let first_ptr = float_ptr(&first.fields.as_slice()[0].segments()[0]);
|
||||
let second_ptr = float_ptr(&second.fields.as_slice()[0].segments()[0]);
|
||||
|
||||
let merged = merge_same_labelset(&schema, vec![first, second]).unwrap();
|
||||
assert_eq!(merged.len(), 1, "one label set, one merged series");
|
||||
assert_eq!(merged[0].time.len(), 3, "one row per value");
|
||||
assert_eq!(
|
||||
run_ranges(&merged[0]),
|
||||
vec![(0, 3)],
|
||||
"fragments holding adjacent positions share one run"
|
||||
);
|
||||
assert_eq!(
|
||||
points_of(&merged[0]),
|
||||
Points::from([
|
||||
(0, 1f64.to_bits()),
|
||||
(1, 2f64.to_bits()),
|
||||
(2, 3f64.to_bits()),
|
||||
])
|
||||
);
|
||||
// One slice per fragment: the second fragment's two rows are one slice of its own buffer, and
|
||||
// neither slice copies a value.
|
||||
let chunks = merged[0].fields.as_slice()[0].segments();
|
||||
assert_eq!(chunks.len(), 2, "one slice per fragment");
|
||||
assert_eq!(float_ptr(&chunks[0]), first_ptr);
|
||||
assert_eq!(float_ptr(&chunks[1]), second_ptr);
|
||||
assert_eq!(chunks[1].len(), 2, "the fragment's two rows are one slice");
|
||||
}
|
||||
|
||||
/// Native histograms, floats, NaNs and complementary fields merge into one aligned series, and
|
||||
/// every value keeps the storage it already had: the histogram table and the float buffers are
|
||||
/// shared, not rebuilt.
|
||||
#[test]
|
||||
fn merge_keeps_native_histograms_and_complementary_fields_without_copying_them() {
|
||||
let schema = grid_schema(2, 4);
|
||||
let labels = Labels::from([("job".to_string(), "x".to_string())]);
|
||||
let histogram = "0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///";
|
||||
// The first fragment holds a native histogram in field 0 and a float in field 1 at position 0.
|
||||
let (first, first_batch) =
|
||||
fragment_with_histograms(&schema, &labels, &[(0, None, Some(histogram), Some(1.0))]);
|
||||
// The second holds field 0's float at position 1 and field 1's NaN at position 2, leaving the
|
||||
// other field missing at each.
|
||||
let (second, _) = fragment_with_histograms(
|
||||
&schema,
|
||||
&labels,
|
||||
&[(1, Some(2.0), None, None), (2, None, None, Some(f64::NAN))],
|
||||
);
|
||||
let second_field1 = float_ptr(&second.fields.as_slice()[1].segments()[0]);
|
||||
|
||||
let merged = merge_same_labelset(&schema, vec![first, second]).unwrap();
|
||||
assert_eq!(merged.len(), 1);
|
||||
assert_eq!(
|
||||
run_ranges(&merged[0]),
|
||||
vec![(0, 3)],
|
||||
"positions 0, 1 and 2 are one run"
|
||||
);
|
||||
assert_eq!(merged[0].time.len(), 3);
|
||||
assert_eq!(merged[0].fields.len(), 2);
|
||||
|
||||
// Field 0: the histogram, the float, and a null at the position only field 1 fills.
|
||||
let field0 = merged[0].fields.as_slice()[0].segments();
|
||||
assert_eq!(field0.len(), 3, "a histogram, a float, and one null run");
|
||||
let DenseSamplesRef::Mixed(mixed) = field0[0].dense().unwrap() else {
|
||||
panic!("the histogram lost its mixed column")
|
||||
};
|
||||
assert!(
|
||||
Arc::ptr_eq(mixed.histograms().batch(), &first_batch),
|
||||
"the histogram table was rebuilt"
|
||||
);
|
||||
assert!(
|
||||
matches!(field0[0].sample(0), SampleRef::Histogram(view) if view.count == 1.0),
|
||||
"the histogram did not survive as a histogram"
|
||||
);
|
||||
assert!(
|
||||
matches!(field0[1].sample(0), SampleRef::Float(value) if value.to_bits() == 2f64.to_bits()),
|
||||
"field 0 lost the other fragment's float"
|
||||
);
|
||||
assert!(
|
||||
matches!(field0[2].sample(0), SampleRef::Missing),
|
||||
"field 0 filled a position only field 1 holds"
|
||||
);
|
||||
|
||||
// Field 1: its value, the null field 0 fills, and the NaN, which is a value like any other.
|
||||
let field1 = merged[0].fields.as_slice()[1].segments();
|
||||
assert_eq!(field1.len(), 3, "a float, one null run, and a NaN");
|
||||
assert!(
|
||||
matches!(field1[0].sample(0), SampleRef::Float(value) if value.to_bits() == 1f64.to_bits())
|
||||
);
|
||||
assert!(matches!(field1[1].sample(0), SampleRef::Missing));
|
||||
assert!(
|
||||
matches!(field1[2].sample(0), SampleRef::Float(value) if value.is_nan()),
|
||||
"the NaN was dropped"
|
||||
);
|
||||
// The NaN came out as a slice of the second fragment's buffer, one row in.
|
||||
assert_eq!(
|
||||
float_ptr(&field1[2]),
|
||||
second_field1.wrapping_add(1),
|
||||
"the NaN was copied instead of sliced"
|
||||
);
|
||||
|
||||
// Two fragments holding one field at one position still collide, histograms included.
|
||||
let at_zero =
|
||||
|| fragment_with_histograms(&schema, &labels, &[(0, None, Some(histogram), None)]).0;
|
||||
assert!(
|
||||
merge_same_labelset(&schema, vec![at_zero(), at_zero()]).is_err(),
|
||||
"two histograms of one field at one position merged"
|
||||
);
|
||||
}
|
||||
|
||||
/// A merge over many fragments of many segments keeps one row per value: a million-position grid
|
||||
/// costs a span per run and a sample per value, and locating a row never rescans the segments
|
||||
/// before it.
|
||||
#[test]
|
||||
fn merge_of_many_segments_keeps_one_row_per_value() {
|
||||
const GRID: usize = 1_000_000;
|
||||
const SEGMENTS: usize = 1_000;
|
||||
let schema = grid_schema(1, GRID as u64);
|
||||
let labels = Labels::from([("job".to_string(), "x".to_string())]);
|
||||
// A fragment of one value per segment, one chunk per value, the segments a thousand positions
|
||||
// apart.
|
||||
let fragment = |offset: usize| {
|
||||
let mut chunks = Vec::with_capacity(SEGMENTS);
|
||||
let mut spans = Vec::with_capacity(SEGMENTS);
|
||||
for segment in 0..SEGMENTS {
|
||||
let position = offset + segment * (GRID / SEGMENTS);
|
||||
chunks.push(Samples::from_float(Float64Array::from(vec![
|
||||
position as f64,
|
||||
])));
|
||||
spans.push(GridSpan::new(position, 1));
|
||||
}
|
||||
let time = TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans).unwrap();
|
||||
let fields = SeriesFields::one(Samples::try_from_chunks(chunks).unwrap());
|
||||
Series::try_new(&schema, metric_of(&labels), time, fields).unwrap()
|
||||
};
|
||||
|
||||
let merged = merge_same_labelset(&schema, vec![fragment(0), fragment(1)]).unwrap();
|
||||
assert_eq!(merged.len(), 1);
|
||||
let series = &merged[0];
|
||||
assert_eq!(
|
||||
series.time.grid().unwrap().timestamps().len(),
|
||||
GRID,
|
||||
"the grid really holds a million positions"
|
||||
);
|
||||
assert_eq!(series.time.len(), 2 * SEGMENTS, "one row per value");
|
||||
assert_eq!(
|
||||
series.time.runs().count(),
|
||||
SEGMENTS,
|
||||
"two adjacent values per segment are one run, and the holes between are spans"
|
||||
);
|
||||
assert_eq!(run_ranges(series)[0], (0, 2));
|
||||
let field = &series.fields.as_slice()[0];
|
||||
assert_eq!(
|
||||
field.len(),
|
||||
2 * SEGMENTS,
|
||||
"the field holds one sample per merged row"
|
||||
);
|
||||
assert_eq!(
|
||||
field.segments().len(),
|
||||
2 * SEGMENTS,
|
||||
"one chunk per value: no hole was densified into the payload"
|
||||
);
|
||||
assert!(field.segments().iter().all(|chunk| chunk.len() == 1));
|
||||
assert_eq!(
|
||||
points_of(series).len(),
|
||||
2 * SEGMENTS,
|
||||
"every value survived and no hole became one"
|
||||
);
|
||||
}
|
||||
|
||||
/// A label set whose fragments all closed without a value still yields one series: a runtime that
|
||||
/// closes a label set needs one answer per set, and an empty grid series is the legal one.
|
||||
#[test]
|
||||
fn merge_of_empty_fragments_yields_one_empty_series() {
|
||||
let schema = grid_schema(2, 4);
|
||||
let labels = Labels::from([("job".to_string(), "x".to_string())]);
|
||||
let empty = || {
|
||||
let time =
|
||||
TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), Vec::new()).unwrap();
|
||||
let fields = SeriesFields::try_from_vec(vec![
|
||||
Samples::from_float(Float64Array::new_null(0)),
|
||||
Samples::from_float(Float64Array::new_null(0)),
|
||||
])
|
||||
.unwrap();
|
||||
Series::try_new(&schema, metric_of(&labels), time, fields).unwrap()
|
||||
};
|
||||
|
||||
let merged = merge_same_labelset(&schema, vec![empty(), empty()]).unwrap();
|
||||
assert_eq!(merged.len(), 1, "the label set vanished");
|
||||
assert_eq!(merged[0].metric, metric_of(&labels));
|
||||
assert_eq!(merged[0].time.len(), 0);
|
||||
assert!(
|
||||
merged[0].time.grid().is_some(),
|
||||
"an empty series keeps its grid"
|
||||
);
|
||||
assert!(
|
||||
run_ranges(&merged[0]).is_empty(),
|
||||
"an empty series has no run"
|
||||
);
|
||||
assert_eq!(merged[0].fields.len(), 2);
|
||||
for field in merged[0].fields.iter() {
|
||||
assert!(field.is_empty(), "an empty fragment contributed a row");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Series` built as a struct literal can carry fields that do not line up with its axis; the
|
||||
/// merge checks the alignment before it reads a row, so it reports such a fragment instead of
|
||||
/// reading past a field or dropping the values the axis never reaches.
|
||||
#[test]
|
||||
fn merge_rejects_fragments_whose_fields_do_not_fill_their_axis() {
|
||||
let schema = grid_schema(1, 8);
|
||||
let grid = schema.eval_grid.clone().unwrap();
|
||||
let labels = Labels::from([("job".to_string(), "x".to_string())]);
|
||||
// A well-formed fragment gives the malformed one a label set to merge into.
|
||||
let partner = || series_of(&schema, &labels, &Points::from([(1, 7f64.to_bits())])).unwrap();
|
||||
// `(axis rows, field rows)`: a field shorter than its axis, one longer than it, and a value on
|
||||
// an axis of no rows at all. The last two leave every axis row self-consistent, so only the
|
||||
// merge's alignment check catches them.
|
||||
for (axis_rows, field_rows) in [(2, 1), (1, 2), (0, 1)] {
|
||||
let spans = if axis_rows == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![GridSpan::new(1, axis_rows)]
|
||||
};
|
||||
let time = TimeAxis::from_grid_spans(grid.clone(), spans).unwrap();
|
||||
let values = Float64Array::from(
|
||||
(0..field_rows)
|
||||
.map(|row| row as f64 + 1.0)
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
let malformed = Series {
|
||||
metric: metric_of(&labels),
|
||||
time,
|
||||
fields: SeriesFields::one(Samples::from_float(values)),
|
||||
};
|
||||
let error = merge_same_labelset(&schema, vec![partner(), malformed])
|
||||
.expect_err("a fragment whose fields do not fill its axis merged");
|
||||
assert!(
|
||||
error.to_string().contains("rows of its axis"),
|
||||
"{axis_rows} axis rows with a {field_rows}-row field: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Acceptance: the builder's observable shape.
|
||||
//
|
||||
|
||||
@@ -94,18 +94,10 @@ impl FloatHistogram {
|
||||
})
|
||||
}
|
||||
|
||||
/// The bytes this histogram's own heap buffers hold, by capacity.
|
||||
/// Estimates the heap held by the bucket lists, custom bounds and preserved span layout.
|
||||
///
|
||||
/// Everything a histogram keeps besides its scalars is on the heap: the bucket lists of both
|
||||
/// sides, the custom bounds, and the span layout of a histogram read from a view, with the
|
||||
/// `[Vec; 2]` array that holds the two layout vectors. No scalar of the struct shows any of it:
|
||||
/// a histogram of 4096 positive buckets is 64 KiB of buckets, and a window that retains one
|
||||
/// histogram per grid point retains that much per point.
|
||||
///
|
||||
/// The layout array is stored inline in the histogram, so a ledger charging
|
||||
/// `size_of::<FloatHistogram>()` per slot already pays for those 48 bytes. Counting the whole
|
||||
/// footprint as one figure here costs a header of over-estimate on a reservation, against a
|
||||
/// payload of tens of kilobytes that would otherwise be missing from it entirely.
|
||||
/// A histogram can own tens of kilobytes of buckets that its struct size does not include.
|
||||
/// Capacity slack and small header overestimates are acceptable for window reservations.
|
||||
pub(crate) fn heap_bytes(&self) -> usize {
|
||||
fn buckets(side: &Buckets) -> usize {
|
||||
side.capacity() * std::mem::size_of::<(i32, f64)>()
|
||||
|
||||
@@ -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 [...]`.
|
||||
|
||||
+891
-983
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+82
-108
@@ -192,26 +192,12 @@ impl PendingBatch {
|
||||
|
||||
/// The bytes this batch's own vectors hold, by capacity.
|
||||
fn bytes(&self) -> usize {
|
||||
let spans = self
|
||||
.spans
|
||||
.iter()
|
||||
.map(|spans| spans.capacity() * std::mem::size_of::<std::ops::Range<usize>>())
|
||||
.fold(0usize, usize::saturating_add);
|
||||
let columns = self
|
||||
.columns
|
||||
.iter()
|
||||
.map(|column| column.capacity() * std::mem::size_of::<Option<f64>>())
|
||||
.fold(0usize, usize::saturating_add);
|
||||
self.indices
|
||||
.capacity()
|
||||
.saturating_mul(std::mem::size_of::<usize>())
|
||||
.saturating_add(
|
||||
self.eval_ts
|
||||
.capacity()
|
||||
.saturating_mul(std::mem::size_of::<i64>()),
|
||||
)
|
||||
.saturating_add(spans)
|
||||
.saturating_add(columns)
|
||||
let spans: usize = self.spans.iter().map(|spans| spans.capacity()).sum();
|
||||
let columns: usize = self.columns.iter().map(|column| column.capacity()).sum();
|
||||
self.indices.capacity() * std::mem::size_of::<usize>()
|
||||
+ self.eval_ts.capacity() * std::mem::size_of::<i64>()
|
||||
+ spans * std::mem::size_of::<Range<usize>>()
|
||||
+ columns * std::mem::size_of::<Option<f64>>()
|
||||
}
|
||||
|
||||
/// Drops the accumulated points, keeping the allocations.
|
||||
@@ -303,34 +289,23 @@ struct SeriesState {
|
||||
impl SeriesState {
|
||||
/// The bytes this series' identity holds, which the rows handed out do not cover.
|
||||
fn identity_bytes(&self) -> usize {
|
||||
// A scan slices the primary key out of a decoded dictionary-values buffer, so the bytes the
|
||||
// key shows are not the bytes it keeps: a key of a few bytes pins the whole buffer it was
|
||||
// sliced out of, which `capacity` reports for the allocation behind the slice. Charging
|
||||
// the key's length instead would show a handful of bytes for an allocation the size of a
|
||||
// decoded batch. (A buffer that does not own its memory reports no capacity, and then the
|
||||
// bytes it shows are all there is.)
|
||||
//
|
||||
// No dedupe is needed against a second slice of the same allocation: one evaluator holds
|
||||
// one series at a time, and a window over an evaluated input holds no key at all, so a
|
||||
// pass over this state charges one slice of one allocation rather than one per slice.
|
||||
// A scan slices the primary key out of a decoded buffer, so the bytes the key shows are not
|
||||
// the bytes it keeps: a key of a few bytes pins the allocation it was sliced out of.
|
||||
// Charging the slice length instead would show a handful of bytes for an allocation the
|
||||
// size of a decoded batch. One evaluator holds one series at a time, and an evaluated input
|
||||
// holds no key at all, so there is no second slice of the same allocation to dedupe.
|
||||
let primary_key = self
|
||||
.primary_key
|
||||
.as_ref()
|
||||
.map_or(0, |key| key.capacity().max(key.len()));
|
||||
let metric: usize = self
|
||||
.metric
|
||||
.name()
|
||||
.map_or(0, |name| name.len())
|
||||
.saturating_add(
|
||||
self.metric
|
||||
.tags()
|
||||
.iter()
|
||||
.map(|tag| tag.name.len() + tag.value.len())
|
||||
.fold(0usize, usize::saturating_add),
|
||||
);
|
||||
std::mem::size_of::<SeriesState>()
|
||||
.saturating_add(primary_key)
|
||||
.saturating_add(metric)
|
||||
let metric: usize = self.metric.name().map_or(0, |name| name.len())
|
||||
+ self
|
||||
.metric
|
||||
.tags()
|
||||
.iter()
|
||||
.map(|tag| tag.name.len() + tag.value.len())
|
||||
.sum::<usize>();
|
||||
std::mem::size_of::<SeriesState>() + primary_key + metric
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,7 +331,17 @@ struct FieldSamples {
|
||||
head: usize,
|
||||
/// Native histogram samples, kept apart from the floats as Prometheus does.
|
||||
histograms: Vec<(i64, FloatHistogram)>,
|
||||
/// Histograms before `histogram_head` are behind every remaining window; their payloads are
|
||||
/// released by [`advance_histograms`](Self::advance_histograms).
|
||||
histogram_head: usize,
|
||||
/// Estimated payload of the histograms this field still holds: the bucket lists and other
|
||||
/// buffers the samples own, which no `size_of` of a slot shows.
|
||||
///
|
||||
/// Measured for a histogram when it is admitted and released with it, so a retained sample is
|
||||
/// not walked again on every push. A histogram is never modified once admitted, so the payload
|
||||
/// its release subtracts is the one its admission added. Samples already behind every window
|
||||
/// keep their payload in the figure until the drain releases them.
|
||||
histogram_bytes: usize,
|
||||
/// Sequence number of `values[0]`. Absolute and monotonic across the series this evaluator
|
||||
/// evaluates, so a reset keeps its position when `head` samples are dropped instead of every
|
||||
/// index being renumbered. An empty field holds the number of samples already dropped, which
|
||||
@@ -392,37 +377,14 @@ fn resets_between(resets: &[CounterReset], start: u64, end: u64) -> &[CounterRes
|
||||
}
|
||||
|
||||
impl FieldSamples {
|
||||
/// The bytes this field's buffers hold, by capacity.
|
||||
///
|
||||
/// The histogram term is the slot of every retained sample plus the payload the histogram in
|
||||
/// that slot owns: a slot is one `(i64, FloatHistogram)` worth of struct, and the buckets the
|
||||
/// histogram keeps are on the heap behind it, up to tens of kilobytes per sample. Only the
|
||||
/// retained slice is walked, which is the storage the windows still read; the samples before
|
||||
/// `head` are gone, their payloads with them.
|
||||
/// The bytes this field's buffers hold, by capacity: the samples, the history behind `head`
|
||||
/// included, plus the estimated payload of the histograms still held.
|
||||
fn bytes(&self) -> usize {
|
||||
let histograms = self.histograms[self.histogram_head..]
|
||||
.iter()
|
||||
.map(|(_, histogram)| histogram.heap_bytes())
|
||||
.fold(0usize, usize::saturating_add);
|
||||
self.timestamps
|
||||
.capacity()
|
||||
.saturating_mul(std::mem::size_of::<i64>())
|
||||
.saturating_add(
|
||||
self.values
|
||||
.capacity()
|
||||
.saturating_mul(std::mem::size_of::<f64>()),
|
||||
)
|
||||
.saturating_add(
|
||||
self.histograms
|
||||
.capacity()
|
||||
.saturating_mul(std::mem::size_of::<(i64, FloatHistogram)>()),
|
||||
)
|
||||
.saturating_add(histograms)
|
||||
.saturating_add(
|
||||
self.resets
|
||||
.capacity()
|
||||
.saturating_mul(std::mem::size_of::<CounterReset>()),
|
||||
)
|
||||
self.timestamps.capacity() * std::mem::size_of::<i64>()
|
||||
+ self.values.capacity() * std::mem::size_of::<f64>()
|
||||
+ self.histograms.capacity() * std::mem::size_of::<(i64, FloatHistogram)>()
|
||||
+ self.resets.capacity() * std::mem::size_of::<CounterReset>()
|
||||
+ self.histogram_bytes
|
||||
}
|
||||
|
||||
fn new(index_resets: bool) -> Self {
|
||||
@@ -498,6 +460,23 @@ impl FieldSamples {
|
||||
self.resets.drain(..dropped);
|
||||
}
|
||||
|
||||
/// Drops the histograms before `histogram_head`, releasing the payload they held.
|
||||
///
|
||||
/// The dropped samples are measured as they go, which costs one measurement per dropped
|
||||
/// histogram in total: the retained ones are never scanned again.
|
||||
fn advance_histograms(&mut self) {
|
||||
let head = std::mem::take(&mut self.histogram_head);
|
||||
if head == 0 {
|
||||
return;
|
||||
}
|
||||
let dropped: usize = self.histograms[..head]
|
||||
.iter()
|
||||
.map(|(_, histogram)| histogram.heap_bytes())
|
||||
.sum();
|
||||
self.histogram_bytes = self.histogram_bytes.saturating_sub(dropped);
|
||||
self.histograms.drain(..head);
|
||||
}
|
||||
|
||||
/// The resets inside the window holding `len` samples from `head`.
|
||||
fn resets_in(&self, len: usize) -> &[CounterReset] {
|
||||
let start = self.base + self.head as u64;
|
||||
@@ -507,22 +486,20 @@ impl FieldSamples {
|
||||
|
||||
/// The bytes the histograms a row holds box, beyond the slots they sit in.
|
||||
///
|
||||
/// A slot is an `Option<GridSample>`: a pointer and a tag, which is all
|
||||
/// `size_of::<Option<GridSample>>()` is. A result that is a native histogram does not live in that
|
||||
/// slot itself: the slot points at a `FloatHistogram` on the heap, which owns its bucket
|
||||
/// lists in turn, and both are what the row keeps alive between pushes. Only slots that hold a
|
||||
/// histogram are counted, and only those the last evaluated point left in place: a push clears the
|
||||
/// row, so the slots past its length hold nothing.
|
||||
/// A slot is an `Option<GridSample>`: a pointer and a tag. A result that is a native histogram
|
||||
/// points at a [`FloatHistogram`] on the heap, which owns its bucket lists in turn, and both stay
|
||||
/// alive between pushes. Only slots the last evaluated point left in place are counted: a push
|
||||
/// clears the row.
|
||||
fn boxed_bytes(row: &[Option<GridSample>]) -> usize {
|
||||
row.iter()
|
||||
.flatten()
|
||||
.filter_map(|sample| match sample {
|
||||
.map(|sample| match sample {
|
||||
GridSample::Histogram(histogram) => {
|
||||
Some(std::mem::size_of::<FloatHistogram>().saturating_add(histogram.heap_bytes()))
|
||||
std::mem::size_of::<FloatHistogram>() + histogram.heap_bytes()
|
||||
}
|
||||
GridSample::Float(_) => None,
|
||||
GridSample::Float(_) => 0,
|
||||
})
|
||||
.fold(0usize, usize::saturating_add)
|
||||
.sum()
|
||||
}
|
||||
|
||||
impl RangeEvaluator {
|
||||
@@ -645,34 +622,30 @@ impl RangeEvaluator {
|
||||
self.batch_calls
|
||||
}
|
||||
|
||||
/// An accounted lower bound on the bytes this evaluator keeps between pushes.
|
||||
/// An estimate of the bytes this evaluator keeps between pushes.
|
||||
///
|
||||
/// Counted by capacity, so it is what the storage holds rather than what it uses: the retained
|
||||
/// samples per field (timestamps, values and the native histograms with the payload each of
|
||||
/// them owns), the reset index, the row a push fills with the histograms it boxes, and the
|
||||
/// pending batch's own vectors. Left out are the kernel's scratch buffers, this struct's `Vec`
|
||||
/// headers and the grid, which every chunk addressed on it shares.
|
||||
/// samples per field (timestamps, values, the reset index and the native histograms with the
|
||||
/// payload each of them owns), the row a push fills with the histograms it boxes, the identity
|
||||
/// of the open series and the pending batch's own vectors. Left out are the kernel's scratch
|
||||
/// buffers, this struct's `Vec` headers and the grid, which every chunk addressed on it shares.
|
||||
///
|
||||
/// The figure is an estimate, not a ledger of every allocation: a histogram's payload is
|
||||
/// measured once when it is admitted and released with it, so neither the retained samples nor
|
||||
/// the transient allocations of a push are walked again.
|
||||
///
|
||||
/// A push is the only caller that also holds the incoming chunk, and it charges that itself for
|
||||
/// as long as the call runs; vector growth during a push is neither reserved nor bounded by one
|
||||
/// doubling, so this is the storage's size, not a peak over the push. The figure must not be
|
||||
/// per-chunk either: charging every chunk consumed would make the charge grow with the chunk
|
||||
/// count, so a fixed window over a long series would read as an allocation failure even though
|
||||
/// the window holds no more samples.
|
||||
/// as long as the call runs. The figure must not be per-chunk either: charging every chunk
|
||||
/// consumed would make the charge grow with the chunk count, so a fixed window over a long
|
||||
/// series would read as an allocation failure even though the window holds no more samples.
|
||||
pub(crate) fn retained_bytes(&self) -> usize {
|
||||
let per_field = self
|
||||
.fields
|
||||
.iter()
|
||||
.map(FieldSamples::bytes)
|
||||
.fold(0usize, usize::saturating_add);
|
||||
let fields: usize = self.fields.iter().map(FieldSamples::bytes).sum();
|
||||
let row = self.row.capacity() * std::mem::size_of::<Option<GridSample>>();
|
||||
let boxed = boxed_bytes(&self.row);
|
||||
let series = self.series.as_ref().map_or(0, SeriesState::identity_bytes);
|
||||
per_field
|
||||
.saturating_add(row)
|
||||
.saturating_add(boxed)
|
||||
.saturating_add(series)
|
||||
.saturating_add(self.pending.bytes())
|
||||
fields
|
||||
+ row
|
||||
+ boxed_bytes(&self.row)
|
||||
+ self.series.as_ref().map_or(0, SeriesState::identity_bytes)
|
||||
+ self.pending.bytes()
|
||||
}
|
||||
|
||||
/// Schema of the evaluated series: the input fields on the evaluation grid.
|
||||
@@ -1054,6 +1027,8 @@ impl RangeEvaluator {
|
||||
if !raw && h.reset_hint != CounterResetHint::Gauge {
|
||||
h.reset_hint = CounterResetHint::Unknown;
|
||||
}
|
||||
field.histogram_bytes =
|
||||
field.histogram_bytes.saturating_add(h.heap_bytes());
|
||||
field.histograms.push((shifted, h));
|
||||
}
|
||||
}
|
||||
@@ -1223,8 +1198,7 @@ impl RangeEvaluator {
|
||||
field.histogram_head = field.histograms.len();
|
||||
}
|
||||
field.advance();
|
||||
field.histograms.drain(..field.histogram_head);
|
||||
field.histogram_head = 0;
|
||||
field.advance_histograms();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -831,13 +831,15 @@ fn histogram_chunk(schema: &SeriesSchema, buckets: i32, ts: i64) -> RawSeriesChu
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A window has to reserve what a native histogram it retains owns, not only the slot it sits in.
|
||||
/// A window retaining a native histogram is charged for the payload it owns, not only the slot.
|
||||
///
|
||||
/// The histogram sample below stays ahead of the second grid point's window, so the evaluator keeps
|
||||
/// it, and the two runs differ in nothing but the number of buckets on the positive side: 4 and
|
||||
/// 4096. Those buckets are `(index, count)` pairs on the heap, which no `size_of` of the struct
|
||||
/// shows -- 64 KiB for the wider one -- so the bytes the evaluator reports have to grow by at least
|
||||
/// that payload between the two. A figure counting slots alone would report one number for both.
|
||||
/// shows -- about 64 KiB for the wider one. The property is that this payload dominates the
|
||||
/// estimate, not that it is counted to the byte: the wider histogram alone has to be reported as at
|
||||
/// least half the physical width of its buckets, and the narrow one has to stay far below that. A
|
||||
/// figure counting slots alone would report one number for both.
|
||||
#[test]
|
||||
fn a_retained_histogram_is_charged_for_its_buckets() {
|
||||
let retained = |buckets: i32| -> usize {
|
||||
@@ -864,12 +866,114 @@ fn a_retained_histogram_is_charged_for_its_buckets() {
|
||||
evaluator.retained_bytes()
|
||||
};
|
||||
let (few, many) = (4, 4096);
|
||||
let payload = usize::try_from(many - few).unwrap() * std::mem::size_of::<(i32, f64)>();
|
||||
let physical = usize::try_from(many).unwrap() * std::mem::size_of::<(i32, f64)>();
|
||||
let (narrow, wide) = (retained(few), retained(many));
|
||||
assert!(
|
||||
wide >= narrow + payload,
|
||||
"a window retaining one histogram of {many} buckets reports {wide} bytes, not the {narrow} \
|
||||
it reports for {few} buckets plus the {payload} bytes of bucket payload between them",
|
||||
wide >= physical / 2,
|
||||
"a window retaining one histogram of {many} buckets reports {wide} bytes, not at least half \
|
||||
the {physical} bytes its buckets occupy",
|
||||
);
|
||||
assert!(
|
||||
narrow < wide / 2,
|
||||
"a window retaining one histogram of {few} buckets reports {narrow} bytes, not far below \
|
||||
the {wide} bytes it reports for {many} buckets: the bucket payload is not what the \
|
||||
estimate follows",
|
||||
);
|
||||
}
|
||||
|
||||
/// The payload a retained histogram is charged for is released with the sample.
|
||||
///
|
||||
/// The histogram below is most of what the evaluator holds, and it stays inside the second grid
|
||||
/// point's window: a push that only reaches the first point retains it. The chunk at 30 s is beyond
|
||||
/// the window of every later point, so the evaluation that push triggers drops the histogram while
|
||||
/// the series is still open. The estimate must come back down by its payload: one that charges at
|
||||
/// admission and never releases it would keep reporting the history of every histogram the series
|
||||
/// carried. The closing chunk then drains what is left and ends the series, so the estimate falls
|
||||
/// back to the field and row buffers' capacity, with no series identity and no histogram payload.
|
||||
#[test]
|
||||
fn an_evicted_histogram_releases_its_payload() {
|
||||
let schema = raw_schema(1);
|
||||
let buckets = 4096;
|
||||
let payload = usize::try_from(buckets).unwrap() * std::mem::size_of::<(i32, f64)>();
|
||||
let mut evaluator = RangeEvaluator::try_new(
|
||||
&schema,
|
||||
grid(0, 10_000, 3),
|
||||
// 20 s of window over 10 s of step: the histogram at 0 is inside the window of the second
|
||||
// point but outside the third's, so the second push evicts it.
|
||||
RangeWindow {
|
||||
range_ms: 20_000,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
},
|
||||
RangeFunction::CountOverTime,
|
||||
)
|
||||
.unwrap();
|
||||
evaluator
|
||||
.push(&histogram_chunk(&schema, buckets, 0))
|
||||
.unwrap();
|
||||
let retained = evaluator.retained_bytes();
|
||||
assert!(
|
||||
retained >= payload,
|
||||
"a window retaining one histogram of {buckets} buckets reports {retained} bytes, less than \
|
||||
the {payload} bytes of buckets it holds",
|
||||
);
|
||||
|
||||
// The float chunk keeps the series open, so only the window drops the histogram.
|
||||
evaluator
|
||||
.push(&chunk(&[(30_000, vec![Some(1.0)])], 1, 0, false))
|
||||
.unwrap();
|
||||
let evicted = evaluator.retained_bytes();
|
||||
assert!(
|
||||
retained.saturating_sub(evicted) >= payload / 2,
|
||||
"dropping one histogram of {payload} bytes left the estimate at {evicted} bytes, down from \
|
||||
{retained}: the payload it owned is still counted",
|
||||
);
|
||||
|
||||
evaluator
|
||||
.push(&chunk(&[(40_000, vec![Some(2.0)])], 1, 0, true))
|
||||
.unwrap();
|
||||
let closed = evaluator.retained_bytes();
|
||||
assert!(
|
||||
closed < payload / 2,
|
||||
"a closed series still reports {closed} bytes, of which the {payload} bytes of bucket \
|
||||
payload were released with their samples",
|
||||
);
|
||||
}
|
||||
|
||||
/// A fixed-size window over a long series of histograms reports a fixed size.
|
||||
///
|
||||
/// Each push adds one histogram and the next point's window drops the one before it, so the
|
||||
/// payload charged at admission has to come back at eviction. A counter that only grew would make
|
||||
/// the estimate follow the length of the series instead of the window over it.
|
||||
#[test]
|
||||
fn a_fixed_window_over_histograms_keeps_the_estimate_bounded() {
|
||||
let peak_retained = |chunks: i64| -> usize {
|
||||
let schema = raw_schema(1);
|
||||
let mut evaluator = RangeEvaluator::try_new(
|
||||
&schema,
|
||||
grid(0, 1, 1024),
|
||||
// One millisecond of window over a one millisecond step: the next point evicts the
|
||||
// sample of this one.
|
||||
RangeWindow {
|
||||
range_ms: 1,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
},
|
||||
RangeFunction::CountOverTime,
|
||||
)
|
||||
.unwrap();
|
||||
let mut peak = 0;
|
||||
for ts in 0..chunks {
|
||||
// Left open: the window, not the close, is what releases the sample.
|
||||
evaluator.push(&histogram_chunk(&schema, 64, ts)).unwrap();
|
||||
peak = peak.max(evaluator.retained_bytes());
|
||||
}
|
||||
peak
|
||||
};
|
||||
assert_eq!(
|
||||
peak_retained(8),
|
||||
peak_retained(64),
|
||||
"a fixed-size window over a series of histograms grew with the length of the series"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+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