mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 08:25:29 +00:00
Merge remote-tracking branch 'upstream/feat/narthex-native-binary-runtime' into feat/narthex-multi-selector
This commit is contained in:
@@ -156,7 +156,8 @@ fn aggregate_point<'a>(
|
||||
/// The Kahan sum or the mean of `histograms` in order, without compaction; `None` when there is
|
||||
/// none or they mix exponential and custom buckets. Prometheus `sum_over_time` and
|
||||
/// `avg_over_time` run the same steps as the aggregations. Histograms are consumed one at a
|
||||
/// time, so the first error ends the fold.
|
||||
/// time, so the first error ends the fold. The result is derived, so it carries no start
|
||||
/// timestamp.
|
||||
pub(crate) fn sum_or_avg(
|
||||
op: HistogramAggregate,
|
||||
histograms: impl IntoIterator<Item = Result<FloatHistogram>>,
|
||||
@@ -236,5 +237,11 @@ pub(crate) fn sum_or_avg(
|
||||
}
|
||||
},
|
||||
}
|
||||
// The result was derived from its inputs, so it carries no start timestamp of its own, like
|
||||
// every other operation that builds one. Clearing it here covers the fold that added nothing:
|
||||
// the first histogram of a window becomes the result as it arrived, and the adds above are
|
||||
// what drop the field otherwise, which would make the payload depend on the sample count.
|
||||
// The bucket layout is left as the fold built it -- compaction belongs to the caller.
|
||||
value.start_timestamp = None;
|
||||
Ok(Some(value))
|
||||
}
|
||||
|
||||
@@ -35,6 +35,22 @@ type Buckets = Vec<(i32, f64)>;
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct FloatHistogram {
|
||||
pub(crate) reset_hint: CounterResetHint,
|
||||
/// The start timestamp of the sample this histogram was read from, in milliseconds.
|
||||
///
|
||||
/// It is metadata of GreptimeDB's histogram row, not part of the histogram value that
|
||||
/// Prometheus's `FloatHistogram` models. This owned form preserves it -- [`Self::try_from_view`]
|
||||
/// reads it off the sample and [`Self::push_to`] writes it back -- while every operation that
|
||||
/// derives a histogram from its input ([`Self::add`], [`Self::kahan_add`], [`Self::mul`],
|
||||
/// [`Self::div`], [`Self::compact`], [`Self::copy_to_schema`], with the constructors beside
|
||||
/// them) clears it. [`Self::equals`] does not compare it.
|
||||
///
|
||||
/// Both halves are this module's own policy and say nothing about how Prometheus propagates
|
||||
/// these timestamps: its `FloatHistogram` does not carry the field, while its rate and reset
|
||||
/// evaluation receives start timestamps through a separate channel. This crate's native range
|
||||
/// kernel does not read the field; the legacy extrapolation path does, to synthesize a zero
|
||||
/// point. So a selection that keeps the field preserves what was stored, and does not by itself
|
||||
/// make a native rate agree with the legacy one.
|
||||
pub(crate) start_timestamp: Option<i64>,
|
||||
pub(crate) schema: i32,
|
||||
pub(crate) zero_threshold: f64,
|
||||
pub(crate) zero_count: f64,
|
||||
@@ -62,6 +78,7 @@ impl FloatHistogram {
|
||||
pub(crate) fn try_from_view(view: &HistogramView<'_>) -> Result<Self> {
|
||||
Ok(Self {
|
||||
reset_hint: view.reset_hint,
|
||||
start_timestamp: view.start_timestamp,
|
||||
schema: view.schema,
|
||||
zero_threshold: view.zero_threshold,
|
||||
zero_count: view.zero_count,
|
||||
@@ -130,7 +147,7 @@ impl FloatHistogram {
|
||||
count: self.count,
|
||||
zero_count: self.zero_count,
|
||||
reset_hint: self.reset_hint,
|
||||
start_timestamp: None,
|
||||
start_timestamp: self.start_timestamp,
|
||||
custom_values: &self.custom_values,
|
||||
positive: BucketSideView {
|
||||
span_offsets: &positive_offsets,
|
||||
@@ -151,6 +168,7 @@ impl FloatHistogram {
|
||||
pub(crate) fn empty_like(&self) -> Self {
|
||||
Self {
|
||||
reset_hint: CounterResetHint::Unknown,
|
||||
start_timestamp: None,
|
||||
schema: self.schema,
|
||||
zero_threshold: 0.0,
|
||||
zero_count: 0.0,
|
||||
@@ -169,6 +187,8 @@ impl FloatHistogram {
|
||||
|
||||
/// Go `Mul`.
|
||||
pub(crate) fn mul(&mut self, factor: f64) {
|
||||
// A result this operation derived, so it carries no start timestamp of its own.
|
||||
self.start_timestamp = None;
|
||||
self.zero_count *= factor;
|
||||
self.count *= factor;
|
||||
self.sum *= factor;
|
||||
@@ -182,6 +202,8 @@ impl FloatHistogram {
|
||||
|
||||
/// Go `Div`; dividing by zero removes every bucket.
|
||||
pub(crate) fn div(&mut self, scalar: f64) {
|
||||
// A result this operation derived, so it carries no start timestamp of its own.
|
||||
self.start_timestamp = None;
|
||||
self.zero_count /= scalar;
|
||||
self.count /= scalar;
|
||||
self.sum /= scalar;
|
||||
@@ -215,6 +237,8 @@ impl FloatHistogram {
|
||||
|
||||
/// Go `Compact(0)`: drops empty buckets.
|
||||
pub(crate) fn compact(&mut self) {
|
||||
// A result this operation derived, so it carries no start timestamp of its own.
|
||||
self.start_timestamp = None;
|
||||
self.positive.retain(|&(_, count)| count != 0.0);
|
||||
self.negative.retain(|&(_, count)| count != 0.0);
|
||||
self.layout = None;
|
||||
@@ -223,13 +247,19 @@ impl FloatHistogram {
|
||||
/// Go `CopyToSchema`; `target` must not exceed the schema.
|
||||
pub(crate) fn copy_to_schema(&self, target: i32) -> Result<Self> {
|
||||
if target == self.schema {
|
||||
return Ok(self.clone());
|
||||
// The copy is a histogram this call produced, like the reduced one below: a start
|
||||
// timestamp belongs to the sample that carried it, not to a value derived from it.
|
||||
return Ok(Self {
|
||||
start_timestamp: None,
|
||||
..self.clone()
|
||||
});
|
||||
}
|
||||
if self.uses_custom_buckets() || target == CUSTOM_BUCKETS_SCHEMA || target > self.schema {
|
||||
return Err(incompatible_schema());
|
||||
}
|
||||
Ok(Self {
|
||||
reset_hint: CounterResetHint::Unknown,
|
||||
start_timestamp: None,
|
||||
schema: target,
|
||||
zero_threshold: self.zero_threshold,
|
||||
zero_count: self.zero_count,
|
||||
@@ -255,6 +285,8 @@ impl FloatHistogram {
|
||||
fn add_or_sub(&mut self, other: &Self, subtract: bool) -> Result<AddOutcome> {
|
||||
check_schemas(self, other)?;
|
||||
self.layout = None;
|
||||
// A result this operation derived, so it carries no start timestamp of its own.
|
||||
self.start_timestamp = None;
|
||||
let mut outcome = AddOutcome {
|
||||
counter_reset_collision: self.adjust_counter_reset(other),
|
||||
custom_bounds_reconciled: false,
|
||||
@@ -323,6 +355,8 @@ impl FloatHistogram {
|
||||
) -> Result<(Self, AddOutcome)> {
|
||||
check_schemas(self, other)?;
|
||||
self.layout = None;
|
||||
// A result this operation derived, so it carries no start timestamp of its own.
|
||||
self.start_timestamp = None;
|
||||
let mut outcome = AddOutcome {
|
||||
counter_reset_collision: self.adjust_counter_reset(other),
|
||||
custom_bounds_reconciled: false,
|
||||
@@ -410,6 +444,7 @@ impl FloatHistogram {
|
||||
fn new_compensation(&self) -> Self {
|
||||
Self {
|
||||
reset_hint: self.reset_hint,
|
||||
start_timestamp: None,
|
||||
schema: self.schema,
|
||||
zero_threshold: self.zero_threshold,
|
||||
zero_count: 0.0,
|
||||
|
||||
@@ -16,6 +16,9 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::error::DataFusionError;
|
||||
use datatypes::series::histogram::{
|
||||
BucketSideView, CounterResetHint, HistogramBatchBuilder, HistogramView,
|
||||
};
|
||||
use datatypes::series::samples::{FieldSpec, SampleRef, Series, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis};
|
||||
|
||||
@@ -383,6 +386,75 @@ fn histogram_points(series: &Series) -> BTreeMap<usize, String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The start timestamp is payload of a histogram that was read, and not of one that was computed.
|
||||
///
|
||||
/// This pins GreptimeDB's own payload policy, not a Prometheus expectation: the timestamp is read
|
||||
/// off a sample ([`FloatHistogram::try_from_view`]) and written back
|
||||
/// ([`FloatHistogram::push_to`]), which is what a selection needs to hand a sample on unchanged,
|
||||
/// and every operation that derives a value from its input clears it. Nothing else depends on the
|
||||
/// field: the type derives `Debug` and `Clone` only, so it has no equality, hash or serialized form
|
||||
/// that could compare it, and [`FloatHistogram::equals`] is Go `Equals` on counts and bucket layout.
|
||||
#[test]
|
||||
fn a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one() {
|
||||
let offsets = [0];
|
||||
let lengths = [2];
|
||||
let buckets = [1.0, 2.0];
|
||||
let view = HistogramView {
|
||||
schema: 0,
|
||||
zero_threshold: 0.0,
|
||||
zero_count: 0.0,
|
||||
count: 3.0,
|
||||
sum: 3.0,
|
||||
reset_hint: CounterResetHint::Unknown,
|
||||
start_timestamp: Some(1500),
|
||||
custom_values: &[],
|
||||
positive: BucketSideView {
|
||||
span_offsets: &offsets,
|
||||
span_lengths: &lengths,
|
||||
buckets: &buckets,
|
||||
},
|
||||
negative: BucketSideView {
|
||||
span_offsets: &[],
|
||||
span_lengths: &[],
|
||||
buckets: &[],
|
||||
},
|
||||
};
|
||||
let histogram = FloatHistogram::try_from_view(&view).unwrap();
|
||||
assert_eq!(histogram.start_timestamp, Some(1500));
|
||||
|
||||
// Writing it back keeps it, which is what makes a selected sample a sample.
|
||||
let mut builder = HistogramBatchBuilder::new();
|
||||
histogram.push_to(&mut builder).unwrap();
|
||||
let table = builder.finish().unwrap();
|
||||
assert_eq!(
|
||||
table.view(0).unwrap().start_timestamp,
|
||||
Some(1500),
|
||||
"the histogram was written back without the start timestamp it was read with"
|
||||
);
|
||||
|
||||
// A value derived from it carries none, whichever operation derived it.
|
||||
let mut added = histogram.clone();
|
||||
added.add(&histogram).unwrap();
|
||||
assert_eq!(added.start_timestamp, None);
|
||||
let mut summed = histogram.clone();
|
||||
let (compensation, _) = summed.kahan_add(&histogram, None).unwrap();
|
||||
assert_eq!(summed.start_timestamp, None);
|
||||
assert_eq!(compensation.start_timestamp, None);
|
||||
let mut multiplied = histogram.clone();
|
||||
multiplied.mul(2.0);
|
||||
assert_eq!(multiplied.start_timestamp, None);
|
||||
let mut divided = histogram.clone();
|
||||
divided.div(2.0);
|
||||
assert_eq!(divided.start_timestamp, None);
|
||||
let mut compacted = histogram.clone();
|
||||
compacted.compact();
|
||||
assert_eq!(compacted.start_timestamp, None);
|
||||
assert_eq!(histogram.copy_to_schema(0).unwrap().start_timestamp, None);
|
||||
assert_eq!(histogram.empty_like().start_timestamp, None);
|
||||
// The one it was read into is still the sample it was read from.
|
||||
assert_eq!(histogram.start_timestamp, Some(1500));
|
||||
}
|
||||
|
||||
/// `histogram_quantile` drops all metadata labels; the single-histogram functions drop only
|
||||
/// `__name__`, as Prometheus does.
|
||||
#[test]
|
||||
|
||||
+1849
-184
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1010,6 +1010,180 @@ fn histogram_chunk(schema: &SeriesSchema, buckets: i32, ts: i64) -> RawSeriesChu
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The single histogram sample of [`histogram_chunk`], read with `start_timestamp`.
|
||||
///
|
||||
/// A sample carries the start timestamp a scan read it with, and it is payload rather than a
|
||||
/// property of the value.
|
||||
fn histogram_chunk_from(
|
||||
schema: &SeriesSchema,
|
||||
buckets: i32,
|
||||
ts: i64,
|
||||
start_timestamp: Option<i64>,
|
||||
is_last: bool,
|
||||
) -> RawSeriesChunk {
|
||||
let offsets = [0];
|
||||
let lengths = [buckets];
|
||||
let counts = vec![1.0; usize::try_from(buckets).unwrap()];
|
||||
let mut builder = HistogramBatchBuilder::new();
|
||||
let index = builder
|
||||
.push(HistogramView {
|
||||
schema: 0,
|
||||
zero_threshold: 0.0,
|
||||
zero_count: 0.0,
|
||||
count: f64::from(buckets),
|
||||
sum: f64::from(buckets),
|
||||
reset_hint: CounterResetHint::Unknown,
|
||||
start_timestamp,
|
||||
custom_values: &[],
|
||||
positive: BucketSideView {
|
||||
span_offsets: &offsets,
|
||||
span_lengths: &lengths,
|
||||
buckets: &counts,
|
||||
},
|
||||
negative: BucketSideView {
|
||||
span_offsets: &[],
|
||||
span_lengths: &[],
|
||||
buckets: &[],
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
let samples = Samples::try_from_histogram(
|
||||
UInt32Array::from(vec![Some(index)]),
|
||||
builder.finish().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
RawSeriesChunk::try_new(
|
||||
schema,
|
||||
Buffer::from(0u64.to_le_bytes().to_vec()),
|
||||
Some(metric(0)),
|
||||
RawTimestamps::try_new(ScalarBuffer::from(vec![ts])).unwrap(),
|
||||
SeriesFields::try_from_vec(vec![samples]).unwrap(),
|
||||
is_last,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A function that hands back the sample it selected hands back that sample's payload.
|
||||
///
|
||||
/// `last_over_time` and `first_over_time` select a sample instead of computing one, so the
|
||||
/// histogram that leaves them is the histogram that arrived, start timestamp included. The window
|
||||
/// here holds two samples that differ in bucket count and in start timestamp, so the count and the
|
||||
/// timestamp together say which one was selected rather than only that some timestamp survived:
|
||||
/// the last sample for `last_over_time`, the first one for `first_over_time`. What this pins is
|
||||
/// that the selection passes the stored payload through; it does not pin a Prometheus result, whose
|
||||
/// histogram values carry no such field, and it does not claim that a native rate reads the field
|
||||
/// afterwards. A histogram computed from samples carries none, as
|
||||
/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one`
|
||||
/// pins for the operations that build one.
|
||||
#[test]
|
||||
fn a_selected_histogram_keeps_its_start_timestamp() {
|
||||
let schema = raw_schema(1);
|
||||
let (first_start, last_start): (i64, i64) = (1_500, 2_500);
|
||||
// One bucket at 0ms and two at 5000ms, each read with its own start timestamp. Both samples
|
||||
// are inside the window of the second grid point; the first point is decided on the first
|
||||
// chunk alone, before the second sample has arrived.
|
||||
let chunks = [
|
||||
histogram_chunk_from(&schema, 1, 0, Some(first_start), false),
|
||||
histogram_chunk_from(&schema, 2, 5_000, Some(last_start), true),
|
||||
];
|
||||
// The histogram of every row the function hands out, read off the output's own views: the
|
||||
// bucket count tells the selected sample apart from any other, the start timestamp is the
|
||||
// payload this test is about.
|
||||
let selected = |function: RangeFunction| -> Vec<(usize, f64, Option<i64>)> {
|
||||
let mut evaluator = RangeEvaluator::try_new(
|
||||
&schema,
|
||||
grid(0, 10_000, 2),
|
||||
RangeWindow {
|
||||
range_ms: 20_000,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
},
|
||||
function,
|
||||
)
|
||||
.unwrap();
|
||||
let out = collect_chunks(&mut evaluator, &chunks);
|
||||
assert!(!out.is_empty(), "{function:?} answered no chunk");
|
||||
let mut picked = Vec::new();
|
||||
for chunk in &out {
|
||||
let mut cursor = chunk.series.fields.as_slice()[0].cursor();
|
||||
for (position, row) in chunk.series.time.positions() {
|
||||
match cursor.at(row).expect("the axis and the fields are aligned") {
|
||||
SampleRef::Histogram(view) => {
|
||||
picked.push((position, view.count, view.start_timestamp));
|
||||
}
|
||||
SampleRef::Float(_) => panic!("{function:?} answered a float for a histogram"),
|
||||
SampleRef::Missing => {
|
||||
panic!("{function:?} handed out a row of its own axis without a sample")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
picked
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
selected(RangeFunction::LastOverTime),
|
||||
[(0, 1.0, Some(first_start)), (1, 2.0, Some(last_start))],
|
||||
"last_over_time did not hand back the sample it selected"
|
||||
);
|
||||
assert_eq!(
|
||||
selected(RangeFunction::FirstOverTime),
|
||||
[(0, 1.0, Some(first_start)), (1, 1.0, Some(first_start))],
|
||||
"first_over_time did not hand back the sample it selected"
|
||||
);
|
||||
}
|
||||
|
||||
/// A histogram computed from a window carries no start timestamp, even when the window holds one.
|
||||
///
|
||||
/// `sum_over_time` computes a histogram rather than selecting one, so the timestamp the sample was
|
||||
/// read with is not part of the result -- the rule the histogram operations themselves follow, as
|
||||
/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one`
|
||||
/// pins. The fold clears the field while adding, so a window holding two histograms already loses
|
||||
/// it; a window holding one must not depend on that, or whether a result carries the field would
|
||||
/// say how many samples the window held rather than what the function did.
|
||||
#[test]
|
||||
fn a_computed_histogram_drops_its_start_timestamp() {
|
||||
let schema = raw_schema(1);
|
||||
let start: i64 = 1_500;
|
||||
// One histogram sample inside the window of both grid points, so the fold adds nothing to it
|
||||
// and the single input is the whole result.
|
||||
let chunks = [histogram_chunk_from(&schema, 1, 0, Some(start), true)];
|
||||
let mut evaluator = RangeEvaluator::try_new(
|
||||
&schema,
|
||||
grid(0, 10_000, 2),
|
||||
RangeWindow {
|
||||
range_ms: 20_000,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
},
|
||||
RangeFunction::SumOverTime,
|
||||
)
|
||||
.unwrap();
|
||||
let out = collect_chunks(&mut evaluator, &chunks);
|
||||
let mut computed = Vec::new();
|
||||
for chunk in &out {
|
||||
let mut cursor = chunk.series.fields.as_slice()[0].cursor();
|
||||
for (position, row) in chunk.series.time.positions() {
|
||||
match cursor.at(row).expect("the axis and the fields are aligned") {
|
||||
SampleRef::Histogram(view) => {
|
||||
computed.push((position, view.count, view.start_timestamp));
|
||||
}
|
||||
SampleRef::Float(_) => panic!("sum_over_time answered a float for a histogram"),
|
||||
SampleRef::Missing => {
|
||||
panic!("sum_over_time handed out a row of its own axis without a sample")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The sum of one histogram is that histogram, so the count says the sample was summed rather
|
||||
// than passed over; only the start timestamp has to be gone.
|
||||
assert_eq!(
|
||||
computed,
|
||||
[(0, 1.0, None), (1, 1.0, None)],
|
||||
"sum_over_time kept the start timestamp of the histogram it summed"
|
||||
);
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -269,6 +269,67 @@ fn limit_operators_keep_histogram_samples() {
|
||||
assert_eq!(kinds(&kept[0], 0), [(1, "histogram")]);
|
||||
}
|
||||
|
||||
/// A selection hands back the sample it selected, start timestamp included.
|
||||
///
|
||||
/// `limitk` and `limit_ratio` choose samples rather than compute them, so a histogram that arrives
|
||||
/// with a start timestamp leaves with it. The count and the sum are compared too, so a computed
|
||||
/// value that happened to carry a timestamp would not pass for the sample selected. What this pins
|
||||
/// is that the selection passes the stored payload through, not a Prometheus result and not a
|
||||
/// downstream rate that reads the field. A histogram computed from samples carries none, as
|
||||
/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one`
|
||||
/// pins for the operations that build one.
|
||||
#[test]
|
||||
fn limit_operators_keep_the_start_timestamp_of_a_selected_sample() {
|
||||
let histogram =
|
||||
OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///");
|
||||
let start = 1_500;
|
||||
// The sample a scan read, which is what a selection hands on.
|
||||
let stamped = || {
|
||||
let mut read = FloatHistogram::try_from_view(&histogram.view()).unwrap();
|
||||
read.start_timestamp = Some(start);
|
||||
GridSample::Histogram(Box::new(read))
|
||||
};
|
||||
// What a limit operator keeps out of one series: the count and sum of the histogram it kept,
|
||||
// so the sample selected is named, and the start timestamp it kept with it.
|
||||
let kept = |series: &Series| -> Vec<(usize, f64, f64, Option<i64>)> {
|
||||
let samples = &series.fields.as_slice()[0];
|
||||
series
|
||||
.time
|
||||
.positions()
|
||||
.filter_map(|(point, row)| match samples.sample(row) {
|
||||
SampleRef::Histogram(view) => {
|
||||
Some((point, view.count, view.sum, view.start_timestamp))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let source = histogram.view();
|
||||
let expected = |point: usize| (point, source.count, source.sum, Some(start));
|
||||
|
||||
let schema = schema(3, 1);
|
||||
let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone())).unwrap();
|
||||
builder.push_samples(0, &[Some(stamped())]).unwrap();
|
||||
builder.push_samples(2, &[Some(stamped())]).unwrap();
|
||||
let series = builder.finish(metric("__name__=a")).unwrap().unwrap();
|
||||
|
||||
let by_ratio = limit_ratio(1.0, &schema, std::slice::from_ref(&series)).unwrap();
|
||||
assert_eq!(by_ratio.len(), 1);
|
||||
assert_eq!(
|
||||
kept(&by_ratio[0]),
|
||||
[expected(0), expected(2)],
|
||||
"limit_ratio did not hand back the samples it selected"
|
||||
);
|
||||
|
||||
let by_count = limitk(1.0, &Grouping::By(Vec::new()), &schema, &[series]).unwrap();
|
||||
assert_eq!(by_count.len(), 1);
|
||||
assert_eq!(
|
||||
kept(&by_count[0]),
|
||||
[expected(0), expected(2)],
|
||||
"limitk did not hand back the samples it selected"
|
||||
);
|
||||
}
|
||||
|
||||
fn grouping(kind: &str, labels: &str) -> Grouping {
|
||||
match kind {
|
||||
"without" => Grouping::Without(names(labels)),
|
||||
|
||||
+878
-65
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,251 @@
|
||||
// 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.
|
||||
|
||||
//! A nested binary and map tree answered through the public native API.
|
||||
//!
|
||||
//! This is an external integration test: it reaches the evaluator the way a consumer above this
|
||||
//! crate does, through [`promql::native::execute`] and [`promql::native::plan`], and it builds the
|
||||
//! evaluated chunks it feeds in itself instead of reading them from a scan. What it checks is that
|
||||
//! `abs(A - (B / C))` is answered at the absolute grid positions both sides fill, under one unnamed
|
||||
//! label set, however the three inputs are split up and interleaved.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool};
|
||||
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
|
||||
use datatypes::arrow::array::Float64Array;
|
||||
use datatypes::series::samples::{
|
||||
FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
|
||||
};
|
||||
use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis};
|
||||
use datatypes::series::{Label, MetricName, SeriesOrdering};
|
||||
use promql::evaluated::EvaluatedChunk;
|
||||
use promql::map::MathOp;
|
||||
use promql::native::execute::{NativeExecutionState, NativeExecutor};
|
||||
use promql::native::metrics::NodePath;
|
||||
use promql::native::plan::{BoundInput, BoundMap, NativeExpr, NativeNode, NativeTree, NativeType};
|
||||
use promql::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels};
|
||||
|
||||
/// The statement's grid: five points one second apart, starting at zero.
|
||||
fn grid() -> Arc<EvalGrid> {
|
||||
let spec = GridSpec::try_new(0, 1_000, 5).expect("a five-point grid");
|
||||
Arc::new(EvalGrid::try_new(spec).expect("the grid materialises its timestamps"))
|
||||
}
|
||||
|
||||
/// The layout every node of the tree binds: one float field evaluated on `grid`.
|
||||
fn evaluated_schema(grid: &Arc<EvalGrid>) -> Arc<SeriesSchema> {
|
||||
Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec { name: "v0".into() }]),
|
||||
eval_grid: Some(Arc::clone(grid)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `name{host="h1",job="x"}`, the label set all three inputs of the tree share.
|
||||
fn metric(name: &str) -> MetricName {
|
||||
MetricName::try_new(
|
||||
Some(name.into()),
|
||||
vec![
|
||||
Label {
|
||||
name: "host".into(),
|
||||
value: "h1".into(),
|
||||
},
|
||||
Label {
|
||||
name: "job".into(),
|
||||
value: "x".into(),
|
||||
},
|
||||
],
|
||||
)
|
||||
.expect("two distinct labels")
|
||||
}
|
||||
|
||||
/// The runs of consecutive positions in `rows`, as the spans a chunk is addressed by.
|
||||
///
|
||||
/// A chunk carries only the positions it holds a value at, so an input with a hole in the middle
|
||||
/// costs the runs it has and not a row per empty position.
|
||||
fn spans(rows: &[(usize, f64)]) -> Vec<GridSpan> {
|
||||
let mut runs: Vec<(usize, usize)> = Vec::new();
|
||||
for &(position, _) in rows {
|
||||
match runs.last_mut() {
|
||||
Some((start, len)) if *start + *len == position => *len += 1,
|
||||
_ => runs.push((position, 1)),
|
||||
}
|
||||
}
|
||||
runs.into_iter()
|
||||
.map(|(start, len)| GridSpan::new(start, len))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One evaluated chunk of the series `name`, holding `rows` at their absolute grid positions.
|
||||
///
|
||||
/// The chunk closes its series when `is_last`, which is what tells a consumer no row follows.
|
||||
fn chunk(
|
||||
schema: &SeriesSchema,
|
||||
name: &str,
|
||||
rows: &[(usize, f64)],
|
||||
is_last: bool,
|
||||
) -> EvaluatedChunk {
|
||||
let grid = schema.eval_grid.clone().expect("the schema has no grid");
|
||||
let time = TimeAxis::from_grid_spans(grid, spans(rows)).expect("ordered runs on the grid");
|
||||
let values: Vec<f64> = rows.iter().map(|&(_, value)| value).collect();
|
||||
let samples = Samples::from_float(Float64Array::from(values));
|
||||
let series = Series::try_new(schema, metric(name), time, SeriesFields::one(samples))
|
||||
.expect("one field aligned with the axis");
|
||||
EvaluatedChunk::try_new(series, is_last).expect("the axis is addressed on the grid")
|
||||
}
|
||||
|
||||
/// An evaluated source bound to `schema`'s grid and field layout.
|
||||
fn source(schema: &Arc<SeriesSchema>) -> NativeNode {
|
||||
let output = NativeType::Samples(Arc::clone(schema));
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
output: output.clone(),
|
||||
ordering: SeriesOrdering::KeyThenTime,
|
||||
}),
|
||||
output,
|
||||
}
|
||||
}
|
||||
|
||||
/// `abs(A - (B / C))`, with every node bound to `schema`'s grid and field layout.
|
||||
///
|
||||
/// The operands are matched on every label but `__name__` (`ignoring()` with no labels), one
|
||||
/// series to one, so a point is decided exactly where both sides of an operator hold a value.
|
||||
fn bound_tree(schema: &Arc<SeriesSchema>) -> NativeTree {
|
||||
let binary = |left: NativeNode, right: NativeNode, op: BinaryOp| NativeNode {
|
||||
expr: NativeExpr::Binary {
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
matching: BinaryMatching {
|
||||
op,
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
},
|
||||
},
|
||||
output: NativeType::Samples(Arc::clone(schema)),
|
||||
};
|
||||
let divide = binary(source(schema), source(schema), BinaryOp::Div);
|
||||
let subtract = binary(source(schema), divide, BinaryOp::Sub);
|
||||
NativeTree::try_new(NativeNode {
|
||||
expr: NativeExpr::Map {
|
||||
input: Box::new(subtract),
|
||||
op: BoundMap {
|
||||
ops: vec![MathOp::Abs].into(),
|
||||
},
|
||||
},
|
||||
output: NativeType::Samples(Arc::clone(schema)),
|
||||
})
|
||||
.expect("the contract of every node in this tree holds")
|
||||
}
|
||||
|
||||
/// Runs `tree` over `pushes`, in the order given, and returns what the root produced.
|
||||
///
|
||||
/// Nothing is handed out while the inputs are still arriving: a binary node needs both operands
|
||||
/// whole, so the chunks it is given are retained and the root answers on [`NativeExecutor::finish`].
|
||||
fn run(tree: &NativeTree, pushes: Vec<(&NodePath, EvaluatedChunk)>) -> Vec<EvaluatedChunk> {
|
||||
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
|
||||
let metrics = ExecutionPlanMetricsSet::new();
|
||||
let state = NativeExecutionState::try_new(tree, Arc::clone(&pool), &metrics, 0)
|
||||
.expect("the runtime executes this tree");
|
||||
let mut executor = NativeExecutor::new(state);
|
||||
for (path, chunk) in pushes {
|
||||
executor
|
||||
.push_evaluated_at(path, chunk)
|
||||
.expect("the chunk is bound to the input it is pushed at");
|
||||
let pulled = executor.next_chunk().expect("the pull succeeds");
|
||||
assert!(
|
||||
pulled.is_none(),
|
||||
"answered at {path} before its input ended"
|
||||
);
|
||||
}
|
||||
let chunks = executor.finish().expect("every series closed");
|
||||
assert_eq!(executor.state().reserved_bytes(), 0, "nothing held");
|
||||
assert_eq!(pool.reserved(), 0, "a finished execution reserves nothing");
|
||||
chunks
|
||||
}
|
||||
|
||||
/// Checks the one chunk the tree must answer with, position by position.
|
||||
fn assert_addressed_result(chunks: &[EvaluatedChunk], grid: &Arc<EvalGrid>) {
|
||||
assert_eq!(chunks.len(), 1, "one series, closed by one chunk");
|
||||
let chunk = &chunks[0];
|
||||
assert!(chunk.is_last, "the chunk that answers closes the series");
|
||||
// Arithmetic and `abs` drop the metric name and keep the labels the match was made on.
|
||||
assert_eq!(chunk.series.metric.name(), None, "the result is unnamed");
|
||||
let mut tags = Vec::new();
|
||||
for label in chunk.series.metric.tags() {
|
||||
tags.push((label.name.as_ref(), label.value.as_ref()));
|
||||
}
|
||||
assert_eq!(tags, vec![("host", "h1"), ("job", "x")]);
|
||||
// The chunk is addressed on the statement's grid and holds a row only where a value was
|
||||
// decided: p1 has a value on the left side alone, and p3 on the right side alone.
|
||||
let axis = chunk.series.time.grid().expect("addressed on a grid");
|
||||
assert_eq!(axis.spec(), grid.spec());
|
||||
assert_eq!(chunk.series.fields.len(), 1, "one field");
|
||||
let field = &chunk.series.fields.as_slice()[0];
|
||||
let mut values = Vec::new();
|
||||
for (position, row) in chunk.series.time.positions() {
|
||||
match field.sample(row) {
|
||||
SampleRef::Float(value) => values.push((position, value)),
|
||||
_ => panic!("the row at {row} holds no float"),
|
||||
}
|
||||
}
|
||||
assert_eq!(values, vec![(0, 6.0), (2, 8.0), (4, 8.0)]);
|
||||
}
|
||||
|
||||
/// `abs(A - (B / C))` through the public API, at the positions both operands fill.
|
||||
///
|
||||
/// The same result is asserted literally for each arrival order, and the two runs are never
|
||||
/// compared with each other, so each one has to hold on its own.
|
||||
#[test]
|
||||
fn public_nested_binary_map_is_addressed() {
|
||||
let grid = grid();
|
||||
let schema = evaluated_schema(&grid);
|
||||
let tree = bound_tree(&schema);
|
||||
// The root is the map; its input is the subtraction, whose right input is the division.
|
||||
let minuend = NodePath::root().input();
|
||||
let a = minuend.left();
|
||||
let b = minuend.right().left();
|
||||
let c = minuend.right().right();
|
||||
|
||||
// What each input holds: A has no value at p3, B none at p1 and C none at p1 or p3.
|
||||
let a_rows: &[(usize, f64)] = &[(0, -2.0), (1, 100.0), (2, 10.0), (4, -3.0)];
|
||||
let b_rows: &[(usize, f64)] = &[(0, 8.0), (2, 6.0), (3, 99.0), (4, 20.0)];
|
||||
let c_rows: &[(usize, f64)] = &[(0, 2.0), (2, 3.0), (4, 4.0)];
|
||||
|
||||
// Each input arrives whole, as one closing chunk, in the order B, C, A.
|
||||
let whole = run(
|
||||
&tree,
|
||||
vec![
|
||||
(&b, chunk(&schema, "b", b_rows, true)),
|
||||
(&c, chunk(&schema, "c", c_rows, true)),
|
||||
(&a, chunk(&schema, "a", a_rows, true)),
|
||||
],
|
||||
);
|
||||
assert_addressed_result(&whole, &grid);
|
||||
|
||||
// The same values split up and interleaved: A only up to p1 first, B and C only at p0 first,
|
||||
// then the tails in the reverse order.
|
||||
let split = run(
|
||||
&tree,
|
||||
vec![
|
||||
(&b, chunk(&schema, "b", &b_rows[..1], false)),
|
||||
(&c, chunk(&schema, "c", &c_rows[..1], false)),
|
||||
(&a, chunk(&schema, "a", &a_rows[..2], false)),
|
||||
(&c, chunk(&schema, "c", &c_rows[1..], true)),
|
||||
(&a, chunk(&schema, "a", &a_rows[2..], true)),
|
||||
(&b, chunk(&schema, "b", &b_rows[1..], true)),
|
||||
],
|
||||
);
|
||||
assert_addressed_result(&split, &grid);
|
||||
}
|
||||
Reference in New Issue
Block a user