mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-29 06:04:06 +00:00
feat(promql): evaluate instant selectors on shared typed samples
Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
@@ -17,7 +17,7 @@ use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use common_query::prelude::{greptime_native_histogram, greptime_value};
|
||||
use datafusion::arrow::array::{Array, TimestampMillisecondArray, UInt64Array};
|
||||
use datafusion::arrow::array::{Array, Float64Array, TimestampMillisecondArray, UInt64Array};
|
||||
use datafusion::arrow::datatypes::{DataType, SchemaRef};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::common::stats::Precision;
|
||||
@@ -39,6 +39,8 @@ use datafusion::physical_plan::{
|
||||
};
|
||||
use datafusion_expr::ident;
|
||||
use datatypes::arrow::compute;
|
||||
use datatypes::series::raw::RawTimeAxis;
|
||||
use datatypes::series::samples::{Samples, SeriesFields};
|
||||
use datatypes::timestamp::timestamp_array_to_primitive;
|
||||
use futures::{Stream, StreamExt, ready};
|
||||
use greptime_proto::substrait_extension as pb;
|
||||
@@ -53,10 +55,9 @@ use crate::extension_plan::{
|
||||
nanoseconds_per_native_tick, prometheus_stale_sample_column, resolve_column_name,
|
||||
serialize_column_index, timestamp_unit,
|
||||
};
|
||||
use crate::instant_eval::{MAX_INSTANT_MANIPULATE_OUTPUT_POINTS, select_instants};
|
||||
use crate::metrics::PROMQL_SERIES_COUNT;
|
||||
|
||||
const MAX_INSTANT_MANIPULATE_OUTPUT_POINTS: usize = 1_000_000;
|
||||
|
||||
fn mixed_sample_fields(field: Option<&str>) -> [Option<&str>; 2] {
|
||||
let companion = match field {
|
||||
Some(field) if field == greptime_value() => Some(greptime_native_histogram()),
|
||||
@@ -679,6 +680,44 @@ impl InstantManipulateStream {
|
||||
// Returning Pending after consuming a ready batch without a wake can stall the stream.
|
||||
return Ok(RecordBatch::new_empty(self.schema.clone()));
|
||||
}
|
||||
if let Some(timestamps) = ts_column
|
||||
.as_any()
|
||||
.downcast_ref::<TimestampMillisecondArray>()
|
||||
.filter(|timestamps| timestamps.null_count() == 0)
|
||||
{
|
||||
let values = timestamps.values();
|
||||
let float_fields: Option<Vec<_>> = self
|
||||
.field_indices
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|index| {
|
||||
input
|
||||
.column(*index)
|
||||
.as_any()
|
||||
.downcast_ref::<Float64Array>()
|
||||
.cloned()
|
||||
})
|
||||
.collect();
|
||||
if let Some(float_fields) = float_fields
|
||||
&& !float_fields.is_empty()
|
||||
&& values.windows(2).all(|pair| pair[0] < pair[1])
|
||||
{
|
||||
let time = RawTimeAxis::Explicit(values.clone());
|
||||
let fields = SeriesFields::try_from_vec(
|
||||
float_fields.into_iter().map(Samples::from_float).collect(),
|
||||
)
|
||||
.map_err(|error| DataFusionError::Execution(error.to_string()))?;
|
||||
let (indices, evaluation_timestamps) = select_instants(
|
||||
&time,
|
||||
&fields,
|
||||
self.start..=self.end,
|
||||
self.interval,
|
||||
self.lookback_delta,
|
||||
self.offset,
|
||||
)?;
|
||||
return self.take_record_batch_optional(input, indices, evaluation_timestamps);
|
||||
}
|
||||
}
|
||||
let scale = nanoseconds_per_native_tick(self.time_unit);
|
||||
let stale_sample_columns = self.field_indices.map(|index| {
|
||||
index.and_then(|index| prometheus_stale_sample_column(input.column(index).as_ref()))
|
||||
@@ -866,6 +905,10 @@ fn reuse_constant_column(array: &Arc<dyn Array>, len: usize) -> DataFusionResult
|
||||
ScalarValue::try_from_array(array.as_ref(), 0)?.to_array_of_size(len)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "instant_manipulate/typed_tests.rs"]
|
||||
mod typed_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use common_query::native_histogram::build_histogram_array;
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
|
||||
use datafusion::arrow::array::{Float64Array, Int64Array, StringArray, TimestampMillisecondArray};
|
||||
use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::datasource::memory::MemorySourceConfig;
|
||||
use datafusion::datasource::source::DataSourceExec;
|
||||
use datafusion::execution::context::SessionContext;
|
||||
use datafusion::physical_plan::memory::MemoryStream;
|
||||
use datatypes::arrow::buffer::ScalarBuffer;
|
||||
use datatypes::series::raw::RawTimeAxis;
|
||||
use datatypes::series::samples::{Samples, SeriesFields};
|
||||
|
||||
use super::*;
|
||||
use crate::extension_plan::range_manipulate::ScanNanoseconds;
|
||||
use crate::extension_plan::test_util::TIME_INDEX_COLUMN;
|
||||
use crate::instant_eval::select_instants;
|
||||
|
||||
fn stream(
|
||||
batch: &RecordBatch,
|
||||
start: i64,
|
||||
end: i64,
|
||||
step: i64,
|
||||
lookback: i64,
|
||||
offset: i64,
|
||||
) -> InstantManipulateStream {
|
||||
let schema = batch.schema();
|
||||
InstantManipulateStream {
|
||||
offset,
|
||||
start,
|
||||
end,
|
||||
lookback_delta: lookback,
|
||||
interval: step,
|
||||
time_index: 0,
|
||||
time_unit: TimeUnit::Millisecond,
|
||||
field_indices: [Some(1), None],
|
||||
tsid_index: None,
|
||||
reuse_tsid_column: false,
|
||||
schema: schema.clone(),
|
||||
input: Box::pin(MemoryStream::try_new(vec![], schema, None).unwrap()),
|
||||
metric: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
|
||||
num_series: Count::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn input_batch(times: Vec<i64>, first: Vec<Option<f64>>, second: Vec<Option<f64>>) -> RecordBatch {
|
||||
let len = times.len();
|
||||
let mut schema_metadata = HashMap::new();
|
||||
schema_metadata.insert("schema-key".to_string(), "schema-value".to_string());
|
||||
let mut field_metadata = HashMap::new();
|
||||
field_metadata.insert("field-key".to_string(), "field-value".to_string());
|
||||
let schema = Arc::new(Schema::new_with_metadata(
|
||||
vec![
|
||||
Field::new(
|
||||
TIME_INDEX_COLUMN,
|
||||
DataType::Timestamp(TimeUnit::Millisecond, None),
|
||||
false,
|
||||
),
|
||||
Field::new("value", DataType::Float64, true).with_metadata(field_metadata),
|
||||
Field::new("other", DataType::Float64, true),
|
||||
Field::new("payload", DataType::Utf8, true),
|
||||
Field::new("exact", DataType::Int64, false),
|
||||
],
|
||||
schema_metadata,
|
||||
));
|
||||
RecordBatch::try_new(
|
||||
schema,
|
||||
vec![
|
||||
Arc::new(TimestampMillisecondArray::from(times)),
|
||||
Arc::new(Float64Array::from(first)),
|
||||
Arc::new(Float64Array::from(second)),
|
||||
Arc::new(StringArray::from_iter_values((0..len).map(|_| "payload"))),
|
||||
Arc::new(Int64Array::from(
|
||||
(0..len)
|
||||
.map(|i| 9_007_199_254_740_993_i64 + i as i64 * 2)
|
||||
.collect::<Vec<_>>(),
|
||||
)),
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn eligible_arrow_stream_uses_typed_selection_and_preserves_payload() {
|
||||
let stale = f64::from_bits(PROMETHEUS_STALE_NAN_BITS);
|
||||
let original = input_batch(
|
||||
vec![0, 10, 20, 30],
|
||||
vec![Some(1.0), Some(2.0), None, Some(4.0)],
|
||||
vec![Some(10.0), Some(20.0), Some(stale), Some(40.0)],
|
||||
);
|
||||
let view = original.slice(1, 3);
|
||||
drop(original);
|
||||
let source_schema = view.schema();
|
||||
let expected_schema = source_schema.clone();
|
||||
let source = Arc::new(DataSourceExec::new(Arc::new(
|
||||
MemorySourceConfig::try_new(&[vec![view]], source_schema.clone(), None).unwrap(),
|
||||
)));
|
||||
let exec = Arc::new(InstantManipulateExec {
|
||||
offset: 0,
|
||||
start: 10,
|
||||
end: 30,
|
||||
lookback_delta: 10,
|
||||
interval: 10,
|
||||
time_index_column: TIME_INDEX_COLUMN.to_string(),
|
||||
field_column: Some("value".to_string()),
|
||||
reuse_tsid_column: false,
|
||||
output_schema: source_schema,
|
||||
properties: source.properties().clone(),
|
||||
input: source,
|
||||
metric: ExecutionPlanMetricsSet::new(),
|
||||
});
|
||||
let batches = datafusion::physical_plan::collect(exec, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.unwrap();
|
||||
let result = &batches[0];
|
||||
let times = result
|
||||
.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<TimestampMillisecondArray>()
|
||||
.unwrap();
|
||||
assert_eq!(times.values(), &[10, 20, 30]);
|
||||
let values = result
|
||||
.column(1)
|
||||
.as_any()
|
||||
.downcast_ref::<Float64Array>()
|
||||
.unwrap();
|
||||
assert_eq!(values.values(), &[2.0, 0.0, 4.0]);
|
||||
assert!(!values.is_valid(1));
|
||||
let payload = result
|
||||
.column(3)
|
||||
.as_any()
|
||||
.downcast_ref::<StringArray>()
|
||||
.unwrap();
|
||||
assert_eq!(payload.iter().collect::<Vec<_>>(), [Some("payload"); 3]);
|
||||
let exact = result
|
||||
.column(4)
|
||||
.as_any()
|
||||
.downcast_ref::<Int64Array>()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
exact.values(),
|
||||
&[
|
||||
9_007_199_254_740_995,
|
||||
9_007_199_254_740_997,
|
||||
9_007_199_254_740_999
|
||||
]
|
||||
);
|
||||
let secondary = result
|
||||
.column(2)
|
||||
.as_any()
|
||||
.downcast_ref::<Float64Array>()
|
||||
.unwrap();
|
||||
assert_eq!(secondary.value(1).to_bits(), PROMETHEUS_STALE_NAN_BITS);
|
||||
assert_eq!(result.schema(), expected_schema);
|
||||
assert_eq!(
|
||||
result.schema().metadata().get("schema-key").unwrap(),
|
||||
"schema-value"
|
||||
);
|
||||
assert_eq!(
|
||||
result
|
||||
.schema()
|
||||
.field(1)
|
||||
.metadata()
|
||||
.get("field-key")
|
||||
.unwrap(),
|
||||
"field-value"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_selection_matches_existing_wide_native_scan_oracle() {
|
||||
let stale = f64::from_bits(PROMETHEUS_STALE_NAN_BITS);
|
||||
let timestamps = [0, 10, 20, 30, 40];
|
||||
let values = [Some(1.0), Some(f64::NAN), Some(3.0), Some(stale), Some(5.0)];
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(values.to_vec())));
|
||||
let axis = RawTimeAxis::try_new(ScalarBuffer::from(timestamps.to_vec())).unwrap();
|
||||
let typed = select_instants(&axis, &fields, 5..=45, 10, 20, 0).unwrap();
|
||||
let batch = input_batch(timestamps.to_vec(), values.to_vec(), vec![Some(0.0); 5]);
|
||||
let scanner = stream(&batch, 5, 45, 10, 20, 0);
|
||||
let old = scanner.scan_instants::<i128>(
|
||||
×tamps,
|
||||
5,
|
||||
45,
|
||||
&ScanNanoseconds::<i128>::wide(TimeUnit::Millisecond, 0, 20),
|
||||
5,
|
||||
|row| row == 3,
|
||||
);
|
||||
assert_eq!(typed, old);
|
||||
// Evaluations 5 and 15 select row 0/1; 25 selects 20, stale row 3 suppresses 35,
|
||||
// and 45 selects row 4. The lower lookback boundary is exclusive.
|
||||
assert_eq!(typed, (vec![0, 1, 2, 4], vec![5, 15, 25, 45]));
|
||||
|
||||
for (range, lookback, expected) in [
|
||||
(10..=20, 0, (vec![1, 2], vec![10, 20])),
|
||||
(20..=20, 10, (vec![2], vec![20])),
|
||||
] {
|
||||
let selected = select_instants(&axis, &fields, range, 10, lookback, 0).unwrap();
|
||||
assert_eq!(selected, expected);
|
||||
}
|
||||
let offset = select_instants(&axis, &fields, 15..=35, 10, 20, 10).unwrap();
|
||||
assert_eq!(offset, (vec![0, 1, 2], vec![15, 25, 35]));
|
||||
|
||||
let lower_axis = RawTimeAxis::try_new(ScalarBuffer::from(vec![0, 10])).unwrap();
|
||||
let lower_fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
Some(1.0),
|
||||
Some(2.0),
|
||||
])));
|
||||
assert_eq!(
|
||||
select_instants(&lower_axis, &lower_fields, 20..=20, 1, 10, 0).unwrap(),
|
||||
(vec![], vec![])
|
||||
);
|
||||
let missing_fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
Some(1.0),
|
||||
None,
|
||||
])));
|
||||
assert_eq!(
|
||||
select_instants(&lower_axis, &missing_fields, 10..=10, 1, 10, 0).unwrap(),
|
||||
(vec![1], vec![10])
|
||||
);
|
||||
|
||||
let edge_axis = RawTimeAxis::try_new(ScalarBuffer::from(vec![i64::MIN, i64::MAX])).unwrap();
|
||||
let edge_fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
Some(1.0),
|
||||
Some(2.0),
|
||||
])));
|
||||
assert_eq!(
|
||||
select_instants(
|
||||
&edge_axis,
|
||||
&edge_fields,
|
||||
i64::MIN..=i64::MIN,
|
||||
1,
|
||||
0,
|
||||
i64::MAX
|
||||
)
|
||||
.unwrap(),
|
||||
(vec![], vec![])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_arrow_timestamps_fall_back_and_invalid_typed_arguments_propagate() {
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
Some(1.0),
|
||||
Some(2.0),
|
||||
])));
|
||||
let duplicate = RawTimeAxis::Explicit(ScalarBuffer::from(vec![10, 10]));
|
||||
assert!(select_instants(&duplicate, &fields, 10..=11, 1, 2, 0).is_err());
|
||||
let batch = input_batch(vec![10, 10], vec![Some(1.0), Some(2.0)], vec![Some(0.0); 2]);
|
||||
let result = stream(&batch, 10, 11, 1, 2, 0).manipulate(batch).unwrap();
|
||||
let times = result
|
||||
.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<TimestampMillisecondArray>()
|
||||
.unwrap();
|
||||
let values = result
|
||||
.column(1)
|
||||
.as_any()
|
||||
.downcast_ref::<Float64Array>()
|
||||
.unwrap();
|
||||
assert_eq!(times.values(), &[10, 11]);
|
||||
assert_eq!(values.values(), &[1.0, 2.0]);
|
||||
|
||||
let batch = input_batch(vec![10, 20], vec![Some(1.0), Some(2.0)], vec![Some(0.0); 2]);
|
||||
let axis = RawTimeAxis::try_new(ScalarBuffer::from(vec![10, 20])).unwrap();
|
||||
let invalid_fields =
|
||||
SeriesFields::one(Samples::from_float(Float64Array::from(vec![Some(1.0); 2])));
|
||||
let typed_error = select_instants(&axis, &invalid_fields, 10..=20, 10, -1, 0)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
let error = stream(&batch, 10, 20, 10, -1, 0)
|
||||
.manipulate(batch)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert_eq!(error, typed_error);
|
||||
assert!(error.contains("lookback must be non-negative"));
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use common_query::prometheus::is_prometheus_stale_nan;
|
||||
use datafusion::error::{DataFusionError, Result};
|
||||
use datatypes::series::raw::RawTimeAxis;
|
||||
use datatypes::series::samples::{SampleRef, SeriesFields};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub(crate) const MAX_INSTANT_MANIPULATE_OUTPUT_POINTS: usize = 1_000_000;
|
||||
|
||||
/// Selects source rows for an aligned PromQL instant-evaluation range.
|
||||
///
|
||||
/// Returns original logical row indices and evaluation timestamps from a complete source axis
|
||||
/// of strictly increasing milliseconds. Any provided field's stale marker suppresses selection;
|
||||
/// missing samples are not stale and remain selectable.
|
||||
pub fn select_instants(
|
||||
time: &RawTimeAxis,
|
||||
fields: &SeriesFields,
|
||||
range: RangeInclusive<i64>,
|
||||
step_ms: i64,
|
||||
lookback_ms: i64,
|
||||
offset_ms: i64,
|
||||
) -> Result<(Vec<u64>, Vec<i64>)> {
|
||||
let start = *range.start();
|
||||
let end = *range.end();
|
||||
if step_ms <= 0 {
|
||||
return Err(DataFusionError::Execution(
|
||||
"InstantManipulate interval must be positive".into(),
|
||||
));
|
||||
}
|
||||
if start > end {
|
||||
return Err(DataFusionError::Execution(
|
||||
"InstantManipulate start must not exceed end".into(),
|
||||
));
|
||||
}
|
||||
if lookback_ms < 0 {
|
||||
return Err(DataFusionError::Execution(
|
||||
"InstantManipulate lookback must be non-negative".into(),
|
||||
));
|
||||
}
|
||||
let timestamps = time.as_explicit().ok_or_else(|| {
|
||||
DataFusionError::Execution("Instant evaluation requires explicit timestamps".into())
|
||||
})?;
|
||||
if timestamps.windows(2).any(|pair| pair[0] >= pair[1]) {
|
||||
return Err(DataFusionError::Execution(
|
||||
"raw timestamps must be strictly increasing".into(),
|
||||
));
|
||||
}
|
||||
if fields
|
||||
.as_slice()
|
||||
.iter()
|
||||
.any(|field| field.len() != timestamps.len())
|
||||
{
|
||||
return Err(DataFusionError::Execution(
|
||||
"series fields and time axis have unequal lengths".into(),
|
||||
));
|
||||
}
|
||||
if timestamps.is_empty() {
|
||||
return Ok((Vec::new(), Vec::new()));
|
||||
}
|
||||
|
||||
// Match the native-tick selector's bounds calculation in wide arithmetic before scanning.
|
||||
let first = timestamps[0] as i128 + offset_ms as i128;
|
||||
let last = timestamps[timestamps.len() - 1] as i128 + offset_ms as i128;
|
||||
let useful_last = if lookback_ms == 0 {
|
||||
last
|
||||
} else {
|
||||
last + lookback_ms as i128 - 1
|
||||
};
|
||||
let query_start = start as i128;
|
||||
let query_end = end as i128;
|
||||
let step = step_ms as i128;
|
||||
let max_start = first.max(query_start);
|
||||
let min_end = useful_last.min(query_end);
|
||||
let (aligned_start, aligned_end) = if max_start > min_end {
|
||||
(1_i128, 0_i128)
|
||||
} else {
|
||||
(
|
||||
query_start + (max_start - query_start) / step * step,
|
||||
query_end - (query_end - min_end) / step * step,
|
||||
)
|
||||
};
|
||||
let estimated_points = if aligned_end >= aligned_start {
|
||||
(aligned_end - aligned_start) / step + 1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if estimated_points > MAX_INSTANT_MANIPULATE_OUTPUT_POINTS as i128 {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"InstantManipulate output points exceed limit: {estimated_points} > {MAX_INSTANT_MANIPULATE_OUTPUT_POINTS}"
|
||||
)));
|
||||
}
|
||||
let mut indices = Vec::with_capacity(estimated_points as usize);
|
||||
let mut evaluation_timestamps = Vec::with_capacity(estimated_points as usize);
|
||||
let mut sample_iters: Vec<_> = fields.iter().map(|field| field.iter()).collect();
|
||||
let mut current_stale = false;
|
||||
let mut cursor = 0usize;
|
||||
for expected in (aligned_start..=aligned_end).step_by(step_ms as usize) {
|
||||
let source_expected = expected - offset_ms as i128;
|
||||
while cursor < timestamps.len() && timestamps[cursor] as i128 <= source_expected {
|
||||
current_stale = false;
|
||||
for samples in &mut sample_iters {
|
||||
let sample = samples.next().ok_or_else(|| {
|
||||
DataFusionError::Execution(
|
||||
"series sample iterator ended before the time axis".into(),
|
||||
)
|
||||
})?;
|
||||
let stale = match sample {
|
||||
SampleRef::Float(value) => is_prometheus_stale_nan(value),
|
||||
SampleRef::Histogram(histogram) => is_prometheus_stale_nan(histogram.sum),
|
||||
SampleRef::Missing => false,
|
||||
};
|
||||
current_stale |= stale;
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
let Some(candidate) = cursor.checked_sub(1) else {
|
||||
continue;
|
||||
};
|
||||
let candidate_ts = timestamps[candidate] as i128 + offset_ms as i128;
|
||||
let lower = expected - lookback_ms as i128;
|
||||
if (candidate_ts == expected || candidate_ts > lower)
|
||||
&& candidate_ts <= expected
|
||||
&& !current_stale
|
||||
{
|
||||
indices.push(candidate as u64);
|
||||
evaluation_timestamps.push(expected as i64);
|
||||
}
|
||||
}
|
||||
Ok((indices, evaluation_timestamps))
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datatypes::arrow::array::{Float64Array, UInt32Array};
|
||||
use datatypes::arrow::buffer::ScalarBuffer;
|
||||
use datatypes::series::histogram::{
|
||||
BucketSideView, CounterResetHint, HistogramBatch, HistogramBatchBuilder, HistogramView,
|
||||
};
|
||||
use datatypes::series::raw::RawTimeAxis;
|
||||
use datatypes::series::samples::{DenseSamplesRef, SampleRef, Samples, SeriesFields};
|
||||
|
||||
use super::select_instants;
|
||||
|
||||
fn axis(times: &[i64]) -> RawTimeAxis {
|
||||
RawTimeAxis::try_new(ScalarBuffer::from(times.to_vec())).unwrap()
|
||||
}
|
||||
|
||||
fn select(
|
||||
times: &[i64],
|
||||
fields: &SeriesFields,
|
||||
range: std::ops::RangeInclusive<i64>,
|
||||
step: i64,
|
||||
lookback: i64,
|
||||
offset: i64,
|
||||
) -> datafusion_common::Result<(Vec<u64>, Vec<i64>)> {
|
||||
select_instants(&axis(times), fields, range, step, lookback, offset)
|
||||
}
|
||||
|
||||
fn histogram_batch(sums: &[f64]) -> Arc<HistogramBatch> {
|
||||
let mut builder = HistogramBatchBuilder::new();
|
||||
for &sum in sums {
|
||||
builder
|
||||
.push(HistogramView {
|
||||
schema: 1,
|
||||
zero_threshold: 0.0,
|
||||
sum,
|
||||
count: 2.0,
|
||||
zero_count: 0.0,
|
||||
reset_hint: CounterResetHint::Unknown,
|
||||
start_timestamp: None,
|
||||
custom_values: &[],
|
||||
positive: BucketSideView {
|
||||
span_offsets: &[],
|
||||
span_lengths: &[],
|
||||
buckets: &[],
|
||||
},
|
||||
negative: BucketSideView {
|
||||
span_offsets: &[],
|
||||
span_lengths: &[],
|
||||
buckets: &[],
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
builder.finish().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_lookback_boundaries_missing_and_nan() {
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
Some(1.0),
|
||||
Some(f64::from_bits(0x7ff8_0000_0000_0042)),
|
||||
None,
|
||||
Some(4.0),
|
||||
])));
|
||||
let (rows, times) = select(&[0, 50, 100, 200], &fields, 50..=200, 50, 50, 0).unwrap();
|
||||
assert_eq!(rows, [1, 2, 3]);
|
||||
assert_eq!(times, [50, 100, 200]);
|
||||
assert!(matches!(
|
||||
fields.get(0).unwrap().sample(rows[0] as usize),
|
||||
SampleRef::Float(v) if v.to_bits() == 0x7ff8_0000_0000_0042
|
||||
));
|
||||
assert!(matches!(
|
||||
fields.get(0).unwrap().sample(rows[1] as usize),
|
||||
SampleRef::Missing
|
||||
));
|
||||
assert!(matches!(
|
||||
fields.get(0).unwrap().sample(rows[2] as usize),
|
||||
SampleRef::Float(4.0)
|
||||
));
|
||||
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![Some(1.0)])));
|
||||
assert!(
|
||||
select(&[50], &fields, 100..=100, 100, 50, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
select(&[52], &fields, 100..=100, 100, 49, 0).unwrap(),
|
||||
(vec![0], vec![100])
|
||||
);
|
||||
assert!(
|
||||
select(&[99], &fields, 100..=100, 100, 0, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
select(&[100], &fields, 100..=100, 100, 0, 0).unwrap(),
|
||||
(vec![0], vec![100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_histogram_mixed_fields_and_independent_chunks_keep_selection_aligned() {
|
||||
let histogram = Samples::try_from_histogram(
|
||||
UInt32Array::from(vec![Some(0), Some(1), Some(2)]),
|
||||
histogram_batch(&[10.0, 20.0, 30.0]),
|
||||
)
|
||||
.unwrap();
|
||||
let mixed_hist = Samples::try_from_histogram(
|
||||
UInt32Array::from(vec![Some(0), None, Some(1)]),
|
||||
histogram_batch(&[100.0, 300.0]),
|
||||
)
|
||||
.unwrap();
|
||||
let mixed = Samples::try_from_mixed(
|
||||
Float64Array::from(vec![None, Some(2.5), None]),
|
||||
match mixed_hist.dense().unwrap() {
|
||||
DenseSamplesRef::Histogram(h) => h.clone(),
|
||||
_ => unreachable!(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let fields = SeriesFields::try_from_vec(vec![
|
||||
Samples::try_from_chunks(vec![
|
||||
histogram.slice(0, 1).unwrap(),
|
||||
histogram.slice(1, 2).unwrap(),
|
||||
])
|
||||
.unwrap(),
|
||||
Samples::try_from_chunks(vec![mixed.slice(0, 2).unwrap(), mixed.slice(2, 1).unwrap()])
|
||||
.unwrap(),
|
||||
Samples::from_float(Float64Array::from(vec![Some(1.0), Some(2.0), Some(3.0)])),
|
||||
])
|
||||
.unwrap();
|
||||
drop(histogram);
|
||||
drop(mixed);
|
||||
drop(mixed_hist);
|
||||
|
||||
let (rows, times) = select(&[10, 20, 30], &fields, 20..=30, 10, 0, 0).unwrap();
|
||||
assert_eq!(rows, [1, 2]);
|
||||
assert_eq!(times, [20, 30]);
|
||||
for (row, expected) in [(1, 20.0), (2, 30.0)] {
|
||||
let SampleRef::Histogram(value) = fields.get(0).unwrap().sample(row) else {
|
||||
panic!("expected native histogram at row {row}");
|
||||
};
|
||||
assert_eq!(value.sum, expected);
|
||||
}
|
||||
assert!(matches!(
|
||||
fields.get(1).unwrap().sample(1),
|
||||
SampleRef::Float(2.5)
|
||||
));
|
||||
assert!(
|
||||
matches!(fields.get(1).unwrap().sample(2), SampleRef::Histogram(value) if value.sum == 300.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_sample_in_any_field_suppresses_without_falling_back() {
|
||||
let stale = f64::from_bits(common_query::prometheus::PROMETHEUS_STALE_NAN_BITS);
|
||||
let float = Samples::from_float(Float64Array::from(vec![
|
||||
Some(42.0),
|
||||
Some(stale),
|
||||
Some(43.0),
|
||||
Some(44.0),
|
||||
]));
|
||||
let hist = Samples::try_from_histogram(
|
||||
UInt32Array::from(vec![Some(0), Some(1), Some(2), Some(3)]),
|
||||
histogram_batch(&[10.0, 20.0, stale, 40.0]),
|
||||
)
|
||||
.unwrap();
|
||||
let fields = SeriesFields::try_from_vec(vec![float, hist]).unwrap();
|
||||
let (rows, times) = select(&[0, 100, 200, 300], &fields, 0..=300, 100, 400, 0).unwrap();
|
||||
assert_eq!(rows, [0, 3]);
|
||||
assert_eq!(times, [0, 300]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_extreme_timestamps_and_point_limit_are_checked_without_large_fixture() {
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![Some(7.0)])));
|
||||
assert_eq!(
|
||||
select(&[i64::MAX], &fields, i64::MAX..=i64::MAX, 1, 0, 0).unwrap(),
|
||||
(vec![0], vec![i64::MAX])
|
||||
);
|
||||
assert_eq!(
|
||||
select(&[i64::MIN], &fields, i64::MIN..=i64::MIN, 1, 0, 0).unwrap(),
|
||||
(vec![0], vec![i64::MIN])
|
||||
);
|
||||
assert_eq!(
|
||||
select(&[i64::MAX], &fields, -1..=-1, 1, 0, i64::MIN).unwrap(),
|
||||
(vec![0], vec![-1])
|
||||
);
|
||||
assert_eq!(
|
||||
select(&[100], &fields, 110..=110, 10, 20, 10).unwrap(),
|
||||
(vec![0], vec![110])
|
||||
);
|
||||
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
Some(f64::from_bits(
|
||||
common_query::prometheus::PROMETHEUS_STALE_NAN_BITS,
|
||||
)),
|
||||
Some(1.0),
|
||||
])));
|
||||
let result = select(&[0, 1_000_000], &fields, 0..=1_000_000, 1, 0, 0);
|
||||
let error = result.unwrap_err().to_string();
|
||||
assert!(
|
||||
error.contains("output points exceed limit: 1000001 > 1000000"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_manual_inputs_are_rejected() {
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
Some(1.0),
|
||||
Some(2.0),
|
||||
])));
|
||||
let invalid_axis = RawTimeAxis::Explicit(ScalarBuffer::from(vec![10, 10]));
|
||||
assert!(select_instants(&invalid_axis, &fields, 0..=10, 1, 0, 0).is_err());
|
||||
let descending_axis = RawTimeAxis::Explicit(ScalarBuffer::from(vec![20, 10]));
|
||||
assert!(select_instants(&descending_axis, &fields, 0..=20, 1, 0, 0).is_err());
|
||||
|
||||
let mismatched = SeriesFields::one(Samples::from_float(Float64Array::from(vec![Some(1.0)])));
|
||||
assert!(select(&[10, 20], &mismatched, 0..=10, 1, 0, 0).is_err());
|
||||
assert!(select(&[10, 20], &fields, 0..=10, 0, 0, 0).is_err());
|
||||
assert!(select(&[10, 20], &fields, 10..=0, 1, 0, 0).is_err());
|
||||
assert!(select(&[10, 20], &fields, 0..=10, 1, -1, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_axis_returns_no_selections() {
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::new_null(0)));
|
||||
assert_eq!(
|
||||
select(&[], &fields, -10..=10, 1, 10, 0).unwrap(),
|
||||
(vec![], vec![])
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
pub mod error;
|
||||
pub mod extension_plan;
|
||||
pub mod functions;
|
||||
pub mod instant_eval;
|
||||
mod metrics;
|
||||
pub mod range_array;
|
||||
pub mod source;
|
||||
|
||||
Reference in New Issue
Block a user