mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 08:25:29 +00:00
perf(promql): evaluate rate and increase over a batch of windows
`RangeEvaluator` called a boxed `FnMut(FloatWindow) -> Option<f64>` once per grid point per field, building a six-field window struct and appending a row for each. A series of thousands of points therefore made thousands of boxed calls and row appends. The counter functions now take a batch: `BatchKernel` is `FnMut(&FloatWindows, &mut Vec<Option<f64>>)`, selected once outside the loop, and `extrapolated_rate_batch` runs concretely typed per `rate` and `increase`. `FloatWindows` reuses the retained arrays and one sample range per window rather than a copy per window, because a counter function reads only a window's endpoints, sample count and resets. Other functions keep the per-window form and the evaluator falls back to it. This batches the computation only. The results still reach `GridSeriesBuilder` one row at a time, and `flush_batch` reuses the evaluator's row buffer rather than allocating per point. Writing a whole batch as columns needs a column entry point on the builder, which is follow-up work; this commit cannot be read as carrying the whole gain of the experimental branch. A window holding a native histogram sample is decided by the mixed-window rules of `histogram::evaluate`, which read both kinds of sample together and report nothing for a counter over a mixed window. The batch kernel reads the floats alone, so a point whose window holds a histogram flushes what is pending and runs on the per-window path. Without that, a mixed window would report a float rate instead of nothing, and a histogram-only window would lose its histogram result. Tests assert the batch path is the one that ran, since both dispatch shapes produce the same output; a mutation that drops the histogram admission check fails them. Window ranges stay absolute into the retained arrays across a batch, and each accumulated point keeps its own grid index, so a batch spanning a skipped grid point or a chunk boundary still writes the right rows. Signed-off-by: discord9 <discord9@users.noreply.github.com>
This commit is contained in:
@@ -14,6 +14,7 @@
|
||||
|
||||
//! Range-vector window evaluation of raw series onto an evaluation grid.
|
||||
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_query::prometheus::is_prometheus_stale_nan;
|
||||
@@ -65,6 +66,45 @@ pub(crate) struct FloatWindow<'a> {
|
||||
/// Computes one window result; `None` means the window has no result.
|
||||
pub(crate) type WindowKernel = Box<dyn FnMut(FloatWindow<'_>) -> Option<f64> + Send>;
|
||||
|
||||
/// The windows of one field at consecutive grid points, as ranges into the field's retained
|
||||
/// samples.
|
||||
pub(crate) struct FloatWindows<'a> {
|
||||
/// The retained samples, in time order.
|
||||
pub timestamps: &'a [i64],
|
||||
pub values: &'a [f64],
|
||||
/// Counter resets over the retained samples, ascending by position.
|
||||
pub resets: &'a [CounterReset],
|
||||
/// Absolute position of `timestamps[0]`: a reset position is `base` plus a sample index.
|
||||
pub base: u64,
|
||||
/// One range per window, ascending and left-open at the start.
|
||||
pub windows: &'a [Range<usize>],
|
||||
/// The evaluation timestamp of each window.
|
||||
pub eval_ts: &'a [i64],
|
||||
pub range_ms: i64,
|
||||
}
|
||||
|
||||
impl FloatWindows<'_> {
|
||||
/// The resets inside window `index`.
|
||||
///
|
||||
/// `windows` are absolute indices into `timestamps`, so a window whose start has already
|
||||
/// been released still maps to the right reset.
|
||||
pub(crate) fn resets_of(&self, index: usize) -> &[CounterReset] {
|
||||
let span = &self.windows[index];
|
||||
resets_between(
|
||||
self.resets,
|
||||
self.base + span.start as u64,
|
||||
self.base + span.end as u64,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes a batch of one field's windows at once, appending one result per window to `out`.
|
||||
pub(crate) type BatchKernel = Box<dyn FnMut(&FloatWindows<'_>, &mut Vec<Option<f64>>) + Send>;
|
||||
|
||||
/// Grid points accumulated before a batch kernel call. Sized to keep the per-field span and
|
||||
/// column buffers in cache while staying large enough to amortise the call.
|
||||
const EVALUATION_BATCH: usize = 512;
|
||||
|
||||
/// Evaluates range windows over raw series, one series at a time.
|
||||
///
|
||||
/// Each series is pushed as its chunks in order and completes on the chunk marked `is_last`.
|
||||
@@ -90,6 +130,120 @@ pub struct RangeEvaluator {
|
||||
drops_metric_name: bool,
|
||||
/// Raised by the first non-empty window, where Prometheus validates function arguments.
|
||||
window_error: Option<String>,
|
||||
/// The batch form of `function`, when it has one and the input allows it. Present only for
|
||||
/// `Replay::PerPoint`, whose windows advance with the grid; an anchored selector replays one
|
||||
/// window and gains nothing from batching.
|
||||
batch: Option<BatchKernel>,
|
||||
/// Windows accumulated for the next batch call.
|
||||
pending: PendingBatch,
|
||||
/// Batch kernel calls made so far. Test-only: both dispatch shapes produce the same output,
|
||||
/// so a test comparing only output could not tell which one ran.
|
||||
#[cfg(test)]
|
||||
batch_calls: usize,
|
||||
}
|
||||
|
||||
/// Windows accumulated for the next batch call: one list per field.
|
||||
struct PendingBatch {
|
||||
/// Grid index of each accumulated point, ascending.
|
||||
///
|
||||
/// Not assumed contiguous: `evaluate` skips the grid points whose window ends before the
|
||||
/// series has a sample, so a batch can span such a gap and must write each point to its own
|
||||
/// row.
|
||||
indices: Vec<usize>,
|
||||
/// Evaluation timestamp of each accumulated point.
|
||||
eval_ts: Vec<i64>,
|
||||
/// The retained-sample range of each point's window, one list per field.
|
||||
spans: Vec<Vec<Range<usize>>>,
|
||||
/// One output column per field, written by the batch kernel.
|
||||
columns: Vec<Vec<Option<f64>>>,
|
||||
}
|
||||
|
||||
impl PendingBatch {
|
||||
fn with_fields(fields: usize) -> Self {
|
||||
Self {
|
||||
indices: Vec::new(),
|
||||
eval_ts: Vec::new(),
|
||||
spans: vec![Vec::new(); fields],
|
||||
columns: vec![Vec::new(); fields],
|
||||
}
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.eval_ts.len()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.eval_ts.is_empty()
|
||||
}
|
||||
|
||||
/// Drops the accumulated points, keeping the allocations.
|
||||
fn clear_points(&mut self) {
|
||||
self.indices.clear();
|
||||
self.eval_ts.clear();
|
||||
for spans in &mut self.spans {
|
||||
spans.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records one point for the next batch call: its evaluation timestamp and, per field, the range
|
||||
/// of retained samples its window covers.
|
||||
///
|
||||
/// The ranges are relative to the retained samples, so samples dropped before the batch flushes
|
||||
/// would shift them; [`flush_batch`] therefore runs before any `advance`.
|
||||
fn accumulate(pending: &mut PendingBatch, index: usize, eval_ts: i64, fields: &[FieldSamples]) {
|
||||
debug_assert_eq!(pending.spans.len(), fields.len());
|
||||
pending.indices.push(index);
|
||||
pending.eval_ts.push(eval_ts);
|
||||
for (spans, field) in pending.spans.iter_mut().zip(fields) {
|
||||
let end = field.head
|
||||
+ field.timestamps[field.head..].partition_point(|×tamp| timestamp <= eval_ts);
|
||||
spans.push(field.head..end);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the batch kernel over the accumulated points and appends its columns.
|
||||
fn flush_batch(
|
||||
kernel: &mut BatchKernel,
|
||||
pending: &mut PendingBatch,
|
||||
fields: &[FieldSamples],
|
||||
range_ms: i64,
|
||||
row: &mut Vec<Option<GridSample>>,
|
||||
output: &mut GridSeriesBuilder,
|
||||
#[cfg(test)] batch_calls: &mut usize,
|
||||
) -> Result<()> {
|
||||
if pending.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// Counted here rather than at the call site, so the number a test reads is by construction
|
||||
// the number of kernel calls that happened.
|
||||
#[cfg(test)]
|
||||
{
|
||||
*batch_calls += 1;
|
||||
}
|
||||
for (index, field) in fields.iter().enumerate() {
|
||||
// `pending.spans` index the retained arrays absolutely, so no adjustment is needed for
|
||||
// samples `advance` has released: those sit before every span start.
|
||||
let batch = FloatWindows {
|
||||
timestamps: &field.timestamps,
|
||||
values: &field.values,
|
||||
resets: &field.resets,
|
||||
base: field.base,
|
||||
windows: &pending.spans[index],
|
||||
eval_ts: &pending.eval_ts,
|
||||
range_ms,
|
||||
};
|
||||
kernel(&batch, &mut pending.columns[index]);
|
||||
}
|
||||
for (offset, &grid_index) in pending.indices.iter().enumerate() {
|
||||
row.clear();
|
||||
for column in &pending.columns {
|
||||
row.push(column[offset].map(GridSample::Float));
|
||||
}
|
||||
output.push_samples(grid_index, row)?;
|
||||
}
|
||||
pending.clear_points();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct SeriesState {
|
||||
@@ -149,6 +303,15 @@ pub(crate) struct CounterReset {
|
||||
pub previous_value: f64,
|
||||
}
|
||||
|
||||
/// The resets inside the window over the absolute positions `[start, end)`.
|
||||
///
|
||||
/// Left-open: a reset at `start` would add back a sample behind the window.
|
||||
fn resets_between(resets: &[CounterReset], start: u64, end: u64) -> &[CounterReset] {
|
||||
let first = resets.partition_point(|reset| reset.position <= start);
|
||||
let count = resets[first..].partition_point(|reset| reset.position < end);
|
||||
&resets[first..first + count]
|
||||
}
|
||||
|
||||
impl FieldSamples {
|
||||
fn new(index_resets: bool) -> Self {
|
||||
Self {
|
||||
@@ -200,11 +363,7 @@ impl FieldSamples {
|
||||
/// The resets inside the window holding `len` samples from `head`.
|
||||
fn resets_in(&self, len: usize) -> &[CounterReset] {
|
||||
let start = self.base + self.head as u64;
|
||||
let end = start + len as u64;
|
||||
// Left-open: a reset at `start` would add back a sample behind the window.
|
||||
let first = self.resets.partition_point(|reset| reset.position <= start);
|
||||
let count = self.resets[first..].partition_point(|reset| reset.position < end);
|
||||
&self.resets[first..first + count]
|
||||
resets_between(&self.resets, start, start + len as u64)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,6 +410,11 @@ impl RangeEvaluator {
|
||||
evaluator.drops_metric_name = function.drops_metric_name();
|
||||
evaluator.window_error = window_error;
|
||||
evaluator.function = Some(function);
|
||||
// An anchored selector replays one window at every point, so its windows do not advance
|
||||
// with the grid and a batch would only repeat the same call.
|
||||
if matches!(evaluator.replay, Replay::PerPoint) {
|
||||
evaluator.batch = function.batch_kernel();
|
||||
}
|
||||
Ok(evaluator)
|
||||
}
|
||||
|
||||
@@ -299,9 +463,20 @@ impl RangeEvaluator {
|
||||
row: Vec::with_capacity(input.fields.len()),
|
||||
drops_metric_name: false,
|
||||
window_error: None,
|
||||
batch: None,
|
||||
pending: PendingBatch::with_fields(input.fields.len()),
|
||||
#[cfg(test)]
|
||||
batch_calls: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Batch kernel calls made so far. Test-only: both dispatch shapes produce the same output,
|
||||
/// so a test comparing only output could not tell which one ran.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn batch_call_count(&self) -> usize {
|
||||
self.batch_calls
|
||||
}
|
||||
|
||||
/// Schema of the evaluated series: the input fields on the evaluation grid.
|
||||
pub fn output_schema(&self) -> &Arc<SeriesSchema> {
|
||||
&self.output_schema
|
||||
@@ -544,6 +719,45 @@ impl RangeEvaluator {
|
||||
};
|
||||
match self.replay {
|
||||
Replay::PerPoint => {
|
||||
// A window holding a native histogram is decided by the mixed-window rules,
|
||||
// which the batch kernel -- reading floats alone -- cannot reproduce. Flush
|
||||
// what is pending and decide this point on the per-window path.
|
||||
let histogram_window = self.fields.iter().any(|field| {
|
||||
field.histograms[field.histogram_head..]
|
||||
.iter()
|
||||
.any(|(timestamp, _)| i128::from(*timestamp) <= i128::from(eval_ts))
|
||||
});
|
||||
if let Some(kernel) = self.batch.as_mut()
|
||||
&& !histogram_window
|
||||
{
|
||||
accumulate(&mut self.pending, state.cursor, eval_ts, &self.fields);
|
||||
if self.pending.len() >= EVALUATION_BATCH {
|
||||
flush_batch(
|
||||
kernel,
|
||||
&mut self.pending,
|
||||
&self.fields,
|
||||
self.window.range_ms,
|
||||
&mut self.row,
|
||||
&mut self.output,
|
||||
#[cfg(test)]
|
||||
&mut self.batch_calls,
|
||||
)?;
|
||||
}
|
||||
state.cursor += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(kernel) = self.batch.as_mut() {
|
||||
flush_batch(
|
||||
kernel,
|
||||
&mut self.pending,
|
||||
&self.fields,
|
||||
self.window.range_ms,
|
||||
&mut self.row,
|
||||
&mut self.output,
|
||||
#[cfg(test)]
|
||||
&mut self.batch_calls,
|
||||
)?;
|
||||
}
|
||||
evaluator.evaluate(eval_ts, eval_ts, &mut self.row)?;
|
||||
self.output.push_samples(state.cursor, &self.row)?;
|
||||
}
|
||||
@@ -562,6 +776,20 @@ impl RangeEvaluator {
|
||||
}
|
||||
state.cursor += 1;
|
||||
}
|
||||
// The accumulated spans index the retained arrays, which `advance` below rewrites, so the
|
||||
// batch has to flush first.
|
||||
if let Some(kernel) = self.batch.as_mut() {
|
||||
flush_batch(
|
||||
kernel,
|
||||
&mut self.pending,
|
||||
&self.fields,
|
||||
self.window.range_ms,
|
||||
&mut self.row,
|
||||
&mut self.output,
|
||||
#[cfg(test)]
|
||||
&mut self.batch_calls,
|
||||
)?;
|
||||
}
|
||||
for field in &mut self.fields {
|
||||
// After the last window, samples are still ingested so that the overflow and
|
||||
// histogram checks do not depend on how the series is chunked, but none are kept.
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
use crate::functions::{EdgeKind, count_edges, extremum, instant_delta, kahan_inc};
|
||||
use crate::go_sort;
|
||||
use crate::range_eval::{FloatWindow, WindowKernel};
|
||||
use crate::range_eval::{BatchKernel, FloatWindow, FloatWindows, WindowKernel};
|
||||
|
||||
/// A PromQL range-vector function over float and native histogram samples.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -77,6 +77,19 @@ impl RangeFunction {
|
||||
matches!(self, Self::Rate | Self::Increase)
|
||||
}
|
||||
|
||||
/// The batch form of this function, when it has one.
|
||||
///
|
||||
/// Only the counter functions have one. The rest keep the per-window form, which the
|
||||
/// evaluator falls back to, so adding a function here is what changes which shape its
|
||||
/// evaluation takes.
|
||||
pub(crate) fn batch_kernel(self) -> Option<BatchKernel> {
|
||||
match self {
|
||||
Self::Rate => Some(Box::new(extrapolated_rate_batch::<true, true>)),
|
||||
Self::Increase => Some(Box::new(extrapolated_rate_batch::<true, false>)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the kernel computing this function over windows read with `offset_ms`.
|
||||
pub(crate) fn kernel(self, offset_ms: i64) -> WindowKernel {
|
||||
match self {
|
||||
@@ -260,6 +273,50 @@ fn extrapolated_rate<const IS_COUNTER: bool, const IS_RATE: bool>(
|
||||
Some(result * factor)
|
||||
}
|
||||
|
||||
/// The batch form of [`extrapolated_rate`], over consecutive windows of one field at once.
|
||||
///
|
||||
/// Computes exactly what calling the per-window form once per point computes -- same arithmetic,
|
||||
/// same order -- but reaches each window's endpoints straight out of the field's arrays. A rate
|
||||
/// needs only the first and last sample, the sample count and the resets, so no per-window slice
|
||||
/// is built and no window struct crosses a boxed call per grid point.
|
||||
pub(crate) fn extrapolated_rate_batch<const IS_COUNTER: bool, const IS_RATE: bool>(
|
||||
batch: &FloatWindows<'_>,
|
||||
out: &mut Vec<Option<f64>>,
|
||||
) {
|
||||
out.clear();
|
||||
out.reserve(batch.windows.len());
|
||||
for (index, span) in batch.windows.iter().enumerate() {
|
||||
let samples_minus_one = span.len().checked_sub(1).filter(|n| *n > 0);
|
||||
let Some(samples_minus_one) = samples_minus_one else {
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let (start, last) = (span.start, span.end - 1);
|
||||
let (first_t, last_t) = (batch.timestamps[start], batch.timestamps[last]);
|
||||
let first = batch.values[start];
|
||||
let mut result = batch.values[last] - first;
|
||||
if IS_COUNTER {
|
||||
// The same additions in the same order as the per-window form, reached through the
|
||||
// evaluator's per-field reset index.
|
||||
result = batch
|
||||
.resets_of(index)
|
||||
.iter()
|
||||
.fold(result, |result, reset| result + reset.previous_value);
|
||||
}
|
||||
let zero_point = (IS_COUNTER && result > 0.0 && first >= 0.0).then(|| first / result);
|
||||
let factor = extrapolation_factor(
|
||||
(first_t, last_t),
|
||||
samples_minus_one,
|
||||
batch.eval_ts[index],
|
||||
batch.range_ms,
|
||||
IS_COUNTER,
|
||||
IS_RATE,
|
||||
zero_point,
|
||||
);
|
||||
out.push(Some(result * factor));
|
||||
}
|
||||
}
|
||||
|
||||
/// The factor `extrapolatedRate` scales the sampled increase by. `zero_point` is the first
|
||||
/// value over the increase, given only when Prometheus extrapolates a counter to zero.
|
||||
pub(super) fn extrapolation_factor(
|
||||
|
||||
@@ -506,6 +506,102 @@ fn functions_match_range_udfs() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `rate` over a float-only series takes the batch path. The per-window path produces the same
|
||||
/// output, so a test comparing values alone could not tell which one ran.
|
||||
#[test]
|
||||
fn rate_over_floats_is_evaluated_in_batches() {
|
||||
let rows: Vec<Row> = (0..20)
|
||||
.map(|index| (index as i64 * 10_000, vec![Some(index as f64)]))
|
||||
.collect();
|
||||
let mut evaluator = RangeEvaluator::try_new(
|
||||
&raw_schema(1),
|
||||
grid(0, 10_000, 20),
|
||||
RangeWindow {
|
||||
range_ms: 30_000,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
},
|
||||
RangeFunction::Rate,
|
||||
)
|
||||
.unwrap();
|
||||
evaluator.push(&chunk(&rows, 1, 0, true)).unwrap();
|
||||
assert!(
|
||||
evaluator.batch_call_count() > 0,
|
||||
"rate over floats must reach the batch kernel"
|
||||
);
|
||||
}
|
||||
|
||||
/// A window holding a native histogram sample keeps its grid point on the per-window path, since
|
||||
/// the batch kernel reads the floats alone and cannot reproduce the mixed-window rules.
|
||||
///
|
||||
/// The series is laid out so every grid point's window contains the histogram: one point fewer
|
||||
/// than the first test, so no point can fall before it.
|
||||
#[test]
|
||||
fn a_histogram_window_keeps_rate_on_the_per_window_path() {
|
||||
let histogram = "0/0/0/4014000000000000/4014000000000000/1/0_1/4014000000000000///";
|
||||
let mut builder = HistogramBatchBuilder::new();
|
||||
let index = builder
|
||||
.push(OwnedHistogram::parse(histogram).view())
|
||||
.unwrap();
|
||||
let histograms = HistogramSamples::try_new(
|
||||
UInt32Array::from(vec![Some(index), None, None]),
|
||||
builder.finish().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let samples = Samples::try_from_mixed(
|
||||
Float64Array::from(vec![None, Some(1.0), Some(3.0)]),
|
||||
histograms,
|
||||
)
|
||||
.unwrap();
|
||||
let chunk = RawSeriesChunk::try_new(
|
||||
&raw_schema(1),
|
||||
Buffer::from(0u64.to_le_bytes().to_vec()),
|
||||
Some(metric(0)),
|
||||
RawTimestamps::try_new(ScalarBuffer::from(vec![0, 10_000, 20_000])).unwrap(),
|
||||
SeriesFields::try_from_vec(vec![samples]).unwrap(),
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
let mut evaluator = RangeEvaluator::try_new(
|
||||
&raw_schema(1),
|
||||
grid(0, 10_000, 3),
|
||||
RangeWindow {
|
||||
range_ms: 30_000,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
},
|
||||
RangeFunction::Rate,
|
||||
)
|
||||
.unwrap();
|
||||
evaluator.push(&chunk).unwrap();
|
||||
assert_eq!(
|
||||
evaluator.batch_call_count(),
|
||||
0,
|
||||
"every window holds the histogram, so none may reach the batch kernel"
|
||||
);
|
||||
}
|
||||
|
||||
/// A function without a batch form never reaches the batch kernel.
|
||||
#[test]
|
||||
fn a_function_without_a_batch_form_stays_on_the_per_window_path() {
|
||||
let rows: Vec<Row> = (0..10)
|
||||
.map(|index| (index as i64 * 10_000, vec![Some(index as f64)]))
|
||||
.collect();
|
||||
let mut evaluator = RangeEvaluator::try_new(
|
||||
&raw_schema(1),
|
||||
grid(0, 10_000, 10),
|
||||
RangeWindow {
|
||||
range_ms: 30_000,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
},
|
||||
RangeFunction::SumOverTime,
|
||||
)
|
||||
.unwrap();
|
||||
evaluator.push(&chunk(&rows, 1, 0, true)).unwrap();
|
||||
assert_eq!(evaluator.batch_call_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_input_and_series_without_results() {
|
||||
let window = RangeWindow {
|
||||
|
||||
Reference in New Issue
Block a user