mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-25 12:14:08 +00:00
chore: merge narthex into feat/narthex-eval-ts
Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
+342
-31
@@ -19,17 +19,20 @@
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::{BTreeMap, BinaryHeap, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::error::{DataFusionError, Result};
|
||||
use datatypes::series::MetricName;
|
||||
use datatypes::series::samples::{SampleRef, Series, SeriesSchema};
|
||||
|
||||
use crate::grid_series::GridSeriesBuilder;
|
||||
use crate::map::{drop_empty_labels, validate_float_series};
|
||||
use crate::grid_series::{GridSeriesBuilder, external};
|
||||
use crate::map::{drop_empty_labels, validate_float_series, validate_scalar};
|
||||
use crate::range_eval::quantile;
|
||||
|
||||
/// Basic float aggregations.
|
||||
/// Float aggregations without a parameter.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum AggregateOp {
|
||||
Sum,
|
||||
@@ -38,6 +41,8 @@ pub enum AggregateOp {
|
||||
Min,
|
||||
Max,
|
||||
Group,
|
||||
Stddev,
|
||||
Stdvar,
|
||||
}
|
||||
|
||||
/// Grouping by series labels. No modifier is `By(&[])`, as in Prometheus.
|
||||
@@ -64,43 +69,336 @@ pub fn aggregate_float(
|
||||
input: &[Series],
|
||||
op: AggregateOp,
|
||||
grouping: Grouping<'_>,
|
||||
) -> Result<Vec<Series>> {
|
||||
let mut aggregator = FloatAggregator::try_new(schema, op, grouping)?;
|
||||
for series in input {
|
||||
aggregator.update(series)?;
|
||||
}
|
||||
aggregator.finish()
|
||||
}
|
||||
|
||||
/// [`aggregate_float`] fed one series at a time, for a caller that does not hold all its input
|
||||
/// at once. Series are folded in the order they arrive, with the same semantics.
|
||||
///
|
||||
/// The grouping labels are copied in, so the aggregator borrows nothing and can live in the
|
||||
/// state of a stream.
|
||||
pub struct FloatAggregator {
|
||||
schema: Arc<SeriesSchema>,
|
||||
op: AggregateOp,
|
||||
/// `by` (true) or `without`, and its labels.
|
||||
by: bool,
|
||||
labels: Vec<Arc<str>>,
|
||||
group_index: HashMap<LabelKey, usize>,
|
||||
groups: Vec<Group>,
|
||||
}
|
||||
|
||||
impl FloatAggregator {
|
||||
pub fn try_new(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
op: AggregateOp,
|
||||
grouping: Grouping<'_>,
|
||||
) -> Result<Self> {
|
||||
validate_input(schema, &[], grouping)?;
|
||||
let (by, labels) = match grouping {
|
||||
Grouping::By(labels) => (true, labels),
|
||||
Grouping::Without(labels) => (false, labels),
|
||||
};
|
||||
Ok(Self {
|
||||
schema: schema.clone(),
|
||||
op,
|
||||
by,
|
||||
labels: labels.iter().map(|label| Arc::from(*label)).collect(),
|
||||
group_index: HashMap::new(),
|
||||
groups: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds `series` into its group. A series that fails validation leaves the state unchanged.
|
||||
pub fn update(&mut self, series: &Series) -> Result<()> {
|
||||
validate_float_series(&self.schema, series)?;
|
||||
let labels: Vec<&str> = self.labels.iter().map(|label| &**label).collect();
|
||||
let grouping = if self.by {
|
||||
Grouping::By(&labels)
|
||||
} else {
|
||||
Grouping::Without(&labels)
|
||||
};
|
||||
let metric = grouping.apply(&series.metric)?;
|
||||
let index = match self.group_index.entry(label_key(&metric)) {
|
||||
Entry::Occupied(entry) => *entry.get(),
|
||||
Entry::Vacant(entry) => {
|
||||
self.groups.push(Group {
|
||||
metric,
|
||||
blocks: BTreeMap::new(),
|
||||
});
|
||||
*entry.insert(self.groups.len() - 1)
|
||||
}
|
||||
};
|
||||
self.groups[index].accumulate(series, self.op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The result of every group, in the order the groups first appeared.
|
||||
pub fn finish(self) -> Result<Vec<Series>> {
|
||||
let width = self.schema.fields.len();
|
||||
let mut builder = GridSeriesBuilder::try_new(self.schema)?;
|
||||
let mut output = Vec::with_capacity(self.groups.len());
|
||||
let mut row = Vec::with_capacity(width);
|
||||
for group in self.groups {
|
||||
// One builder serves every group, so each result series starts explicitly.
|
||||
builder.begin_series();
|
||||
for (&block, states) in &group.blocks {
|
||||
// The last block can extend past the grid; only points with a sample are pushed.
|
||||
for (offset, point) in states.chunks_exact(width).enumerate() {
|
||||
if !point.iter().any(|state| state.seen) {
|
||||
continue;
|
||||
}
|
||||
row.clear();
|
||||
row.extend(point.iter().map(|state| state.finish(self.op)));
|
||||
builder.push(block * BLOCK_POINTS + offset, &row)?;
|
||||
}
|
||||
}
|
||||
output.extend(builder.finish(group.metric)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
/// `quantile(q, v)`, with `q` read at each grid point from an unlabelled single-field scalar on
|
||||
/// the same grid, as Prometheus evaluates the parameter at every step. A point where `q` has no
|
||||
/// value has no result; `q` outside `[0, 1]` or NaN gives what Prometheus' `quantile` gives.
|
||||
pub fn aggregate_quantile(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
input: &[Series],
|
||||
q: &Series,
|
||||
grouping: Grouping<'_>,
|
||||
) -> Result<Vec<Series>> {
|
||||
validate_input(schema, input, grouping)?;
|
||||
let q_axis = validate_scalar(schema, q)?;
|
||||
let q: Vec<(usize, f64)> = q_axis
|
||||
.positions()
|
||||
.zip(q.fields.as_slice()[0].iter())
|
||||
.filter_map(|((point, _), sample)| match sample {
|
||||
SampleRef::Float(value) => Some((point, value)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
// Members keep input order, the order Prometheus appends to its per-step heap.
|
||||
let mut group_index = HashMap::new();
|
||||
let mut groups = Vec::new();
|
||||
let mut groups: Vec<(MetricName, Vec<&Series>)> = Vec::new();
|
||||
for series in input {
|
||||
let metric = grouping.apply(&series.metric)?;
|
||||
let index = *group_index.entry(label_key(&metric)).or_insert_with(|| {
|
||||
groups.push(Group {
|
||||
metric,
|
||||
blocks: BTreeMap::new(),
|
||||
});
|
||||
groups.push((metric, Vec::new()));
|
||||
groups.len() - 1
|
||||
});
|
||||
groups[index].accumulate(series, op)?;
|
||||
groups[index].1.push(series);
|
||||
}
|
||||
let width = schema.fields.len();
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
|
||||
let mut output = Vec::with_capacity(groups.len());
|
||||
let (mut values, mut sorted, mut row) = (Vec::new(), Vec::new(), Vec::with_capacity(width));
|
||||
for (metric, members) in groups {
|
||||
builder.begin_series();
|
||||
// Each member's next position waits in a min-heap, so a point costs the members present
|
||||
// there and not the whole group: a group of short-lived series stays linear in its
|
||||
// samples. Ties pop in member order, the input order Prometheus appends values in.
|
||||
let mut positions: Vec<_> = members
|
||||
.iter()
|
||||
.map(|series| series.time.positions())
|
||||
.collect();
|
||||
// Indexed by field, then member.
|
||||
let mut cursors: Vec<Vec<_>> = (0..width)
|
||||
.map(|field| {
|
||||
members
|
||||
.iter()
|
||||
.map(|series| series.fields.as_slice()[field].cursor())
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
let mut next: BinaryHeap<Reverse<(usize, usize, usize)>> = positions
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.filter_map(|(member, positions)| {
|
||||
positions
|
||||
.next()
|
||||
.map(|(point, row)| Reverse((point, member, row)))
|
||||
})
|
||||
.collect();
|
||||
let mut present = Vec::new();
|
||||
while let Some(&Reverse((point, _, _))) = next.peek() {
|
||||
present.clear();
|
||||
while let Some(&Reverse((at, member, row))) = next.peek()
|
||||
&& at == point
|
||||
{
|
||||
next.pop();
|
||||
present.push((member, row));
|
||||
if let Some((point, row)) = positions[member].next() {
|
||||
next.push(Reverse((point, member, row)));
|
||||
}
|
||||
}
|
||||
let q = q
|
||||
.binary_search_by_key(&point, |&(point, _)| point)
|
||||
.ok()
|
||||
.map(|index| q[index].1);
|
||||
row.clear();
|
||||
for field in &mut cursors {
|
||||
values.clear();
|
||||
for &(member, member_row) in &present {
|
||||
if let Some(SampleRef::Float(value)) = field[member].at(member_row) {
|
||||
values.push(value);
|
||||
}
|
||||
}
|
||||
row.push(match q {
|
||||
Some(q) if !values.is_empty() => Some(quantile(q, &values, &mut sorted)),
|
||||
_ => None,
|
||||
});
|
||||
}
|
||||
builder.push(point, &row)?;
|
||||
}
|
||||
output.extend(builder.finish(metric)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// `count_values(label, v)`: at each grid point, the number of samples in each group of series
|
||||
/// that share a value, with the value written to `label` in Prometheus' `FormatFloat(v, 'f', -1)`
|
||||
/// form. With `by`, `label` is part of the grouping; with `without`, it is dropped if listed.
|
||||
pub fn count_values(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
input: &[Series],
|
||||
label: &str,
|
||||
grouping: Grouping<'_>,
|
||||
) -> Result<Vec<Series>> {
|
||||
// `by` may list the value label, which this operator writes itself, even when an input field
|
||||
// has that name; grouping by any other field name stays unsupported.
|
||||
let other_labels: Vec<&str>;
|
||||
let checked = match grouping {
|
||||
Grouping::By(labels) => {
|
||||
other_labels = labels
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|name| *name != label)
|
||||
.collect();
|
||||
Grouping::By(&other_labels)
|
||||
}
|
||||
without => without,
|
||||
};
|
||||
validate_input(schema, input, checked)?;
|
||||
if label.is_empty() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"invalid label name {label:?}"
|
||||
)));
|
||||
}
|
||||
let by_labels: Vec<&str>;
|
||||
let grouping = match grouping {
|
||||
Grouping::By(labels) => {
|
||||
by_labels = labels.iter().copied().chain([label]).collect();
|
||||
Grouping::By(&by_labels)
|
||||
}
|
||||
without => without,
|
||||
};
|
||||
let width = schema.fields.len();
|
||||
let mut group_index = HashMap::new();
|
||||
// Counts are kept per point that has one, not in blocks: a gauge with distinct values makes
|
||||
// about one group per sample.
|
||||
let mut groups: Vec<(MetricName, BTreeMap<usize, Vec<f64>>)> = Vec::new();
|
||||
for series in input {
|
||||
// Equal bits format to the same label value, so each distinct value of a series
|
||||
// resolves its group once.
|
||||
let mut group_of_value: HashMap<u64, usize> = HashMap::new();
|
||||
for (field_index, field) in series.fields.iter().enumerate() {
|
||||
for ((point, _), sample) in series.time.positions().zip(field.iter()) {
|
||||
let SampleRef::Float(value) = sample else {
|
||||
continue;
|
||||
};
|
||||
let group = match group_of_value.entry(value.to_bits()) {
|
||||
Entry::Occupied(entry) => *entry.get(),
|
||||
Entry::Vacant(entry) => {
|
||||
let mut metric = series.metric.clone();
|
||||
metric
|
||||
.set(label, Arc::from(format_value(value)))
|
||||
.map_err(external)?;
|
||||
let metric = grouping.apply(&metric)?;
|
||||
let index = *group_index.entry(label_key(&metric)).or_insert_with(|| {
|
||||
groups.push((metric, BTreeMap::new()));
|
||||
groups.len() - 1
|
||||
});
|
||||
*entry.insert(index)
|
||||
}
|
||||
};
|
||||
groups[group]
|
||||
.1
|
||||
.entry(point)
|
||||
.or_insert_with(|| vec![0.0; width])[field_index] += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
|
||||
let mut output = Vec::with_capacity(groups.len());
|
||||
let mut row = Vec::with_capacity(schema.fields.len());
|
||||
for group in groups {
|
||||
// One builder serves every group, so each result series starts explicitly.
|
||||
let mut row = Vec::with_capacity(width);
|
||||
for (metric, counts) in groups {
|
||||
builder.begin_series();
|
||||
for (&block, states) in &group.blocks {
|
||||
// The last block can extend past the grid; only points with a sample are pushed.
|
||||
for (offset, point) in states.chunks_exact(schema.fields.len()).enumerate() {
|
||||
if !point.iter().any(|state| state.seen) {
|
||||
continue;
|
||||
}
|
||||
row.clear();
|
||||
row.extend(point.iter().map(|state| state.finish(op)));
|
||||
builder.push(block * BLOCK_POINTS + offset, &row)?;
|
||||
}
|
||||
for (point, counts) in counts {
|
||||
row.clear();
|
||||
row.extend(counts.iter().map(|&count| (count > 0.0).then_some(count)));
|
||||
builder.push(point, &row)?;
|
||||
}
|
||||
output.extend(builder.finish(group.metric)?);
|
||||
output.extend(builder.finish(metric)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Go's `strconv.FormatFloat(value, 'f', -1, 64)`: the fewest significant digits that round-trip,
|
||||
/// in positional notation. When two candidates of that length are equally close, Go takes the
|
||||
/// even one while Rust's shortest formatting rounds up, so the digits are recomputed with Rust's
|
||||
/// exact formatting, which rounds half to even. The recomputed digits only count when they still
|
||||
/// parse back to `value`: just above a power of two the lower neighbour is half as far away, so
|
||||
/// the even candidate can name that neighbour, and only the other one round-trips.
|
||||
fn format_value(value: f64) -> String {
|
||||
match value {
|
||||
f64::INFINITY => return "+Inf".to_string(),
|
||||
f64::NEG_INFINITY => return "-Inf".to_string(),
|
||||
_ if value.is_nan() => return "NaN".to_string(),
|
||||
_ => {}
|
||||
}
|
||||
let shortest = format!("{value:e}");
|
||||
let mantissa = shortest.split_once('e').expect("exponent format").0;
|
||||
let significant = mantissa.chars().filter(char::is_ascii_digit).count();
|
||||
let exact = format!("{value:.precision$e}", precision = significant - 1);
|
||||
let digits = if exact.parse::<f64>() == Ok(value) {
|
||||
&exact
|
||||
} else {
|
||||
&shortest
|
||||
};
|
||||
let (mantissa, exponent) = digits.split_once('e').expect("exponent format");
|
||||
let exponent: i64 = exponent.parse().expect("integer exponent");
|
||||
let (sign, mantissa) = match mantissa.strip_prefix('-') {
|
||||
Some(unsigned) => ("-", unsigned),
|
||||
None => ("", mantissa),
|
||||
};
|
||||
let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
|
||||
// The decimal point goes after `exponent + 1` digits.
|
||||
let point = exponent + 1;
|
||||
let mut out = String::from(sign);
|
||||
if point <= 0 {
|
||||
out.push_str("0.");
|
||||
out.extend(std::iter::repeat_n('0', (-point) as usize));
|
||||
out.push_str(digits.trim_end_matches('0'));
|
||||
} else if point as usize >= digits.len() {
|
||||
out.push_str(&digits);
|
||||
out.extend(std::iter::repeat_n('0', point as usize - digits.len()));
|
||||
} else {
|
||||
let (whole, fraction) = digits.split_at(point as usize);
|
||||
out.push_str(whole);
|
||||
let fraction = fraction.trim_end_matches('0');
|
||||
if !fraction.is_empty() {
|
||||
out.push('.');
|
||||
out.push_str(fraction);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Schema validation is repeated because Series exposes its fields publicly.
|
||||
fn validate_input(schema: &SeriesSchema, input: &[Series], grouping: Grouping<'_>) -> Result<()> {
|
||||
if schema.eval_grid.is_none() {
|
||||
@@ -144,7 +442,9 @@ impl Grouping<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn label_key(metric: &MetricName) -> Vec<(Arc<str>, Arc<str>)> {
|
||||
type LabelKey = Vec<(Arc<str>, Arc<str>)>;
|
||||
|
||||
fn label_key(metric: &MetricName) -> LabelKey {
|
||||
let mut labels = Vec::with_capacity(metric.tags().len() + 1);
|
||||
if let Some(name) = metric.name() {
|
||||
labels.push((Arc::from("__name__"), Arc::from(name)));
|
||||
@@ -170,7 +470,7 @@ struct Group {
|
||||
}
|
||||
|
||||
impl Group {
|
||||
fn accumulate(&mut self, series: &Series, op: AggregateOp) -> Result<()> {
|
||||
fn accumulate(&mut self, series: &Series, op: AggregateOp) {
|
||||
let width = series.fields.len();
|
||||
let mut pending = Vec::with_capacity(BLOCK_POINTS);
|
||||
for (field_index, field) in series.fields.iter().enumerate() {
|
||||
@@ -190,7 +490,6 @@ impl Group {
|
||||
}
|
||||
self.update_block(block, width, field_index, op, &mut pending);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies one field's samples within a block, so a block costs one lookup per field run.
|
||||
@@ -230,10 +529,13 @@ impl FloatState {
|
||||
if !self.seen {
|
||||
*self = Self {
|
||||
seen: true,
|
||||
value: if matches!(op, AggregateOp::Group) {
|
||||
1.0
|
||||
} else {
|
||||
sample
|
||||
value: match op {
|
||||
AggregateOp::Group => 1.0,
|
||||
// The running sum of squared deviations; Prometheus starts it at NaN for a
|
||||
// non-finite first sample.
|
||||
AggregateOp::Stddev | AggregateOp::Stdvar if !sample.is_finite() => f64::NAN,
|
||||
AggregateOp::Stddev | AggregateOp::Stdvar => 0.0,
|
||||
_ => sample,
|
||||
},
|
||||
mean: sample,
|
||||
count: 1.0,
|
||||
@@ -258,6 +560,13 @@ impl FloatState {
|
||||
}
|
||||
}
|
||||
AggregateOp::Group => {}
|
||||
// Welford's update, uncompensated as in Prometheus.
|
||||
AggregateOp::Stddev | AggregateOp::Stdvar => {
|
||||
self.count += 1.0;
|
||||
let delta = sample - self.mean;
|
||||
self.mean += delta / self.count;
|
||||
self.value += delta * (sample - self.mean);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,6 +598,8 @@ impl FloatState {
|
||||
AggregateOp::Avg => self.value / self.count + self.compensation / self.count,
|
||||
AggregateOp::Count => self.count,
|
||||
AggregateOp::Min | AggregateOp::Max | AggregateOp::Group => self.value,
|
||||
AggregateOp::Stdvar => self.value / self.count,
|
||||
AggregateOp::Stddev => (self.value / self.count).sqrt(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -42,6 +42,10 @@ const OPS: [AggregateOp; 6] = [
|
||||
];
|
||||
|
||||
fn schema(fields: &[&str]) -> Arc<SeriesSchema> {
|
||||
schema_with_grid_len(fields, 128)
|
||||
}
|
||||
|
||||
fn schema_with_grid_len(fields: &[&str], len: u64) -> Arc<SeriesSchema> {
|
||||
Arc::new(SeriesSchema {
|
||||
fields: fields
|
||||
.iter()
|
||||
@@ -50,7 +54,7 @@ fn schema(fields: &[&str]) -> Arc<SeriesSchema> {
|
||||
})
|
||||
.collect(),
|
||||
eval_grid: Some(Arc::new(
|
||||
EvalGrid::try_new(GridSpec::try_new(-1000, 250, 128).unwrap()).unwrap(),
|
||||
EvalGrid::try_new(GridSpec::try_new(-1000, 250, len).unwrap()).unwrap(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
@@ -199,6 +203,42 @@ fn aggregates_match_prometheus() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `stddev`, `stdvar`, `quantile` and `count_values` evaluated by the Prometheus v3.15.0 engine;
|
||||
/// see the header of `stat_cases.txt`.
|
||||
#[test]
|
||||
fn stat_aggregates_match_prometheus() {
|
||||
let mut matched = BTreeMap::<String, usize>::new();
|
||||
for case in cases(include_str!("stat_cases.txt")) {
|
||||
let h = &case.header;
|
||||
let labels = h[3]
|
||||
.split(',')
|
||||
.filter(|label| *label != "-")
|
||||
.collect::<Vec<_>>();
|
||||
let grouping = grouping(h, &labels);
|
||||
let output = match h[1].as_str() {
|
||||
"stddev" => aggregate_float(&case.schema, &case.series, AggregateOp::Stddev, grouping),
|
||||
"stdvar" => aggregate_float(&case.schema, &case.series, AggregateOp::Stdvar, grouping),
|
||||
"quantile" => {
|
||||
let q = case.scalar.as_ref().expect("quantile cases carry q");
|
||||
aggregate_quantile(&case.schema, &case.series, q, grouping)
|
||||
}
|
||||
"count_values" => count_values(&case.schema, &case.series, &h[4], grouping),
|
||||
other => panic!("unmapped aggregate {other}"),
|
||||
};
|
||||
assert_result(&case, output.unwrap());
|
||||
*matched.entry(format!("{} {}", h[1], h[2])).or_default() += 1;
|
||||
}
|
||||
for op in ["stddev", "stdvar", "quantile", "count_values"] {
|
||||
for grouping in ["none", "by", "without"] {
|
||||
let count = matched
|
||||
.get(&format!("{op} {grouping}"))
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
assert!(count >= 12, "{op} {grouping}: {count}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compensated_sum_and_overflowing_avg_follow_prometheus() {
|
||||
let schema = schema(&["value"]);
|
||||
@@ -351,18 +391,50 @@ fn fields_are_aggregated_independently() {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let grid_len = multi.eval_grid.as_ref().unwrap().timestamps().len();
|
||||
let q_values: Vec<Option<f64>> = (0..grid_len)
|
||||
.map(|i| Some([0.0, 0.25, 0.5, 0.9, 1.0][i % 5]))
|
||||
.collect();
|
||||
let q = input(
|
||||
&schema(&["scalar"]),
|
||||
MetricName::try_new(None, Vec::new()).unwrap(),
|
||||
0,
|
||||
&[q_values],
|
||||
);
|
||||
type Kernel<'a> = Box<dyn Fn(&Arc<SeriesSchema>, &[Series], Grouping<'_>) -> Vec<Series> + 'a>;
|
||||
let mut kernels: Vec<(String, Kernel<'_>)> = OPS
|
||||
.iter()
|
||||
.chain(&[AggregateOp::Stddev, AggregateOp::Stdvar])
|
||||
.map(|&op| -> (String, Kernel<'_>) {
|
||||
(
|
||||
format!("{op:?}"),
|
||||
Box::new(move |schema, input, grouping| {
|
||||
aggregate_float(schema, input, op, grouping).unwrap()
|
||||
}),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
kernels.push((
|
||||
"quantile".into(),
|
||||
Box::new(|schema, input, grouping| {
|
||||
aggregate_quantile(schema, input, &q, grouping).unwrap()
|
||||
}),
|
||||
));
|
||||
kernels.push((
|
||||
"count_values".into(),
|
||||
Box::new(|schema, input, grouping| count_values(schema, input, "value", grouping).unwrap()),
|
||||
));
|
||||
for grouping in [
|
||||
Grouping::By(&[]),
|
||||
Grouping::By(&["host"]),
|
||||
Grouping::Without(&["i"]),
|
||||
] {
|
||||
for op in OPS {
|
||||
let output = aggregate_float(&multi, &series, op, grouping).unwrap();
|
||||
for (op, kernel) in &kernels {
|
||||
let output = kernel(&multi, &series, grouping);
|
||||
for field in [0, 1] {
|
||||
let expected = aggregate_float(&single, &project(field), op, grouping).unwrap();
|
||||
let expected = kernel(&single, &project(field), grouping);
|
||||
// The multi-field result is cut into pieces where its values are interrupted, so
|
||||
// the comparison is over the dense values of each label set, not over pieces.
|
||||
let grid_len = multi.eval_grid.as_ref().unwrap().timestamps().len();
|
||||
let grouped = |pieces: &[Series], field: usize| {
|
||||
let mut by_metric: BTreeMap<LabelKey, Positions> = BTreeMap::new();
|
||||
for piece in pieces {
|
||||
@@ -394,7 +466,7 @@ fn fields_are_aggregated_independently() {
|
||||
};
|
||||
let actual = grouped(&output, field);
|
||||
let expected = grouped(&expected, 0);
|
||||
assert_eq!(actual, expected, "{op:?} {grouping:?} field {field}");
|
||||
assert_eq!(actual, expected, "{op} {grouping:?} field {field}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -632,6 +704,16 @@ fn unsupported_shapes_and_mutated_schema_fail_without_partial_output() {
|
||||
11,
|
||||
&[vec![Some(1.0)], vec![Some(2.0)]],
|
||||
);
|
||||
// Prometheus rejects an empty `count_values` label name at evaluation.
|
||||
assert!(matches!(
|
||||
count_values(
|
||||
&schema,
|
||||
std::slice::from_ref(&source),
|
||||
"",
|
||||
Grouping::By(&[])
|
||||
),
|
||||
Err(DataFusionError::Execution(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
aggregate_float(
|
||||
&schema,
|
||||
@@ -815,3 +897,170 @@ fn an_aggregation_of_sparse_inputs_is_compared_in_full_against_the_reference() {
|
||||
assert_pieces_eq(&counts, &counted, &metric_of(&Labels::new()));
|
||||
assert_eq!(piece_ranges(&counts), vec![(2, 1), (6, 1)]);
|
||||
}
|
||||
|
||||
/// `count_values` writes value labels the way Go's `strconv.FormatFloat(v, 'f', -1, 64)` does,
|
||||
/// including the round-half-even choice of the last shortest digit; see the header of
|
||||
/// `format_float_cases.txt` (promql-compat `cmd/narthex-golden-formatfloat`).
|
||||
#[test]
|
||||
fn value_labels_format_like_go() {
|
||||
let mut checked = 0;
|
||||
for line in include_str!("format_float_cases.txt").lines() {
|
||||
let (bits, expected) = line.split_once(' ').unwrap();
|
||||
let value = f64::from_bits(u64::from_str_radix(bits, 16).unwrap());
|
||||
assert_eq!(format_value(value), expected, "{bits}");
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked > 2_400, "{checked}");
|
||||
for (value, expected) in [
|
||||
(f64::NAN, "NaN"),
|
||||
(f64::INFINITY, "+Inf"),
|
||||
(f64::NEG_INFINITY, "-Inf"),
|
||||
] {
|
||||
assert_eq!(format_value(value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
/// A point where the `q` scalar has no value has no `quantile` result, as a missing scalar point
|
||||
/// yields no output in the other scalar operators.
|
||||
#[test]
|
||||
fn quantile_without_q_at_a_point_has_no_result() {
|
||||
let schema = schema(&["value"]);
|
||||
let series = [
|
||||
input(
|
||||
&schema,
|
||||
metric("a", &[("i", "0")]),
|
||||
10,
|
||||
&[vec![Some(1.0); 3]],
|
||||
),
|
||||
input(
|
||||
&schema,
|
||||
metric("a", &[("i", "1")]),
|
||||
10,
|
||||
&[vec![Some(3.0); 3]],
|
||||
),
|
||||
];
|
||||
let q = input(
|
||||
&schema,
|
||||
MetricName::try_new(None, Vec::new()).unwrap(),
|
||||
10,
|
||||
&[vec![Some(0.5), None, Some(0.5)]],
|
||||
);
|
||||
let output = aggregate_quantile(&schema, &series, &q, Grouping::By(&[])).unwrap();
|
||||
let (start, values) = values_of(&output, 0, 128);
|
||||
assert_eq!((start, values), (10, vec![Some(2.0), None, Some(2.0)]));
|
||||
}
|
||||
|
||||
/// Listing the value label in `by` repeats what `count_values` adds to the grouping, also when an
|
||||
/// input field has that name; listing another field name is still unsupported.
|
||||
#[test]
|
||||
fn count_values_accepts_its_own_label_in_by() {
|
||||
let schema = schema(&["value"]);
|
||||
let series = [
|
||||
input(&schema, metric("m", &[("i", "0")]), 10, &[vec![Some(1.0)]]),
|
||||
input(&schema, metric("m", &[("i", "1")]), 10, &[vec![Some(2.0)]]),
|
||||
];
|
||||
let rendered = |grouping| {
|
||||
let mut output: Vec<_> = count_values(&schema, &series, "value", grouping)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|series| (format!("{:?}", series.metric), values(series, 0)))
|
||||
.collect();
|
||||
output.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
output
|
||||
};
|
||||
let implicit = rendered(Grouping::By(&[]));
|
||||
assert_eq!(implicit.len(), 2);
|
||||
assert_eq!(implicit, rendered(Grouping::By(&["value"])));
|
||||
assert!(matches!(
|
||||
count_values(&schema, &series, "c", Grouping::By(&["value"])),
|
||||
Err(DataFusionError::NotImplemented(_))
|
||||
));
|
||||
}
|
||||
|
||||
/// A series the aggregator rejects is not folded in part: the series after it aggregate as if it
|
||||
/// had never been offered.
|
||||
#[test]
|
||||
fn a_rejected_series_leaves_the_aggregator_unchanged() {
|
||||
let schema = schema(&["value"]);
|
||||
let other = schema_with_grid_len(&["value"], 64);
|
||||
let first = input(&schema, metric("m", &[("i", "0")]), 10, &[vec![Some(1.0)]]);
|
||||
let second = input(&schema, metric("m", &[("i", "1")]), 10, &[vec![Some(2.0)]]);
|
||||
let foreign = input(&other, metric("m", &[("i", "2")]), 10, &[vec![Some(4.0)]]);
|
||||
|
||||
let mut aggregator =
|
||||
FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap();
|
||||
aggregator.update(&first).unwrap();
|
||||
assert!(aggregator.update(&foreign).is_err());
|
||||
aggregator.update(&second).unwrap();
|
||||
let output = aggregator.finish().unwrap();
|
||||
assert_eq!(values_of(&output, 0, 128), (10, vec![Some(3.0)]));
|
||||
}
|
||||
|
||||
/// A group of short-lived series, one sample each at its own point: every point aggregates the one
|
||||
/// member present there, the shape whose cost must follow the samples and not members × points.
|
||||
#[test]
|
||||
fn quantile_over_one_point_members_reads_each_member_at_its_point() {
|
||||
let schema = schema(&["value"]);
|
||||
let series: Vec<Series> = (0..128)
|
||||
.map(|point| {
|
||||
input(
|
||||
&schema,
|
||||
metric("m", &[("i", &point.to_string())]),
|
||||
point,
|
||||
&[vec![Some(point as f64)]],
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let q = input(
|
||||
&schema,
|
||||
MetricName::try_new(None, Vec::new()).unwrap(),
|
||||
0,
|
||||
&[vec![Some(0.5); 128]],
|
||||
);
|
||||
let output = aggregate_quantile(&schema, &series, &q, Grouping::By(&[])).unwrap();
|
||||
let expected: Vec<Option<f64>> = (0..128).map(|point| Some(point as f64)).collect();
|
||||
assert_eq!(values_of(&output, 0, 128), (0, expected));
|
||||
}
|
||||
|
||||
/// `2^-24` and the float below it format to different labels, so they count as two values: the
|
||||
/// even 16-digit candidate for `2^-24` names the lower neighbour.
|
||||
#[test]
|
||||
fn count_values_keeps_neighbours_of_a_power_of_two_apart() {
|
||||
let schema = schema(&["value"]);
|
||||
let series = [0x3e70_0000_0000_0000, 0x3e6f_ffff_ffff_ffff]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, bits)| {
|
||||
input(
|
||||
&schema,
|
||||
metric("m", &[("i", &index.to_string())]),
|
||||
0,
|
||||
&[vec![Some(f64::from_bits(bits))]],
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut groups: Vec<_> = count_values(&schema, &series, "v", Grouping::By(&[]))
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|series| {
|
||||
(
|
||||
series.metric.get("v").unwrap().to_string(),
|
||||
values(series, 0),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
groups.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(
|
||||
groups,
|
||||
[
|
||||
(
|
||||
"0.00000005960464477539062".to_string(),
|
||||
(0, vec![Some(1.0)])
|
||||
),
|
||||
(
|
||||
"0.00000005960464477539063".to_string(),
|
||||
(0, vec![Some(1.0)])
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
// 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.
|
||||
|
||||
//! `info(v, {selector})`: the series of `v` with the data labels of the info series that share
|
||||
//! their identifying labels, following Prometheus `combineWithInfoSeries` and
|
||||
//! `combineWithInfoVector`.
|
||||
//!
|
||||
//! Selecting the info series is the caller's: the series whose name and data labels match the
|
||||
//! selector, evaluated at every point of the grid like an instant selector, with the value
|
||||
//! replaced by the original timestamp of the selected sample, as Prometheus' `evalSeries` records
|
||||
//! it for `info`. This kernel only combines.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::error::{DataFusionError, Result};
|
||||
use datatypes::series::MetricName;
|
||||
use datatypes::series::samples::{SampleRef, Series, SeriesSchema};
|
||||
use regex::Regex;
|
||||
|
||||
use crate::grid_series::{GridSample, GridSeriesBuilder, LabelSet, external, label_set, owned};
|
||||
use crate::select::MatchOp;
|
||||
|
||||
/// The labels an info series is joined on, as in Prometheus.
|
||||
const IDENTIFYING_LABELS: [&str; 2] = ["instance", "job"];
|
||||
|
||||
/// The second argument of `info`, split the way Prometheus uses it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InfoSelector {
|
||||
/// The `__name__` matchers, which choose the info metrics; none means `target_info`.
|
||||
pub name_matchers: Vec<(MatchOp, Arc<str>)>,
|
||||
/// The names of the other matchers: only these labels are copied. None copies every label
|
||||
/// of the info series.
|
||||
pub data_labels: Vec<Arc<str>>,
|
||||
/// Whether every one of those other matchers matches the empty string, in which case a series
|
||||
/// without a matching info series is kept as it is.
|
||||
pub keep_unmatched: bool,
|
||||
}
|
||||
|
||||
/// Combines `base` with the data labels of `info`.
|
||||
///
|
||||
/// `info` holds the info series the selector chooses, one float field each, whose value at a
|
||||
/// point is the original timestamp of the sample selected there. For each info metric a base
|
||||
/// series takes the info series with the same identifying labels. Several of them at one point are
|
||||
/// compared in input order, as Prometheus compares them in the order its storage returns them: a
|
||||
/// newer one replaces the one kept so far, and one exactly as new is an error. Labels
|
||||
/// the base series already has are kept, and two info metrics giving one label different values
|
||||
/// are an error. A base series without identifying labels matches no info series, since
|
||||
/// Prometheus fetches none for it, and a base series that is itself an info metric is passed
|
||||
/// through. Results that share a label set merge; a field held twice at one point is an error.
|
||||
pub fn info(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
base: &[Series],
|
||||
info: &[Series],
|
||||
selector: &InfoSelector,
|
||||
) -> Result<Vec<Series>> {
|
||||
let grid = schema
|
||||
.eval_grid
|
||||
.as_ref()
|
||||
.ok_or_else(|| DataFusionError::Execution("info requires an evaluated grid".into()))?;
|
||||
let points = grid.timestamps().len();
|
||||
for series in base {
|
||||
if series.time.grid().map(|grid| grid.spec()) != Some(grid.spec())
|
||||
|| series.fields.len() != schema.fields.len()
|
||||
{
|
||||
return Err(DataFusionError::Execution(
|
||||
"info base series does not match its schema".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
for series in info {
|
||||
if series.time.grid().map(|grid| grid.spec()) != Some(grid.spec())
|
||||
|| series.fields.len() != 1
|
||||
{
|
||||
return Err(DataFusionError::Execution(
|
||||
"info series must be single-field series on the base grid".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let name_matchers = effective_name_matchers(&selector.name_matchers)?;
|
||||
let is_info_metric = |name: &str| name_matchers.iter().all(|matcher| matcher.matches(name));
|
||||
|
||||
let mut base_present = vec![false; points];
|
||||
for series in base {
|
||||
for field in series.fields.iter() {
|
||||
for ((point, _), sample) in series.time.positions().zip(field.iter()) {
|
||||
if !matches!(sample, SampleRef::Missing) {
|
||||
base_present[point] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut error = FirstError::default();
|
||||
|
||||
// Prometheus fetches info series per presence pattern of the identifying labels among the
|
||||
// base series it enriches: a present label matches any value the pattern's base series have,
|
||||
// an absent one matches only absence. An info series no pattern admits is never fetched, so
|
||||
// it neither enriches nor conflicts.
|
||||
let mut patterns: HashMap<Vec<bool>, Vec<BTreeSet<Arc<str>>>> = HashMap::new();
|
||||
for series in base {
|
||||
if is_info_metric(series.metric.name().unwrap_or("")) {
|
||||
continue;
|
||||
}
|
||||
let values = identifying_values(&series.metric);
|
||||
let presence: Vec<bool> = values.iter().map(Option::is_some).collect();
|
||||
if !presence.contains(&true) {
|
||||
continue;
|
||||
}
|
||||
let sets = patterns
|
||||
.entry(presence)
|
||||
.or_insert_with(|| vec![BTreeSet::new(); IDENTIFYING_LABELS.len()]);
|
||||
for (set, value) in sets.iter_mut().zip(values) {
|
||||
set.extend(value);
|
||||
}
|
||||
}
|
||||
|
||||
// The info series kept for each signature at each point.
|
||||
let mut by_signature: HashMap<Signature, BTreeMap<usize, (f64, usize)>> = HashMap::new();
|
||||
let mut info_names: BTreeSet<Arc<str>> = BTreeSet::new();
|
||||
for (index, series) in info.iter().enumerate() {
|
||||
let values = identifying_values(&series.metric);
|
||||
let presence: Vec<bool> = values.iter().map(Option::is_some).collect();
|
||||
let fetched = patterns.get(&presence).is_some_and(|sets| {
|
||||
sets.iter()
|
||||
.zip(&values)
|
||||
.all(|(set, value)| value.as_ref().is_none_or(|value| set.contains(value)))
|
||||
});
|
||||
if !fetched {
|
||||
continue;
|
||||
}
|
||||
let name: Arc<str> = Arc::from(series.metric.name().unwrap_or(""));
|
||||
info_names.insert(name.clone());
|
||||
let kept = by_signature.entry((name, values)).or_default();
|
||||
let mut cursor = series.fields.as_slice()[0].cursor();
|
||||
for (point, row) in series.time.positions() {
|
||||
let timestamp = match cursor.at(row).expect("the axis and the fields are aligned") {
|
||||
SampleRef::Missing => continue,
|
||||
SampleRef::Float(timestamp) => timestamp,
|
||||
SampleRef::Histogram(_) => {
|
||||
return Err(DataFusionError::Internal(
|
||||
"info series must hold the original sample timestamps as floats".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
match kept.entry(point) {
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert((timestamp, index));
|
||||
}
|
||||
Entry::Occupied(mut entry) => {
|
||||
let (existing, existing_index) = *entry.get();
|
||||
if timestamp > existing {
|
||||
entry.insert((timestamp, index));
|
||||
} else if timestamp == existing && base_present[point] {
|
||||
error.record(point, 0, || {
|
||||
format!(
|
||||
"found duplicate series for info metric: existing {} @ {}, new \
|
||||
{} @ {}",
|
||||
render(&label_set(&info[existing_index].metric)),
|
||||
existing as i64,
|
||||
render(&label_set(&series.metric)),
|
||||
timestamp as i64
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let width = schema.fields.len();
|
||||
let mut result_index: HashMap<LabelSet, usize> = HashMap::new();
|
||||
let mut results: Vec<(MetricName, Vec<Row>)> = Vec::new();
|
||||
let mut added: Vec<(Arc<str>, Arc<str>)> = Vec::new();
|
||||
let mut chosen: Vec<usize> = Vec::new();
|
||||
for series in base {
|
||||
let ignored = is_info_metric(series.metric.name().unwrap_or(""));
|
||||
// The signature of each info metric is fixed for a series, so its kept series are looked
|
||||
// up once; a point then only reads which of them is kept there.
|
||||
let candidates: Vec<&BTreeMap<usize, (f64, usize)>> = if ignored {
|
||||
Vec::new()
|
||||
} else {
|
||||
let values = identifying_values(&series.metric);
|
||||
info_names
|
||||
.iter()
|
||||
.filter_map(|name| by_signature.get(&(name.clone(), values.clone())))
|
||||
.collect()
|
||||
};
|
||||
// The result of the previous point, reused while the same info series are kept.
|
||||
let mut previous: Option<Choice> = None;
|
||||
let mut cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
|
||||
for (point, row) in series.time.positions() {
|
||||
let mut values = Vec::with_capacity(width);
|
||||
for cursor in &mut cursors {
|
||||
values.push(owned(
|
||||
cursor.at(row).expect("the axis and the fields are aligned"),
|
||||
)?);
|
||||
}
|
||||
if values.iter().all(Option::is_none) {
|
||||
continue;
|
||||
}
|
||||
chosen.clear();
|
||||
chosen.extend(
|
||||
candidates
|
||||
.iter()
|
||||
.filter_map(|kept| kept.get(&point).map(|&(_, index)| index)),
|
||||
);
|
||||
let reuse = previous
|
||||
.as_ref()
|
||||
.is_some_and(|previous| previous.info == chosen);
|
||||
if !reuse {
|
||||
added.clear();
|
||||
let mut conflict = None;
|
||||
for &index in &chosen {
|
||||
if let Err(label) =
|
||||
add_data_labels(&info[index].metric, &series.metric, selector, &mut added)
|
||||
{
|
||||
conflict = Some(label);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let result = if chosen.is_empty() && !selector.keep_unmatched && !ignored {
|
||||
None
|
||||
} else {
|
||||
let mut metric = series.metric.clone();
|
||||
for (name, value) in &added {
|
||||
metric.set(name, value.clone()).map_err(external)?;
|
||||
}
|
||||
Some(match result_index.entry(label_set(&metric)) {
|
||||
std::collections::hash_map::Entry::Occupied(entry) => *entry.get(),
|
||||
std::collections::hash_map::Entry::Vacant(entry) => {
|
||||
results.push((metric, Vec::new()));
|
||||
*entry.insert(results.len() - 1)
|
||||
}
|
||||
})
|
||||
};
|
||||
previous = Some(Choice {
|
||||
info: chosen.clone(),
|
||||
result,
|
||||
conflict,
|
||||
});
|
||||
}
|
||||
let choice = previous.as_ref().expect("set above");
|
||||
if let Some(label) = &choice.conflict {
|
||||
error.record(point, 1, || format!("conflicting label: {label}"));
|
||||
}
|
||||
if let Some(result) = choice.result {
|
||||
results[result].1.push((point, values));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rows of one label set arrive per base series; sorted by point, a field held twice at one
|
||||
// point is a collision.
|
||||
for (metric, rows) in &mut results {
|
||||
rows.sort_by_key(|(point, _)| *point);
|
||||
let mut merged: Vec<Row> = Vec::with_capacity(rows.len());
|
||||
for (point, values) in rows.drain(..) {
|
||||
match merged.last_mut() {
|
||||
Some((last, slots)) if *last == point => {
|
||||
for (slot, value) in slots.iter_mut().zip(values) {
|
||||
if value.is_none() {
|
||||
continue;
|
||||
}
|
||||
if slot.is_some() {
|
||||
error.record(point, 2, || {
|
||||
format!(
|
||||
"vector cannot contain metrics with the same labelset {}",
|
||||
render(&label_set(metric))
|
||||
)
|
||||
});
|
||||
}
|
||||
*slot = value;
|
||||
}
|
||||
}
|
||||
_ => merged.push((point, values)),
|
||||
}
|
||||
}
|
||||
*rows = merged;
|
||||
}
|
||||
if let Some((_, _, message)) = error.0 {
|
||||
return Err(DataFusionError::Execution(message));
|
||||
}
|
||||
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
|
||||
let mut output = Vec::with_capacity(results.len());
|
||||
for (metric, rows) in results {
|
||||
builder.begin_series();
|
||||
for (point, row) in rows {
|
||||
builder.push_samples(point, &row)?;
|
||||
}
|
||||
output.extend(builder.finish(metric)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// The samples of one result series at one grid point, one per field.
|
||||
type Row = (usize, Vec<Option<GridSample>>);
|
||||
|
||||
/// What the info series kept at a point make of one base series.
|
||||
struct Choice {
|
||||
/// The info series, one per info metric that has one.
|
||||
info: Vec<usize>,
|
||||
/// The result series the point goes to, `None` when the point is dropped.
|
||||
result: Option<usize>,
|
||||
/// A label two of the info series set to different values.
|
||||
conflict: Option<Arc<str>>,
|
||||
}
|
||||
|
||||
/// The error Prometheus reports: the one of the first failing step, and within a step the first
|
||||
/// of its checks (the info series, then each base series, then the result label sets).
|
||||
#[derive(Default)]
|
||||
struct FirstError(Option<(usize, u8, String)>);
|
||||
|
||||
impl FirstError {
|
||||
/// Records an error of check `rank` at `point`, formatting it only if it comes first.
|
||||
fn record(&mut self, point: usize, rank: u8, message: impl FnOnce() -> String) {
|
||||
if self
|
||||
.0
|
||||
.as_ref()
|
||||
.is_none_or(|(first, first_rank, _)| (point, rank) < (*first, *first_rank))
|
||||
{
|
||||
self.0 = Some((point, rank, message()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A label set as Prometheus prints one.
|
||||
fn render(labels: &LabelSet) -> String {
|
||||
let labels: Vec<String> = labels
|
||||
.iter()
|
||||
.map(|(name, value)| format!("{name}=\"{value}\""))
|
||||
.collect();
|
||||
format!("{{{}}}", labels.join(", "))
|
||||
}
|
||||
|
||||
/// An info metric name and the identifying label values present on a series.
|
||||
type Signature = (Arc<str>, Vec<Option<Arc<str>>>);
|
||||
|
||||
/// The value of each identifying label, `None` where the series does not have it.
|
||||
fn identifying_values(metric: &MetricName) -> Vec<Option<Arc<str>>> {
|
||||
IDENTIFYING_LABELS
|
||||
.iter()
|
||||
.map(|label| {
|
||||
metric
|
||||
.get(label)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(Arc::from)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Adds the data labels `info` gives a series with labels `base` to `added`; returns the name of
|
||||
/// a label another info metric already set to a different value.
|
||||
fn add_data_labels(
|
||||
info: &MetricName,
|
||||
base: &MetricName,
|
||||
selector: &InfoSelector,
|
||||
added: &mut Vec<(Arc<str>, Arc<str>)>,
|
||||
) -> std::result::Result<(), Arc<str>> {
|
||||
for tag in info.tags() {
|
||||
if tag.value.is_empty()
|
||||
|| (!selector.data_labels.is_empty() && !selector.data_labels.contains(&tag.name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some((_, value)) = added.iter().find(|(name, _)| *name == tag.name) {
|
||||
if *value != tag.value {
|
||||
return Err(tag.name.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if base.get(&tag.name).is_some_and(|value| !value.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
added.push((tag.name.clone(), tag.value.clone()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct NameMatcher {
|
||||
op: MatchOp,
|
||||
value: Arc<str>,
|
||||
regex: Option<Regex>,
|
||||
}
|
||||
|
||||
impl NameMatcher {
|
||||
fn try_new(op: MatchOp, value: Arc<str>) -> Result<Self> {
|
||||
let regex = match op {
|
||||
MatchOp::Regex | MatchOp::NotRegex => {
|
||||
Some(Regex::new(&format!("^(?s:{value})$")).map_err(|error| {
|
||||
DataFusionError::Plan(format!("invalid regular expression {value}: {error}"))
|
||||
})?)
|
||||
}
|
||||
MatchOp::Equal | MatchOp::NotEqual => None,
|
||||
};
|
||||
Ok(Self { op, value, regex })
|
||||
}
|
||||
|
||||
fn matches(&self, name: &str) -> bool {
|
||||
match (self.op, &self.regex) {
|
||||
(MatchOp::Equal, _) => name == &*self.value,
|
||||
(MatchOp::NotEqual, _) => name != &*self.value,
|
||||
(MatchOp::Regex, Some(regex)) => regex.is_match(name),
|
||||
(MatchOp::NotRegex, Some(regex)) => !regex.is_match(name),
|
||||
_ => unreachable!("regex matchers compile their regex"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prometheus `effectiveInfoNameMatchers`: the name matchers as given when one of them selects,
|
||||
/// prefixed with `.+_info` when all of them only exclude, and `target_info` when there are none.
|
||||
fn effective_name_matchers(matchers: &[(MatchOp, Arc<str>)]) -> Result<Vec<NameMatcher>> {
|
||||
let mut effective = Vec::with_capacity(matchers.len() + 1);
|
||||
if matchers.is_empty() {
|
||||
effective.push(NameMatcher::try_new(
|
||||
MatchOp::Equal,
|
||||
Arc::from("target_info"),
|
||||
)?);
|
||||
} else if matchers
|
||||
.iter()
|
||||
.all(|(op, _)| matches!(op, MatchOp::NotEqual | MatchOp::NotRegex))
|
||||
{
|
||||
effective.push(NameMatcher::try_new(MatchOp::Regex, Arc::from(".+_info"))?);
|
||||
}
|
||||
for (op, value) in matchers {
|
||||
effective.push(NameMatcher::try_new(*op, value.clone())?);
|
||||
}
|
||||
Ok(effective)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,267 @@
|
||||
// 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::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use datatypes::series::samples::{FieldSpec, SampleRef, Series, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridSpec};
|
||||
|
||||
use crate::grid_series::reference::{
|
||||
Labels, OwnedHistogram, Points, labels_of, metric_of, points_of, sparse_series,
|
||||
};
|
||||
use crate::grid_series::{GridSample, GridSeriesBuilder};
|
||||
use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
use crate::info::{InfoSelector, info};
|
||||
use crate::select::MatchOp;
|
||||
|
||||
fn parse_labels(text: &str) -> Labels {
|
||||
text.split(',')
|
||||
.filter(|pair| *pair != "-")
|
||||
.map(|pair| {
|
||||
let (name, value) = pair.split_once('=').unwrap();
|
||||
(name.to_string(), value.to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_points(text: &str) -> Points {
|
||||
text.split_whitespace()
|
||||
.map(|point| {
|
||||
let (index, bits) = point.split_once(':').unwrap();
|
||||
(
|
||||
index.parse().unwrap(),
|
||||
u64::from_str_radix(bits, 16).unwrap(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn list(text: &str) -> Vec<&str> {
|
||||
text.split(';').filter(|item| *item != "-").collect()
|
||||
}
|
||||
|
||||
fn name_matcher(text: &str) -> (MatchOp, Arc<str>) {
|
||||
let rest = text.strip_prefix("__name__").unwrap();
|
||||
let (op, value) = [
|
||||
("=~", MatchOp::Regex),
|
||||
("!~", MatchOp::NotRegex),
|
||||
("!=", MatchOp::NotEqual),
|
||||
("=", MatchOp::Equal),
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|(prefix, op)| rest.strip_prefix(prefix).map(|value| (op, value)))
|
||||
.unwrap();
|
||||
(op, Arc::from(value.trim_matches('"')))
|
||||
}
|
||||
|
||||
/// `info` evaluated by the Prometheus v3.15.0 engine; see the header of `prometheus_cases.txt`.
|
||||
#[test]
|
||||
fn info_matches_prometheus() {
|
||||
let (mut matched, mut failed) = (0, 0);
|
||||
for case in include_str!("prometheus_cases.txt")
|
||||
.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 selector = InfoSelector {
|
||||
data_labels: list(spec[0]).into_iter().map(Arc::from).collect(),
|
||||
keep_unmatched: spec[1] == "true",
|
||||
name_matchers: list(spec[2]).into_iter().map(name_matcher).collect(),
|
||||
};
|
||||
let points: u64 = lines[2].split_whitespace().nth(3).unwrap().parse().unwrap();
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: vec![FieldSpec {
|
||||
name: Arc::from("value"),
|
||||
}]
|
||||
.into(),
|
||||
eval_grid: Some(Arc::new(
|
||||
EvalGrid::try_new(GridSpec::try_new(100_000, 10_000, points).unwrap()).unwrap(),
|
||||
)),
|
||||
});
|
||||
let (mut base, mut infos) = (Vec::new(), Vec::new());
|
||||
let mut expected: BTreeMap<Labels, Points> = BTreeMap::new();
|
||||
let mut error = None;
|
||||
for line in &lines[3..] {
|
||||
if let Some(message) = line.strip_prefix("error ") {
|
||||
error = Some(message.to_string());
|
||||
continue;
|
||||
}
|
||||
let (kind, rest) = line.split_once(' ').unwrap();
|
||||
let (labels, values) = rest.split_once(" ;").unwrap();
|
||||
let (labels, values) = (parse_labels(labels), parse_points(values));
|
||||
match kind {
|
||||
"base" => base.extend(sparse_series(&schema, &labels, &values)),
|
||||
"info" => infos.extend(sparse_series(&schema, &labels, &values)),
|
||||
"result" => {
|
||||
expected.insert(labels, values);
|
||||
}
|
||||
other => panic!("unexpected line {other}"),
|
||||
}
|
||||
}
|
||||
match (info(&schema, &base, &infos, &selector), error) {
|
||||
(Ok(actual), None) => {
|
||||
let mut folded: BTreeMap<Labels, Points> = BTreeMap::new();
|
||||
for series in &actual {
|
||||
folded
|
||||
.entry(labels_of(&series.metric))
|
||||
.or_default()
|
||||
.extend(points_of(series));
|
||||
}
|
||||
assert_eq!(folded, expected, "{case}");
|
||||
matched += 1;
|
||||
}
|
||||
(Err(actual), Some(expected)) => {
|
||||
let class = |message: &str| {
|
||||
[
|
||||
"found duplicate series for info metric",
|
||||
"conflicting label",
|
||||
"same labelset",
|
||||
]
|
||||
.into_iter()
|
||||
.find(|class| message.contains(class))
|
||||
};
|
||||
assert_eq!(class(&actual.to_string()), class(&expected), "{case}");
|
||||
failed += 1;
|
||||
}
|
||||
(actual, expected) => panic!("{case}\ngot {actual:?}, expected error {expected:?}"),
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
matched > 200 && failed > 5,
|
||||
"{matched} matched, {failed} failed"
|
||||
);
|
||||
}
|
||||
|
||||
fn grid_schema(fields: usize) -> Arc<SeriesSchema> {
|
||||
Arc::new(SeriesSchema {
|
||||
fields: (0..fields)
|
||||
.map(|field| FieldSpec {
|
||||
name: Arc::from(format!("f{field}")),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into(),
|
||||
eval_grid: Some(Arc::new(
|
||||
EvalGrid::try_new(GridSpec::try_new(0, 10_000, 1).unwrap()).unwrap(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
fn one_point(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
labels: &[(&str, &str)],
|
||||
row: Vec<Option<GridSample>>,
|
||||
) -> Series {
|
||||
let labels: Labels = labels
|
||||
.iter()
|
||||
.map(|(name, value)| (name.to_string(), value.to_string()))
|
||||
.collect();
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap();
|
||||
builder.push_samples(0, &row).unwrap();
|
||||
builder.finish(metric_of(&labels)).unwrap().unwrap()
|
||||
}
|
||||
|
||||
fn target_info() -> Series {
|
||||
one_point(
|
||||
&grid_schema(1),
|
||||
&[
|
||||
("__name__", "target_info"),
|
||||
("job", "x"),
|
||||
("k8s_cluster", "c1"),
|
||||
],
|
||||
vec![Some(GridSample::Float(0.0))],
|
||||
)
|
||||
}
|
||||
|
||||
fn all_labels() -> InfoSelector {
|
||||
InfoSelector {
|
||||
name_matchers: Vec::new(),
|
||||
data_labels: Vec::new(),
|
||||
keep_unmatched: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each field is a series of its own: two base series that end up with one label set merge where
|
||||
/// they hold different fields, and collide only where both hold the same field.
|
||||
#[test]
|
||||
fn results_with_one_label_set_merge_by_field() {
|
||||
let schema = grid_schema(2);
|
||||
let float = |value| Some(GridSample::Float(value));
|
||||
let enriched = one_point(
|
||||
&schema,
|
||||
&[("__name__", "a"), ("job", "x")],
|
||||
vec![float(1.0), None],
|
||||
);
|
||||
let labelled = |row| {
|
||||
one_point(
|
||||
&schema,
|
||||
&[("__name__", "a"), ("job", "x"), ("k8s_cluster", "c1")],
|
||||
row,
|
||||
)
|
||||
};
|
||||
let merged = info(
|
||||
&schema,
|
||||
&[enriched.clone(), labelled(vec![None, float(2.0)])],
|
||||
&[target_info()],
|
||||
&all_labels(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(merged.len(), 1);
|
||||
let fields: Vec<_> = merged[0]
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| match field.sample(0) {
|
||||
SampleRef::Float(value) => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(fields, [Some(1.0), Some(2.0)]);
|
||||
|
||||
let error = info(
|
||||
&schema,
|
||||
&[enriched, labelled(vec![float(3.0), None])],
|
||||
&[target_info()],
|
||||
&all_labels(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("same labelset"), "{error}");
|
||||
}
|
||||
|
||||
/// A native histogram base sample is enriched like a float one.
|
||||
#[test]
|
||||
fn histogram_base_samples_are_enriched() {
|
||||
let schema = grid_schema(1);
|
||||
let histogram =
|
||||
OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///");
|
||||
let base = one_point(
|
||||
&schema,
|
||||
&[("__name__", "a"), ("job", "x")],
|
||||
vec![Some(GridSample::Histogram(Box::new(
|
||||
FloatHistogram::try_from_view(&histogram.view()).unwrap(),
|
||||
)))],
|
||||
);
|
||||
let output = info(&schema, &[base], &[target_info()], &all_labels()).unwrap();
|
||||
assert_eq!(output.len(), 1);
|
||||
assert_eq!(
|
||||
labels_of(&output[0].metric)
|
||||
.get("k8s_cluster")
|
||||
.map(String::as_str),
|
||||
Some("c1")
|
||||
);
|
||||
assert!(matches!(
|
||||
output[0].fields.as_slice()[0].sample(0),
|
||||
SampleRef::Histogram(_)
|
||||
));
|
||||
}
|
||||
@@ -22,6 +22,7 @@ mod go_sort;
|
||||
mod golden;
|
||||
pub mod grid_series;
|
||||
pub mod histogram_eval;
|
||||
pub mod info;
|
||||
pub mod instant_eval;
|
||||
pub mod map;
|
||||
pub mod map_label;
|
||||
|
||||
@@ -23,6 +23,7 @@ mod go_math;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub(crate) use broadcast::validate_scalar;
|
||||
pub use broadcast::{
|
||||
ScalarFunction, ScalarSeriesOperand, map_arithmetic_series, map_compare_series,
|
||||
map_scalar_function,
|
||||
|
||||
@@ -179,7 +179,10 @@ fn map_grid_scalar(
|
||||
builder.finish(metric)
|
||||
}
|
||||
|
||||
fn validate_scalar<'a>(schema: &SeriesSchema, scalar: &'a Series) -> Result<&'a TimeAxis> {
|
||||
pub(crate) fn validate_scalar<'a>(
|
||||
schema: &SeriesSchema,
|
||||
scalar: &'a Series,
|
||||
) -> Result<&'a TimeAxis> {
|
||||
if scalar.metric.name().is_some() || !scalar.metric.tags().is_empty() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"grid scalar must be unlabelled".into(),
|
||||
|
||||
+1849
-184
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -39,6 +39,7 @@ mod histogram;
|
||||
mod tests;
|
||||
|
||||
pub use function::RangeFunction;
|
||||
pub(crate) use function::quantile;
|
||||
|
||||
/// The samples a range selector reads at evaluation time `T`: source timestamps in
|
||||
/// `(E - range_ms, E]`, where `E` is `T - offset_ms`, or `anchor_ms - offset_ms` with `@`.
|
||||
|
||||
@@ -221,7 +221,7 @@ fn variance(values: &[f64]) -> f64 {
|
||||
}
|
||||
|
||||
/// Prometheus `quantile`, which sorts NaN before every number.
|
||||
fn quantile(q: f64, values: &[f64], sorted: &mut Vec<f64>) -> f64 {
|
||||
pub(crate) fn quantile(q: f64, values: &[f64], sorted: &mut Vec<f64>) -> f64 {
|
||||
if q.is_nan() {
|
||||
return f64::NAN;
|
||||
}
|
||||
|
||||
@@ -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