mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
refactor(promql): trim native PromQL comments and redundant tests (#10704)
* refactor(promql): trim native PromQL comments and redundant tests Production code is unchanged: only comments change in non-test files. Comments that restated code, narrated history, or cross-referenced other comments are removed; comments that contradicted the code are corrected. Tests that drove the same branch as a surviving test or golden case are removed, and src/promql/AGENTS.md gains comment and test rules. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): preserve recursive map validation coverage Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(promql): preserve empty-close and empty grouping coverage Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
@@ -67,6 +67,19 @@ scan per selector, each carrying a `RawSeriesSource` that answers explicit-label
|
||||
The frame schema is compared exactly at the merge scan, so its declaration and
|
||||
the region's output change together.
|
||||
|
||||
## Comments and tests
|
||||
|
||||
Docs on public items state the contract: inputs, guarantees, errors. Private
|
||||
comments record only what code cannot: Prometheus quirks (name the Prometheus
|
||||
function), memory-accounting preconditions, finality and ordering invariants.
|
||||
Do not restate code, narrate history ("used to", "this change"), or point at
|
||||
other comments. When a comment explains why a state cannot occur, prefer a type
|
||||
that rules it out.
|
||||
|
||||
A new test must catch a concrete failure that existing tests and golden cases
|
||||
would miss: an unreached branch, or a wrong result on a reached one (e.g. the
|
||||
sign of a zero). Kernel values belong in golden cases, not in executor tests.
|
||||
|
||||
## Gotchas
|
||||
|
||||
A series closes exactly once per input series, on the chunk that says so—not
|
||||
|
||||
+124
-334
File diff suppressed because it is too large
Load Diff
@@ -15,15 +15,14 @@
|
||||
//! Partial aggregation: the state one execution partition folds its series into, and the merge
|
||||
//! of such states into the final result.
|
||||
//!
|
||||
//! A merge regroups the operations of a serial fold, so floating-point results differ from
|
||||
//! [`aggregate_float`](crate::aggregate::aggregate_float) by rounding. The same reassociation can
|
||||
//! also move an overflow of finite values: a serial `sum` of `[1e308, 1e308, -1e308]` is `+Inf`,
|
||||
//! while the merge of `[1e308]` and `[1e308, -1e308]` is finite. `stddev` and `stdvar` differ
|
||||
//! more where the samples differ by little more than the rounding of their mean: Prometheus'
|
||||
//! uncompensated Welford update rounds the mean on every sample, and no pairwise merge reproduces
|
||||
//! those roundings. For `[1e16]` and `[1e16 + 2]` Prometheus gives a variance of 2 and the merge
|
||||
//! gives the exact 1. Explicit NaN and infinite inputs follow the same rules as the serial fold. Where the serial fold keeps the first of two equal
|
||||
//! values, as `min` and `max` do for `0` and `-0`, a merge keeps the one merged first.
|
||||
//! A merge reassociates a serial fold, so results can differ from
|
||||
//! [`aggregate_float`](crate::aggregate::aggregate_float) by rounding, and an overflow of finite
|
||||
//! values can move: a serial `sum` of `[1e308, 1e308, -1e308]` is `+Inf`, while the merge of
|
||||
//! `[1e308]` and `[1e308, -1e308]` is finite. `stddev`/`stdvar` differ more for nearly equal
|
||||
//! samples, since Prometheus' uncompensated Welford update rounds the mean on every sample: for
|
||||
//! `[1e16]` and `[1e16 + 2]` Prometheus gives a variance of 2 and the merge the exact 1. Where the
|
||||
//! serial fold keeps the first of two equal values (`min`/`max` on `0` and `-0`), a merge keeps
|
||||
//! the one merged first.
|
||||
|
||||
use std::collections::btree_map::Entry as BTreeEntry;
|
||||
use std::collections::hash_map::Entry;
|
||||
@@ -65,8 +64,8 @@ pub enum StateField {
|
||||
}
|
||||
|
||||
impl AggregateOp {
|
||||
/// The components the state of this aggregation carries; the others are unused and need not
|
||||
/// be stored. `group` has none: a state that exists has a value of 1.
|
||||
/// The components the state of this aggregation carries. `group` has none: a present state
|
||||
/// means 1.
|
||||
pub fn state_fields(self) -> &'static [StateField] {
|
||||
use StateField::*;
|
||||
match self {
|
||||
@@ -81,16 +80,9 @@ impl AggregateOp {
|
||||
}
|
||||
|
||||
/// The state of one field of one group at one grid point.
|
||||
///
|
||||
/// The fold and the frame carry the same five components, so they share one type: the frame's own
|
||||
/// [`AggregateStateValues`] is the definition, and this is the name the aggregate side reads it by.
|
||||
pub use datatypes::series::aggregate_state::AggregateStateValues as AccumulatorState;
|
||||
|
||||
/// The state of one execution partition, with its groups in the order they first appeared.
|
||||
///
|
||||
/// A group is the frame's own [`StateSeries`]: field-major states addressed on that group's sparse
|
||||
/// absolute grid positions. Exporting therefore hands the same representation over instead of
|
||||
/// transposing a second one into it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PartialAggregate {
|
||||
pub op: AggregateOp,
|
||||
@@ -107,14 +99,12 @@ pub struct StateRow {
|
||||
}
|
||||
|
||||
impl FloatAggregator {
|
||||
/// The state folded so far, for a merge with the state of other partitions.
|
||||
/// The state folded so far, for merging with other partitions.
|
||||
pub fn finish_partial(self) -> Result<PartialAggregate> {
|
||||
self.finish_partial_inner()
|
||||
}
|
||||
|
||||
/// [`Self::finish_partial`] that admits what it builds first: the fold state and the groups it
|
||||
/// is exported as, at the exact capacity [`Self::finish_partial_inner`] gives them. A refusal
|
||||
/// consumes the aggregator, so the caller drops the execution.
|
||||
/// [`Self::finish_partial`], admitting the exported groups before building them.
|
||||
pub(crate) fn finish_partial_budgeted(
|
||||
self,
|
||||
mut budget: impl FnMut(usize) -> Result<()>,
|
||||
@@ -122,10 +112,6 @@ impl FloatAggregator {
|
||||
let width = self.schema.fields.len();
|
||||
let mut partial_bytes = self.groups.len().saturating_mul(size_of::<StateSeries>());
|
||||
for group in &self.groups {
|
||||
// A group that folded histograms keeps them in its own map instead of the blocks, so
|
||||
// the points it exports and what each of their payloads builds come from there: the
|
||||
// export builds two one-row Arrow batches per point, which the chunk they are handed
|
||||
// to is charged for only once that chunk exists.
|
||||
let (points, payloads) = if group.histograms.is_empty() {
|
||||
(seen_points(group, width, self.op), 0)
|
||||
} else {
|
||||
@@ -154,11 +140,7 @@ impl FloatAggregator {
|
||||
self.finish_partial_inner()
|
||||
}
|
||||
|
||||
/// Turns the fold into the frame's own groups: field-major states on sparse absolute positions.
|
||||
///
|
||||
/// The blocks are walked once, in ascending position order, so a position's states are appended
|
||||
/// to every field at the same time and adjacent positions coalesce into one span as they come.
|
||||
/// What comes out is the representation the frame writes; no per-point vector is built.
|
||||
/// Turns the fold into field-major states on sparse absolute positions, in one ascending walk.
|
||||
fn finish_partial_inner(self) -> Result<PartialAggregate> {
|
||||
let width = self.schema.fields.len();
|
||||
let grid = self.schema.eval_grid.as_ref().ok_or_else(|| {
|
||||
@@ -173,8 +155,7 @@ impl FloatAggregator {
|
||||
let points = if group.histograms.is_empty() {
|
||||
seen_points(&group, width, op)
|
||||
} else {
|
||||
// A field's state is one family, so a group that kept histogram payloads exports
|
||||
// those: a float state beside them would be one column carrying two kinds.
|
||||
// Same per-group rule as `finish_histogram_group`.
|
||||
if group.blocks.values().any(|states| {
|
||||
states
|
||||
.chunks_exact(op.state_words())
|
||||
@@ -190,8 +171,6 @@ impl FloatAggregator {
|
||||
let mut states: Vec<Vec<Option<StatePayload>>> =
|
||||
(0..width).map(|_| Vec::with_capacity(points)).collect();
|
||||
if !group.histograms.is_empty() {
|
||||
// The histogram fold is keyed by absolute position, and its keys are ordered, so one
|
||||
// pass visits each carried position once with its fields' payloads.
|
||||
let mut position = None;
|
||||
for (&(point, field), accumulator) in &group.histograms {
|
||||
if position != Some(point) {
|
||||
@@ -206,11 +185,7 @@ impl FloatAggregator {
|
||||
}
|
||||
position = Some(point);
|
||||
}
|
||||
// The row just opened is the one this position's payloads belong to. It is the
|
||||
// row the field's states just grew, not the one the span *count* names: adjacent
|
||||
// points share one span while each of them still opens its own row, so a run
|
||||
// index would write every point of the run into the run's first row, leave the
|
||||
// rest empty, and the frame would drop them.
|
||||
// The row just pushed, not the span index: adjacent points share a span.
|
||||
let row = states[field].len() - 1;
|
||||
states[field][row] = Some(accumulator.payload(self.op)?);
|
||||
}
|
||||
@@ -255,7 +230,6 @@ impl FloatAggregator {
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends `position` to `spans`, extending the last run when it continues.
|
||||
fn extend_spans(spans: &mut Vec<GridSpan>, position: usize) {
|
||||
match spans.last_mut() {
|
||||
Some(span) if span.start() + span.len() == position => {
|
||||
@@ -265,25 +239,14 @@ fn extend_spans(spans: &mut Vec<GridSpan>, position: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes one one-row batch of the frame's histogram layout costs before its bucket data.
|
||||
///
|
||||
/// Every column of the layout owns an Arrow array node with its own buffers, and that cost does not
|
||||
/// shrink for a histogram with one bucket: one row measures 2.6 KB whatever the bucket count, which
|
||||
/// is what a payload reports once the batch exists to be measured. It is rounded up here, so a batch
|
||||
/// whose bucket lists land at the top of their buffer capacity is covered too.
|
||||
/// Bytes a one-row histogram batch costs before its bucket data: about 2.6 KB measured regardless
|
||||
/// of bucket count, rounded up to cover buffer capacity slack.
|
||||
pub(super) const HISTOGRAM_LAYOUT_ROW_BYTES: usize = 3 * 1024;
|
||||
|
||||
/// Bytes one exported point's payload builds: the boxed state and the two one-row batches
|
||||
/// [`HistogramAccumulator::payload`] makes from the accumulator's live histogram and its
|
||||
/// compensation.
|
||||
///
|
||||
/// It is counted from the histograms the payload is built from rather than from the batches, which
|
||||
/// is the point: this is what the export admits before those batches exist. The bucket data a batch
|
||||
/// writes is charged at the width of the padded Rust pair, which bounds the `f64` each bucket costs,
|
||||
/// and the layout is charged per batch.
|
||||
/// Bytes [`HistogramAccumulator::payload`] builds for one point, estimated from the accumulator
|
||||
/// so the export can admit it before the two batches exist.
|
||||
pub(super) fn exported_payload_bytes(accumulator: &HistogramAccumulator) -> usize {
|
||||
// The batch the payload builds from the live value is the mean once an average switched, and
|
||||
// the other one is the compensation paired with it: the widest of the three bounds both.
|
||||
// The widest of the three bounds both exported histograms.
|
||||
let widest = [
|
||||
Some(&accumulator.value),
|
||||
accumulator.mean.as_ref(),
|
||||
@@ -301,7 +264,7 @@ pub(super) fn exported_payload_bytes(accumulator: &HistogramAccumulator) -> usiz
|
||||
)
|
||||
}
|
||||
|
||||
/// The points of `group` that carry a state: the ones a partial of it holds.
|
||||
/// The number of points of `group` that carry a float state.
|
||||
fn seen_points(group: &Group, width: usize, op: AggregateOp) -> usize {
|
||||
let words = op.state_words();
|
||||
let point_words = width.saturating_mul(words);
|
||||
@@ -315,9 +278,8 @@ fn seen_points(group: &Group, width: usize, op: AggregateOp) -> usize {
|
||||
})
|
||||
}
|
||||
|
||||
/// Bytes a group's label key holds: a pair per capacity slot, and the `__name__` entry, whose
|
||||
/// label and value `label_key` copies, each with its own `Arc` header. The other label strings are
|
||||
/// the metric's, already counted with it.
|
||||
/// Bytes a group's label key holds beyond the metric: its slots and the `__name__` strings
|
||||
/// `label_key` copies.
|
||||
fn key_bytes(key: &LabelKey) -> usize {
|
||||
let name = key
|
||||
.iter()
|
||||
@@ -333,8 +295,7 @@ fn key_bytes(key: &LabelKey) -> usize {
|
||||
.saturating_add(name)
|
||||
}
|
||||
|
||||
/// Coarse bytes the key of `metric` holds while it is built: a pair per slot, the `__name__` label
|
||||
/// and a copy of the metric name, each with its `Arc` header.
|
||||
/// Bytes the key of `metric` takes while it is built.
|
||||
fn key_workspace_bytes(metric: &SeriesLabels) -> usize {
|
||||
metric
|
||||
.tags()
|
||||
@@ -347,8 +308,8 @@ fn key_workspace_bytes(metric: &SeriesLabels) -> usize {
|
||||
.saturating_add(size_of::<LabelKey>())
|
||||
}
|
||||
|
||||
/// Merges the partial states of one aggregation into its result. Groups are identified by their
|
||||
/// full label set, already grouped by the partitions, and keep the order they first arrive in.
|
||||
/// Merges the partial states of one aggregation into its result. Groups are keyed by their full
|
||||
/// label set and keep their first-arrival order.
|
||||
pub struct FloatMerger {
|
||||
schema: Arc<SeriesSchema>,
|
||||
op: AggregateOp,
|
||||
@@ -373,13 +334,11 @@ impl FloatMerger {
|
||||
})
|
||||
}
|
||||
|
||||
/// Bytes this merge keeps: groups, labels, blocks, B-tree nodes, index table and its keys. Added
|
||||
/// to by the allocations that change it, never recounted.
|
||||
/// Bytes admitted for this merge, maintained incrementally.
|
||||
pub(crate) fn state_bytes(&self) -> usize {
|
||||
self.retained
|
||||
}
|
||||
|
||||
/// What the merged inputs recorded about their points.
|
||||
pub(crate) fn evidence_summary(&self) -> HistogramEvidence {
|
||||
evidence_summary(&self.groups)
|
||||
}
|
||||
@@ -475,12 +434,8 @@ impl FloatMerger {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Merges one Arrow-backed histogram state row: every present field's payload is merged into
|
||||
/// that position's own state.
|
||||
///
|
||||
/// A histogram state is sparse in both directions - a position is carried when any field has a
|
||||
/// contribution there, and a field may be absent at a carried position - so the row is walked
|
||||
/// position by position and each present component is merged where it belongs.
|
||||
/// Merges one histogram state row. A carried position may lack some fields; each carried
|
||||
/// position must have at least one.
|
||||
fn merge_histogram_row(
|
||||
&mut self,
|
||||
row: &StateRow,
|
||||
@@ -537,7 +492,7 @@ impl FloatMerger {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The group this row's labels name, opening it (and its key) on first sight.
|
||||
/// The group `metric` names, opened on first sight.
|
||||
fn open_row_group(
|
||||
&mut self,
|
||||
metric: &SeriesLabels,
|
||||
@@ -576,8 +531,6 @@ impl FloatMerger {
|
||||
0
|
||||
};
|
||||
if vacant {
|
||||
// Admit the state this position is about to hold before allocating it: both histograms
|
||||
// the payload carries and the map node that holds them.
|
||||
let incoming = payload.value.as_arrow().get_array_memory_size()
|
||||
+ payload.compensation.as_arrow().get_array_memory_size();
|
||||
budget(
|
||||
@@ -631,8 +584,7 @@ impl FloatMerger {
|
||||
};
|
||||
let key_live = key_bytes(&key);
|
||||
let metric_live = metric_bytes(&metric);
|
||||
// A realloc that cannot grow in place keeps both buffers alive while it copies, so a
|
||||
// growing step admits the new buffer beside the old one, which `retained` already holds.
|
||||
// A realloc keeps both buffers alive while it copies.
|
||||
budget(
|
||||
self.retained
|
||||
.saturating_add(live)
|
||||
@@ -727,8 +679,7 @@ impl FloatMerger {
|
||||
finish_groups(self.schema, self.op, self.groups)
|
||||
}
|
||||
|
||||
/// [`Self::finish`] that admits the result it builds, on top of what the merge still holds. The
|
||||
/// merge is consumed either way, so a caller that budgets drops it on a refusal.
|
||||
/// [`Self::finish`], admitting the result on top of what the merge still holds.
|
||||
pub(crate) fn finish_budgeted(
|
||||
self,
|
||||
budget: impl FnMut(usize) -> Result<()>,
|
||||
@@ -737,10 +688,8 @@ impl FloatMerger {
|
||||
}
|
||||
}
|
||||
|
||||
/// One present field's histogram state at one position, read from the row's component arrays.
|
||||
///
|
||||
/// The two payload components are decoded into the kernel's own histograms, and the components a
|
||||
/// kind may omit - an average's count and mode flag - default to what the merge would fold from.
|
||||
/// One field's histogram state at one position, or `None` if absent. An average's count and mode
|
||||
/// flag default when the kind omits them.
|
||||
fn histogram_state_at(
|
||||
fields: &StateFieldsBatch,
|
||||
field: usize,
|
||||
@@ -847,10 +796,8 @@ fn missing_payload_component() -> DataFusionError {
|
||||
DataFusionError::Execution("present aggregate state has a missing component".into())
|
||||
}
|
||||
|
||||
/// One present field's state at one position, read from the row's component arrays.
|
||||
///
|
||||
/// The components come from the row's own declaration; the native aggregate caller checks
|
||||
/// compatibility before this runs, so a component list that disagrees is caught before this runs.
|
||||
/// One field's float state at one position, or `None` if absent. The caller has checked the
|
||||
/// component list against the op.
|
||||
fn state_at(
|
||||
fields: &StateFieldsBatch,
|
||||
field: usize,
|
||||
@@ -876,11 +823,7 @@ fn state_at(
|
||||
)
|
||||
})?;
|
||||
}
|
||||
// A histogram state's payload is not numeric components, so this merge cannot read one:
|
||||
// [`FloatMerger::merge_row`] sends a histogram row to `merge_histogram_row`, so a
|
||||
// histogram component reaching here is a row whose kind says numeric and whose payload
|
||||
// says otherwise. Refusing is what keeps a histogram from being folded as the numeric
|
||||
// state it is not.
|
||||
// `merge_row` routes histogram rows elsewhere, so these mean a malformed row.
|
||||
StateComponent::HistogramValue
|
||||
| StateComponent::HistogramCompensation
|
||||
| StateComponent::Poisoned
|
||||
@@ -915,22 +858,18 @@ fn state_at(
|
||||
Ok(Some(state))
|
||||
}
|
||||
|
||||
/// The exported form of the state in `words`, or `None` if it has seen no sample.
|
||||
///
|
||||
/// Only the components the op keeps are filled in; the rest stay at their defaults, exactly as the
|
||||
/// frame that carries them leaves them out.
|
||||
/// The exported form of the state in `words`, or `None` if it has seen no sample. Components the
|
||||
/// op does not keep stay at their defaults.
|
||||
fn state_partial(words: &[f64], op: AggregateOp) -> Option<AccumulatorState> {
|
||||
if !state_seen(words, op) {
|
||||
return None;
|
||||
}
|
||||
Some(match op {
|
||||
// `value`, its compensation, then the presence flag.
|
||||
AggregateOp::Sum => AccumulatorState {
|
||||
value: words[0],
|
||||
compensation: words[1],
|
||||
..Default::default()
|
||||
},
|
||||
// `value`, `compensation`, `mean`, the incremental flag, then the count.
|
||||
AggregateOp::Avg => AccumulatorState {
|
||||
value: words[0],
|
||||
compensation: words[1],
|
||||
@@ -947,7 +886,6 @@ fn state_partial(words: &[f64], op: AggregateOp) -> Option<AccumulatorState> {
|
||||
..Default::default()
|
||||
},
|
||||
AggregateOp::Group => AccumulatorState::default(),
|
||||
// `value`, `mean`, then the count.
|
||||
AggregateOp::Stddev | AggregateOp::Stdvar => AccumulatorState {
|
||||
value: words[0],
|
||||
mean: words[1],
|
||||
@@ -963,7 +901,6 @@ impl<'a> FloatState<'a> {
|
||||
let (op, words) = (self.op, self.words);
|
||||
match op {
|
||||
AggregateOp::Count => words[0] = other.count,
|
||||
// Presence alone, whatever the other side keeps: `group` answers 1 either way.
|
||||
AggregateOp::Group => words[0] = 1.0,
|
||||
AggregateOp::Min | AggregateOp::Max => {
|
||||
words[0] = other.value;
|
||||
@@ -989,7 +926,6 @@ impl<'a> FloatState<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds the state of another partition into this one.
|
||||
fn merge_partial(self, other: &AccumulatorState) {
|
||||
if !state_seen(self.words, self.op) {
|
||||
self.store_partial(other);
|
||||
@@ -1029,10 +965,8 @@ impl<'a> FloatState<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the sums while they stay finite, and otherwise continues with the count-weighted mean, as
|
||||
/// the serial update switches to an incremental mean once its sum overflows.
|
||||
///
|
||||
/// The state words are `value`, `compensation`, `mean`, the incremental flag and the count.
|
||||
/// Adds the sums while they stay finite, otherwise continues with the count-weighted mean, as the
|
||||
/// serial update switches once its sum overflows.
|
||||
fn merge_avg(words: &mut [f64], other: &AccumulatorState) {
|
||||
let count = words[4] + other.count;
|
||||
if words[3] == 0.0 && !other.incremental_mean {
|
||||
@@ -1063,7 +997,7 @@ fn merge_avg(words: &mut [f64], other: &AccumulatorState) {
|
||||
words[4] = count;
|
||||
}
|
||||
|
||||
/// The mean and its compensation, converting a sum as the serial update does on switching.
|
||||
/// The mean and its compensation, converting a sum as the serial update does when switching.
|
||||
fn mean_form(
|
||||
value: f64,
|
||||
compensation: f64,
|
||||
@@ -1078,18 +1012,16 @@ fn mean_form(
|
||||
}
|
||||
}
|
||||
|
||||
/// The compensated sum of two partial sums. Both the other sum and its compensation are added as
|
||||
/// Kahan addends: adding the compensation plainly would drop what the compensation already
|
||||
/// holds once later partials cancel the sums, as merging `[1e100, 1]`, `[-1e100, 1e84]` and
|
||||
/// `[-1e84]` would lose the `1`.
|
||||
/// The compensated sum of two partial sums. The other compensation is a Kahan addend too: adding
|
||||
/// it plainly loses precision once later partials cancel, as merging `[1e100, 1]`,
|
||||
/// `[-1e100, 1e84]` and `[-1e84]` would lose the `1`.
|
||||
fn add_compensated(this: (f64, f64), other: (f64, f64)) -> (f64, f64) {
|
||||
let (value, compensation) = kahan_inc(other.0, this.0, this.1);
|
||||
kahan_inc(other.1, value, compensation)
|
||||
}
|
||||
|
||||
/// Merges `count_values` results of several partitions. Each partial already carries its full
|
||||
/// output label set, value label included, so series with one label set add their counts point
|
||||
/// by point and field by field.
|
||||
/// Merges `count_values` results of several partitions: series with one label set (value label
|
||||
/// included) add their counts per point and field.
|
||||
pub fn merge_count_values(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
partials: impl IntoIterator<Item = Series>,
|
||||
|
||||
@@ -616,22 +616,19 @@ fn incremental_retained_bytes_match_full_recount_for_many_groups() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A state keeps the components its operation folds plus a presence word, which the count already
|
||||
/// provides where the state has one. That is the whole width of a state, so a `max` state costs two
|
||||
/// words where an `avg` state costs five instead of every state costing one fixed struct.
|
||||
/// A state is its exported components plus a presence word, unless the count serves as presence.
|
||||
#[test]
|
||||
fn a_state_is_as_wide_as_the_operation_it_belongs_to() {
|
||||
for (op, words) in [
|
||||
(AggregateOp::Count, 1),
|
||||
(AggregateOp::Group, 1),
|
||||
(AggregateOp::Min, 2),
|
||||
(AggregateOp::Max, 2),
|
||||
(AggregateOp::Sum, 3),
|
||||
(AggregateOp::Stddev, 3),
|
||||
(AggregateOp::Stdvar, 3),
|
||||
(AggregateOp::Avg, 5),
|
||||
for op in [
|
||||
AggregateOp::Count,
|
||||
AggregateOp::Group,
|
||||
AggregateOp::Min,
|
||||
AggregateOp::Max,
|
||||
AggregateOp::Sum,
|
||||
AggregateOp::Stddev,
|
||||
AggregateOp::Stdvar,
|
||||
AggregateOp::Avg,
|
||||
] {
|
||||
assert_eq!(op.state_words(), words, "{op:?}");
|
||||
let counted = op
|
||||
.state_fields()
|
||||
.iter()
|
||||
@@ -695,7 +692,7 @@ fn every_operation_recounts_the_states_it_keeps() {
|
||||
"{op:?} update {index}"
|
||||
);
|
||||
}
|
||||
// Three blocks of two fields, each state as wide as the operation folds it.
|
||||
// The first group wrote two blocks of two fields.
|
||||
let blocks = &aggregator.groups[0].blocks;
|
||||
assert_eq!(blocks.len(), 2, "{op:?} blocks the first group wrote");
|
||||
assert_eq!(
|
||||
@@ -706,39 +703,6 @@ fn every_operation_recounts_the_states_it_keeps() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The unbudgeted entry point is the budgeted one with a no-op budget, so this compares one path
|
||||
/// with itself: it is a smoke check that the wrapper still runs, not evidence that the kernels are
|
||||
/// right. The numbers are checked against Prometheus in `aggregates_match_prometheus` and
|
||||
/// `stat_aggregates_match_prometheus`.
|
||||
#[test]
|
||||
fn every_supported_kind_runs_through_the_unbudgeted_entry_point() {
|
||||
let schema = schema(&["value"]);
|
||||
let series = input(&schema, metric("m", &[]), 0, &[vec![Some(1.0), Some(3.0)]]);
|
||||
for op in [
|
||||
AggregateOp::Sum,
|
||||
AggregateOp::Count,
|
||||
AggregateOp::Avg,
|
||||
AggregateOp::Min,
|
||||
AggregateOp::Max,
|
||||
AggregateOp::Group,
|
||||
AggregateOp::Stddev,
|
||||
AggregateOp::Stdvar,
|
||||
] {
|
||||
let mut plain = FloatAggregator::try_new(&schema, op, Grouping::By(&[])).unwrap();
|
||||
plain.update(&series).unwrap();
|
||||
let plain = plain.finish().unwrap();
|
||||
let mut budgeted =
|
||||
FloatAggregator::try_new_budgeted(&schema, op, Grouping::By(&[]), |_| Ok(())).unwrap();
|
||||
budgeted.update_budgeted(&series, |_| Ok(())).unwrap();
|
||||
let budgeted = budgeted.finish_budgeted(|_| Ok(())).unwrap();
|
||||
assert_eq!(
|
||||
values_of(&plain, 0, 128),
|
||||
values_of(&budgeted, 0, 128),
|
||||
"{op:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_updates_in_one_group_and_block_keep_one_block_charge() {
|
||||
let schema = schema(&["value"]);
|
||||
@@ -767,8 +731,8 @@ fn adjacent_blocks_are_admitted_and_accounted_separately() {
|
||||
.unwrap();
|
||||
assert_eq!(aggregator.groups(), 1);
|
||||
assert_eq!(aggregator.groups[0].blocks.len(), 2);
|
||||
// A new block is admitted on the retained state alone, so the last admission settles at
|
||||
// exactly what the fold keeps and no staging buffer is charged for the samples in it.
|
||||
// A new block is admitted on the retained state alone, so the last admission is exactly what
|
||||
// the fold keeps.
|
||||
let block = block_bytes(schema.fields.len(), AggregateOp::Sum);
|
||||
let (first, second) = (
|
||||
admissions[admissions.len() - 2],
|
||||
@@ -868,9 +832,7 @@ fn a_rejected_later_block_keeps_the_blocks_the_group_already_holds() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The fold admits exactly the figures it reports: a bound equal to the peak it asked for admits
|
||||
/// the whole series, and one byte less refuses it. The staging pass that used to buffer a block's
|
||||
/// samples is gone, so the block no longer costs a buffer beside its states.
|
||||
/// A bound equal to the peak the fold asked for admits the whole series; one byte less refuses it.
|
||||
#[test]
|
||||
fn a_bound_equal_to_the_fold_peak_admits_the_whole_series() {
|
||||
let schema = schema(&["value", "other"]);
|
||||
@@ -970,10 +932,6 @@ fn the_fold_releases_the_series_workspace_before_it_admits_a_block() {
|
||||
/// A chunk admits its workspace and the group it may open in one pool call, releases the
|
||||
/// workspace at the fold entry, and pays for each block it opens: three calls for a chunk that
|
||||
/// falls in one block, four for one that opens two.
|
||||
///
|
||||
/// The fold used to admit the workspace, then a wider bound of it, then the grouping and its key,
|
||||
/// then the new group on top of them: six admissions for a chunk that opens a group and one block,
|
||||
/// seven for one that opens two, on top of the runtime's own resize once the chunk is folded.
|
||||
#[test]
|
||||
fn a_chunk_admits_its_workspace_release_and_blocks_in_three_or_four_calls() {
|
||||
let schema = schema(&["value", "other"]);
|
||||
@@ -1585,11 +1543,7 @@ fn unsupported_shapes_and_mutated_schema_fail_without_partial_output() {
|
||||
Samples::try_from_histogram(UInt32Array::from(vec![None]), batch).unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
// `count` and `group` ask only whether a sample is present, so a histogram is one
|
||||
// contribution for them, `min`/`max` skip it, and `sum`/`avg` fold whatever payload they are
|
||||
// handed -- this column holds no sample at all, so there is nothing for them to fold. No
|
||||
// operation this route folds refuses a histogram series any more; what it does with each sample
|
||||
// is the fold's decision.
|
||||
// No operation refuses a histogram-typed column; this one holds no sample at all.
|
||||
for op in OPS {
|
||||
let answer = aggregate_float(
|
||||
&schema,
|
||||
@@ -1633,59 +1587,7 @@ fn unsupported_shapes_and_mutated_schema_fail_without_partial_output() {
|
||||
assert!(aggregate_float(&raw_schema, &[], AggregateOp::Sum, Grouping::By(&[])).is_err());
|
||||
}
|
||||
|
||||
/// Aggregating a series of several runs folds the positions its axis carries, once each.
|
||||
///
|
||||
/// The rows of a sparse input are not adjacent, so a fold that walked `0..len` and added the
|
||||
/// first position would aggregate the holes as if they were the carried rows.
|
||||
#[test]
|
||||
fn aggregates_fold_a_sparse_axis_by_its_positions() {
|
||||
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1000, 8).unwrap()).unwrap());
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: vec![FieldSpec {
|
||||
name: Arc::from("value"),
|
||||
}]
|
||||
.into(),
|
||||
eval_grid: Some(grid),
|
||||
});
|
||||
let mut points = crate::grid_series::reference::Points::new();
|
||||
for (position, value) in [(1, 1.0), (2, 2.0), (6, 6.0)] {
|
||||
points.insert(position, f64::to_bits(value));
|
||||
}
|
||||
let a = crate::grid_series::reference::sparse_series(
|
||||
&schema,
|
||||
&Labels::from([("host".to_string(), "a".to_string())]),
|
||||
&points,
|
||||
)
|
||||
.unwrap();
|
||||
let mut other = crate::grid_series::reference::Points::new();
|
||||
for (position, value) in [(2, 20.0), (6, 60.0)] {
|
||||
other.insert(position, f64::to_bits(value));
|
||||
}
|
||||
let b = crate::grid_series::reference::sparse_series(
|
||||
&schema,
|
||||
&Labels::from([("host".to_string(), "b".to_string())]),
|
||||
&other,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// `By(&[])`: one group over both series, since their `host` labels differ.
|
||||
let pieces = aggregate_float(&schema, &[a, b], AggregateOp::Sum, Grouping::By(&[])).unwrap();
|
||||
// One group, one piece: the group holds a result at positions 1, 2 and 6.
|
||||
let dense = crate::grid_series::reference::stitch(&pieces);
|
||||
let values = dense
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(position, row)| row[0].map(|value| (position, value)))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(values, vec![(1, 1.0), (2, 22.0), (6, 66.0)]);
|
||||
}
|
||||
|
||||
/// F: an aggregation over inputs of several runs folds the carried positions and reports them as
|
||||
/// the runs they make up, compared in full against the dense reference.
|
||||
///
|
||||
/// Series `a` holds 1, 2 and 6; series `b` holds 2 and 6 with a different value. Their sum is 1 at
|
||||
/// position 1, 22 at 2 and 66 at 6, and the hole at 3..5 is not a row: the result's runs are
|
||||
/// `[(1, 2), (6, 1)]`, not `[(1, 6)]`.
|
||||
/// The hole at 3..5 must not become rows: the sum's runs are `[(1, 2), (6, 1)]`, not `[(1, 6)]`.
|
||||
#[test]
|
||||
fn an_aggregation_of_sparse_inputs_is_compared_in_full_against_the_reference() {
|
||||
use crate::grid_series::reference::{
|
||||
@@ -1746,7 +1648,7 @@ fn an_aggregation_of_sparse_inputs_is_compared_in_full_against_the_reference() {
|
||||
}
|
||||
assert_eq!(stitch(&pieces), expected);
|
||||
|
||||
// `count` keeps the same axis: two inputs hold something at positions 1, 2 and 6.
|
||||
// `count` over `b` alone keeps `b`'s runs.
|
||||
let counts = aggregate_float(&schema, &[b], AggregateOp::Count, Grouping::By(&[]))
|
||||
.expect("one float input");
|
||||
let mut counted: Dense = vec![vec![None]; 8];
|
||||
@@ -2180,10 +2082,8 @@ fn merge_charges_one_block_per_new_block_not_per_point() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_admits_groups_and_blocks_before_it_inserts_them() {
|
||||
fn a_refused_merge_leaves_the_retained_figure_unchanged() {
|
||||
let schema = schema(&["value"]);
|
||||
// A group opens on the first position its row carries, so every row here carries one: the
|
||||
// group, its index slot and its block are each admitted before they are allocated.
|
||||
let one_point =
|
||||
|| TimeAxis::Grid(GridRange::try_new(schema.eval_grid.clone().unwrap(), 0, 1).unwrap());
|
||||
let point = || {
|
||||
@@ -2230,10 +2130,10 @@ fn merge_admits_groups_and_blocks_before_it_inserts_them() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Building a label key copies the metric name, so the copy is admitted before it is made: a
|
||||
/// refusal arrives before the merge touches anything, even for a group and block it already has.
|
||||
/// Building a label key copies the metric name, so the merge admits it even for a group and block
|
||||
/// it already has.
|
||||
#[test]
|
||||
fn merge_admits_the_key_before_it_builds_it() {
|
||||
fn merge_admits_the_key_even_for_an_existing_group() {
|
||||
let schema = schema(&["value"]);
|
||||
let series = input(&schema, metric("m", &[("job", "a")]), 0, &[vec![Some(1.0)]]);
|
||||
let partial = || {
|
||||
@@ -2301,52 +2201,6 @@ fn a_long_metric_name_is_held_by_the_group_and_by_its_key() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The budgeted partial path keeps the numbers of the public one: one partition, so the merged
|
||||
/// result is the serial fold bit for bit, for every supported aggregation.
|
||||
#[test]
|
||||
fn budgeted_partial_state_merges_to_the_public_numbers() {
|
||||
let schema = schema(&["value"]);
|
||||
let series = input(
|
||||
&schema,
|
||||
metric("m", &[]),
|
||||
0,
|
||||
&[vec![Some(1.0), None, Some(3.0), Some(-2.0)]],
|
||||
);
|
||||
for op in [
|
||||
AggregateOp::Sum,
|
||||
AggregateOp::Count,
|
||||
AggregateOp::Avg,
|
||||
AggregateOp::Min,
|
||||
AggregateOp::Max,
|
||||
AggregateOp::Group,
|
||||
AggregateOp::Stddev,
|
||||
AggregateOp::Stdvar,
|
||||
] {
|
||||
let serial = aggregate_float(
|
||||
&schema,
|
||||
std::slice::from_ref(&series),
|
||||
op,
|
||||
Grouping::By(&[]),
|
||||
)
|
||||
.unwrap();
|
||||
let expected = values_of(&serial, 0, 128);
|
||||
let mut aggregator = FloatAggregator::try_new(&schema, op, Grouping::By(&[])).unwrap();
|
||||
aggregator.update(&series).unwrap();
|
||||
let partial = aggregator.finish_partial_budgeted(|_| Ok(())).unwrap();
|
||||
let mut merger = FloatMerger::try_new(&schema, op).unwrap();
|
||||
merge_partial_budgeted(&mut merger, partial.clone(), |_| Ok(())).unwrap();
|
||||
let merged = merger.finish_budgeted(|_| Ok(())).unwrap();
|
||||
assert_eq!(values_of(&merged, 0, 128), expected, "{op:?} budgeted");
|
||||
let mut plain = FloatMerger::try_new(&schema, op).unwrap();
|
||||
merge_partial(&mut plain, partial);
|
||||
assert_eq!(
|
||||
values_of(&plain.finish().unwrap(), 0, 128),
|
||||
expected,
|
||||
"{op:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Partial states merged in any partition and merge order give the serial result, within the
|
||||
/// rounding a regrouped fold may change: the same groups, points and fields, the same NaN and
|
||||
/// infinities. Each partial keeps only the components its aggregation declares, so the layout
|
||||
@@ -2560,7 +2414,7 @@ fn a_merge_rejects_state_that_does_not_fit() {
|
||||
// Another aggregation: its state is not this merge's state.
|
||||
let other = state_row_of(AggregateOp::Avg, partial(AggregateOp::Avg).groups.remove(0));
|
||||
assert!(merger.merge_row(&other, |_| Ok(())).is_err());
|
||||
// More fields than the merge's schema holds: the shape no longer fits.
|
||||
// More fields than the merge's schema holds.
|
||||
let mut wide =
|
||||
FloatAggregator::try_new(&wide_schema, AggregateOp::Sum, Grouping::By(&[])).unwrap();
|
||||
wide.update(&input(
|
||||
@@ -2639,12 +2493,8 @@ fn count_values_keeps_neighbours_of_a_power_of_two_apart() {
|
||||
);
|
||||
}
|
||||
|
||||
/// `count` and `group` ask whether a sample is present, so a histogram is one contribution.
|
||||
///
|
||||
/// Prometheus counts every present sample whatever its type is, and answers `1` for a non-empty
|
||||
/// group. A native histogram therefore counts once - including one that observed nothing - and
|
||||
/// contributes nothing to a group that has no other sample. Every other aggregate reads the value,
|
||||
/// so it must still refuse a histogram rather than count it.
|
||||
/// Prometheus counts every present sample whatever its type, so a histogram counts once, including
|
||||
/// one that observed nothing.
|
||||
#[test]
|
||||
fn count_and_group_count_histogram_samples() {
|
||||
use crate::grid_series::reference::OwnedHistogram;
|
||||
@@ -2732,8 +2582,8 @@ fn count_and_group_count_histogram_samples() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `min`, `max`, `stddev`, `stdvar` and `quantile` read a float value, so a histogram sample is
|
||||
/// skipped rather than refused - and a group holding only histograms has no answer at all.
|
||||
/// `min` and `max` skip a histogram sample rather than refuse it, and a point holding only
|
||||
/// histograms has no answer. `sum` and `avg` refuse a group mixing floats and histograms.
|
||||
#[test]
|
||||
fn value_reading_aggregates_skip_histogram_samples() {
|
||||
use crate::grid_series::reference::OwnedHistogram;
|
||||
@@ -3931,35 +3781,6 @@ fn assert_histogram_close(actual: &HistogramView<'_>, expected: &HistogramView<'
|
||||
}
|
||||
}
|
||||
|
||||
/// Two partitions' sums merge into the answer one fold over both partitions' samples gives.
|
||||
#[test]
|
||||
fn merging_two_partials_answers_the_sum_the_one_fold_answers() {
|
||||
let schema = schema_with_grid_len(&["value"], 1);
|
||||
let sample =
|
||||
|sum: f64| histogram_sample(0, &[(0, 1.0)], &[], 1.0, sum, CounterResetHint::Unknown);
|
||||
let first = [
|
||||
histogram_series(&schema, "a", vec![(0, sample(1.0))]),
|
||||
histogram_series(&schema, "b", vec![(0, sample(2.0))]),
|
||||
];
|
||||
let second = [
|
||||
histogram_series(&schema, "c", vec![(0, sample(3.0))]),
|
||||
histogram_series(&schema, "d", vec![(0, sample(4.0))]),
|
||||
];
|
||||
let both: Vec<Series> = first.iter().chain(&second).cloned().collect();
|
||||
let left = partial_state(AggregateOp::Sum, &schema, &first);
|
||||
let right = partial_state(AggregateOp::Sum, &schema, &second);
|
||||
let merged =
|
||||
merged_histogram_answer(AggregateOp::Sum, &[left, right]).expect("a merged answer");
|
||||
let complete = aggregate_answer(&schema, &both, AggregateOp::Sum);
|
||||
let row = answered_row(&merged);
|
||||
assert_histogram_close(
|
||||
&row.view(0).expect("one answer row"),
|
||||
&answered_histogram(&complete, 0, 0),
|
||||
);
|
||||
assert_eq!(merged.sum, 10.0);
|
||||
assert_eq!(merged.count, 4.0);
|
||||
}
|
||||
|
||||
/// One partition that switched to a mean and one that is still summing merge into the answer one
|
||||
/// fold over both partitions' samples gives.
|
||||
#[test]
|
||||
@@ -4035,119 +3856,6 @@ fn merging_two_overflowing_partials_answers_a_finite_mean() {
|
||||
assert_eq!(value.count, 1.0);
|
||||
}
|
||||
|
||||
/// A mean-path merge weights each side's mean by that side's own count, so partitions of unequal
|
||||
/// size answer the weighted mean and not an average of two means.
|
||||
///
|
||||
/// Both partitions fold only the sample values `2^1023` and `2^1021`, which keeps every step exact:
|
||||
/// the left one overflows on its second sample and switches to a mean of `2^1023` over 2 samples,
|
||||
/// while the right one keeps summing six samples of `2^1021` into `3 * 2^1022`, a mean of `2^1021`
|
||||
/// over 6. Eight samples in all, so the weights are exactly `2/8` and `6/8`, and the answer is
|
||||
/// `2^1023 * 2/8 + 2^1021 * 6/8 = 7 * 2^1019`. Swapping the two weights answers
|
||||
/// `2^1023 * 6/8 + 2^1021 * 2/8 = 13 * 2^1019`, which is why the assertion is on the literal.
|
||||
#[test]
|
||||
fn merging_unequal_mean_partials_weights_each_mean_by_its_count() {
|
||||
let schema = schema_with_grid_len(&["value"], 1);
|
||||
let large = || {
|
||||
histogram_sample(
|
||||
0,
|
||||
&[(0, 1.0)],
|
||||
&[],
|
||||
1.0,
|
||||
2f64.powi(1023),
|
||||
CounterResetHint::Unknown,
|
||||
)
|
||||
};
|
||||
let small = || {
|
||||
histogram_sample(
|
||||
0,
|
||||
&[(0, 1.0)],
|
||||
&[],
|
||||
1.0,
|
||||
2f64.powi(1021),
|
||||
CounterResetHint::Unknown,
|
||||
)
|
||||
};
|
||||
// `2^1023 + 2^1023` is `Inf`, so the left partition's second sample is what forces its switch.
|
||||
let left_input: Vec<Series> = (0..2)
|
||||
.map(|index| histogram_series(&schema, &format!("a{index}"), vec![(0, large())]))
|
||||
.collect();
|
||||
let right_input: Vec<Series> = (0..6)
|
||||
.map(|index| histogram_series(&schema, &format!("b{index}"), vec![(0, small())]))
|
||||
.collect();
|
||||
let left = partial_state(AggregateOp::Avg, &schema, &left_input);
|
||||
let right = partial_state(AggregateOp::Avg, &schema, &right_input);
|
||||
let left_payload = left.groups[0].states[0][0]
|
||||
.as_ref()
|
||||
.and_then(StatePayload::histogram)
|
||||
.expect("a histogram state");
|
||||
assert!(left_payload.incremental_mean, "the left partition switched");
|
||||
assert_eq!(left_payload.count, 2.0);
|
||||
let right_payload = right.groups[0].states[0][0]
|
||||
.as_ref()
|
||||
.and_then(StatePayload::histogram)
|
||||
.expect("a histogram state");
|
||||
assert!(
|
||||
!right_payload.incremental_mean,
|
||||
"the right partition kept its sum"
|
||||
);
|
||||
assert_eq!(right_payload.count, 6.0);
|
||||
// One side switching is enough to put the merge on its mean path.
|
||||
let value = merged_histogram_answer(AggregateOp::Avg, &[left, right]).expect("a merged answer");
|
||||
assert_eq!(
|
||||
value.sum,
|
||||
7.0 * 2f64.powi(1019),
|
||||
"2^1023 * 2/8 + 2^1021 * 6/8, not an average of the two means"
|
||||
);
|
||||
// The observation counts follow the same weights, and both sides average one observation per
|
||||
// sample, so the answer's count stays 1 whatever the weights are.
|
||||
assert_eq!(value.count, 1.0);
|
||||
assert_eq!(value.positive, vec![(0, 1.0)]);
|
||||
}
|
||||
|
||||
/// A poisoned partition poisons the point whatever the other partition holds, and a poisoned point
|
||||
/// answers nothing.
|
||||
#[test]
|
||||
fn a_poisoned_partial_poisons_the_merged_point() {
|
||||
let schema = schema_with_grid_len(&["value"], 1);
|
||||
let exponential = || histogram_sample(0, &[(0, 1.0)], &[], 1.0, 2.0, CounterResetHint::Unknown);
|
||||
let custom = || {
|
||||
histogram_sample(
|
||||
CUSTOM_BUCKETS,
|
||||
&[(0, 1.0)],
|
||||
&[1.0],
|
||||
1.0,
|
||||
3.0,
|
||||
CounterResetHint::Unknown,
|
||||
)
|
||||
};
|
||||
let poisoned = partial_state(
|
||||
AggregateOp::Sum,
|
||||
&schema,
|
||||
&[
|
||||
histogram_series(&schema, "a", vec![(0, exponential())]),
|
||||
histogram_series(&schema, "b", vec![(0, custom())]),
|
||||
],
|
||||
);
|
||||
let legal = partial_state(
|
||||
AggregateOp::Sum,
|
||||
&schema,
|
||||
&[histogram_series(&schema, "c", vec![(0, exponential())])],
|
||||
);
|
||||
for order in [
|
||||
[poisoned.clone(), legal.clone()],
|
||||
[legal.clone(), poisoned.clone()],
|
||||
] {
|
||||
let merged = merged_histogram_answer(AggregateOp::Sum, &order);
|
||||
assert!(
|
||||
merged.is_none(),
|
||||
"a poisoned point answers nothing, whichever side poisoned it"
|
||||
);
|
||||
let evidence = merged_histogram_evidence(AggregateOp::Sum, &order);
|
||||
assert!(evidence.poisoned);
|
||||
assert!(evidence.incompatible_layout);
|
||||
}
|
||||
}
|
||||
|
||||
/// Which partition arrived first does not change what the merge reports: a reconciliation between
|
||||
/// two partitions is reported whichever way the pair is merged.
|
||||
#[test]
|
||||
|
||||
+10
-40
@@ -18,38 +18,23 @@ use datafusion::error::{DataFusionError, Result};
|
||||
use datatypes::series::samples::Series;
|
||||
use datatypes::series::time::GridRange;
|
||||
|
||||
/// One slice of one evaluated series: the rows holding a value that its evaluator handed over at
|
||||
/// once, which may form several runs of consecutive positions.
|
||||
/// One slice of one evaluated series, addressed on absolute grid positions.
|
||||
///
|
||||
/// The series' [`TimeAxis`](datatypes::series::time::TimeAxis) covers the positions this chunk
|
||||
/// holds, and those positions are absolute on the grid: a consumer that concatenates the chunks of
|
||||
/// a series never reorders them, and never has to translate a chunk-local row number into a grid
|
||||
/// position. The rows of one chunk need not be adjacent -- a sparse chunk says which positions it
|
||||
/// holds through [`TimeAxis::positions`](datatypes::series::time::TimeAxis::positions) -- so a
|
||||
/// consumer reads them with that traversal instead of indexing from the first position.
|
||||
///
|
||||
/// A chunk carries only positions that hold a value. A position no chunk carries either holds no
|
||||
/// value or has not been decided yet, and a consumer cannot tell the two apart, so it must not
|
||||
/// infer progress from the last row it saw: only `is_last` says the series is complete. The gaps
|
||||
/// this leaves between the chunks of a series are what keeps a sparse series from costing a row
|
||||
/// per empty position. A single field may still hold a null at a position another field fills,
|
||||
/// since the fields of one chunk are row-aligned.
|
||||
///
|
||||
/// A series closes exactly once, on the chunk that carries `is_last`. A closed prefix is followed
|
||||
/// by a closing chunk when nothing is left, even when that chunk holds no values, so a consumer
|
||||
/// can tell "nothing more here" from "no more input".
|
||||
/// A chunk carries only positions where some field holds a value (another field may be null
|
||||
/// there), and its rows need not be adjacent; read them
|
||||
/// through [`TimeAxis::positions`](datatypes::series::time::TimeAxis::positions). A position no
|
||||
/// chunk carries is either empty or not decided yet, so only `is_last` says the series is
|
||||
/// complete. A series closes exactly once, and a closing chunk is emitted even when it holds no
|
||||
/// values.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EvaluatedChunk {
|
||||
/// The evaluated values, addressed on their absolute grid positions.
|
||||
pub series: Series,
|
||||
/// Whether this is the final chunk of this series.
|
||||
pub is_last: bool,
|
||||
}
|
||||
|
||||
impl EvaluatedChunk {
|
||||
/// Wraps `series`, checking that it is addressed on a grid.
|
||||
/// Errors when `series` is not addressed on a grid.
|
||||
pub fn try_new(series: Series, is_last: bool) -> Result<Self> {
|
||||
// Both grid axes are addressed on the grid; the explicit axes are not.
|
||||
if series.time.grid().is_none() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"an evaluated chunk must be addressed on a grid".to_string(),
|
||||
@@ -58,19 +43,9 @@ impl EvaluatedChunk {
|
||||
Ok(Self { series, is_last })
|
||||
}
|
||||
|
||||
/// The absolute grid range this chunk holds rows for, when its rows form one run.
|
||||
///
|
||||
/// Ranges of one series never go backwards and never overlap, and they need not be adjacent:
|
||||
/// the positions between two chunks either hold no value or have not been decided yet. An
|
||||
/// empty range is meaningful: it reports that the chunk closed the series without holding a
|
||||
/// row of its own.
|
||||
///
|
||||
/// `None` means the chunk holds several runs: it is addressed on a grid, but its rows are not
|
||||
/// one range, and reading the positions between them would read holes. Walk the axis instead
|
||||
/// ([`TimeAxis::positions`](datatypes::series::time::TimeAxis::positions)).
|
||||
/// The grid range of this chunk's rows, or `None` when they form several runs. Ranges of one
|
||||
/// series never go backwards or overlap; an empty range is a close without rows.
|
||||
pub fn range(&self) -> Option<&GridRange> {
|
||||
// `try_new` rejects everything but a grid axis, and `series` is public, so a chunk built
|
||||
// by struct literal is answered from the axis rather than trusted.
|
||||
self.series.time.as_grid_range()
|
||||
}
|
||||
}
|
||||
@@ -101,7 +76,6 @@ mod tests {
|
||||
SeriesLabels::try_new(Some("requests".into()), Vec::new()).unwrap()
|
||||
}
|
||||
|
||||
/// `values` are the floats this chunk finished evaluating; `start` is their absolute offset.
|
||||
fn chunk(
|
||||
schema: &SeriesSchema,
|
||||
start: usize,
|
||||
@@ -119,8 +93,6 @@ mod tests {
|
||||
EvaluatedChunk::try_new(series, is_last).unwrap()
|
||||
}
|
||||
|
||||
/// A chunk without values is still a chunk: it is how a closed prefix is reported, and a
|
||||
/// consumer needs it to tell "nothing more here" from "no more input".
|
||||
#[test]
|
||||
fn a_chunk_can_cover_no_positions() {
|
||||
let schema = schema();
|
||||
@@ -137,7 +109,6 @@ mod tests {
|
||||
assert!(chunk.is_last);
|
||||
}
|
||||
|
||||
/// The range is absolute, so concatenating two chunks of one series never reorders them.
|
||||
#[test]
|
||||
fn a_range_is_absolute_on_its_grid() {
|
||||
let schema = schema();
|
||||
@@ -151,7 +122,6 @@ mod tests {
|
||||
assert_eq!((second.start(), second.len()), (2, 2));
|
||||
}
|
||||
|
||||
/// A chunk that is not addressed on a grid cannot be indexed by a consumer.
|
||||
#[test]
|
||||
fn a_chunk_must_be_addressed_on_a_grid() {
|
||||
let samples = Samples::from_float(Float64Array::from(vec![1.0]));
|
||||
|
||||
+38
-131
@@ -85,12 +85,11 @@ pub(crate) fn segment_bytes(segment: &Samples) -> usize {
|
||||
.get_array_memory_size()
|
||||
.saturating_add(mixed.histograms().indices().get_array_memory_size())
|
||||
.saturating_add(table_bytes(mixed.histograms().batch())),
|
||||
// `segments` hands out dense segments only, so a nested chunk never reaches here.
|
||||
// `segments` yields dense segments only.
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes one histogram table holds: the batch struct and the arrays its columns view.
|
||||
pub(crate) fn table_bytes(table: &Arc<HistogramBatch>) -> usize {
|
||||
std::mem::size_of::<HistogramBatch>().saturating_add(table.as_arrow().get_array_memory_size())
|
||||
}
|
||||
@@ -99,35 +98,21 @@ pub(crate) fn field_builder_bytes(width: usize) -> usize {
|
||||
width.saturating_mul(std::mem::size_of::<FieldBuilder>())
|
||||
}
|
||||
|
||||
/// Builds one grid series from rows pushed at absolute grid indices.
|
||||
/// Builds one grid series from rows pushed at increasing absolute grid indices.
|
||||
///
|
||||
/// A push names one position and the value each field holds there. Rows are accumulated
|
||||
/// compactly: a row is kept only when at least one field holds a value at that position, so an
|
||||
/// empty stretch costs one skipped push and no storage at all. Fields stay row-aligned, so a field
|
||||
/// with no value at a retained row still gets a null there; the Arrow layout needs one row per
|
||||
/// retained position, and the position does hold a value.
|
||||
/// A row is kept only when at least one field holds a value; a field without a value at a kept row
|
||||
/// gets a null. The rows are handed out as one [`Series`] whose [`TimeAxis`] names their maximal
|
||||
/// runs, so positions without a value cost nothing.
|
||||
///
|
||||
/// [`GridSeriesBuilder::finish`] hands out all the buffered rows as **one** [`Series`], whose
|
||||
/// [`TimeAxis`] names the maximal runs of consecutive positions the rows make up. The rows are not
|
||||
/// densified: the axis says where they sit, so a series over two far-apart positions costs two rows
|
||||
/// and two spans, not a row per position between them.
|
||||
///
|
||||
/// A builder serves one series at a time. [`GridSeriesBuilder::begin_series`] starts the next one;
|
||||
/// nothing else resets the series state, so [`GridSeriesBuilder::take_buffered`] can hand out the
|
||||
/// rows gathered so far and let the same series go on.
|
||||
/// A builder serves one series at a time; only [`GridSeriesBuilder::begin_series`] resets it.
|
||||
pub struct GridSeriesBuilder {
|
||||
schema: Arc<SeriesSchema>,
|
||||
grid: Arc<EvalGrid>,
|
||||
/// Smallest index the next push may use.
|
||||
next: usize,
|
||||
/// Grid index of each retained row, ascending.
|
||||
///
|
||||
/// This vector is the only record of where the gaps are, and it says only where rows sit:
|
||||
/// with `V` entries, `F` fields and `k` runs (`k <= V`) the whole series costs `8*F*V` value
|
||||
/// bytes plus validity bits, one `usize` per retained row and `O(k)` run descriptors. Nothing
|
||||
/// is proportional to the positions holding no value.
|
||||
indices: Vec<usize>,
|
||||
/// One row per retained row, per field; empty when nothing is buffered.
|
||||
/// Empty until the first retained row of a hand-out.
|
||||
fields: Vec<FieldBuilder>,
|
||||
}
|
||||
|
||||
@@ -164,7 +149,7 @@ pub(crate) fn owned(sample: SampleRef<'_>) -> Result<Option<GridSample>> {
|
||||
}
|
||||
|
||||
impl GridSeriesBuilder {
|
||||
/// Creates a builder for series of `schema`, which must have an evaluation grid.
|
||||
/// Errors when `schema` has no evaluation grid.
|
||||
pub fn try_new(schema: Arc<SeriesSchema>) -> Result<Self> {
|
||||
let grid = schema.eval_grid.clone().ok_or_else(|| {
|
||||
DataFusionError::Execution("grid series schema requires an evaluation grid".into())
|
||||
@@ -180,8 +165,8 @@ impl GridSeriesBuilder {
|
||||
|
||||
/// Reserves capacity for the exact number of valued rows in the next series.
|
||||
///
|
||||
/// Call after `begin_series` and before its first push. Existing public callers may continue
|
||||
/// to rely on normal growth; callers with a budget can reserve the concrete row capacity first.
|
||||
/// Call after `begin_series` and before its first push; callers that skip it rely on normal
|
||||
/// growth.
|
||||
pub(crate) fn reserve_rows(&mut self, rows: usize) -> Result<()> {
|
||||
self.indices
|
||||
.try_reserve_exact(rows.saturating_sub(self.indices.len()))
|
||||
@@ -210,7 +195,7 @@ impl GridSeriesBuilder {
|
||||
|
||||
/// Pushes the field values at absolute grid `index`; `None` is a missing value.
|
||||
///
|
||||
/// Indices must be strictly increasing; skipped indices are positions that hold no value.
|
||||
/// Errors unless indices strictly increase within the grid and `values` has one entry per field.
|
||||
pub fn push(&mut self, index: usize, values: &[Option<f64>]) -> Result<()> {
|
||||
if !self.start_row(index, values.len(), values.iter().all(Option::is_none))? {
|
||||
return Ok(());
|
||||
@@ -243,13 +228,8 @@ impl GridSeriesBuilder {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Like [`GridSeriesBuilder::push_samples`], with the values taken as the fields hand them out.
|
||||
///
|
||||
/// A histogram value goes into its column straight from the view it was read as: the owned
|
||||
/// form beside this builder exists for the paths that compute a histogram, while a selection
|
||||
/// that only hands a sample on has nothing to compute and copies nothing. The row this writes
|
||||
/// and the row [`GridSeriesBuilder::push_samples`] writes are the same, so a value pushed
|
||||
/// either way leaves the same payload.
|
||||
/// Like [`GridSeriesBuilder::push_samples`], copying histograms from their views without an
|
||||
/// owned intermediate.
|
||||
pub(crate) fn push_refs(&mut self, index: usize, values: &[SampleRef<'_>]) -> Result<()> {
|
||||
if !self.start_row(
|
||||
index,
|
||||
@@ -291,8 +271,6 @@ impl GridSeriesBuilder {
|
||||
}
|
||||
self.next = index + 1;
|
||||
if empty {
|
||||
// A position holding no value anywhere is not a row: an index absent from `indices`
|
||||
// already says exactly that, so writing it down would only cost storage.
|
||||
return Ok(false);
|
||||
}
|
||||
if self.fields.is_empty() {
|
||||
@@ -302,23 +280,14 @@ impl GridSeriesBuilder {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Whether rows have been pushed that no caller has taken yet.
|
||||
///
|
||||
/// Every hand-out drains the buffer, so "rows buffered" and "rows a caller has not taken" are
|
||||
/// the same thing: a `true` here means the next [`Self::finish`] or [`Self::take_buffered`] has
|
||||
/// something to return.
|
||||
/// Whether the next [`Self::finish`] or [`Self::take_buffered`] has rows to return.
|
||||
pub fn has_pending(&self) -> bool {
|
||||
!self.indices.is_empty()
|
||||
}
|
||||
|
||||
/// Starts the series the following pushes belong to.
|
||||
/// Starts the series the following pushes belong to and resets the index cursor.
|
||||
///
|
||||
/// This is the only place that resets the series state, so it is the logical-series boundary:
|
||||
/// [`Self::finish`] hands the rows out but resets nothing, and [`Self::take_buffered`]
|
||||
/// deliberately does not reset anything either.
|
||||
///
|
||||
/// Panics in debug builds when rows are still pending, which means the previous series was
|
||||
/// left unread.
|
||||
/// Panics in debug builds when rows of the previous series are still pending.
|
||||
pub fn begin_series(&mut self) {
|
||||
debug_assert!(
|
||||
!self.has_pending(),
|
||||
@@ -329,30 +298,21 @@ impl GridSeriesBuilder {
|
||||
self.fields.clear();
|
||||
}
|
||||
|
||||
/// Hands out every row buffered so far as one series, without ending the series.
|
||||
/// Hands out the rows pushed since the last hand-out as one [`Series`], or `None` when there
|
||||
/// are none. The index cursor is kept, so later pushes continue the same series.
|
||||
///
|
||||
/// This is a prefix flush: the rows pushed since the last hand-out become one [`Series`] whose
|
||||
/// axis names the runs they make up. `None` means nothing is buffered, and the caller may push
|
||||
/// more rows. Later pushes still belong to the same logical series, so the caller keeps the
|
||||
/// metric and reads the next hand-out as a continuation rather than as a new series.
|
||||
///
|
||||
/// Nothing is reset: not the metric, not the index cursor, not the position order. A caller
|
||||
/// that wants a new series calls [`Self::begin_series`].
|
||||
/// Same as [`Self::finish`]; the name marks a prefix flush at the call site.
|
||||
pub fn take_buffered(&mut self, metric: SeriesLabels) -> Result<Option<Series>> {
|
||||
self.collect(metric)
|
||||
}
|
||||
|
||||
/// Returns the series the pushed rows make up: one [`Series`] over the runs of consecutive
|
||||
/// positions that hold a value, or `None` when no retained row holds one.
|
||||
///
|
||||
/// The rows share the one buffer per field, so the result costs a span per run and not a row
|
||||
/// per position between the runs. This ends the logical series; the next one starts with
|
||||
/// [`Self::begin_series`], which is the only reset.
|
||||
/// Hands out the rows pushed since the last hand-out as one [`Series`], or `None` when there
|
||||
/// are none. Same as [`Self::take_buffered`]: neither resets the index cursor, so a caller
|
||||
/// starting another series calls [`Self::begin_series`].
|
||||
pub fn finish(&mut self, metric: SeriesLabels) -> Result<Option<Series>> {
|
||||
self.collect(metric)
|
||||
}
|
||||
|
||||
/// Turns the buffered rows into one series over the runs they make up.
|
||||
fn collect(&mut self, metric: SeriesLabels) -> Result<Option<Series>> {
|
||||
if self.indices.is_empty() {
|
||||
return Ok(None);
|
||||
@@ -377,8 +337,6 @@ impl GridSeriesBuilder {
|
||||
samples.push(sample);
|
||||
}
|
||||
let fields = SeriesFields::try_from_vec(samples).map_err(external)?;
|
||||
// The runs are all the axis has to remember about the gaps, and the rows are already
|
||||
// compact, so no position holding no value is visited or stored.
|
||||
let run_count = count_runs(&indices);
|
||||
let spans = spans_of(&indices, run_count)?;
|
||||
let time = TimeAxis::from_grid_spans(self.grid.clone(), spans).map_err(external)?;
|
||||
@@ -388,7 +346,7 @@ impl GridSeriesBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cuts the retained indices into maximal runs of consecutive positions.
|
||||
/// Counts the maximal runs of consecutive positions in ascending `indices`.
|
||||
fn count_runs(indices: &[usize]) -> usize {
|
||||
indices
|
||||
.windows(2)
|
||||
@@ -431,8 +389,7 @@ impl FieldBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the value columns of a row holding a histogram, opening the histogram column if this
|
||||
/// is its first value, and hands back the column the new row's index still goes into.
|
||||
/// Writes the float side of a histogram row and returns the column its index goes into.
|
||||
fn start_histogram(&mut self) -> &mut HistogramColumn {
|
||||
self.values.push(0.0);
|
||||
self.nulls.append(false);
|
||||
@@ -476,15 +433,10 @@ pub(crate) fn label_set(metric: &SeriesLabels) -> LabelSet {
|
||||
}
|
||||
|
||||
/// Merges series that share a label set into one, as Prometheus does after a function that
|
||||
/// rewrites labels or drops `__name__`; two of them holding one field at one point fail, whether
|
||||
/// the samples are floats or native histograms.
|
||||
/// rewrites labels or drops `__name__`. Errors when two of them hold the same field at one point.
|
||||
///
|
||||
/// The merge rearranges the payloads instead of rewriting them: a merged row takes the value its
|
||||
/// member carries at that position -- a float, a NaN, or a native histogram -- and a field another
|
||||
/// field's row does not fill keeps a null there. The values keep their storage: a run of rows one
|
||||
/// member holds in one dense segment is handed out as a [`Samples::slice`] of that segment, so a
|
||||
/// histogram table is shared rather than copied. The result costs one row per position holding a
|
||||
/// value, plus the rows the other fields fill, and nothing for a position of the grid holding none.
|
||||
/// Values are sliced from their segments rather than copied. Merged series keep the order of their
|
||||
/// first member; the first member's metric names the result.
|
||||
pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> Result<Vec<Series>> {
|
||||
let mut groups: HashMap<LabelSet, Vec<usize>> = HashMap::with_capacity(series.len());
|
||||
let mut collided = false;
|
||||
@@ -503,31 +455,22 @@ pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> R
|
||||
return Ok(series);
|
||||
}
|
||||
|
||||
// The merged axis and the fields placed on it are the schema's grid: a member of another grid
|
||||
// would land its rows at positions naming other timestamps.
|
||||
let grid = schema.eval_grid.clone().ok_or_else(|| {
|
||||
DataFusionError::Execution("grid series schema requires an evaluation grid".into())
|
||||
})?;
|
||||
let mut series: Vec<Option<Series>> = series.into_iter().map(Some).collect();
|
||||
let mut output = Vec::with_capacity(groups.len());
|
||||
// The groups in the order their first member arrived: a `HashMap` would hand the merged series
|
||||
// back in an order that changes between runs, and the root's chunk stream exposes exactly this
|
||||
// order, so two executions of one query could report their series differently.
|
||||
// Order by first member so the output order is deterministic across runs.
|
||||
let mut groups: Vec<(LabelSet, Vec<usize>)> = groups.into_iter().collect();
|
||||
groups.sort_unstable_by_key(|(_, members)| members[0]);
|
||||
// `(absolute position, member slot, compact row)`, sorted by position before merging. The slot
|
||||
// indexes the group's fragments, so a row names its member without a search.
|
||||
// `(absolute position, member slot, compact row)`.
|
||||
let mut rows: Vec<(usize, usize, usize)> = Vec::new();
|
||||
// The position of each merged row, ascending, with the positions several fragments share held
|
||||
// once.
|
||||
let mut positions: Vec<usize> = Vec::new();
|
||||
for (labels, members) in groups {
|
||||
if let [member] = members[..] {
|
||||
output.extend(series[member].take());
|
||||
continue;
|
||||
}
|
||||
// Validate every fragment before indexing it: the merge reads its fields and places its
|
||||
// rows on the schema's grid.
|
||||
let mut fragments: Vec<&Series> = Vec::with_capacity(members.len());
|
||||
for &member in &members {
|
||||
let fragment = series[member].as_ref().ok_or_else(|| {
|
||||
@@ -550,8 +493,6 @@ pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> R
|
||||
fragment.fields.len()
|
||||
)));
|
||||
}
|
||||
// The alignment is checked before a row is read: a field of another length would either
|
||||
// run off the axis or leave values the axis never reaches.
|
||||
let time_len = fragment.time.len();
|
||||
if let Some((field, samples)) = fragment
|
||||
.fields
|
||||
@@ -569,8 +510,6 @@ pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> R
|
||||
}
|
||||
rows.clear();
|
||||
for (member_slot, fragment) in fragments.iter().enumerate() {
|
||||
// One forward reader per field: the axis names the rows that exist, and a row holding
|
||||
// no value in any field is not a merged row.
|
||||
let mut readers: Vec<FieldReader<'_>> =
|
||||
fragment.fields.iter().map(FieldReader::new).collect();
|
||||
for (position, row) in fragment.time.positions() {
|
||||
@@ -584,8 +523,7 @@ pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> R
|
||||
}
|
||||
}
|
||||
}
|
||||
// By position, then by member slot: the slots follow the order the fragments were collected
|
||||
// in, so a member's rows only go forward and its readers never go back.
|
||||
// Within one member, rows stay ascending, so its `FieldReader`s only move forward.
|
||||
rows.sort_unstable();
|
||||
positions.clear();
|
||||
positions.extend(rows.iter().map(|&(position, _, _)| position));
|
||||
@@ -598,42 +536,31 @@ pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> R
|
||||
.collect();
|
||||
fields.push(merge_field(&mut readers, &rows, &labels)?);
|
||||
}
|
||||
// The runs are all the axis remembers about the holes, so a sparse merge stores one span
|
||||
// per run and no row for the positions between them.
|
||||
let time =
|
||||
TimeAxis::from_grid_spans(grid.clone(), spans_of(&positions, count_runs(&positions))?)
|
||||
.map_err(external)?;
|
||||
let fields = SeriesFields::try_from_vec(fields).map_err(external)?;
|
||||
// The first fragment names the output, as it always has: a label set ignores empty values,
|
||||
// so the metric of the first member is the one the merged series keeps.
|
||||
// Members may differ in empty-valued labels; the first member's metric is kept.
|
||||
let metric = fragments[0].metric.clone();
|
||||
output.push(Series::try_new(schema, metric, time, fields).map_err(external)?);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Builds one field of the merged series, one sample per merged row.
|
||||
///
|
||||
/// The rows are walked in output order. A row holding a value of this field in one member continues
|
||||
/// the run of rows that member holds in one dense segment, and a run is handed out as one
|
||||
/// [`Samples::slice`]; the rows another field fills become one null run, so the field stays aligned
|
||||
/// with the merged axis while sharing the values it carries.
|
||||
/// Builds one field of the merged series, one sample per merged position: slices of member segments
|
||||
/// for values, null runs for positions only other fields fill.
|
||||
fn merge_field(
|
||||
readers: &mut [FieldReader<'_>],
|
||||
rows: &[(usize, usize, usize)],
|
||||
labels: &LabelSet,
|
||||
) -> Result<Samples> {
|
||||
let mut chunks: Vec<Samples> = Vec::new();
|
||||
// The run of values the last merged row continued, if any.
|
||||
let mut run: Option<FieldRun<'_>> = None;
|
||||
// Merged rows this field leaves empty, waiting for the null run that carries them.
|
||||
let mut missing = 0;
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let position = rows[start].0;
|
||||
let mut end = start;
|
||||
// At most one member may hold this field here; the second value is the collision Prometheus
|
||||
// rejects, since the two label sets became one.
|
||||
let mut value: Option<(usize, &Samples, usize)> = None;
|
||||
while end < rows.len() && rows[end].0 == position {
|
||||
let (_, member, row) = rows[end];
|
||||
@@ -688,32 +615,21 @@ fn merge_field(
|
||||
Samples::try_from_chunks(chunks).map_err(external)
|
||||
}
|
||||
|
||||
/// A run of merged rows one member field fills out of one dense segment, without copying values.
|
||||
///
|
||||
/// The run grows only while the next merged row is the same member's next row in the same segment,
|
||||
/// so handing it out is one [`Samples::slice`] of that segment: the payload stays where it is, and
|
||||
/// the rows a hole skipped are not part of the run.
|
||||
/// Consecutive rows of one member's dense segment, handed out as one [`Samples::slice`].
|
||||
struct FieldRun<'a> {
|
||||
/// The member slot the run reads, which indexes the [`FieldReader`]s of the field.
|
||||
member: usize,
|
||||
/// The dense segment holding the run's values.
|
||||
segment: &'a Samples,
|
||||
/// Offset of the run's first row inside `segment`.
|
||||
offset: usize,
|
||||
/// How many rows of `segment` the run covers.
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl FieldRun<'_> {
|
||||
/// Returns whether the value at `offset` of `segment` continues the run: the same member's next
|
||||
/// row in the same dense segment.
|
||||
fn continues(&self, member: usize, segment: &Samples, offset: usize) -> bool {
|
||||
self.member == member
|
||||
&& std::ptr::eq(self.segment, segment)
|
||||
&& self.offset + self.len == offset
|
||||
}
|
||||
|
||||
/// Pushes the run as one slice of its dense segment.
|
||||
fn push(self, chunks: &mut Vec<Samples>) -> Result<()> {
|
||||
chunks.push(
|
||||
self.segment
|
||||
@@ -724,22 +640,16 @@ impl FieldRun<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads one field's rows by locating the dense segment each row sits in.
|
||||
///
|
||||
/// [`Samples::sample`] rescans a chunked field from its first segment on every row, so reading a
|
||||
/// field row by row would cost a scan over the segments before it. The rows a merge reads only go
|
||||
/// forward, so this walks the segments once and returns the segment with the offset of the row
|
||||
/// inside it, which is what a [`FieldRun`] slices.
|
||||
/// Forward-only reader over a chunked field. [`Samples::sample`] rescans segments from the first on
|
||||
/// every call; this walks them once.
|
||||
struct FieldReader<'a> {
|
||||
segments: &'a [Samples],
|
||||
/// Index of the segment `start` belongs to.
|
||||
segment: usize,
|
||||
/// Logical row the current segment starts at.
|
||||
start: usize,
|
||||
}
|
||||
|
||||
impl<'a> FieldReader<'a> {
|
||||
/// Creates a reader at the first row of `samples`.
|
||||
fn new(samples: &'a Samples) -> Self {
|
||||
Self {
|
||||
segments: samples.segments(),
|
||||
@@ -748,10 +658,8 @@ impl<'a> FieldReader<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the dense segment holding `row` and the offset of `row` inside it.
|
||||
///
|
||||
/// Rows must not go backwards. A row past the field is an error rather than a panic: a member is
|
||||
/// only read after its fields are validated to align with its axis.
|
||||
/// Returns the dense segment holding `row` and the offset inside it. `row` must not go
|
||||
/// backwards.
|
||||
fn locate(&mut self, row: usize) -> Result<(&'a Samples, usize)> {
|
||||
while let Some(segment) = self.segments.get(self.segment) {
|
||||
if let Some(offset) = row
|
||||
@@ -769,7 +677,6 @@ impl<'a> FieldReader<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes the merged rows a field leaves empty as one null run.
|
||||
fn push_missing(chunks: &mut Vec<Samples>, missing: &mut usize) {
|
||||
if *missing != 0 {
|
||||
chunks.push(Samples::from_float(Float64Array::new_null(*missing)));
|
||||
|
||||
@@ -35,9 +35,6 @@ use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
pub(crate) type Dense = Vec<Vec<Option<f64>>>;
|
||||
|
||||
/// Expands a grid series to a dense matrix over its whole grid.
|
||||
///
|
||||
/// The axis names the absolute position of every row, so a series of several runs expands to the
|
||||
/// same matrix a dense one would.
|
||||
pub(crate) fn expand(series: &Series) -> Dense {
|
||||
let Some(grid) = series.time.grid() else {
|
||||
panic!("expected a grid series, got {:?}", series.time);
|
||||
@@ -111,9 +108,6 @@ fn assert_series_matches(
|
||||
let Some(grid) = actual.time.grid() else {
|
||||
panic!("expected a grid series, got {:?}", actual.time);
|
||||
};
|
||||
// Trimmed means: the carried rows start at the first valid position and end at the last, and
|
||||
// there is one row per valid position. A series of several runs satisfies both only when it
|
||||
// carries the same positions.
|
||||
assert_eq!(
|
||||
(actual.time.first_position(), actual.time.last_position()),
|
||||
(Some(first), Some(last)),
|
||||
@@ -135,12 +129,8 @@ fn assert_series_matches(
|
||||
assert_eq!(bits(&expand(actual)), bits(expected), "{context}");
|
||||
}
|
||||
|
||||
/// Stitches the pieces of one series back into a dense matrix over the whole grid.
|
||||
///
|
||||
/// A result only carries the positions holding a value, and a stream may hand it out as several
|
||||
/// pieces, so comparing against a dense expectation means putting them back together. Two pieces
|
||||
/// covering one position would be a protocol violation, so it fails here rather than silently
|
||||
/// overwriting.
|
||||
/// Stitches the pieces of one series back into a dense matrix over the whole grid; panics when two
|
||||
/// pieces cover one position.
|
||||
pub(crate) fn stitch(pieces: &[Series]) -> Dense {
|
||||
let mut dense: Option<Dense> = None;
|
||||
for piece in pieces {
|
||||
@@ -174,9 +164,6 @@ pub(crate) fn stitch(pieces: &[Series]) -> Dense {
|
||||
}
|
||||
|
||||
/// The `(start, len)` of every run of one series, in grid order.
|
||||
///
|
||||
/// A series names the rows it carries through its axis, so a result of several runs reports one
|
||||
/// entry per run and never the envelope: the positions between two runs hold no row.
|
||||
pub(crate) fn run_ranges(series: &Series) -> Vec<(usize, usize)> {
|
||||
if series.time.grid().is_none() {
|
||||
panic!("expected a grid series, got {:?}", series.time);
|
||||
@@ -194,11 +181,8 @@ pub(crate) fn piece_ranges(pieces: &[Series]) -> Vec<(usize, usize)> {
|
||||
pieces.iter().flat_map(run_ranges).collect()
|
||||
}
|
||||
|
||||
/// Asserts `actual` -- one series, or none -- reproduces `expected` over the grid.
|
||||
///
|
||||
/// A result carries only the positions that hold a value, so its rows may form several runs: the
|
||||
/// comparison expands it over the grid and checks it covers exactly the valued positions. `None`
|
||||
/// means no row survived, which is only right when `expected` holds no value either.
|
||||
/// Asserts `actual` covers exactly the valued positions of `expected` with the same values; `None`
|
||||
/// matches an `expected` without values.
|
||||
pub(crate) fn assert_result_eq(actual: Option<&Series>, expected: &Dense, metric: &SeriesLabels) {
|
||||
match actual {
|
||||
Some(actual) => assert_pieces_eq(std::slice::from_ref(actual), expected, metric),
|
||||
@@ -219,7 +203,6 @@ pub(crate) fn assert_pieces_eq(pieces: &[Series], expected: &Dense, metric: &Ser
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
if valued.is_empty() {
|
||||
// Nothing holds a value anywhere, so there is no piece at all -- not one piece of nulls.
|
||||
assert!(
|
||||
pieces.is_empty(),
|
||||
"expected no pieces, got {}",
|
||||
@@ -246,11 +229,7 @@ pub(crate) fn assert_pieces_eq(pieces: &[Series], expected: &Dense, metric: &Ser
|
||||
);
|
||||
}
|
||||
|
||||
/// The points of each label set of `pieces`, folded back into one dense point map first.
|
||||
///
|
||||
/// An operator hands out one series per logical output, and a stream may hand one of them over as
|
||||
/// several chunks, while a fixture pins dense points, so the pieces of a label set are joined
|
||||
/// before comparing.
|
||||
/// The points of each label set of `pieces`, joining the chunks of one label set.
|
||||
pub(crate) fn points_by_labels(pieces: Vec<Series>) -> std::collections::BTreeMap<Labels, Points> {
|
||||
crate::golden::fold_pieces(pieces)
|
||||
.iter()
|
||||
@@ -414,10 +393,8 @@ pub(crate) fn labels_of(metric: &SeriesLabels) -> Labels {
|
||||
labels
|
||||
}
|
||||
|
||||
/// A single-field series of `schema` holding `points`; `None` without points.
|
||||
///
|
||||
/// Built directly rather than through the builder: this is an *input* to an operator, so a hole
|
||||
/// stays a null inside one series instead of cutting it into pieces.
|
||||
/// A single-field dense series of `schema` holding `points`, holes as nulls; `None` without
|
||||
/// points.
|
||||
pub(crate) fn series_of(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
labels: &Labels,
|
||||
@@ -440,13 +417,8 @@ pub(crate) fn series_of(
|
||||
)
|
||||
}
|
||||
|
||||
/// A single-field series of `schema` holding `points` on an axis that skips the positions between
|
||||
/// them: one run per maximal stretch of consecutive keys.
|
||||
///
|
||||
/// This is a series of several grid runs, the shape an input can already have; it is built by hand
|
||||
/// here because the builder is the thing under test. The field holds one row per key, in key
|
||||
/// order, so a consumer that forgets to read the axis will read the wrong values rather than
|
||||
/// merely a shorter series.
|
||||
/// A single-field series of `schema` holding `points` on a sparse axis, one run per stretch of
|
||||
/// consecutive keys. Built by hand because the builder is under test.
|
||||
pub(crate) fn sparse_series(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
labels: &Labels,
|
||||
@@ -471,8 +443,6 @@ pub(crate) fn sparse_series(
|
||||
Series::try_new(
|
||||
schema,
|
||||
metric_of(labels),
|
||||
// A one-run axis is the dense fast path, so a sparse fixture of one run is the same
|
||||
// series either shape would build.
|
||||
time,
|
||||
SeriesFields::one(Samples::from_float(values)),
|
||||
)
|
||||
|
||||
@@ -60,11 +60,6 @@ fn metric(host: usize) -> SeriesLabels {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The series one builder hands out, expanded over the whole grid, has to reproduce the dense
|
||||
/// matrix it was pushed from.
|
||||
///
|
||||
/// This is the contract of the whole change: one series per logical output, one dense answer, and
|
||||
/// the rows never cover a position holding no value.
|
||||
#[test]
|
||||
fn the_series_of_one_push_sequence_matches_the_pushed_rows() {
|
||||
for seed in 0..200 {
|
||||
@@ -72,7 +67,6 @@ fn the_series_of_one_push_sequence_matches_the_pushed_rows() {
|
||||
let fields = rng.random_range(1..=3);
|
||||
let grid_len = rng.random_range(1..64);
|
||||
let mut builder = GridSeriesBuilder::try_new(grid_schema(fields, grid_len)).unwrap();
|
||||
// One builder serves several series, as it does inside an operator.
|
||||
for host in 0..3 {
|
||||
builder.begin_series();
|
||||
let expected = random_dense(&mut rng, grid_len as usize, fields);
|
||||
@@ -102,8 +96,6 @@ fn builder_rejects_invalid_rows() {
|
||||
assert!(GridSeriesBuilder::try_new(Arc::new(schema)).is_err());
|
||||
}
|
||||
|
||||
/// Label sets compare without empty values, which Prometheus does not have: a series with
|
||||
/// `host=""` and one without `host` merge.
|
||||
#[test]
|
||||
fn merge_treats_empty_label_values_as_absent() {
|
||||
let schema = grid_schema(1, 2);
|
||||
@@ -131,16 +123,10 @@ fn merge_treats_empty_label_values_as_absent() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Members whose rows never share a position merge without colliding, so the whole merge runs to
|
||||
/// completion for every row. Each member is located once per row while collecting; resolving it
|
||||
/// again per row inside the merge would be a search per row, which is what a wide fan-in of
|
||||
/// disjoint single-point members would pay.
|
||||
#[test]
|
||||
fn merge_keeps_every_row_of_many_disjoint_members() {
|
||||
const MEMBERS: usize = 64;
|
||||
let schema = grid_schema(1, (2 * MEMBERS) as u64);
|
||||
// One value per member at an even position, so no two members share a position and the
|
||||
// collision check never fires.
|
||||
let series = (0..MEMBERS)
|
||||
.map(|index| {
|
||||
let labels = Labels::from([
|
||||
@@ -181,8 +167,6 @@ fn merge_keeps_every_row_of_many_disjoint_members() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Series of one label set merge field by field: different fields at one point combine, and
|
||||
/// only one field present in both collides.
|
||||
#[test]
|
||||
fn merge_combines_disjoint_fields_at_one_point() {
|
||||
let schema = grid_schema(2, 1);
|
||||
@@ -214,9 +198,6 @@ fn merge_combines_disjoint_fields_at_one_point() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Native histograms merge like floats: members of one label set combine by field and position,
|
||||
/// histograms and floats keep their type, and a field held twice at one point collides whatever
|
||||
/// the sample types.
|
||||
#[test]
|
||||
fn merge_keeps_histograms_and_rejects_any_doubled_field() {
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -301,18 +282,10 @@ fn merge_keeps_histograms_and_rejects_any_doubled_field() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The histogram payloads of one label set merge by position, whatever table each shard filed its
|
||||
/// own payload in.
|
||||
///
|
||||
/// A label set reaches a merge as one fragment per producer, and every fragment was built by its own
|
||||
/// builder: each holds its own histogram table and its own indices into it, so the merged field has
|
||||
/// to be rebuilt over the union of the positions with each row still naming the payload it was
|
||||
/// pushed with. The fragments here are complementary, the position neither of two fragments holds
|
||||
/// stays a hole, and a fragment that pushes nothing adds no row.
|
||||
/// Each shard holds its own histogram table; merged rows must still name the payload their shard
|
||||
/// pushed.
|
||||
#[test]
|
||||
fn merge_keeps_each_shards_histogram_payload() {
|
||||
// One histogram per shard, each with its own count, sum and bucket payload: `count/sum` are the
|
||||
// two fields a reader of the merged series checks a payload by.
|
||||
let payloads = [
|
||||
OwnedHistogram::parse(
|
||||
"0/0/0/3ff0000000000000/3ff0000000000000/1/0_2/4000000000000000,4008000000000000///",
|
||||
@@ -336,8 +309,6 @@ fn merge_keeps_each_shards_histogram_payload() {
|
||||
.unwrap()
|
||||
.expect("the shard holds the rows it pushed")
|
||||
};
|
||||
// A shard of the same label set holding nothing finishes with no series at all, so it adds
|
||||
// neither a row nor a gap to what the others pushed.
|
||||
assert!(
|
||||
GridSeriesBuilder::try_new(schema.clone())
|
||||
.unwrap()
|
||||
@@ -364,8 +335,7 @@ fn merge_keeps_each_shards_histogram_payload() {
|
||||
(point, histogram.sum, histogram.count)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// One row per valued position, in order: position 2 is a hole in every shard and stays a hole,
|
||||
// and each row carries the payload its own shard pushed.
|
||||
// Position 2 is a hole in every shard.
|
||||
assert_eq!(
|
||||
vec![
|
||||
(0, scalars[0].0, scalars[0].1),
|
||||
@@ -375,8 +345,6 @@ fn merge_keeps_each_shards_histogram_payload() {
|
||||
],
|
||||
merged_rows
|
||||
);
|
||||
// The merged field is one freshly built table over those rows: the rows the shards held are
|
||||
// addressed by the merged series' own indices, so a row cannot name a shard's table.
|
||||
let SampleRef::Histogram(first) = field.sample(0) else {
|
||||
panic!("the merged field holds no histogram");
|
||||
};
|
||||
@@ -389,44 +357,6 @@ fn merge_keeps_each_shards_histogram_payload() {
|
||||
assert_eq!(1, second.positive.span_offsets[0]);
|
||||
}
|
||||
|
||||
/// Two shards of one label set holding a histogram at one position are refused.
|
||||
///
|
||||
/// The merge collects the pieces of one label set into one series, so a position two pieces fill
|
||||
/// would carry two values of one field: that is the collision Prometheus reports rather than a
|
||||
/// choice for this node to make. The refusal names the shared label set, as it does for floats.
|
||||
#[test]
|
||||
fn merge_rejects_a_histogram_position_two_shards_hold() {
|
||||
let payloads = [
|
||||
OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/1/0_1/4000000000000000///"),
|
||||
OwnedHistogram::parse("0/0/0/4000000000000000/4000000000000000/1/0_1/4000000000000000///"),
|
||||
];
|
||||
let schema = grid_schema(1, 8);
|
||||
let shard = |point: usize, payload: usize| {
|
||||
let histogram = FloatHistogram::try_from_view(&payloads[payload].view()).unwrap();
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap();
|
||||
builder
|
||||
.push_samples(point, &[Some(GridSample::Histogram(Box::new(histogram)))])
|
||||
.unwrap();
|
||||
builder.finish(metric(0)).unwrap().unwrap()
|
||||
};
|
||||
// Complementary positions merge whatever payloads they hold, so the only reason the second pair
|
||||
// is refused is the position both of them fill.
|
||||
let merged = merge_same_labelset(&schema, vec![shard(0, 0), shard(1, 1)]).unwrap();
|
||||
assert_eq!(1, merged.len());
|
||||
assert_eq!(
|
||||
2,
|
||||
merged[0].time.len(),
|
||||
"two shards holding different positions merge"
|
||||
);
|
||||
let error = merge_same_labelset(&schema, vec![shard(1, 0), shard(1, 1)]).unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("same labelset"),
|
||||
"the refusal does not name the shared label set: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Two values a million positions apart are one series with two rows, addressed by two runs: the
|
||||
/// positions between them cost neither a row nor a value buffer sized by the span.
|
||||
#[test]
|
||||
fn runs_never_bridge_positions_without_a_value() {
|
||||
const SPAN: usize = 1_000_000;
|
||||
@@ -436,7 +366,6 @@ fn runs_never_bridge_positions_without_a_value() {
|
||||
assert!(builder.has_pending());
|
||||
|
||||
let series = builder.finish(metric(0)).unwrap().expect("two rows");
|
||||
// One series over a million-position grid, with two runs, and the axis says where they sit.
|
||||
assert_eq!(
|
||||
series.time.grid().expect("a grid series").spec().len as usize,
|
||||
SPAN,
|
||||
@@ -448,8 +377,6 @@ fn runs_never_bridge_positions_without_a_value() {
|
||||
"two far-apart rows are two runs"
|
||||
);
|
||||
assert_eq!(series.time.len(), 2, "two values, two rows");
|
||||
// Two field rows, and the value buffer is exactly as long as the values pushed: nothing is
|
||||
// sized by the grid or by the span between the runs.
|
||||
assert_eq!(series.fields.len(), 1);
|
||||
assert_eq!(
|
||||
series.fields.as_slice()[0].len(),
|
||||
@@ -466,8 +393,6 @@ fn runs_never_bridge_positions_without_a_value() {
|
||||
std::mem::size_of_val(values.values().as_ref()) < SPAN / 1000,
|
||||
"the value buffer is sized by the span, not by the values"
|
||||
);
|
||||
// The axis resolves both rows on the shared grid, so a consumer reads the right instants
|
||||
// without the series carrying one per position of the span.
|
||||
assert_eq!(
|
||||
(series.time.timestamp(0), series.time.timestamp(1)),
|
||||
(Some(-5_000 + 10 * 1_000), Some(-5_000 + 900_000 * 1_000))
|
||||
@@ -475,8 +400,6 @@ fn runs_never_bridge_positions_without_a_value() {
|
||||
assert!(!builder.has_pending());
|
||||
}
|
||||
|
||||
/// A prefix flush hands out the whole buffer as one series, runs and all, and ends nothing: the
|
||||
/// same logical series keeps going, so the position cursor is not reset either.
|
||||
#[test]
|
||||
fn a_prefix_flush_hands_out_the_whole_buffer_and_ends_nothing() {
|
||||
let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap();
|
||||
@@ -490,8 +413,7 @@ fn a_prefix_flush_hands_out_the_whole_buffer_and_ends_nothing() {
|
||||
.expect("three rows");
|
||||
assert_eq!(run_ranges(&prefix), vec![(0, 1), (5, 1), (9, 1)]);
|
||||
assert!(!builder.has_pending());
|
||||
// A second flush has nothing to hand out, and the series is not over: only `begin_series`
|
||||
// resets it, so a position before the prefix is still refused.
|
||||
// The index cursor survives a flush; only `begin_series` resets it.
|
||||
assert!(builder.take_buffered(metric(0)).unwrap().is_none());
|
||||
assert!(builder.push(9, &[Some(4.0)]).is_err());
|
||||
assert!(builder.finish(metric(0)).unwrap().is_none());
|
||||
@@ -502,7 +424,6 @@ fn a_prefix_flush_hands_out_the_whole_buffer_and_ends_nothing() {
|
||||
assert_eq!(run_ranges(&next), vec![(0, 1)]);
|
||||
}
|
||||
|
||||
/// A push whose values are all missing holds no row, so it neither opens nor widens a run.
|
||||
#[test]
|
||||
fn an_all_missing_push_holds_no_row() {
|
||||
let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap();
|
||||
@@ -516,28 +437,6 @@ fn an_all_missing_push_holds_no_row() {
|
||||
assert!(!builder.has_pending());
|
||||
}
|
||||
|
||||
/// Values and nulls alternating over a long grid: every valued position is a run of its own, so
|
||||
/// the run count grows with the values while the row count stays at one per value.
|
||||
#[test]
|
||||
fn alternating_values_and_nulls_yield_one_row_per_value() {
|
||||
const GRID: usize = 200_000;
|
||||
let mut builder = GridSeriesBuilder::try_new(grid_schema(1, GRID as u64)).unwrap();
|
||||
for index in 0..GRID {
|
||||
let value = (index % 2 == 0).then_some(index as f64);
|
||||
builder.push(index, &[value]).unwrap();
|
||||
}
|
||||
let series = builder.finish(metric(0)).unwrap().expect("half the grid");
|
||||
assert_eq!(
|
||||
series.time.len(),
|
||||
GRID / 2,
|
||||
"one row per value, and none for the empties"
|
||||
);
|
||||
let expected: Vec<(usize, usize)> = (0..GRID / 2).map(|i| (i * 2, 1)).collect();
|
||||
assert_eq!(run_ranges(&series), expected);
|
||||
}
|
||||
|
||||
/// Rows of one series stay aligned across fields: a field with no value where another has one
|
||||
/// still gets a row there, holding a null. That is the one null a series keeps.
|
||||
#[test]
|
||||
fn rows_stay_aligned_across_fields() {
|
||||
let mut builder = GridSeriesBuilder::try_new(grid_schema(2, 4)).unwrap();
|
||||
@@ -560,11 +459,6 @@ fn rows_stay_aligned_across_fields() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A series of several runs is one row buffer plus one span per run: the rows are compact, so the
|
||||
/// holes between the runs are not in the value buffer at all.
|
||||
///
|
||||
/// The assertion is not vacuous: the runs are separated by holes, so a builder that kept the
|
||||
/// envelope would have to write a row per position of it, and the buffer would be 100 long.
|
||||
#[test]
|
||||
fn a_multi_run_series_keeps_one_row_per_value() {
|
||||
let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 100)).unwrap();
|
||||
@@ -578,14 +472,12 @@ fn a_multi_run_series_keeps_one_row_per_value() {
|
||||
Some(DenseSamplesRef::Float(values)) => values,
|
||||
_ => panic!("expected float samples"),
|
||||
};
|
||||
// One buffer holding exactly the six pushed rows, in push order.
|
||||
assert_eq!(values.len(), 6);
|
||||
assert_eq!(values.values().as_ref(), &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert_eq!(
|
||||
std::mem::size_of_val(values.values().as_ref()),
|
||||
6 * size_of::<f64>()
|
||||
);
|
||||
// The rows read back through the axis are the pushed values at the pushed positions.
|
||||
let mut cursor = series.fields.as_slice()[0].cursor();
|
||||
let read: Vec<(usize, f64)> = series
|
||||
.time
|
||||
@@ -608,8 +500,6 @@ fn a_multi_run_series_keeps_one_row_per_value() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Dense pushes of the same positions give the same series whether the gaps were skipped or
|
||||
/// pushed as all-missing rows.
|
||||
#[test]
|
||||
fn skipped_and_all_missing_positions_are_the_same_series() {
|
||||
let mut skipped = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap();
|
||||
@@ -630,8 +520,6 @@ fn skipped_and_all_missing_positions_are_the_same_series() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Series are handed out in the order their rows were pushed, so one builder serves many series,
|
||||
/// as long as each one starts with `begin_series`.
|
||||
#[test]
|
||||
fn one_builder_serves_several_series() {
|
||||
let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 10)).unwrap();
|
||||
@@ -641,7 +529,6 @@ fn one_builder_serves_several_series() {
|
||||
assert_eq!(run_ranges(&first), vec![(0, 1), (2, 1)]);
|
||||
assert_eq!(first.metric, metric(0));
|
||||
|
||||
// Positions start over with each series, which only `begin_series` allows.
|
||||
assert!(
|
||||
builder.push(1, &[Some(3.0)]).is_err(),
|
||||
"a series ends where the positions restart"
|
||||
@@ -655,55 +542,9 @@ fn one_builder_serves_several_series() {
|
||||
assert!(!builder.has_pending());
|
||||
}
|
||||
|
||||
/// A prefix flush hands every buffered row to the caller, so `finish` only has the rows pushed
|
||||
/// after it: nothing is repeated, and nothing the caller took is dropped.
|
||||
#[test]
|
||||
fn finish_hands_out_only_the_rows_pushed_after_a_prefix_flush() {
|
||||
let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 20)).unwrap();
|
||||
builder.push(0, &[Some(1.0)]).unwrap();
|
||||
builder.push(5, &[Some(2.0)]).unwrap();
|
||||
builder.push(9, &[Some(3.0)]).unwrap();
|
||||
// Merging fragments of one label set: payloads are shared, not rebuilt.
|
||||
|
||||
let prefix = builder
|
||||
.take_buffered(metric(0))
|
||||
.unwrap()
|
||||
.expect("three rows");
|
||||
assert_eq!(run_ranges(&prefix), vec![(0, 1), (5, 1), (9, 1)]);
|
||||
|
||||
// A row after the prefix: it belongs to the same series, so the metric is the same and only
|
||||
// the positions after the ones already handed out can appear.
|
||||
builder.push(15, &[Some(4.0)]).unwrap();
|
||||
let rest = builder
|
||||
.finish(metric(0))
|
||||
.unwrap()
|
||||
.expect("the row pushed since");
|
||||
assert_eq!(
|
||||
run_ranges(&rest),
|
||||
vec![(15, 1)],
|
||||
"finish repeated a row the caller already took"
|
||||
);
|
||||
assert_eq!(
|
||||
match rest.fields.as_slice()[0].dense() {
|
||||
Some(DenseSamplesRef::Float(values)) => values.value(0),
|
||||
_ => panic!("expected float samples"),
|
||||
},
|
||||
4.0,
|
||||
"the row carries another position's value"
|
||||
);
|
||||
assert!(!builder.has_pending());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Merging: one label set handed over in several fragments.
|
||||
//
|
||||
// A runtime hands one label set over as fragments, and the merge is the only place that puts them
|
||||
// back into one series. What these tests pin is that the values move without being rebuilt: the
|
||||
// merged series shares the fragments' payloads, keeps native histograms and NaNs, and still costs
|
||||
// one row per position holding a value.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The start of the float buffer a dense float segment reads, to show a merge shared the buffer
|
||||
/// instead of copying it.
|
||||
/// The start of a dense float segment's buffer, to check a merge shared it.
|
||||
fn float_ptr(segment: &Samples) -> *const f64 {
|
||||
match segment.dense() {
|
||||
Some(DenseSamplesRef::Float(values)) => values.values().as_ptr(),
|
||||
@@ -713,10 +554,8 @@ fn float_ptr(segment: &Samples) -> *const f64 {
|
||||
|
||||
type FragmentRow<'a> = (usize, Option<f64>, Option<&'a str>, Option<f64>);
|
||||
|
||||
/// A two-field fragment: field 0 holds a float or a native histogram, field 1 a float.
|
||||
///
|
||||
/// `rows` holds `(position, field 0 float, field 0 histogram, field 1 float)` in ascending position
|
||||
/// order; a row holds a value when some field has one at that position.
|
||||
/// A two-field fragment from `(position, field 0 float, field 0 histogram, field 1 float)` rows in
|
||||
/// ascending position order.
|
||||
fn fragment_with_histograms(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
labels: &Labels,
|
||||
@@ -757,8 +596,6 @@ fn fragment_with_histograms(
|
||||
)
|
||||
}
|
||||
|
||||
/// Two fragments a boundary kept apart -- the first holding position 0, the second positions 1 and
|
||||
/// 2 -- become one series of one run, each fragment's rows at its own positions.
|
||||
#[test]
|
||||
fn merge_of_adjacent_fragments_is_one_run() {
|
||||
let schema = grid_schema(1, 4);
|
||||
@@ -789,8 +626,7 @@ fn merge_of_adjacent_fragments_is_one_run() {
|
||||
(2, 3f64.to_bits()),
|
||||
])
|
||||
);
|
||||
// One slice per fragment: the second fragment's two rows are one slice of its own buffer, and
|
||||
// neither slice copies a value.
|
||||
// One slice per fragment, neither copied.
|
||||
let chunks = merged[0].fields.as_slice()[0].segments();
|
||||
assert_eq!(chunks.len(), 2, "one slice per fragment");
|
||||
assert_eq!(float_ptr(&chunks[0]), first_ptr);
|
||||
@@ -798,19 +634,13 @@ fn merge_of_adjacent_fragments_is_one_run() {
|
||||
assert_eq!(chunks[1].len(), 2, "the fragment's two rows are one slice");
|
||||
}
|
||||
|
||||
/// Native histograms, floats, NaNs and complementary fields merge into one aligned series, and
|
||||
/// every value keeps the storage it already had: the histogram table and the float buffers are
|
||||
/// shared, not rebuilt.
|
||||
#[test]
|
||||
fn merge_keeps_native_histograms_and_complementary_fields_without_copying_them() {
|
||||
let schema = grid_schema(2, 4);
|
||||
let labels = Labels::from([("job".to_string(), "x".to_string())]);
|
||||
let histogram = "0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///";
|
||||
// The first fragment holds a native histogram in field 0 and a float in field 1 at position 0.
|
||||
let (first, first_batch) =
|
||||
fragment_with_histograms(&schema, &labels, &[(0, None, Some(histogram), Some(1.0))]);
|
||||
// The second holds field 0's float at position 1 and field 1's NaN at position 2, leaving the
|
||||
// other field missing at each.
|
||||
let (second, _) = fragment_with_histograms(
|
||||
&schema,
|
||||
&labels,
|
||||
@@ -828,7 +658,6 @@ fn merge_keeps_native_histograms_and_complementary_fields_without_copying_them()
|
||||
assert_eq!(merged[0].time.len(), 3);
|
||||
assert_eq!(merged[0].fields.len(), 2);
|
||||
|
||||
// Field 0: the histogram, the float, and a null at the position only field 1 fills.
|
||||
let field0 = merged[0].fields.as_slice()[0].segments();
|
||||
assert_eq!(field0.len(), 3, "a histogram, a float, and one null run");
|
||||
let DenseSamplesRef::Mixed(mixed) = field0[0].dense().unwrap() else {
|
||||
@@ -851,7 +680,6 @@ fn merge_keeps_native_histograms_and_complementary_fields_without_copying_them()
|
||||
"field 0 filled a position only field 1 holds"
|
||||
);
|
||||
|
||||
// Field 1: its value, the null field 0 fills, and the NaN, which is a value like any other.
|
||||
let field1 = merged[0].fields.as_slice()[1].segments();
|
||||
assert_eq!(field1.len(), 3, "a float, one null run, and a NaN");
|
||||
assert!(
|
||||
@@ -862,14 +690,12 @@ fn merge_keeps_native_histograms_and_complementary_fields_without_copying_them()
|
||||
matches!(field1[2].sample(0), SampleRef::Float(value) if value.is_nan()),
|
||||
"the NaN was dropped"
|
||||
);
|
||||
// The NaN came out as a slice of the second fragment's buffer, one row in.
|
||||
assert_eq!(
|
||||
float_ptr(&field1[2]),
|
||||
second_field1.wrapping_add(1),
|
||||
"the NaN was copied instead of sliced"
|
||||
);
|
||||
|
||||
// Two fragments holding one field at one position still collide, histograms included.
|
||||
let at_zero =
|
||||
|| fragment_with_histograms(&schema, &labels, &[(0, None, Some(histogram), None)]).0;
|
||||
assert!(
|
||||
@@ -878,17 +704,12 @@ fn merge_keeps_native_histograms_and_complementary_fields_without_copying_them()
|
||||
);
|
||||
}
|
||||
|
||||
/// A merge over many fragments of many segments keeps one row per value: a million-position grid
|
||||
/// costs a span per run and a sample per value, and locating a row never rescans the segments
|
||||
/// before it.
|
||||
#[test]
|
||||
fn merge_of_many_segments_keeps_one_row_per_value() {
|
||||
const GRID: usize = 1_000_000;
|
||||
const SEGMENTS: usize = 1_000;
|
||||
let schema = grid_schema(1, GRID as u64);
|
||||
let labels = Labels::from([("job".to_string(), "x".to_string())]);
|
||||
// A fragment of one value per segment, one chunk per value, the segments a thousand positions
|
||||
// apart.
|
||||
let fragment = |offset: usize| {
|
||||
let mut chunks = Vec::with_capacity(SEGMENTS);
|
||||
let mut spans = Vec::with_capacity(SEGMENTS);
|
||||
@@ -938,8 +759,6 @@ fn merge_of_many_segments_keeps_one_row_per_value() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A label set whose fragments all closed without a value still yields one series: a runtime that
|
||||
/// closes a label set needs one answer per set, and an empty grid series is the legal one.
|
||||
#[test]
|
||||
fn merge_of_empty_fragments_yields_one_empty_series() {
|
||||
let schema = grid_schema(2, 4);
|
||||
@@ -973,19 +792,13 @@ fn merge_of_empty_fragments_yields_one_empty_series() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Series` built as a struct literal can carry fields that do not line up with its axis; the
|
||||
/// merge checks the alignment before it reads a row, so it reports such a fragment instead of
|
||||
/// reading past a field or dropping the values the axis never reaches.
|
||||
#[test]
|
||||
fn merge_rejects_fragments_whose_fields_do_not_fill_their_axis() {
|
||||
let schema = grid_schema(1, 8);
|
||||
let grid = schema.eval_grid.clone().unwrap();
|
||||
let labels = Labels::from([("job".to_string(), "x".to_string())]);
|
||||
// A well-formed fragment gives the malformed one a label set to merge into.
|
||||
let partner = || series_of(&schema, &labels, &Points::from([(1, 7f64.to_bits())])).unwrap();
|
||||
// `(axis rows, field rows)`: a field shorter than its axis, one longer than it, and a value on
|
||||
// an axis of no rows at all. The last two leave every axis row self-consistent, so only the
|
||||
// merge's alignment check catches them.
|
||||
// `(axis rows, field rows)`: shorter field, longer field, and a value on an empty axis.
|
||||
for (axis_rows, field_rows) in [(2, 1), (1, 2), (0, 1)] {
|
||||
let spans = if axis_rows == 0 {
|
||||
Vec::new()
|
||||
@@ -1012,13 +825,7 @@ fn merge_rejects_fragments_whose_fields_do_not_fill_their_axis() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Acceptance: the builder's observable shape.
|
||||
//
|
||||
// A builder hands out one `Series` per logical output, whose axis names the runs of positions that
|
||||
// hold a value. What these tests pin is that shape -- the fast path, the run count, the row count,
|
||||
// the field layout -- and not just the values, which the differential tests already cover.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The builder's output shape: fast path, run count, row count and field layout.
|
||||
|
||||
mod acceptance {
|
||||
use std::sync::Arc;
|
||||
@@ -1035,7 +842,6 @@ mod acceptance {
|
||||
use super::super::{GridSample, GridSeriesBuilder};
|
||||
use super::metric;
|
||||
|
||||
/// The schema of a `fields`-field series on a `len`-position grid with a ten-millisecond step.
|
||||
fn schema(fields: usize, len: u64) -> Arc<SeriesSchema> {
|
||||
Arc::new(SeriesSchema {
|
||||
fields: (0..fields)
|
||||
@@ -1050,7 +856,6 @@ mod acceptance {
|
||||
})
|
||||
}
|
||||
|
||||
/// Pushes one row per position, `value(index)` giving each field its value or a hole.
|
||||
fn build(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
len: usize,
|
||||
@@ -1063,10 +868,6 @@ mod acceptance {
|
||||
builder.finish(metric(0)).unwrap()
|
||||
}
|
||||
|
||||
/// B: a contiguous result keeps the `TimeAxis::Grid` fast path.
|
||||
///
|
||||
/// Every position holding a value is one range, and a range is what the axis stores: a span
|
||||
/// list of one element would be the same rows described the slower way.
|
||||
#[test]
|
||||
fn a_contiguous_result_is_a_grid_range_and_not_a_span_list() {
|
||||
const POINTS: u64 = 9;
|
||||
@@ -1089,8 +890,6 @@ mod acceptance {
|
||||
"one run over the whole span"
|
||||
);
|
||||
assert_eq!(series.time.len(), POINTS as usize);
|
||||
// The axis lends the grid's buffer instead of copying it: the fast path is not only a
|
||||
// label, it is the same rows without per-series timestamp storage.
|
||||
assert!(
|
||||
matches!(
|
||||
series.time.timestamps().unwrap(),
|
||||
@@ -1100,11 +899,6 @@ mod acceptance {
|
||||
);
|
||||
}
|
||||
|
||||
/// B: alternating valued and missing positions stay one series of one-run-per-value.
|
||||
///
|
||||
/// Sixteen positions, eight values: eight runs and eight rows, in **one** series with eight
|
||||
/// field samples per field. The constant that would inflate is the grid: the axis holds eight
|
||||
/// rows, not sixteen.
|
||||
#[test]
|
||||
fn alternating_values_and_holes_make_one_series_of_one_run_per_value() {
|
||||
const POINTS: usize = 16;
|
||||
@@ -1146,17 +940,10 @@ mod acceptance {
|
||||
);
|
||||
}
|
||||
|
||||
/// B: the positions delivered in one series with holes and in several pushes give the same
|
||||
/// dense result, so the delivery boundaries do not decide the answer.
|
||||
///
|
||||
/// The builder is the production entry point for this shape: `take_buffered` is the prefix
|
||||
/// flush a streaming evaluator uses, and `finish` closes the series.
|
||||
#[test]
|
||||
fn one_series_with_holes_and_several_prefix_flushes_expand_alike() {
|
||||
const POINTS: usize = 12;
|
||||
let schema = schema(1, POINTS as u64);
|
||||
// One builder, one series, every position pushed: holes are pushed as nulls, so this is
|
||||
// one dense series over the whole grid.
|
||||
let mut holed = GridSeriesBuilder::try_new(schema.clone()).unwrap();
|
||||
let valued = |index: usize| matches!(index, 0 | 1 | 4 | 9);
|
||||
for index in 0..POINTS {
|
||||
@@ -1166,7 +953,6 @@ mod acceptance {
|
||||
let one = holed.finish(metric(0)).unwrap().expect("four values");
|
||||
assert_eq!(run_ranges(&one), vec![(0, 2), (4, 1), (9, 1)]);
|
||||
|
||||
// The same rows flushed as prefixes: rows 0..5, then 5..10, then the rest.
|
||||
let mut flushed = GridSeriesBuilder::try_new(schema.clone()).unwrap();
|
||||
let mut pieces = Vec::new();
|
||||
for (index, take) in [(0..5), (5..10), (10..POINTS)].into_iter().enumerate() {
|
||||
@@ -1184,13 +970,11 @@ mod acceptance {
|
||||
}
|
||||
}
|
||||
pieces.push(flushed.finish(metric(0)).unwrap().expect("two more values"));
|
||||
// A prefix flush does not end the series, so the pieces are the pieces of one logical
|
||||
// output: together they cover each valued position once.
|
||||
// `stitch` panics if a flush repeated a row.
|
||||
assert_eq!(pieces.len(), 2, "two hand-outs of the one series");
|
||||
let mut expanded = expand(&one);
|
||||
let expanded = expand(&one);
|
||||
let stitched = stitch(&pieces);
|
||||
assert_eq!(stitched, expanded, "the flushed rows moved");
|
||||
// The first hand-out is the prefix of the whole, in run terms.
|
||||
let prefix = run_ranges(&pieces[0]);
|
||||
assert_eq!(prefix, vec![(0, 2), (4, 1)]);
|
||||
assert_eq!(
|
||||
@@ -1198,16 +982,8 @@ mod acceptance {
|
||||
prefix.as_slice(),
|
||||
"the prefix is the beginning of the whole series"
|
||||
);
|
||||
expanded[4] = vec![Some(4.0)];
|
||||
assert_eq!(stitched[4], expanded[4]);
|
||||
}
|
||||
|
||||
/// D: fields with complementary holes keep one row per position and a null where a field has
|
||||
/// no value, so no field loses a row another field fills.
|
||||
///
|
||||
/// Field A holds values at positions 0 and 5, field B at 2 and 5. Positions 0, 2 and 5 hold
|
||||
/// something, so the axis carries three rows and each field has a null at the two positions it
|
||||
/// does not fill.
|
||||
#[test]
|
||||
fn complementary_field_holes_keep_every_field_row_aligned() {
|
||||
const POINTS: usize = 8;
|
||||
@@ -1260,11 +1036,6 @@ mod acceptance {
|
||||
);
|
||||
}
|
||||
|
||||
/// D: an ordinary NaN is a *value*: it keeps its row and its payload is not a hole.
|
||||
///
|
||||
/// The stale marker Prometheus uses is a particular NaN payload; an ordinary NaN must survive
|
||||
/// as a sample, including when it is the only value at a position and when it sits next to a
|
||||
/// hole.
|
||||
#[test]
|
||||
fn an_ordinary_nan_is_a_present_value_and_not_a_hole() {
|
||||
const POINTS: usize = 6;
|
||||
@@ -1307,7 +1078,6 @@ mod acceptance {
|
||||
read[2].1.is_some_and(f64::is_nan),
|
||||
"the second NaN was dropped"
|
||||
);
|
||||
// The dense reference agrees, and it holds no value at the hole.
|
||||
let dense = expand(&series);
|
||||
assert_eq!(dense.len(), POINTS);
|
||||
assert!(dense[1][0].is_some_and(f64::is_nan));
|
||||
@@ -1316,22 +1086,13 @@ mod acceptance {
|
||||
assert!(dense[5][0].is_some_and(f64::is_nan));
|
||||
}
|
||||
|
||||
/// D: a float field and a histogram field on one axis, and an all-histogram one, keep their
|
||||
/// sample kinds and their row alignment.
|
||||
///
|
||||
/// `Samples::try_from_mixed` rejects a position holding both a float and a histogram, so the
|
||||
/// two kinds take turns; the positions holding one are the rows of the axis, and a histogram
|
||||
/// sample reads back as `SampleRef::Histogram`, not as a float.
|
||||
#[test]
|
||||
fn mixed_and_histogram_fields_keep_their_sample_kinds() {
|
||||
const POINTS: usize = 8;
|
||||
let schema = schema(2, POINTS as u64);
|
||||
let text = "0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///";
|
||||
let owned = OwnedHistogram::parse(text);
|
||||
// Position -> the value of each field: field 0 is mixed (float or histogram), field 1 is
|
||||
// all-histogram. A position holds a row when either field has a value there.
|
||||
// A position holds a row only when some field has a value there, so 2, 4, 5 and 7 -- which
|
||||
// are absent from this list -- are holes rather than rows of nulls.
|
||||
// Field 0 is mixed, field 1 all-histogram; positions 2, 4, 5 and 7 are holes.
|
||||
let rows: [(usize, Option<f64>, bool); 4] = [
|
||||
(0, Some(0.0), false),
|
||||
(1, None, true),
|
||||
@@ -1348,7 +1109,6 @@ mod acceptance {
|
||||
let mut values = Vec::with_capacity(2);
|
||||
values.push(float.map(GridSample::Float));
|
||||
expected_rows.push((index, float.is_some(), *histogram));
|
||||
// Field 1 holds a histogram whenever the row says so.
|
||||
let histogram_sample = if *histogram {
|
||||
Some(GridSample::Histogram(Box::new(
|
||||
crate::histogram_eval::float_histogram::FloatHistogram::try_from_view(
|
||||
@@ -1377,8 +1137,6 @@ mod acceptance {
|
||||
vec![(0, 2), (3, 1), (6, 1)],
|
||||
"rows at 0-1, 3 and 6"
|
||||
);
|
||||
// A field that never held a histogram stays a plain float column; the all-histogram one is
|
||||
// a mixed column whose float side is null everywhere.
|
||||
assert!(
|
||||
matches!(
|
||||
series.fields.as_slice()[0].dense(),
|
||||
@@ -1430,13 +1188,7 @@ mod acceptance {
|
||||
}
|
||||
}
|
||||
|
||||
/// E: one set of points, five representations of it, one answer.
|
||||
///
|
||||
/// The variants are a contiguous axis with explicit nulls, a fragmented axis built by
|
||||
/// `sparse_series`, the same fragmented positions split into different span groupings, and the
|
||||
/// field samples split into different chunk boundaries. A representation is a way of saying
|
||||
/// where the rows sit and where the sample descriptors end, so none of them may change what a
|
||||
/// reader sees.
|
||||
/// Axis and chunk representations of one set of points must read the same.
|
||||
#[test]
|
||||
fn one_set_of_points_in_five_representations_expands_the_same() {
|
||||
const POINTS: usize = 10;
|
||||
@@ -1467,10 +1219,7 @@ mod acceptance {
|
||||
assert_eq!(fragmented.time.len(), points.len());
|
||||
assert_eq!(run_ranges(&fragmented), vec![(0, 2), (4, 1), (7, 2)]);
|
||||
|
||||
// 3. The same positions, split into different span groupings: `[(0,2),(4,1),(7,2)]` and
|
||||
// `[(0,1),(1,1),(4,1),(7,2)]` are the same rows, described with three and four spans.
|
||||
// The axis keeps adjacent spans apart, so the raw span count differs while the set of
|
||||
// carried positions -- and therefore the expanded matrix -- does not.
|
||||
// 3. The same positions with adjacent spans kept apart.
|
||||
let regrouped = {
|
||||
let values: Vec<f64> = points.values().map(|bits| f64::from_bits(*bits)).collect();
|
||||
let time = TimeAxis::from_grid_spans(
|
||||
@@ -1503,8 +1252,7 @@ mod acceptance {
|
||||
"the coalesced axis stores three"
|
||||
);
|
||||
|
||||
// 4. The same rows with the field samples in different chunks: two chunks and three
|
||||
// chunks, split at different points. A chunk boundary is a descriptor, not a row.
|
||||
// 4. The same rows with the field samples split into two and three chunks.
|
||||
let chunked = |cuts: &[usize]| -> Series {
|
||||
let values: Vec<f64> = points.values().map(|bits| f64::from_bits(*bits)).collect();
|
||||
let mut chunks = Vec::new();
|
||||
@@ -1541,9 +1289,7 @@ mod acceptance {
|
||||
assert_eq!(*dense, expected, "variant {index} disagrees");
|
||||
}
|
||||
|
||||
// Where the axis is genuinely the same, the runs are compared directly; across regroupings
|
||||
// only the expanded positions are, since a span boundary at 0|1 and at 0..2 are the same
|
||||
// rows.
|
||||
// Regrouped spans change the run list, so only the expanded positions are compared there.
|
||||
let positions = |series: &Series| -> Vec<usize> {
|
||||
series
|
||||
.time
|
||||
@@ -1567,7 +1313,6 @@ mod acceptance {
|
||||
"variant {index} lost the grid"
|
||||
);
|
||||
}
|
||||
// The chunked variants read the same samples row by row.
|
||||
let read = |series: &Series| -> Vec<Option<f64>> {
|
||||
let mut cursor = series.fields.as_slice()[0].cursor();
|
||||
series
|
||||
@@ -1588,8 +1333,7 @@ mod acceptance {
|
||||
}
|
||||
}
|
||||
|
||||
/// The payload of one histogram, field by field, with every float compared by its bits so that a
|
||||
/// value that moved by one bit is not equal.
|
||||
/// The payload of one histogram with floats as bits.
|
||||
fn payload(view: &HistogramView<'_>) -> Vec<u64> {
|
||||
let hint = match view.reset_hint {
|
||||
CounterResetHint::Unknown => 0,
|
||||
@@ -1620,8 +1364,7 @@ fn payload(view: &HistogramView<'_>) -> Vec<u64> {
|
||||
bits
|
||||
}
|
||||
|
||||
/// A value pushed from the view it was read as lands in the result as the payload the owned route
|
||||
/// writes, start timestamp included: a selection that only hands a sample on leaves it as it is.
|
||||
/// `push_refs` and `push_samples` write the same payload, start timestamp included.
|
||||
#[test]
|
||||
fn a_pushed_view_writes_the_payload_of_the_owned_route() {
|
||||
let schema = grid_schema(2, 3);
|
||||
@@ -1629,7 +1372,6 @@ fn a_pushed_view_writes_the_payload_of_the_owned_route() {
|
||||
OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///"),
|
||||
OwnedHistogram::parse("0/0/0/4000000000000000/4008000000000000/1/0_1/4000000000000000///"),
|
||||
];
|
||||
// The sample a scan read: the payload of its row plus the start timestamp the row carried.
|
||||
let mut stamped = histograms[1].view();
|
||||
stamped.start_timestamp = Some(1_500);
|
||||
let views = [histograms[0].view(), stamped];
|
||||
@@ -1699,7 +1441,6 @@ fn a_pushed_view_writes_the_payload_of_the_owned_route() {
|
||||
],
|
||||
"the pushed view lost the payload it was read with"
|
||||
);
|
||||
// The comparison covers the start timestamp, which the two routes had to preserve.
|
||||
assert_ne!(
|
||||
payload(&views[1]),
|
||||
payload(&histograms[1].view()),
|
||||
|
||||
@@ -20,8 +20,6 @@
|
||||
mod aggregate;
|
||||
mod bounds;
|
||||
mod classic;
|
||||
// `sub`, `copy_to_schema`, `detect_reset` and `equals` are for the native histogram range
|
||||
// functions and binary operators, which build on other branches.
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub(crate) mod float_histogram;
|
||||
pub(crate) mod legacy_bridge;
|
||||
@@ -50,8 +48,9 @@ use crate::map::validate_grid_series;
|
||||
|
||||
pub(crate) const BUCKET_LABEL: &str = "le";
|
||||
|
||||
/// Histogram inputs that can produce the same output must meet at one partition. The kernel
|
||||
/// still groups by metadata before removing it, so distinct histograms are not mixed together.
|
||||
/// Labels left out of the routing key, so histogram inputs that can produce the same output meet
|
||||
/// at one partition. The kernel still groups by the metadata labels before dropping them; `le` is
|
||||
/// removed before grouping.
|
||||
pub(crate) const HISTOGRAM_ROUTING_EXCLUDED_LABELS: [&str; 4] =
|
||||
[BUCKET_LABEL, "__name__", "__type__", "__unit__"];
|
||||
|
||||
@@ -68,10 +67,7 @@ pub enum HistogramFunction {
|
||||
/// `q`, each result labelled with `label` set to `q` as Prometheus' `FormatOpenMetricsFloat`
|
||||
/// writes it. Results that then share a label set merge as [`merge_same_labelset`] does, so a
|
||||
/// repeated `q`, or a `label` that overwrites the label telling two histograms apart, fails at a
|
||||
/// point both hold.
|
||||
///
|
||||
/// Each `q` is a constant. Prometheus evaluates the quantile arguments at every step, so a
|
||||
/// quantile that varies over time is not this kernel's to evaluate.
|
||||
/// point both hold. Each `q` is a constant; a per-step quantile is not supported here.
|
||||
pub fn histogram_quantiles(
|
||||
label: &str,
|
||||
quantiles: &[f64],
|
||||
@@ -125,8 +121,7 @@ pub(crate) fn evaluate_histograms_with_annotations(
|
||||
parameters: Option<HistogramParameters<'_>>,
|
||||
collector: Option<&PromqlAnnotationCollector>,
|
||||
) -> Result<Vec<Series>> {
|
||||
// The groups in the order their first member arrived, so the result is in one order on every
|
||||
// run, as `merge_same_labelset` keeps it.
|
||||
// Groups keep first-arrival order so the output order is deterministic.
|
||||
let mut index: HashMap<LabelSet, usize> = HashMap::new();
|
||||
let mut groups: Vec<Group<'_>> = Vec::new();
|
||||
let mut group_of = |metric: SeriesLabels| {
|
||||
@@ -156,8 +151,6 @@ pub(crate) fn evaluate_histograms_with_annotations(
|
||||
match upper_bound {
|
||||
Some(upper_bound) => group.classic.push((upper_bound, series)),
|
||||
None => {
|
||||
// A label set carries at most one native histogram series: a second one would
|
||||
// overwrite the first and drop it from the result.
|
||||
debug_assert!(
|
||||
group.native.is_none(),
|
||||
"one label set carries at most one native histogram series; a second one for \
|
||||
@@ -175,18 +168,15 @@ pub(crate) fn evaluate_histograms_with_annotations(
|
||||
let mut native_buckets = Vec::new();
|
||||
let mut values = vec![None; schema.fields.len()];
|
||||
for mut group in groups {
|
||||
// One builder serves every group, so each result series starts explicitly.
|
||||
builder.begin_series();
|
||||
// The positions any member carries, merged once: the holes no member holds are never
|
||||
// visited, so a group of sparse series costs its rows and not its envelope.
|
||||
// Visit only positions some member holds, so sparse groups cost their rows, not their
|
||||
// envelope.
|
||||
let axes = group
|
||||
.classic
|
||||
.iter()
|
||||
.map(|member| &member.1.time)
|
||||
.chain(group.native.map(|native| &native.time));
|
||||
// One forward cursor per member and field. The merged positions only increase, so each
|
||||
// member's rows do too: reading them costs one pass over the field, not a chunk scan per
|
||||
// row. The classic members come first, then the native one.
|
||||
// One forward cursor per member and field: classic members first, then the native one.
|
||||
let members = group
|
||||
.classic
|
||||
.iter()
|
||||
@@ -252,7 +242,6 @@ pub(crate) fn evaluate_histograms_with_annotations(
|
||||
HistogramFunction::Fraction { lower, upper }
|
||||
}
|
||||
};
|
||||
// A native histogram and classic buckets of one label set conflict.
|
||||
*value = match (native, classic_buckets.is_empty()) {
|
||||
(Some(_), false) => {
|
||||
if let Some(collector) = collector {
|
||||
@@ -308,7 +297,7 @@ impl Group<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that `series` is addressed on a grid, which is what a position lookup needs.
|
||||
/// Errors unless `series` is on a grid axis.
|
||||
fn grid_axis(series: &Series) -> Result<&TimeAxis> {
|
||||
if series.time.grid().is_none() {
|
||||
return Err(DataFusionError::Execution(
|
||||
@@ -344,13 +333,8 @@ pub enum NativeHistogramFunction {
|
||||
}
|
||||
|
||||
/// Applies `function` to the native histogram samples of `series`; float samples are dropped and
|
||||
/// so is `__name__`. `None` when the series has no histogram sample.
|
||||
///
|
||||
/// Histogram samples may leave holes, but the holes only skip positions: the result is one series
|
||||
/// over the runs of consecutive positions that hold a value.
|
||||
///
|
||||
/// Series that share a label set once their names are dropped must then go through
|
||||
/// [`merge_same_labelset`].
|
||||
/// so is `__name__`. `None` when the series has no histogram sample. Series that share a label
|
||||
/// set once their names are dropped must then go through [`merge_same_labelset`].
|
||||
pub fn map_native_histogram(
|
||||
function: NativeHistogramFunction,
|
||||
schema: &Arc<SeriesSchema>,
|
||||
@@ -360,8 +344,6 @@ pub fn map_native_histogram(
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
|
||||
let mut buckets = Vec::new();
|
||||
let mut values = vec![None; schema.fields.len()];
|
||||
// One cursor per field, driven by the positions the axis carries: a series of several runs
|
||||
// costs its rows, and the positions it skips are never visited.
|
||||
let mut cursors = series
|
||||
.fields
|
||||
.iter()
|
||||
@@ -386,7 +368,6 @@ pub fn map_native_histogram(
|
||||
}
|
||||
|
||||
impl NativeHistogramFunction {
|
||||
/// The PromQL name of the function.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Count => "histogram_count",
|
||||
|
||||
@@ -21,7 +21,6 @@ use datafusion::error::Result;
|
||||
|
||||
use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
|
||||
/// A native histogram aggregation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum HistogramAggregate {
|
||||
Sum,
|
||||
@@ -29,14 +28,9 @@ pub(crate) enum HistogramAggregate {
|
||||
}
|
||||
|
||||
/// 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. The result is derived, so it carries no start
|
||||
/// timestamp.
|
||||
///
|
||||
/// The flag reports whether any add had to reconcile two different custom-bucket sets, which is
|
||||
/// what Prometheus annotates with an info. It is carried out of the fold rather than recomputed:
|
||||
/// the fold already calls [`FloatHistogram::kahan_add`] and receives that outcome.
|
||||
/// none or they mix exponential and custom buckets. The first input error ends the fold. The
|
||||
/// result has no start timestamp. The flag reports whether any add reconciled two different
|
||||
/// custom-bucket sets, which Prometheus annotates with an info.
|
||||
pub(crate) fn sum_or_avg(
|
||||
op: HistogramAggregate,
|
||||
histograms: impl IntoIterator<Item = Result<FloatHistogram>>,
|
||||
@@ -120,11 +114,8 @@ 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.
|
||||
// A single-input fold returns its input unchanged, so clear the start timestamp the adds
|
||||
// would otherwise have cleared.
|
||||
value.start_timestamp = None;
|
||||
Ok((Some(value), custom_reconciled))
|
||||
}
|
||||
|
||||
@@ -31,11 +31,8 @@ use crate::histogram_eval::native::{CUSTOM_BUCKETS_SCHEMA, bound};
|
||||
|
||||
type Buckets = Vec<(i32, f64)>;
|
||||
|
||||
/// How often this thread built an owned histogram from a view, so a test can hold a path to the
|
||||
/// copies it should not make rather than to the shape of its arguments. Test-only: a copy and a
|
||||
/// borrow produce the same value, so a test comparing only values could not tell the two apart. The
|
||||
/// counter belongs to the calling thread, so tests running side by side cannot see each other's
|
||||
/// work.
|
||||
/// Counts owned histograms built from views on this thread, so a test can assert that a path
|
||||
/// borrows instead of copying; the values alone cannot tell the two apart.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod copies {
|
||||
use std::cell::Cell;
|
||||
@@ -45,13 +42,11 @@ pub(crate) mod copies {
|
||||
static MATERIALIZED: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Records one owned histogram built from a view.
|
||||
pub(crate) fn record_materialized() {
|
||||
MATERIALIZED.with(|built| built.set(built.get() + 1));
|
||||
}
|
||||
|
||||
/// The owned histograms built from a view on this thread since the last call, which starts a
|
||||
/// new count.
|
||||
/// Returns the count since the last call and resets it.
|
||||
pub(crate) fn take_materialized() -> usize {
|
||||
MATERIALIZED.with(|built| built.replace(0))
|
||||
}
|
||||
@@ -63,19 +58,12 @@ 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.
|
||||
/// GreptimeDB row metadata; Prometheus `FloatHistogram` has no such field. [`Self::try_from_view`]
|
||||
/// reads it and [`Self::push_to`] writes it back. A histogram derived by an operation
|
||||
/// ([`Self::add`], [`Self::kahan_add`], [`Self::sub`], [`Self::mul`], [`Self::div`],
|
||||
/// [`Self::compact`], [`Self::copy_to_schema`], [`Self::empty_like`]) has none, and
|
||||
/// [`Self::equals`] ignores it. The native range kernels read it to detect counter resets
|
||||
/// ([`Self::detect_counter_reset_shifted`]) and to extrapolate `rate`/`increase` to a zero point.
|
||||
pub(crate) start_timestamp: Option<i64>,
|
||||
pub(crate) schema: i32,
|
||||
pub(crate) zero_threshold: f64,
|
||||
@@ -143,10 +131,8 @@ impl FloatHistogram {
|
||||
})
|
||||
}
|
||||
|
||||
/// Estimates the heap held by the bucket lists, custom bounds and preserved span layout.
|
||||
///
|
||||
/// A histogram can own tens of kilobytes of buckets that its struct size does not include.
|
||||
/// Capacity slack and small header overestimates are acceptable for window reservations.
|
||||
/// Estimated heap bytes of the bucket lists, custom bounds and span layout, for memory
|
||||
/// reservations; may overestimate slightly.
|
||||
pub(crate) fn heap_bytes(&self) -> usize {
|
||||
fn buckets(side: &Buckets) -> usize {
|
||||
side.capacity() * std::mem::size_of::<(i32, f64)>()
|
||||
@@ -170,11 +156,7 @@ impl FloatHistogram {
|
||||
}
|
||||
|
||||
/// The spans of each side: the layout a view was read with, or the compacted layout of a
|
||||
/// histogram this crate derived.
|
||||
///
|
||||
/// [`crate::histogram_eval::legacy_bridge`] reads them to build the legacy
|
||||
/// `NativeHistogram`, whose spans are explicit where this type keeps them in the bucket
|
||||
/// indices.
|
||||
/// derived histogram.
|
||||
pub(crate) fn spans(&self) -> [Vec<(i32, i32)>; 2] {
|
||||
self.layout
|
||||
.clone()
|
||||
@@ -238,7 +220,6 @@ 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;
|
||||
@@ -253,7 +234,6 @@ 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;
|
||||
@@ -288,7 +268,6 @@ 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);
|
||||
@@ -298,8 +277,6 @@ 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 {
|
||||
// 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()
|
||||
@@ -336,7 +313,6 @@ 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),
|
||||
@@ -406,7 +382,6 @@ 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),
|
||||
@@ -493,9 +468,8 @@ impl FloatHistogram {
|
||||
|
||||
/// Go `newCompensationHistogram`: the layout of `self` with zero counts.
|
||||
///
|
||||
/// This is the zero compensation a fold starts from, and the only zero a compensated add may be
|
||||
/// seeded with: an [`Self::empty_like`] histogram has no bucket indices, while the Kahan update
|
||||
/// indexes the compensation by the value's positions.
|
||||
/// A compensated add must start from this, not from [`Self::empty_like`]: the Kahan update
|
||||
/// indexes the compensation by the value's bucket positions.
|
||||
pub(crate) fn new_compensation(&self) -> Self {
|
||||
Self {
|
||||
reset_hint: self.reset_hint,
|
||||
@@ -663,19 +637,13 @@ impl FloatHistogram {
|
||||
bound(idx, self.schema, &self.custom_values)
|
||||
}
|
||||
|
||||
/// Detects a counter reset for a window whose timestamps an `offset` has already moved.
|
||||
/// Detects a counter reset from `previous` to `self`, by start timestamp (Prometheus
|
||||
/// `isStartTimestampReset`) or by `detect_reset`. `previous_ts` and `current_ts` are sample
|
||||
/// times already shifted by `offset_ms`, as `range_eval` hands them.
|
||||
///
|
||||
/// `range_eval` hands its windows at `timestamp + offset_ms` while a histogram's start
|
||||
/// timestamp stays on the axis the sender wrote it on, so one of the two has to move. The
|
||||
/// window timestamps are moved back here rather than the start timestamps forward, because a
|
||||
/// start of `0` means "the sender stated none" and moving it forward can cancel the offset
|
||||
/// into a real instant: a start of 2500ms under `offset -2.5s` would become that `0` and stop
|
||||
/// being read as a reset. Restoring the sample times keeps the absence meaning what it means.
|
||||
///
|
||||
/// The subtraction wraps, which is what Go's `int64` arithmetic does and what
|
||||
/// [`crate::range_eval::function::extrapolation_factor`] relies on for the same reason: real
|
||||
/// timestamps are nowhere near the range where the two disagree, and wrapping cannot turn a
|
||||
/// missing start timestamp into a present one.
|
||||
/// The sample times are shifted back rather than the start timestamps forward: a start of `0`
|
||||
/// means none was stated, and shifting could turn a real start into `0` (2500ms under
|
||||
/// `offset -2.5s`). The subtraction wraps, like Go `int64` arithmetic.
|
||||
pub(crate) fn detect_counter_reset_shifted(
|
||||
&self,
|
||||
previous: &Self,
|
||||
|
||||
@@ -12,20 +12,9 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The legacy native-histogram estimators, delegated to the native kernel.
|
||||
//!
|
||||
//! `prom_native_histogram_quantile` and `prom_native_histogram_fraction` used to estimate with the
|
||||
//! bucket walk inside `NativeHistogram` itself: exponential bucket bounds computed as `2^x`, and a
|
||||
//! forward walk from the lowest bucket only. The native kernel (`histogram_eval`) walks the same
|
||||
//! histogram the way Prometheus does -- the bound table in `bounds` and, for a quantile above the
|
||||
//! median of a histogram whose sum is not NaN, a walk from the highest bucket down -- so keeping
|
||||
//! both estimators leaves two answers for one histogram that differ in their last places.
|
||||
//!
|
||||
//! These functions read a [`NativeHistogram`] through the borrowed [`HistogramView`] that both
|
||||
//! representations share, hand it to the kernel as the [`FloatHistogram`] the kernel owns, and
|
||||
//! return the answer in the shape the legacy UDFs report it. The scalar arithmetic -- `add`, `sub`,
|
||||
//! `scale`, `divide_by` -- takes the same route below the estimators, so Prometheus's rules for
|
||||
//! reconciling a zero bucket, reducing a schema and intersecting custom bounds live in one place.
|
||||
//! Legacy [`NativeHistogram`] quantile, fraction and arithmetic, evaluated by the native kernel
|
||||
//! so both paths share one implementation of Prometheus's histogram rules. Each function reads
|
||||
//! the histogram through a [`HistogramView`] and returns results in the legacy UDFs' shape.
|
||||
|
||||
use common_query::native_histogram::{
|
||||
CounterResetHint, NativeHistogram, NativeHistogramQuantileInfo, Span,
|
||||
@@ -36,11 +25,8 @@ use datatypes::series::histogram::{BucketSideView, HistogramView};
|
||||
use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
use crate::histogram_eval::native;
|
||||
|
||||
/// A [`NativeHistogram`] borrowed as a [`HistogramView`], the form the native kernel reads.
|
||||
///
|
||||
/// A view holds its spans as two parallel slices while a `NativeHistogram` holds them as
|
||||
/// [`Span`]s, so the offsets and lengths are copied here and the counts, bounds and metadata stay
|
||||
/// borrowed for as long as the view lives.
|
||||
/// A [`NativeHistogram`] borrowed as a [`HistogramView`]. Span offsets and lengths are copied
|
||||
/// into parallel columns; everything else stays borrowed.
|
||||
pub(crate) struct LegacyView<'a> {
|
||||
histogram: &'a NativeHistogram,
|
||||
positive_offsets: Vec<i32>,
|
||||
@@ -62,7 +48,6 @@ impl<'a> LegacyView<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The view of the histogram these span columns were taken from.
|
||||
pub(crate) fn view(&self) -> HistogramView<'_> {
|
||||
HistogramView {
|
||||
schema: self.histogram.schema,
|
||||
@@ -99,9 +84,8 @@ pub(crate) fn quantile_with_info(
|
||||
let view = LegacyView::new(histogram);
|
||||
match native::quantile(q, &view.view(), &mut Vec::new()) {
|
||||
Ok(value) => (value, nan_observation_info(histogram, q)),
|
||||
// The kernel refuses a layout it cannot walk, a custom histogram carrying a zero count
|
||||
// among them. The legacy estimator reported a histogram it could not read as no estimate,
|
||||
// which is the same NaN without a note about NaN observations.
|
||||
// A layout the kernel refuses (e.g. custom buckets with a zero count) is NaN with no
|
||||
// note, as the legacy estimator answered.
|
||||
Err(_) => (f64::NAN, None),
|
||||
}
|
||||
}
|
||||
@@ -115,8 +99,8 @@ pub(crate) fn fraction_with_info(
|
||||
let view = LegacyView::new(histogram);
|
||||
match native::fraction(lower, upper, &view.view(), &mut Vec::new()) {
|
||||
Ok(value) => {
|
||||
// The same answer the legacy estimator gave: a fraction is degenerate, and reports
|
||||
// nothing, unless it runs for a non-empty histogram over an increasing pair of bounds.
|
||||
// A degenerate fraction (empty histogram, NaN or non-increasing bounds) reports
|
||||
// nothing, as the legacy estimator did.
|
||||
let excluded_nans = histogram.count != 0.0
|
||||
&& !lower.is_nan()
|
||||
&& !upper.is_nan()
|
||||
@@ -129,13 +113,9 @@ pub(crate) fn fraction_with_info(
|
||||
}
|
||||
}
|
||||
|
||||
/// The note for a NaN observation, which the kernel accounts for but does not report.
|
||||
///
|
||||
/// A NaN observation leaves the sum NaN and puts fewer observations in the buckets than the count
|
||||
/// holds them (Prometheus marks it the same way). The kernel then walks the buckets forward from
|
||||
/// the lowest, so the note distinguishes the two outcomes: the estimate is skewed higher when the
|
||||
/// requested rank falls inside the buckets' total, and NaN when it falls past it because the
|
||||
/// observations the buckets cannot carry were the highest ones.
|
||||
/// The NaN-observation note the kernel does not report. A NaN observation leaves the sum NaN and
|
||||
/// the bucket total below the count: the estimate is NaN when the requested rank falls past the
|
||||
/// bucket total, and skewed otherwise.
|
||||
fn nan_observation_info(
|
||||
histogram: &NativeHistogram,
|
||||
q: f64,
|
||||
@@ -154,8 +134,7 @@ fn nan_observation_info(
|
||||
})
|
||||
}
|
||||
|
||||
/// What the populated buckets hold, summed in the order the kernel walks them: the negative side
|
||||
/// from its highest index down, the zero bucket, then the positive side upwards.
|
||||
/// The sum of all bucket counts, in the kernel's forward walk order so rounding matches.
|
||||
fn bucket_total(histogram: &NativeHistogram) -> f64 {
|
||||
let mut total = 0.0;
|
||||
for count in histogram.negative_buckets.iter().rev() {
|
||||
@@ -168,10 +147,7 @@ fn bucket_total(histogram: &NativeHistogram) -> f64 {
|
||||
total
|
||||
}
|
||||
|
||||
/// The native kernel's owned form of `histogram`.
|
||||
///
|
||||
/// A view borrows the offsets and lengths it needs from two temporary slices, so the copy happens
|
||||
/// here and the `FloatHistogram` owns the counts that result.
|
||||
/// The native kernel's owned form of `histogram`; errors on a span list that steps backwards.
|
||||
fn float_histogram(histogram: &NativeHistogram) -> Result<FloatHistogram> {
|
||||
if steps_backwards(&histogram.positive_spans) || steps_backwards(&histogram.negative_spans) {
|
||||
return Err(datafusion::error::DataFusionError::Execution(
|
||||
@@ -182,12 +158,9 @@ fn float_histogram(histogram: &NativeHistogram) -> Result<FloatHistogram> {
|
||||
FloatHistogram::try_from_view(&view.view())
|
||||
}
|
||||
|
||||
/// Whether a span list steps backwards, which the legacy `bucket_indices` refused.
|
||||
///
|
||||
/// The kernel's `side_from_view` adds each offset to a running index and accepts a later span that
|
||||
/// steps backwards, so the expanded indices repeat or go negative. Legacy refused such a list
|
||||
/// outright, so the bridge refuses it too: `add`/`sub` answer `None` as they did, and
|
||||
/// `scale`/`divide_by` keep their field-by-field fallback.
|
||||
/// Whether a later span has a negative offset. `side_from_view` would accept it and produce
|
||||
/// repeated indices; legacy refused it, so `add`/`sub` answer `None` and `scale`/`divide_by` fall
|
||||
/// back to field-by-field arithmetic.
|
||||
fn steps_backwards(spans: &[Span]) -> bool {
|
||||
spans.iter().skip(1).any(|span| span.offset < 0)
|
||||
}
|
||||
@@ -245,12 +218,8 @@ fn combine(
|
||||
combined.add(&other)
|
||||
}
|
||||
.ok()?;
|
||||
// The outcome reports what the kernel already folded into the result, and the legacy callers
|
||||
// report both from the operands before the call: `custom_bounds_reconciled` is the intersection
|
||||
// the kernel keeps in `custom_values`, which `needs_custom_reconciliation` announces, and a
|
||||
// `counter_reset_collision` is the contradiction the kernel answers with an unknown hint, which
|
||||
// is what the legacy arithmetic derived from two hints that disagree. Holding the kernel to
|
||||
// both keeps a change there from dropping either.
|
||||
// Legacy callers derive both annotations from the operands before the call; these asserts
|
||||
// keep the kernel's outcome consistent with that.
|
||||
debug_assert_eq!(
|
||||
outcome.custom_bounds_reconciled,
|
||||
left.needs_custom_reconciliation(right)
|
||||
@@ -261,8 +230,7 @@ fn combine(
|
||||
if subtract {
|
||||
combined.reset_hint = CounterResetHint::Gauge;
|
||||
}
|
||||
// The legacy arithmetic compacted a sum, so a bucket the two sides cancel out of leaves no
|
||||
// span behind; the kernel keeps the bucket until a caller drops it.
|
||||
// Legacy arithmetic compacted the result, dropping buckets that cancel out.
|
||||
combined.compact();
|
||||
Some(legacy_histogram(&combined))
|
||||
}
|
||||
@@ -270,10 +238,8 @@ fn combine(
|
||||
/// `histogram * factor`, a gauge histogram for a negative factor.
|
||||
pub(crate) fn scale(histogram: &NativeHistogram, factor: f64) -> NativeHistogram {
|
||||
let Ok(mut scaled) = float_histogram(histogram) else {
|
||||
// A layout the kernel cannot read -- spans that disagree with the counts, or a bucket index
|
||||
// that leaves `i32` once expanded -- keeps the field-by-field scaling the legacy caller
|
||||
// had, so such a histogram is still multiplied instead of dropped, and reports its layout
|
||||
// when it is serialized. Scaling has no bounds to reconcile, so nothing is lost here.
|
||||
// A layout the kernel cannot read is still scaled field by field instead of dropped;
|
||||
// scaling needs no bucket reconciliation.
|
||||
return field_scaled(histogram, factor);
|
||||
};
|
||||
scaled.mul(factor);
|
||||
@@ -346,9 +312,6 @@ mod tests {
|
||||
use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
use crate::histogram_eval::native;
|
||||
|
||||
/// Every kind of histogram the legacy representation can hold: exponential and custom, one
|
||||
/// side and two, a zero bucket, gaps between the spans, a NaN sum standing for NaN
|
||||
/// observations, and a histogram with no buckets at all.
|
||||
fn fixtures() -> Vec<(&'static str, NativeHistogram)> {
|
||||
let mut custom = empty(CUSTOM_BUCKETS_SCHEMA, 0.0, 7.0, 21.0, 0.0);
|
||||
custom.custom_values = vec![1.0, 2.0, 4.0];
|
||||
@@ -452,8 +415,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The legacy UDFs read their quantile out of the kernel now, so the two must agree to the
|
||||
/// last bit for every kind of histogram the legacy representation can hold.
|
||||
#[test]
|
||||
fn quantile_with_info_is_the_native_quantile() {
|
||||
for (name, histogram) in fixtures() {
|
||||
@@ -485,18 +446,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Prometheus's NaN branch walks the remaining buckets and leaves the last one for the
|
||||
/// interpolation, so a multi-bucket `sum = NaN` histogram answers with the top bucket rather
|
||||
/// than the bucket the rank fell into. Pinning the number here, rather than only comparing
|
||||
/// against the kernel, keeps a future kernel change from silently re-deciding it.
|
||||
/// Prometheus's NaN branch walks the remaining buckets and interpolates in the last one, not
|
||||
/// the bucket the rank fell into.
|
||||
#[test]
|
||||
fn quantile_with_nan_sum_uses_the_last_bucket() {
|
||||
let mut histogram = empty(0, 0.0, 10.0, f64::NAN, 0.0);
|
||||
histogram.positive_spans = vec![span(0, 2)];
|
||||
histogram.positive_buckets = vec![8.0, 1.0];
|
||||
|
||||
// The nine observations the buckets hold are fewer than the count of ten and the sum is
|
||||
// NaN, so the note reports the skew: the rank still falls inside what the buckets carry.
|
||||
// Buckets hold 9 of 10 observations; rank 5 is inside them, so the note is a skew.
|
||||
let (value, info) = quantile_with_info(&histogram, 0.5);
|
||||
assert_eq!(
|
||||
value.to_bits(),
|
||||
@@ -511,16 +469,13 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The other half of the same note: a rank past the total the buckets carry is no estimate at
|
||||
/// all, because the observations the buckets cannot hold were the highest ones.
|
||||
#[test]
|
||||
fn quantile_with_nan_sum_below_the_rank_is_nan() {
|
||||
let mut histogram = empty(0, 0.0, 10.0, f64::NAN, 0.0);
|
||||
histogram.positive_spans = vec![span(0, 2)];
|
||||
histogram.positive_buckets = vec![8.0, 1.0];
|
||||
|
||||
// The rank 0.95 * 10 = 9.5 lies past the 9 observations the buckets hold, so the forward
|
||||
// walk never reaches it and the estimate is NaN rather than the last bucket's bound.
|
||||
// Rank 9.5 lies past the 9 observations the buckets hold.
|
||||
let (value, info) = quantile_with_info(&histogram, 0.95);
|
||||
assert!(
|
||||
value.is_nan(),
|
||||
@@ -532,8 +487,7 @@ mod tests {
|
||||
"the note says the NaN observations were the highest ones"
|
||||
);
|
||||
|
||||
// The single-bucket fixture the earlier note test uses reaches the same branch: the rank
|
||||
// 0.9 * 10 = 9 lies past the 8 observations the one bucket holds.
|
||||
// Single bucket: rank 9 lies past its 8 observations.
|
||||
let mut single = empty(0, 0.0, 10.0, f64::NAN, 0.0);
|
||||
single.positive_spans = vec![span(0, 1)];
|
||||
single.positive_buckets = vec![8.0];
|
||||
@@ -544,31 +498,23 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A tie between two buckets that do not touch resolves differently in the two walks, and that
|
||||
/// difference is why the kernel replaced the estimator: the legacy walk goes up from the lowest
|
||||
/// bucket and stops at the first one the rank fits in, while the kernel walks a finite-sum
|
||||
/// histogram at or above the median down from the highest. Both numbers are pinned as literals,
|
||||
/// the legacy one computed through the estimator still in `common/query`, so that a later
|
||||
/// change to either walk shows up as an arithmetic difference instead of a quiet one.
|
||||
/// The `common/query` estimator walks up from the lowest bucket; Prometheus (the kernel) walks
|
||||
/// a finite-sum histogram down from the highest for q >= 0.5, so an exact tie between two
|
||||
/// non-adjacent buckets resolves differently.
|
||||
#[test]
|
||||
fn exact_tie_answers_one_from_the_legacy_walk_and_two_from_the_kernel() {
|
||||
let mut tie = empty(0, 0.0, 2.0, 3.75, 0.0);
|
||||
// Index 0 and index 2 hold one observation each, and index 1 is empty, so the two buckets
|
||||
// do not touch and nothing interpolates across the gap.
|
||||
// One observation at index 0 and one at index 2.
|
||||
tie.positive_spans = vec![span(0, 1), span(1, 1)];
|
||||
tie.positive_buckets = vec![1.0, 1.0];
|
||||
|
||||
// `NativeHistogram::quantile_with_info` is the estimator the legacy UDF used before the
|
||||
// kernel replaced it and is still in the workspace: rank 0.5 * 2 = 1 fills the bucket at
|
||||
// index 0 exactly, whose fraction is 1, so the answer is that bucket's upper bound.
|
||||
// Rank 1 fills the bucket at index 0 exactly: its upper bound.
|
||||
assert_eq!(
|
||||
tie.quantile_with_info(0.5),
|
||||
(1.0, None),
|
||||
"the legacy walk answers with the upper bound of (0.5, 1]"
|
||||
);
|
||||
|
||||
// The kernel's backwards walk meets the bucket at index 2 first, and the rank inside it is
|
||||
// 0, so the answer is the lower bound of (2, 4].
|
||||
let (value, info) = quantile_with_info(&tie, 0.5);
|
||||
assert_eq!(
|
||||
value.to_bits(),
|
||||
@@ -581,7 +527,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The same agreement for `histogram_fraction`, whose legacy wrapper also returns a note.
|
||||
#[test]
|
||||
fn fraction_with_info_is_the_native_fraction() {
|
||||
for (name, histogram) in fixtures() {
|
||||
@@ -659,8 +604,7 @@ mod tests {
|
||||
nan_right.positive_spans = vec![span(0, 1)];
|
||||
nan_right.positive_buckets = vec![2.0];
|
||||
|
||||
// Every operand carries a start timestamp of its own, because the arithmetic is expected to
|
||||
// clear it: a sum differs from both samples it was derived from, so it names no start.
|
||||
// Start timestamps the arithmetic must clear.
|
||||
same_left.start_timestamp = Some(1_000);
|
||||
same_right.start_timestamp = Some(2_000);
|
||||
fine.start_timestamp = Some(3_001);
|
||||
@@ -681,7 +625,6 @@ mod tests {
|
||||
]
|
||||
}
|
||||
|
||||
/// The buckets a side holds that carry observations, by index and bit pattern.
|
||||
fn populated_buckets(spans: &[Span], buckets: &[f64]) -> Vec<(i32, u64)> {
|
||||
let (offsets, lengths) = columns(spans);
|
||||
let mut index = 0;
|
||||
@@ -721,7 +664,6 @@ mod tests {
|
||||
side.iter().map(|&(_, count)| count.to_bits()).collect()
|
||||
}
|
||||
|
||||
/// A span list as the `(offset, length)` pairs [`FloatHistogram::spans`] reports.
|
||||
fn segments(spans: &[Span]) -> Vec<(i32, i32)> {
|
||||
spans
|
||||
.iter()
|
||||
@@ -729,19 +671,8 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every field of the legacy payload against the kernel's, span segmentation included: a
|
||||
/// comparison of the populated buckets alone cannot tell one span of two buckets from two
|
||||
/// spans of one bucket each, and says nothing about the metadata beside the counts.
|
||||
///
|
||||
/// `expected_start_timestamp` states the policy of the operation that produced the payload. One
|
||||
/// that derives a histogram from its input -- `add`, `sub`, `scale`, `divide_by` -- clears the
|
||||
/// start timestamp, because the field names the start of the sample the payload was read from
|
||||
/// and a derived value is not that sample; the kernel clears it in the same step, so both sides
|
||||
/// must carry the value passed here. `scale` and `divide_by` keep a field-by-field fallback for
|
||||
/// a layout the kernel cannot read, which derives nothing and copies the field, and the test
|
||||
/// that exercises it asserts `Some(..)` where it belongs. `quantile_with_info` and
|
||||
/// `fraction_with_info` return no payload and leave their input untouched, so they have no
|
||||
/// start timestamp to compare here.
|
||||
/// Compares every field, span segmentation included: populated buckets alone cannot tell one
|
||||
/// span of two buckets from two spans of one.
|
||||
fn assert_same_payload(
|
||||
name: &str,
|
||||
legacy: &NativeHistogram,
|
||||
@@ -812,22 +743,18 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The added histogram is the kernel's addition, bucket for bucket and bit for bit.
|
||||
#[test]
|
||||
fn add_is_the_native_add() {
|
||||
for (name, left, right) in pairs() {
|
||||
let combined = add(&left, &right).unwrap();
|
||||
let mut native = float_histogram(&left).unwrap();
|
||||
native.add(&float_histogram(&right).unwrap()).unwrap();
|
||||
// The bridge compacts a sum, dropping the buckets the two sides left empty, so the
|
||||
// kernel's own addition needs the same step before the two payloads can be compared
|
||||
// bucket for bucket.
|
||||
// The bridge compacts its result.
|
||||
native.compact();
|
||||
assert_same_payload(name, &combined, &native, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// The same for subtraction, which the kernel reports as an addition of the negation.
|
||||
#[test]
|
||||
fn sub_is_the_native_sub() {
|
||||
for (name, left, right) in pairs() {
|
||||
@@ -841,8 +768,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Scaling and dividing move every count and leave the layout alone, as the kernel's own
|
||||
/// multiplication and division do.
|
||||
#[test]
|
||||
fn scale_and_divide_by_are_the_native_mul_and_div() {
|
||||
for (name, histogram, _) in pairs() {
|
||||
@@ -860,8 +785,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The note the legacy UDFs turn into an annotation follows the kernel's outcome instead of a
|
||||
/// second reading of the histogram.
|
||||
#[test]
|
||||
fn nan_notes_follow_the_kernel_outcome() {
|
||||
use NativeHistogramQuantileInfo::{NaNResult, NaNSkew};
|
||||
@@ -891,17 +814,12 @@ mod tests {
|
||||
assert!(!fraction_with_info(&nan_sum, 2.0, 1.0).1);
|
||||
}
|
||||
|
||||
/// The two conversions are inverse: the payload survives `NativeHistogram` to
|
||||
/// [`FloatHistogram`] and back field for field, including the parts a comparison of the counts
|
||||
/// alone would not see.
|
||||
#[test]
|
||||
fn round_trip_preserves_the_payload_and_its_span_layout() {
|
||||
let mut exponential = empty(2, 0.5, 12.0, -7.5, 1.0);
|
||||
exponential.reset_hint = CounterResetHint::NotCounterReset;
|
||||
exponential.start_timestamp = Some(1_234_567);
|
||||
// A zero-length span carries nothing but its offset, and the two gaps between the three
|
||||
// populated segments are part of the layout the legacy representation reports: the counts
|
||||
// live at indices 2 and 3 and then 5, with nothing at 4.
|
||||
// A zero-length span and gaps: counts at indices 2, 3 and 5.
|
||||
exponential.positive_spans = vec![span(0, 0), span(2, 2), span(1, 1)];
|
||||
exponential.positive_buckets = vec![1.0, 3.0, 2.0];
|
||||
exponential.negative_spans = vec![span(-2, 2)];
|
||||
@@ -947,8 +865,6 @@ mod tests {
|
||||
count_bits(&original.negative_buckets),
|
||||
"{name} negative buckets"
|
||||
);
|
||||
// Everything else the payload holds -- schema, zero threshold, count, sum and the zero
|
||||
// count -- is compared in one place above.
|
||||
assert_eq!(
|
||||
round_tripped, original,
|
||||
"{name}: the round trip changed the histogram"
|
||||
@@ -956,9 +872,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A histogram an operation derived carries no start timestamp: the field names the start of
|
||||
/// the sample the payload was read from, and a sum, a difference, a product or a quotient is
|
||||
/// not that sample.
|
||||
#[test]
|
||||
fn the_arithmetic_clears_the_start_timestamp() {
|
||||
let mut left = empty(0, 0.0, 2.0, 3.0, 0.0);
|
||||
@@ -981,13 +894,10 @@ mod tests {
|
||||
"{name}: a derived histogram names no start"
|
||||
);
|
||||
}
|
||||
// Reading the operands is not deriving from them.
|
||||
assert_eq!(left.start_timestamp, Some(1_000));
|
||||
assert_eq!(right.start_timestamp, Some(2_000));
|
||||
}
|
||||
|
||||
/// The estimators read the buckets rather than the sample's start timestamp, and neither of
|
||||
/// them hands back a payload, so the field neither changes the answer nor changes itself.
|
||||
#[test]
|
||||
fn the_estimators_leave_the_start_timestamp_alone() {
|
||||
let mut timed = empty(2, 0.5, 20.0, -3.0, 3.0);
|
||||
@@ -1143,10 +1053,8 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Payloads the legacy caller could still produce and the kernel refuses to read: a span whose
|
||||
/// length disagrees with the counts, a span list that steps backwards, an index that leaves
|
||||
/// `i32` once expanded, and a negative span length. All four carry the same numbers, so the
|
||||
/// field-by-field answers below are the same for each of them.
|
||||
/// Layouts the kernel refuses to read, all with the same counts so the field-by-field
|
||||
/// answers match.
|
||||
fn unreadable_layouts() -> Vec<(&'static str, NativeHistogram, Option<i64>)> {
|
||||
// The span claims one bucket and the counts hold two.
|
||||
let mut short_counts = empty(0, 0.0, 3.0, 5.0, 1.0);
|
||||
@@ -1174,9 +1082,6 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A layout the kernel cannot walk keeps the field-by-field scaling and division the legacy
|
||||
/// caller had, so such a histogram is still multiplied instead of dropped, and keeps the start
|
||||
/// timestamp it was stored with.
|
||||
#[test]
|
||||
fn scale_and_divide_fall_back_to_the_fields_for_an_unreadable_layout() {
|
||||
for (name, histogram, start_timestamp) in unreadable_layouts() {
|
||||
@@ -1251,9 +1156,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The factors that are not a plain finite number, on a layout the kernel can walk: a zero
|
||||
/// divisor leaves no bucket, a NaN factor reaches every count, and a negative one turns the
|
||||
/// histogram into a gauge.
|
||||
#[test]
|
||||
fn scale_and_divide_by_the_edge_factors() {
|
||||
let mut histogram = empty(0, 0.0, 4.0, 6.0, 0.0);
|
||||
|
||||
@@ -447,8 +447,6 @@ pub(super) fn variance(h: &HistogramView<'_>, buckets: &mut Vec<NativeBucket>) -
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// The last bucket of finite values ends at `f64::MAX`; only the next one, which counts
|
||||
/// infinite observations, ends at +Inf.
|
||||
#[test]
|
||||
fn last_finite_bucket_ends_at_max() {
|
||||
for schema in [-4, 0, 3, 8] {
|
||||
|
||||
@@ -20,7 +20,7 @@ use datatypes::series::histogram::{
|
||||
BucketSideView, CounterResetHint, HistogramBatchBuilder, HistogramView,
|
||||
};
|
||||
use datatypes::series::samples::{FieldSpec, SampleRef, Series, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis};
|
||||
use datatypes::series::time::{EvalGrid, GridSpec};
|
||||
|
||||
use super::float_histogram::{AddOutcome, FloatHistogram};
|
||||
use super::{
|
||||
@@ -315,10 +315,6 @@ fn native_histograms_match_prometheus() {
|
||||
};
|
||||
assert_outcome(case, actual, &case.outcome);
|
||||
}
|
||||
// The aggregate cases are the 241 the fixture's spec names, and these are what the verdicts
|
||||
// above saw of them: every group that mixes the two kinds refused, every answer of a group that
|
||||
// does not compared, and the three single-sample zero sums that keep no sign compared against a
|
||||
// pinned `+0` (see [`pin_negative_zero_sum`]).
|
||||
assert_eq!(tally.refused, 138, "mixed groups refused");
|
||||
assert_eq!(tally.compared, 275, "histogram answers compared");
|
||||
assert_eq!(tally.negative_zero_sums, 3, "single-sample zero sums");
|
||||
@@ -459,42 +455,18 @@ fn histogram_arithmetic_matches_prometheus() {
|
||||
/// The message both halves of the kernel use when one field, or one group, holds both kinds.
|
||||
const MIXED_KINDS: &str = "cannot mix float and histogram samples in one field";
|
||||
|
||||
/// What the aggregate cases asserted, tallied so the test can pin how much of the fixture the fold
|
||||
/// covered.
|
||||
/// How much of the fixture the aggregate cases covered.
|
||||
#[derive(Default)]
|
||||
struct FoldTally {
|
||||
/// Groups whose raw input had to be refused, one per group.
|
||||
refused: usize,
|
||||
/// Histogram answers compared with a fixture answer, one per answered (group, position).
|
||||
compared: usize,
|
||||
/// Answers where a single sample's `-0.0` came back as `+0.0` ([`pin_negative_zero_sum`]).
|
||||
negative_zero_sums: usize,
|
||||
}
|
||||
|
||||
/// Folds the input of a `sum`/`avg` case, with or without `by (job)`, through the native aggregate
|
||||
/// and compares the histograms with the fixture; what a group that mixes the two kinds gets is
|
||||
/// asserted apart from that comparison, on the group's raw input.
|
||||
///
|
||||
/// The kernel folds one kind per field, so a group that saw a float sample and a histogram sample is
|
||||
/// refused whole -- `Group::accumulate` refuses a column holding both, and `finish_histogram_group`
|
||||
/// refuses a group that folded a float anywhere -- rather than answered step by step. A group is
|
||||
/// therefore one of two things here:
|
||||
///
|
||||
/// * A group whose samples are all histograms is folded with every histogram point it carries, no
|
||||
/// point taken out first, and its answer is compared with the fixture's bit for bit.
|
||||
/// * A group that carries a float sample is handed to the kernel as it arrived, floats and
|
||||
/// histograms together, and the fold must refuse it.
|
||||
///
|
||||
/// The fixtures are silent exactly where those two rules stop agreeing: 179 (group, step) pairs in
|
||||
/// `native_cases.txt` hold both a float and a histogram, and neither a float nor a histogram answer
|
||||
/// sits on any of them. A fixture does answer a mixed group's other steps, the ones one kind holds
|
||||
/// alone, and the kernel refuses those along with the group, so 140 of the file's 415 histogram
|
||||
/// answers belong to a mixed group and are not compared -- 138 mixed groups are refused instead.
|
||||
///
|
||||
/// The retired `aggregate_histograms` stopped folding the current (group, step, field) at a mixed
|
||||
/// bucket layout, drained the remaining iterator and propagated later conversion errors, then
|
||||
/// discarded that point if it had a float. Other steps continued. The kernel does not exercise
|
||||
/// that drain and error ordering here, so this coverage has not migrated it.
|
||||
/// Folds a `sum`/`avg` case, with or without `by (job)`, through the native aggregate. The kernel
|
||||
/// refuses a whole group that holds both floats and histograms, while Prometheus answers that
|
||||
/// group's single-kind steps; so a mixed group is asserted to be refused, and only histogram-only
|
||||
/// groups are compared with the fixture bit for bit.
|
||||
fn assert_aggregates(
|
||||
case: &GoldenCase,
|
||||
schema: &Arc<SeriesSchema>,
|
||||
@@ -515,9 +487,7 @@ fn assert_aggregates(
|
||||
}
|
||||
group
|
||||
};
|
||||
// Every group's members as they arrived, the kinds those members carry, and how many samples sit
|
||||
// at each of the group's steps: one step's answer is one fold over the samples the group has
|
||||
// there.
|
||||
// Members per group, the kinds they carry, and the sample count at each step.
|
||||
let mut members: BTreeMap<Labels, Vec<Series>> = BTreeMap::new();
|
||||
let mut kinds: BTreeMap<Labels, (bool, bool)> = BTreeMap::new();
|
||||
let mut samples: BTreeMap<Labels, BTreeMap<usize, usize>> = BTreeMap::new();
|
||||
@@ -542,8 +512,6 @@ fn assert_aggregates(
|
||||
for (group, group_members) in &members {
|
||||
let (has_float, has_histogram) = kinds[group];
|
||||
if has_float && has_histogram {
|
||||
// Its raw input, floats and histograms both: the refusal is per group, so it may not see
|
||||
// a group whose mixed steps were taken out for it.
|
||||
let error = match aggregate_float(schema, group_members, op, Grouping::By(&by)) {
|
||||
Ok(_) => panic!(
|
||||
"case {:?}: group {group:?} carries both kinds and was answered",
|
||||
@@ -559,8 +527,6 @@ fn assert_aggregates(
|
||||
tally.refused += 1;
|
||||
continue;
|
||||
}
|
||||
// Select histogram-only groups by input kind. A future float-only group is outside this
|
||||
// histogram comparison; it must not be ignored based on the kind of its output.
|
||||
if has_histogram {
|
||||
folded.extend(group_members.iter().cloned());
|
||||
}
|
||||
@@ -579,8 +545,7 @@ fn assert_aggregates(
|
||||
(labels.clone(), points)
|
||||
})
|
||||
.collect();
|
||||
// Even an empty input is evaluated and checked against this case's expected groups. In
|
||||
// particular, all-mixed and genuinely empty cases cannot borrow a previous case's verdict.
|
||||
// Evaluated even when empty, so an all-mixed case still checks its expected groups.
|
||||
let answers = aggregate_float(schema, &folded, op, Grouping::By(&by)).unwrap();
|
||||
let mut actual: BTreeMap<Labels, &Series> = BTreeMap::new();
|
||||
for series in &answers {
|
||||
@@ -641,27 +606,12 @@ fn assert_aggregates(
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixture's answer at one position, with its one known difference from this kernel set aside.
|
||||
///
|
||||
/// Prometheus v3.15.0 starts a group's fold from `h.Copy()` of the first sample and holds a
|
||||
/// compensation only once an add produced one (`engine.go:3694-3708`), and it adds that compensation
|
||||
/// in only when it is there (`:4013-4019`). A fold of one sample therefore hands that sample's own
|
||||
/// `-0.0` back. This kernel always holds a compensation beside the value and always adds it, and
|
||||
/// `-0.0 + +0.0` is `+0.0`: the zero keeps no sign. That is a deviation, not an equivalence, and it
|
||||
/// is pinned rather than smoothed -- the position folded exactly one sample, the fixture holds
|
||||
/// `-0.0` in its sum, and this kernel must answer `+0.0` there. Only then is the expected sum
|
||||
/// rewritten, and only for the comparison: that field of that answer, every other field and every
|
||||
/// other position stays bit-identical. Five fixtures hold such a sum
|
||||
/// (`native_cases.txt:4305,4410,4464,4513,4569`); the two that sit in a mixed group's answer are
|
||||
/// refused with the group, so three reach the comparison.
|
||||
/// Pins the one place this kernel's answer differs from Prometheus' by a zero's sign.
|
||||
///
|
||||
/// A fold of exactly one sample answers `+0.0` where Prometheus hands the sample's own `-0.0` back:
|
||||
/// this accumulator always seeds a compensation and always adds it, while Prometheus only adds one
|
||||
/// that exists. Recorded in <https://github.com/GreptimeTeam/greptimedb/issues/10530>, together with
|
||||
/// why closing it is not a mechanical change. The actual side still compares raw bits; only the
|
||||
/// expected side rewrites this field, and only after checking the fold had one sample and the
|
||||
/// kernel answered `+0.0`.
|
||||
/// The fixture's answer with its one known deviation set aside: a fold of exactly one sample
|
||||
/// answers `+0.0` where Prometheus hands the sample's own `-0.0` back, because this accumulator
|
||||
/// always adds a compensation and Prometheus adds one only when an add produced it
|
||||
/// (`engine.go:3694-3708`, `:4013-4019`). Tracked in
|
||||
/// <https://github.com/GreptimeTeam/greptimedb/issues/10530>. Only the expected sum is rewritten,
|
||||
/// and only after checking the fold had one sample and the kernel answered `+0.0`.
|
||||
fn pin_negative_zero_sum(
|
||||
case: &GoldenCase,
|
||||
labels: &Labels,
|
||||
@@ -716,14 +666,8 @@ 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.
|
||||
/// GreptimeDB's own policy, not Prometheus': a read and written-back histogram keeps its start
|
||||
/// timestamp, a derived one has none.
|
||||
#[test]
|
||||
fn a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one() {
|
||||
let offsets = [0];
|
||||
@@ -752,7 +696,6 @@ fn a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one() {
|
||||
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();
|
||||
@@ -762,7 +705,6 @@ fn a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one() {
|
||||
"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);
|
||||
@@ -781,7 +723,6 @@ fn a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one() {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -1006,11 +947,8 @@ fn aggregation_propagates_errors_other_than_mixed_schemas() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A result names the runs its rows make up, not the envelope of the input.
|
||||
///
|
||||
/// The input is one ordinary contiguous range whose middle row holds no histogram, the shape a
|
||||
/// sparse evaluation already hands over. Only positions 0 and 2 carry a result, so the output must
|
||||
/// be two one-row runs of two rows -- not a padded range of three rows over the same span.
|
||||
/// A contiguous input whose middle row holds no histogram yields two one-row runs, not a padded
|
||||
/// three-row range.
|
||||
#[test]
|
||||
fn histogram_aggregation_names_the_runs_of_its_results() {
|
||||
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1_000, 3).unwrap()).unwrap());
|
||||
@@ -1061,27 +999,9 @@ fn histogram_aggregation_names_the_runs_of_its_results() {
|
||||
histogram_points(output),
|
||||
BTreeMap::from([(0, wanted.clone()), (2, wanted)])
|
||||
);
|
||||
|
||||
// A dense axis over the same span would hold a row at the hole as well: three rows against the
|
||||
// two the assertions above allow.
|
||||
let dense = TimeAxis::Grid(GridRange::try_new(grid, 0, 3).unwrap());
|
||||
assert_eq!(
|
||||
dense
|
||||
.runs()
|
||||
.map(|run| (run.position, run.len))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(0, 3)]
|
||||
);
|
||||
assert_eq!(dense.len(), 3);
|
||||
assert!(dense.len() > output.time.len());
|
||||
}
|
||||
|
||||
/// F: `histogram_count` (and its relatives) over a series of several runs reports one value per
|
||||
/// histogram position, at that position, dropping the float samples that share the axis.
|
||||
///
|
||||
/// The input holds histograms at 1 and 6 and a float at 3: the float position holds a row (so the
|
||||
/// axis carries it) but no histogram, so the mapped result holds nothing there -- and the axis
|
||||
/// names the two runs that remain.
|
||||
/// Histograms at 1 and 6 and a float at 3: the float row is dropped and splits the result runs.
|
||||
#[test]
|
||||
fn native_histogram_functions_keep_the_runs_of_a_sparse_series() {
|
||||
use crate::grid_series::reference::{
|
||||
@@ -1141,9 +1061,7 @@ fn native_histogram_functions_keep_the_runs_of_a_sparse_series() {
|
||||
expected[6] = vec![Some(value)];
|
||||
assert_result_eq(Some(&mapped), &expected, &metric_of(&metric));
|
||||
}
|
||||
// The spread functions read the same positions too; their value is a bucket-wide statistic, so
|
||||
// the assertion here is that both positions survive and hold a finite number -- the kernel's
|
||||
// own arithmetic is pinned by the fixtures elsewhere.
|
||||
// Variance values are pinned by the golden fixtures; here only the positions matter.
|
||||
for function in [
|
||||
NativeHistogramFunction::StdVar,
|
||||
NativeHistogramFunction::StdDev,
|
||||
|
||||
+20
-41
@@ -16,10 +16,9 @@
|
||||
//! 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.
|
||||
//! The caller selects the info series like an instant selector, with each value replaced by the
|
||||
//! original timestamp of the selected sample (Prometheus `evalSeries` for `info`). This kernel only
|
||||
//! combines.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -42,30 +41,26 @@ use crate::vector_match::{Budget, HISTOGRAM_ROW_BYTES, owned_histogram_bytes};
|
||||
/// 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.
|
||||
/// The second argument of `info`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
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.
|
||||
/// The labels to copy, from the other matchers; empty 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.
|
||||
/// Whether every other matcher matches the empty string; then a series without a matching
|
||||
/// info series is kept unchanged.
|
||||
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.
|
||||
/// `info` holds single-float-field series whose value is the original sample timestamp. For each
|
||||
/// info metric a base series takes the info series with the same identifying labels; at one point
|
||||
/// the newest wins, and a tie where the base has a sample is an error. Labels the base series
|
||||
/// already has are kept; two info metrics setting one label to different values is an error. A
|
||||
/// base series without identifying labels matches nothing, and one that is itself an info metric
|
||||
/// passes through. Results sharing a label set merge; a field held twice at one point is an error.
|
||||
pub fn info(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
base: &[Series],
|
||||
@@ -75,11 +70,8 @@ pub fn info(
|
||||
info_inner(schema, base, info, selector, None)
|
||||
}
|
||||
|
||||
/// [`info()`], handing the live workspace it holds to `reserve` before it allocates it.
|
||||
///
|
||||
/// What the index of the info series and the rows of the results keep is held until the operation
|
||||
/// returns; the merge of one label set's rows is a phase, and the builder's columns join the phase
|
||||
/// of the output they are finished as. A total `reserve` refuses ends the operation with that error.
|
||||
/// [`info()`], reserving its workspace through `reserve` before allocating it. A refused
|
||||
/// reservation fails the operation with that error.
|
||||
pub(crate) fn info_with_reservation(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
base: &[Series],
|
||||
@@ -91,7 +83,6 @@ pub(crate) fn info_with_reservation(
|
||||
info_inner(schema, base, info, selector, Some(&mut budget))
|
||||
}
|
||||
|
||||
/// The one info kernel, whether or not a caller accounts for its workspace.
|
||||
fn info_inner(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
base: &[Series],
|
||||
@@ -147,11 +138,8 @@ fn info_inner(
|
||||
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.
|
||||
// A base series without a sample is not in Prometheus' base matrix at all, so it selects no
|
||||
// info series.
|
||||
// sampled base series: a present label matches any value those base series have, an absent
|
||||
// one matches only absence. An info series no pattern admits neither enriches nor conflicts.
|
||||
let mut patterns: HashMap<Vec<bool>, Vec<BTreeSet<Arc<str>>>> = HashMap::new();
|
||||
for (series, _) in base.iter().zip(&sampled).filter(|(_, sampled)| **sampled) {
|
||||
if is_info_metric(series.metric.name().unwrap_or("")) {
|
||||
@@ -184,8 +172,6 @@ fn info_inner(
|
||||
if !fetched {
|
||||
continue;
|
||||
}
|
||||
// The entry of a signature and the newest series it keeps at each point the series
|
||||
// holds a sample, charged before they are allocated.
|
||||
if let Some(budget) = budget.as_deref_mut() {
|
||||
budget.hold(
|
||||
series
|
||||
@@ -240,8 +226,6 @@ fn info_inner(
|
||||
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 {
|
||||
@@ -253,8 +237,6 @@ fn info_inner(
|
||||
};
|
||||
// The result of the previous point, reused while the same info series are kept.
|
||||
let mut previous: Option<Choice> = None;
|
||||
// A row of this series is kept by the result it goes to, so every row it can have is held
|
||||
// before the walk; a histogram is held as it is copied.
|
||||
if let Some(budget) = budget.as_deref_mut() {
|
||||
budget.hold(series.time.len().saturating_mul(row_bytes(width)))?;
|
||||
}
|
||||
@@ -369,8 +351,7 @@ fn info_inner(
|
||||
}
|
||||
for (metric, rows) in results {
|
||||
builder.begin_series();
|
||||
// This series' columns, reserved before its first row. They stay live inside the series
|
||||
// it is finished as, so the phase keeps them.
|
||||
// The columns stay live in the finished series, so they grow the phase.
|
||||
if let Some(budget) = budget.as_deref_mut() {
|
||||
budget.grow(column_bytes(&rows, width))?;
|
||||
}
|
||||
@@ -477,10 +458,8 @@ impl FirstError {
|
||||
/// 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.
|
||||
///
|
||||
/// The values share the series' own label strings, which the retained operands already hold and
|
||||
/// charge, so the patterns and signatures built from them allocate no label text of their own.
|
||||
/// The value of each identifying label, `None` where the series does not have it. The values share
|
||||
/// the series' label strings, which are already charged.
|
||||
fn identifying_values(metric: &SeriesLabels) -> Vec<Option<Arc<str>>> {
|
||||
IDENTIFYING_LABELS
|
||||
.iter()
|
||||
|
||||
@@ -27,17 +27,11 @@ use crate::map::drop_metric_name;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The source rows [`select_instants`] examined, counted per row.
|
||||
///
|
||||
/// The selector advances one cursor over the axis, so the rows it reads can never outnumber the
|
||||
/// rows of the axis: one pass, not one per grid point. Counting them is what keeps a second pass
|
||||
/// over the axis from being added back unobserved, since the selection it returns is the same
|
||||
/// either way.
|
||||
/// Source rows [`select_instants`] examined, so tests can assert it makes one pass over the axis.
|
||||
#[cfg(test)]
|
||||
pub(crate) static AXIS_ROWS_READ: std::sync::atomic::AtomicU64 =
|
||||
std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Counts one row of the axis examined; a no-op outside tests.
|
||||
fn row_read() {
|
||||
#[cfg(test)]
|
||||
AXIS_ROWS_READ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
@@ -47,8 +41,7 @@ fn row_read() {
|
||||
/// rules of [`select_instants`]: the last sample at or before `at_ms` (shifted by `offset_ms`) and
|
||||
/// not more than the lookback before it, unless a stale marker is the latest sample there.
|
||||
///
|
||||
/// `None` means the anchor selects nothing, which is what an anchor outside the series' data or one
|
||||
/// whose only candidate is too old or stale reports.
|
||||
/// `None` means the anchor selects nothing.
|
||||
pub fn select_instant_at(
|
||||
time: &RawTimestamps,
|
||||
fields: &SeriesFields,
|
||||
@@ -56,9 +49,6 @@ pub fn select_instant_at(
|
||||
lookback_ms: i64,
|
||||
offset_ms: i64,
|
||||
) -> Result<Option<u64>> {
|
||||
// One point at the anchor is the same rule `select_instants` applies per grid point, so the
|
||||
// anchor is asked of it rather than re-derived here: a second copy of the boundary arithmetic
|
||||
// is a second place for the lookback edge to disagree.
|
||||
let (indices, _) = select_instants(time, fields, at_ms..=at_ms, 1, lookback_ms, offset_ms)?;
|
||||
Ok(indices.into_iter().next())
|
||||
}
|
||||
@@ -76,9 +66,8 @@ pub(crate) struct InstantCandidateSpan {
|
||||
|
||||
/// Clips the candidate span using only the source axis endpoints; allocates nothing.
|
||||
///
|
||||
/// The caller validates `step_ms > 0`, `lookback_ms >= 0` and the ordered query range. The wide
|
||||
/// count leaves each caller's existing conversion to `usize` unchanged. The end is a scan bound,
|
||||
/// not necessarily a grid position when the query end is not aligned to its start.
|
||||
/// The caller validates `step_ms > 0`, `lookback_ms >= 0` and the ordered query range. The end is a
|
||||
/// scan bound, not necessarily a grid position when the query end is not aligned to its start.
|
||||
pub(crate) fn instant_candidate_span(
|
||||
endpoints: Option<(i64, i64)>,
|
||||
range: RangeInclusive<i64>,
|
||||
@@ -117,18 +106,12 @@ pub(crate) fn instant_candidate_span(
|
||||
|
||||
/// Selects source rows for an aligned PromQL instant-evaluation range.
|
||||
///
|
||||
/// Returns original logical row indices and evaluation timestamps from a complete source axis of
|
||||
/// strictly increasing milliseconds. Any provided field's stale marker suppresses selection;
|
||||
/// missing samples are not stale and remain selectable.
|
||||
/// Returns source row indices and evaluation timestamps from a complete source axis of strictly
|
||||
/// increasing milliseconds. Any provided field's stale marker suppresses selection; missing samples
|
||||
/// are not stale and remain selectable.
|
||||
///
|
||||
/// The ordering of the axis is [`RawTimestamps`]' own guarantee, checked when it was built, so this
|
||||
/// walks the axis once -- one cursor advance per row -- and validates nothing about it again.
|
||||
///
|
||||
/// The two vectors it returns hold one `u64` source row index and one `i64` evaluation timestamp
|
||||
/// per selected point, so what it allocates is 16 bytes per point of the clipped grid rather than
|
||||
/// anything proportional to the samples of the axis. It reserves none of that: every caller grows
|
||||
/// a memory reservation for those two vectors before it calls, which is what bounds an instant
|
||||
/// selection now that the kernel carries no point limit of its own.
|
||||
/// Allocates 16 bytes per point of the `instant_candidate_span` and reserves none of it; callers
|
||||
/// grow their memory reservation before calling.
|
||||
pub fn select_instants(
|
||||
time: &RawTimestamps,
|
||||
fields: &SeriesFields,
|
||||
@@ -221,16 +204,10 @@ pub fn select_instants(
|
||||
/// which sample is selected but not the time reported. The metric name, `__type__` and `__unit__`
|
||||
/// are dropped.
|
||||
///
|
||||
/// `indices` and `evaluation_timestamps` are a selection of `time` and `fields` as
|
||||
/// [`select_instants`] returns one: grid positions increasing, rows not decreasing. `schema` holds
|
||||
/// the evaluation grid the timestamps lie on and one field per field of `fields`. A field without a
|
||||
/// sample in the selected row has no result there.
|
||||
///
|
||||
/// `timestamp(x @ t)` selects at `t` for every point, so its selection repeats one row. This
|
||||
/// kernel reports the sample the caller selected and does not decide the selector's time
|
||||
/// modifiers: the native Instant caller selects the sample under the intersection of the ordinary
|
||||
/// anchored selector window and the timestamp function's unshifted window. `info()` retains ordinary
|
||||
/// selector offset behavior.
|
||||
/// `indices` and `evaluation_timestamps` are a selection as [`select_instants`] returns one: grid
|
||||
/// positions increasing, rows not decreasing (an `@` selection repeats one row). `schema` holds the
|
||||
/// evaluation grid and one field per field of `fields`. The caller decides which sample the time
|
||||
/// modifiers select; this kernel reports the selected one.
|
||||
pub fn timestamp_of_selection(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
metric: &SeriesLabels,
|
||||
@@ -316,13 +293,8 @@ pub fn timestamp_of_evaluated(
|
||||
}
|
||||
|
||||
/// One series over an instant selection, each field holding `value(sample, original time)` where
|
||||
/// the selected row has a sample for it.
|
||||
///
|
||||
/// The selection is `indices` and `evaluation_timestamps` as [`select_instants`] returns them: one
|
||||
/// source row and one grid timestamp per selected point, with positions increasing and rows not
|
||||
/// decreasing. An `@` selection, which reads one row at every point, repeats that row; it is the
|
||||
/// caller's to build. A selection off the grid, going back, or naming a row the series does not
|
||||
/// have fails.
|
||||
/// the selected row has a sample for it. A selection off the grid, going back, or naming a row the
|
||||
/// series does not have fails.
|
||||
fn project_selection(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
metric: SeriesLabels,
|
||||
@@ -346,7 +318,7 @@ fn project_selection(
|
||||
let spec = grid.spec();
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
|
||||
let mut cursors: Vec<_> = fields.iter().map(|field| field.cursor()).collect();
|
||||
// Consecutive points often select the same row, which a cursor reads only once.
|
||||
// Consecutive points often select the same row; `row` is reused instead of re-read.
|
||||
let mut row: Vec<Option<f64>> = Vec::with_capacity(fields.len());
|
||||
let mut last: Option<(i128, usize)> = None;
|
||||
for (&index, ×tamp) in indices.iter().zip(evaluation_timestamps) {
|
||||
|
||||
@@ -219,10 +219,8 @@ fn offset_extreme_timestamps_are_checked_without_large_fixture() {
|
||||
(vec![0], vec![110])
|
||||
);
|
||||
|
||||
// A grid of a million and one points used to be refused by a point limit of the kernel's own.
|
||||
// The kernel decides it now, and the reservation its caller grows before the call is what
|
||||
// stands in for that limit; the stale marker still suppresses the points row zero would answer,
|
||||
// so only the one sample after it is selected.
|
||||
// A million-point grid has no kernel-side limit; the stale marker at row zero suppresses
|
||||
// every point before the second sample.
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
Some(f64::from_bits(
|
||||
common_query::prometheus::PROMETHEUS_STALE_NAN_BITS,
|
||||
@@ -234,13 +232,7 @@ fn offset_extreme_timestamps_are_checked_without_large_fixture() {
|
||||
assert_eq!(times, [1_000_000]);
|
||||
}
|
||||
|
||||
/// A selection walks its axis once, whatever the grid it selects onto.
|
||||
///
|
||||
/// The strictly increasing order of the timestamps is `RawTimestamps`' guarantee, checked when the
|
||||
/// axis is built, so the selector has nothing left to validate: the rows it reads are the rows of
|
||||
/// the axis, once each, and a second pass over them -- such as a re-check of their order -- would
|
||||
/// show up here as twice as many. The selection itself is the same either way, which is why the
|
||||
/// count has to be what the test reads.
|
||||
/// A second pass over the axis would select the same rows, so the read count is what is checked.
|
||||
#[test]
|
||||
fn a_selection_reads_its_axis_once() {
|
||||
let rows = 5_000;
|
||||
@@ -252,14 +244,11 @@ fn a_selection_reads_its_axis_once() {
|
||||
assert!(!selected.is_empty(), "the selection is what reads the axis");
|
||||
AXIS_ROWS_READ.load(Ordering::Relaxed)
|
||||
};
|
||||
// Every row is selected: one pass, no more.
|
||||
assert_eq!(
|
||||
read(0..=rows as i64 - 1, 1),
|
||||
rows as u64,
|
||||
"the axis was walked more than once"
|
||||
);
|
||||
// Fewer points over the whole axis read it once as well: the pass follows the samples, not the
|
||||
// points, so it never exceeds the rows of the axis however many points the grid holds.
|
||||
for step in [10, 499] {
|
||||
let visited = read(0..=rows as i64 - 1, step);
|
||||
assert!(
|
||||
@@ -272,8 +261,7 @@ fn a_selection_reads_its_axis_once() {
|
||||
|
||||
#[test]
|
||||
fn instant_candidate_span_preserves_unaligned_and_wide_ranges() {
|
||||
// The query end is not on the start's lattice. The scan bound is 125, but stepping from 100
|
||||
// visits only 100, 110 and 120, as it did before clipping was shared.
|
||||
// The query end is off the start's lattice: the scan bound is 125, the points 100, 110, 120.
|
||||
let span = instant_candidate_span(Some((100, 120)), 100..=125, 10, 1, 0);
|
||||
assert_eq!(
|
||||
span,
|
||||
@@ -288,8 +276,7 @@ fn instant_candidate_span_preserves_unaligned_and_wide_ranges() {
|
||||
assert_eq!(rows, [0, 1, 2]);
|
||||
assert_eq!(timestamps, [100, 110, 120]);
|
||||
|
||||
// This count exceeds usize on 64-bit platforms. Computing the bound must neither allocate nor
|
||||
// truncate it; each caller retains its own existing conversion when consuming the result.
|
||||
// The count exceeds u64; it must not be truncated.
|
||||
let wide = instant_candidate_span(Some((i64::MIN, i64::MAX)), i64::MIN..=i64::MAX, 1, 0, 0);
|
||||
assert_eq!(wide.start, i64::MIN as i128);
|
||||
assert_eq!(wide.end, i64::MAX as i128);
|
||||
@@ -302,8 +289,7 @@ fn invalid_manual_inputs_are_rejected() {
|
||||
Some(1.0),
|
||||
Some(2.0),
|
||||
])));
|
||||
// `RawTimestamps` validates at construction, so duplicate or descending axes are
|
||||
// rejected before `select_instants` can receive them.
|
||||
// Duplicate or descending axes cannot reach `select_instants`.
|
||||
assert!(RawTimestamps::try_new(ScalarBuffer::from(vec![10, 10])).is_err());
|
||||
assert!(RawTimestamps::try_new(ScalarBuffer::from(vec![20, 10])).is_err());
|
||||
|
||||
@@ -421,8 +407,7 @@ fn timestamp_matches_prometheus() {
|
||||
×tamps,
|
||||
)
|
||||
} else {
|
||||
// Any evaluated series holding the selected points: only where it holds
|
||||
// values matters to `timestamp`.
|
||||
// `timestamp` reads only where the series holds values.
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap();
|
||||
for at in ×tamps {
|
||||
builder
|
||||
|
||||
+22
-54
@@ -50,15 +50,11 @@ use crate::map_time::DateFunction;
|
||||
/// Float math supported by the evaluated-series kernel.
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MathOp {
|
||||
/// Absolute value.
|
||||
Abs,
|
||||
/// Rounds towards positive infinity.
|
||||
Ceil,
|
||||
/// Rounds towards negative infinity.
|
||||
Floor,
|
||||
/// IEEE square root, returning NaN for negative input.
|
||||
Sqrt,
|
||||
/// Rounds to a constant multiple; use `1.0` for PromQL's default argument.
|
||||
/// Rounds to a multiple of `nearest`; PromQL's default is `1.0`.
|
||||
Round {
|
||||
nearest: f64,
|
||||
},
|
||||
@@ -108,8 +104,7 @@ pub enum ArithmeticOp {
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ArithmeticOp {
|
||||
/// The operator as the query wrote it, which is how the existing planner names it in the info
|
||||
/// it records for a dropped histogram sample.
|
||||
/// The operator as written in the query, which names it in the dropped-histogram info.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Add => "+",
|
||||
@@ -133,27 +128,15 @@ pub enum ScalarOperand {
|
||||
/// Applies float math to every field of one evaluated series and drops the metric name, like
|
||||
/// Prometheus' `simpleFloatFunc`.
|
||||
///
|
||||
/// Transcendental functions use Rust's platform math library. Results can differ from Prometheus
|
||||
/// for subnormals, overflow boundaries, large trigonometric inputs, and rounding-sensitive inputs.
|
||||
/// Requires an evaluated grid axis; missingness is validity, not a NaN payload, so raw staleness
|
||||
/// must be resolved before. Missing samples stay missing and NaNs stay values. Histogram samples
|
||||
/// are skipped: their points have no result. Returns `None` for `clamp` with `max < min`, which
|
||||
/// yields no series in Prometheus, or when a series with histograms has no float result left.
|
||||
///
|
||||
/// The explicit schema and actual grid range are preserved. Fields are processed in their own
|
||||
/// chunk boundaries, without expanding to the full grid or densifying chunked samples. Missing
|
||||
/// samples stay missing; ordinary NaNs remain values. An empty or all-missing input is valid.
|
||||
/// Transcendental functions use the platform math library and can differ from Go in the last bits.
|
||||
///
|
||||
/// Eval must resolve raw staleness before calling this kernel. Evaluated samples use validity,
|
||||
/// not NaN payloads, for missingness: arithmetic can produce the reserved stale bit pattern too.
|
||||
/// Raw time axes are rejected.
|
||||
///
|
||||
/// Native histogram samples are skipped, as Prometheus' math functions process only float
|
||||
/// samples: a point holding a histogram has no result in that field, and a series with no float
|
||||
/// sample left has none at all. Float-only fields keep their chunks; a field with histograms is
|
||||
/// rebuilt point by point.
|
||||
///
|
||||
/// Returns `None` for `clamp` with `max < min`, which yields no series in Prometheus.
|
||||
///
|
||||
/// Distinct inputs can share a label set once the name is dropped. Merging them, or failing
|
||||
/// when both have a value at one step, is left to the caller (Prometheus
|
||||
/// `mergeSeriesWithSameLabelset`).
|
||||
/// Distinct inputs can share a label set once the name is dropped; merging them is left to the
|
||||
/// caller (Prometheus `mergeSeriesWithSameLabelset`).
|
||||
pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Option<Series>> {
|
||||
if op.is_empty_clamp() {
|
||||
validate_grid_series(schema, series)?;
|
||||
@@ -188,8 +171,7 @@ pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Op
|
||||
|
||||
/// Applies arithmetic against a constant scalar to every field and drops the metric name.
|
||||
///
|
||||
/// Shares the evaluated-grid, missingness, unsupported-type and same-labelset contract of
|
||||
/// [`map_math`]. Arithmetic uses [`ArithmeticOp::calculate`], including its platform math behavior.
|
||||
/// Same contract as [`map_math`], except that histogram samples are rejected.
|
||||
pub fn map_arithmetic(
|
||||
schema: &SeriesSchema,
|
||||
series: &Series,
|
||||
@@ -201,13 +183,9 @@ pub fn map_arithmetic(
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Applies literal scalar arithmetic to float and histogram samples. Float-only series retain the
|
||||
/// original kernel unchanged; histogram-capable fields are traversed sample-by-sample.
|
||||
///
|
||||
/// The second element of the answer reports whether a histogram sample was dropped because the
|
||||
/// operation has no histogram form — `2 / h`, or `h + 1`, which Prometheus answers by dropping the
|
||||
/// sample rather than failing the query. The caller records the info; this kernel is also used on
|
||||
/// paths that hold no collector.
|
||||
/// Applies literal scalar arithmetic to float and histogram samples. Histograms support only
|
||||
/// `h * s`, `s * h` and `h / s`; under any other operator (`2 / h`, `h + 1`) the sample is dropped,
|
||||
/// as in Prometheus, and the second element reports that one was.
|
||||
pub(crate) fn map_arithmetic_literal(
|
||||
schema: &SeriesSchema,
|
||||
series: &Series,
|
||||
@@ -247,8 +225,6 @@ pub(crate) fn map_arithmetic_literal(
|
||||
Ok((output, dropped_histogram))
|
||||
}
|
||||
|
||||
/// Applies one literal scalar operation to one run of samples, reporting whether any histogram
|
||||
/// position had no answer.
|
||||
fn map_arithmetic_segment(
|
||||
samples: &Samples,
|
||||
op: ArithmeticOp,
|
||||
@@ -310,9 +286,7 @@ fn map_arithmetic_segment(
|
||||
Ok((samples, dropped_histogram))
|
||||
}
|
||||
|
||||
/// Produces an unlabelled scalar over exactly the requested evaluated range.
|
||||
///
|
||||
/// Scalar results require a single-field schema. No points outside `range` are allocated.
|
||||
/// An unlabelled constant over exactly `range`; the schema must have one field.
|
||||
pub fn constant_series(schema: &SeriesSchema, range: GridRange, scalar: f64) -> Result<Series> {
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
|
||||
scalar;
|
||||
@@ -327,7 +301,7 @@ pub fn constant_series(schema: &SeriesSchema, range: GridRange, scalar: f64) ->
|
||||
.map_err(series_error)
|
||||
}
|
||||
|
||||
/// Evaluates `pi()` without a vector input, preserving the requested short grid range.
|
||||
/// `pi()` over `range`.
|
||||
pub fn map_pi(schema: &SeriesSchema, range: GridRange) -> Result<Series> {
|
||||
constant_series(schema, range, PI)
|
||||
}
|
||||
@@ -348,9 +322,9 @@ fn map_float_fields(
|
||||
.map_err(series_error)
|
||||
}
|
||||
|
||||
/// Prometheus `DropReserved(schema.IsMetadataLabel)` drops the type and unit labels with the
|
||||
/// name. Empty values are dropped too: Prometheus has no empty labels, and keeping them would
|
||||
/// hide a same-labelset collision from the caller.
|
||||
/// Drops `__name__`, `__type__` and `__unit__`, as Prometheus `DropReserved(schema.IsMetadataLabel)`
|
||||
/// does. Empty values are dropped too: Prometheus has no empty labels, and keeping them would hide
|
||||
/// a same-labelset collision from the caller.
|
||||
pub(crate) fn drop_metric_name(metric: &SeriesLabels) -> Result<SeriesLabels> {
|
||||
let tags = metric.tags();
|
||||
let reject = |label: &Label| {
|
||||
@@ -378,7 +352,6 @@ pub(crate) fn drop_empty_labels(metric: &SeriesLabels) -> Result<SeriesLabels> {
|
||||
rebuild_labels(metric, name, |_| true)
|
||||
}
|
||||
|
||||
/// One rebuild: removing labels one by one copies the label array each time.
|
||||
fn rebuild_labels(
|
||||
metric: &SeriesLabels,
|
||||
name: Option<Arc<str>>,
|
||||
@@ -398,7 +371,6 @@ impl MathOp {
|
||||
floats.unary(|sample| self.calculate(sample))
|
||||
}
|
||||
|
||||
/// The function applied to one sample.
|
||||
pub(crate) fn calculate(self, v: f64) -> f64 {
|
||||
match self {
|
||||
Self::Exp => v.exp(),
|
||||
@@ -482,9 +454,8 @@ fn go_min(x: f64, y: f64) -> f64 {
|
||||
}
|
||||
|
||||
impl ArithmeticOp {
|
||||
/// Evaluates two floats using Rust arithmetic and platform math, also used by constant folding.
|
||||
/// `^` can differ from Prometheus for subnormal bases or large exponents; `atan2` can differ
|
||||
/// when both operands are negative and their ratio underflows to zero.
|
||||
/// Evaluates `left op right`; constant folding uses it too. `^` and `atan2` use the platform
|
||||
/// math library and can differ from Go for subnormal or extreme operands.
|
||||
#[inline]
|
||||
pub fn calculate(self, left: f64, right: f64) -> f64 {
|
||||
match self {
|
||||
@@ -532,10 +503,8 @@ fn series_error(error: datatypes::error::Error) -> DataFusionError {
|
||||
DataFusionError::External(Box::new(error))
|
||||
}
|
||||
|
||||
/// Checks an evaluated float series up front, so no segment of another type yields a result.
|
||||
///
|
||||
/// Returns the validated axis: it is addressed on a grid, so the caller reads the rows it carries
|
||||
/// with the axis traversal rather than assuming a contiguous range.
|
||||
/// Checks `series` against `schema` and its grid, and rejects any non-float sample. Returns the
|
||||
/// axis, which may skip positions, so callers traverse it rather than assume a contiguous range.
|
||||
pub(crate) fn validate_float_series<'a>(
|
||||
schema: &SeriesSchema,
|
||||
series: &'a Series,
|
||||
@@ -550,7 +519,6 @@ pub(crate) fn validate_float_series<'a>(
|
||||
Ok(time)
|
||||
}
|
||||
|
||||
/// Whether every field of `series` holds float samples only.
|
||||
pub(crate) fn is_float_series(series: &Series) -> bool {
|
||||
series.fields.iter().all(|field| {
|
||||
field
|
||||
|
||||
@@ -32,18 +32,13 @@ pub enum ScalarSeriesOperand<'a> {
|
||||
Right(&'a Series),
|
||||
}
|
||||
|
||||
/// Applies arithmetic between vector fields and a time-varying scalar, aligned by absolute grid
|
||||
/// index, and drops the metric name.
|
||||
/// Applies arithmetic between vector fields and a time-varying scalar on the same grid, and drops
|
||||
/// the metric name.
|
||||
///
|
||||
/// Prometheus scalars exist at every step; a missing scalar point here yields a missing output.
|
||||
/// The output covers the valid rows and nothing else, and `None` means there is none. A scalar
|
||||
/// point holding no value is a hole in the one result series, not the end of a piece: the axis
|
||||
/// names the runs of consecutive valid positions. The scalar must be unlabelled and single-field
|
||||
/// on the same grid; histogram/mixed/raw inputs are rejected even outside the overlap. Both
|
||||
/// operands may skip positions: only the positions both carry are evaluated, and the two axes are
|
||||
/// aligned by intersecting their runs, never by subtracting one axis' first position from the
|
||||
/// other's indices. Two unlabelled single-field inputs also evaluate scalar–scalar operations.
|
||||
/// Same-labelset merging is left to the caller, as in [`crate::map::map_math`].
|
||||
/// Only positions both operands carry are evaluated; a missing scalar point yields a missing
|
||||
/// output, and `None` means no output row. The scalar must be unlabelled and single-field, and both
|
||||
/// inputs must hold floats only, even outside the overlap. Two scalars also work. Same-labelset
|
||||
/// merging is left to the caller.
|
||||
pub fn map_arithmetic_series(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
vector: &Series,
|
||||
@@ -65,13 +60,9 @@ pub fn map_arithmetic_series(
|
||||
/// Compares against a time-varying scalar. Filter keeps vector values and labels; bool emits
|
||||
/// 0/1 and drops the metric name.
|
||||
///
|
||||
/// Shares [`map_arithmetic_series`]'s alignment and row-keeping contract. Each field is compared
|
||||
/// independently; a row is kept where any field passes a filter.
|
||||
///
|
||||
/// A histogram has no ordering against a scalar, so the positions it holds answer nothing; the
|
||||
/// second element of the answer reports whether one was dropped so the caller can say so. The
|
||||
/// literal-scalar form ([`crate::map::map_compare_literal`]) applies the same rule, and both exist
|
||||
/// because a time-varying scalar cannot be folded into a constant.
|
||||
/// Aligns like [`map_arithmetic_series`]. Each field is compared independently; a row is kept
|
||||
/// where any field passes. Histogram samples are dropped, as in
|
||||
/// [`crate::map::map_compare_literal`], and the second element reports whether one was.
|
||||
pub fn map_compare_series(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
vector: &Series,
|
||||
@@ -103,10 +94,7 @@ pub(crate) enum ScalarFunction {
|
||||
|
||||
impl ScalarFunction {
|
||||
/// Go's `math.Max` / `math.Min`: an infinity of the function's own sign wins over NaN, NaN
|
||||
/// over any other value, and `+0` is greater than `-0`.
|
||||
///
|
||||
/// Both are symmetric in their arguments, signed zero included, so the kernel does not depend
|
||||
/// on which operand came first.
|
||||
/// over any other value, and `+0` is greater than `-0`. Symmetric in its arguments.
|
||||
pub(crate) fn apply(self, a: f64, b: f64) -> f64 {
|
||||
let (wins, signed_zero_wins) = match self {
|
||||
Self::MaxOf => (f64::INFINITY, false),
|
||||
@@ -130,12 +118,8 @@ impl ScalarFunction {
|
||||
}
|
||||
}
|
||||
|
||||
/// A math function whose parameters are scalar expressions, which Prometheus evaluates at every
|
||||
/// step, with those parameters as time-varying scalars.
|
||||
///
|
||||
/// All but `max_of` and `min_of` map an evaluated vector's fields onto the same fields; those two
|
||||
/// are functions of two scalars, so the series they map is the unlabelled one-field scalar the
|
||||
/// call's first operand evaluates to.
|
||||
/// A math function whose parameters are time-varying scalars. For `max_of` and `min_of` the
|
||||
/// mapped series is the first scalar operand.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ParameterizedMath<'a> {
|
||||
/// `round(v, to_nearest)`.
|
||||
@@ -146,16 +130,13 @@ pub enum ParameterizedMath<'a> {
|
||||
ClampMin { min: &'a Series },
|
||||
/// `clamp_max(v, max)`.
|
||||
ClampMax { max: &'a Series },
|
||||
/// `max_of(a, b)`, whose two operands are scalars: the input of the call is `a` and `other` is
|
||||
/// `b`.
|
||||
/// `max_of(a, b)`: the mapped series is `a`, `other` is `b`.
|
||||
MaxOf { other: &'a Series },
|
||||
/// `min_of(a, b)`, whose two operands are scalars: the input of the call is `a` and `other` is
|
||||
/// `b`.
|
||||
/// `min_of(a, b)`: the mapped series is `a`, `other` is `b`.
|
||||
MinOf { other: &'a Series },
|
||||
}
|
||||
|
||||
impl<'a> ParameterizedMath<'a> {
|
||||
/// The parameters in argument order.
|
||||
fn parameters(self) -> Vec<&'a Series> {
|
||||
match self {
|
||||
Self::Round { to_nearest } => vec![to_nearest],
|
||||
@@ -166,7 +147,7 @@ impl<'a> ParameterizedMath<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The function with the parameter values of one point, in argument order.
|
||||
/// Binds one point's parameter values, given in argument order.
|
||||
fn at(self, values: &[f64]) -> PointMath {
|
||||
match self {
|
||||
Self::Round { .. } => PointMath::Math(MathOp::Round { nearest: values[0] }),
|
||||
@@ -188,14 +169,10 @@ impl<'a> ParameterizedMath<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What one point's parameter values make of a parameterized math function: the kernel that reads
|
||||
/// the input's own value, with everything else the point decides already bound.
|
||||
/// A parameterized math function with one point's parameters bound.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum PointMath {
|
||||
/// A math function of the input's value, as `round` is.
|
||||
Math(MathOp),
|
||||
/// The larger or smaller of the input's value and the parameter's, which are the two operands
|
||||
/// of `max_of` and `min_of`.
|
||||
Scalar {
|
||||
function: ScalarFunction,
|
||||
other: f64,
|
||||
@@ -203,8 +180,7 @@ enum PointMath {
|
||||
}
|
||||
|
||||
impl PointMath {
|
||||
/// The value the function answers for `value`, or `None` where it answers nothing: a `clamp`
|
||||
/// whose bounds were written the wrong way round has no result at that point.
|
||||
/// `None` for a `clamp` with `max < min`, which has no result at that point.
|
||||
fn calculate(self, value: f64) -> Option<f64> {
|
||||
match self {
|
||||
Self::Math(op) => (!op.is_empty_clamp()).then(|| op.calculate(value)),
|
||||
@@ -213,17 +189,12 @@ impl PointMath {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `function` to every field with its parameters read at each point from time-varying
|
||||
/// scalars, and drops the metric name, as [`crate::map::map_math`] does with constant parameters;
|
||||
/// native histogram samples are skipped the same way.
|
||||
/// Applies `function` to every float field with parameters read per point, and drops the metric
|
||||
/// name, like [`crate::map::map_math`] with constant parameters; histogram samples are skipped.
|
||||
///
|
||||
/// A point where a parameter has no value has no result. `clamp` with `max < min` at a point has
|
||||
/// no result there, as Prometheus returns an empty vector for that step. `None` means no point
|
||||
/// holds a result. Same-labelset merging is left to the caller.
|
||||
///
|
||||
/// `series` is one evaluated series, which for `max_of` and `min_of` is the unlabelled one-field
|
||||
/// scalar their first argument evaluates to: those two are functions of two scalars, so what they
|
||||
/// map is the first of them and what they read per point is the second.
|
||||
/// A point where a parameter has no value, or where `clamp` has `max < min` (Prometheus returns an
|
||||
/// empty vector for that step), has no result. `None` means no point has one. Same-labelset merging
|
||||
/// is left to the caller.
|
||||
pub fn map_math_with_parameters(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
series: &Series,
|
||||
@@ -235,7 +206,7 @@ pub fn map_math_with_parameters(
|
||||
for parameter in ¶meters {
|
||||
parameter_axes.push(validate_scalar(schema, parameter)?);
|
||||
}
|
||||
// Points only increase, so each parameter's row does too and one cursor reads it.
|
||||
// Points only increase, so one forward cursor per parameter suffices.
|
||||
let mut parameter_cursors: Vec<_> = parameters
|
||||
.iter()
|
||||
.map(|parameter| parameter.fields.as_slice()[0].cursor())
|
||||
@@ -268,18 +239,17 @@ pub fn map_math_with_parameters(
|
||||
builder.finish(drop_metric_name(&series.metric)?)
|
||||
}
|
||||
|
||||
/// Calls `calculate(left, right, vector_sample)` at each index where both operands exist.
|
||||
/// What a vector sample that holds no float value means to the kernel being applied.
|
||||
/// How [`map_grid_scalar`] treats a histogram sample in the vector.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum NonFloatSample {
|
||||
/// The caller proved the vector holds floats only, so a histogram here is a bug.
|
||||
/// The vector is validated as float-only.
|
||||
Impossible,
|
||||
/// The operation has no answer for it: the position answers nothing and the caller is told
|
||||
/// that a sample was dropped, which is what Prometheus does with a histogram under an operator
|
||||
/// it has no meaning for.
|
||||
/// The position yields nothing and the drop is reported, as Prometheus does for an operator
|
||||
/// undefined on histograms.
|
||||
Drop,
|
||||
}
|
||||
|
||||
/// Calls `calculate(left, right, vector_sample)` at each position where both operands exist.
|
||||
fn map_grid_scalar(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
vector: &Series,
|
||||
@@ -298,9 +268,8 @@ fn map_grid_scalar(
|
||||
};
|
||||
let scalar_time = validate_scalar(schema, scalar_series)?;
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
|
||||
// The shared runs carry both compact rows, so each operand reads its own field from the row
|
||||
// its own axis assigns to the position. A position only one side carries is missing anyway:
|
||||
// the pairing would be missing, and the builder keeps no row for it.
|
||||
// Each operand reads its own row from the shared run; positions only one side carries yield
|
||||
// nothing, so they are skipped.
|
||||
let mut scalar_samples = scalar_series.fields.as_slice()[0].cursor();
|
||||
let mut field_samples = vector
|
||||
.fields
|
||||
|
||||
@@ -38,26 +38,17 @@ pub enum Comparison {
|
||||
Bool(ComparisonOp),
|
||||
}
|
||||
|
||||
/// Compares a vector with a constant scalar, dropping the samples that have no comparison rather
|
||||
/// than failing the query.
|
||||
/// Compares a vector with a constant scalar. Returns `None` when no sample passed, and whether a
|
||||
/// histogram sample was dropped.
|
||||
///
|
||||
/// Prometheus compares float samples only: a histogram has no ordering against a scalar, so the
|
||||
/// position it holds answers nothing. The existing planner says so with an info and answers no
|
||||
/// value there (`NativeHistogramDrop`, `prom_token_to_binary_expr_builder` in
|
||||
/// `query::promql::planner`), which is the behaviour mirrored here. The second element of the
|
||||
/// answer reports whether a histogram was dropped, so the caller can record that info once per
|
||||
/// chunk instead of once per position.
|
||||
///
|
||||
/// The literal form of a filter: `None` still means nothing passed, so the caller hands on no
|
||||
/// value for this chunk.
|
||||
/// Histogram samples have no ordering against a scalar; like the existing planner
|
||||
/// (`NativeHistogramDrop` in `query::promql::planner`), they are dropped rather than rejected.
|
||||
pub fn map_compare_literal(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
series: &Series,
|
||||
comparison: Comparison,
|
||||
scalar: ScalarOperand,
|
||||
) -> Result<(Option<Series>, bool)> {
|
||||
// Whatever kinds the fields carry: a histogram position is dropped, not rejected, so the axis
|
||||
// and the schema are checked without requiring float samples.
|
||||
let time = validate_grid_series(schema, series)?;
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
|
||||
let mut dropped_histogram = false;
|
||||
@@ -106,8 +97,7 @@ impl Comparison {
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Comparison {
|
||||
/// The operator as the query wrote it, which is how the existing planner names it in the info
|
||||
/// it records for a dropped histogram sample.
|
||||
/// The operator as written in the query, which names it in the dropped-histogram info.
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let op = match self {
|
||||
Self::Filter(op) | Self::Bool(op) => op,
|
||||
@@ -124,12 +114,8 @@ impl std::fmt::Display for Comparison {
|
||||
}
|
||||
|
||||
impl ComparisonOp {
|
||||
/// Whether `left op right` holds, by the same IEEE rules the kernels use.
|
||||
///
|
||||
/// Public because a compiler that folds a constant comparison has to fold it with the same
|
||||
/// answer the kernel would compute: NaN satisfies only `NotEqual`, and signed zeros compare
|
||||
/// equal. Defining the six rules a second time is how the folded number and the evaluated one
|
||||
/// would start to disagree.
|
||||
/// Whether `left op right` holds. Constant folding must call this so folded and evaluated
|
||||
/// comparisons agree.
|
||||
#[inline]
|
||||
pub fn apply(self, left: f64, right: f64) -> bool {
|
||||
match self {
|
||||
|
||||
@@ -84,9 +84,6 @@ fn floats(samples: &[Option<f64>]) -> Samples {
|
||||
}
|
||||
|
||||
/// The `(start, len)` of every run of a mapped result, in grid order.
|
||||
///
|
||||
/// A mapped result is one series whose axis names the runs of consecutive positions that hold a
|
||||
/// value, so this is what the assertions here compare: the positions between two runs hold no row.
|
||||
fn run_ranges(result: &Series) -> Vec<(usize, usize)> {
|
||||
if result.time.grid().is_none() {
|
||||
panic!("lost grid axis: {:?}", result.time);
|
||||
@@ -691,13 +688,8 @@ fn math_drops_reserved_metadata_and_empty_labels_with_the_name() {
|
||||
assert_eq!(names, ["__other__", "host"]);
|
||||
}
|
||||
|
||||
/// Time-varying scalars pair by absolute position; a point either one lacks has no result.
|
||||
///
|
||||
/// `max_of(a, b)` and `min_of(a, b)` are functions of two scalars, so the compiler binds the call's
|
||||
/// first operand as the map's input and the second as its one parameter: this is that kernel, with
|
||||
/// two scalars that overlap in three positions, against the values it has to answer there. The
|
||||
/// fixture is not reachable from a compiled tree -- every scalar a tree produces covers its whole
|
||||
/// grid -- so what is pinned here is the kernel's own pairing rather than a query's shape.
|
||||
/// Time-varying scalars pair by absolute position; a point either one lacks has no result. Not
|
||||
/// reachable from a compiled tree, whose scalars cover the whole grid.
|
||||
#[test]
|
||||
fn scalar_functions_pair_scalars_by_position() {
|
||||
let schema = Arc::new(schema(&["scalar"]));
|
||||
|
||||
@@ -50,11 +50,8 @@ fn unary_negation_drops_name_and_keeps_missing_positions_and_payloads() {
|
||||
let SampleRef::Float(negated) = field.iter().nth(2).unwrap() else {
|
||||
panic!("missing negated NaN");
|
||||
};
|
||||
// A multiplication propagates the NaN operand instead of negating it bit for bit: the sign
|
||||
// stays the input's and the quiet bit is set, where the unary kernel this replaced flipped the
|
||||
// sign with `-v`. IEEE leaves both of those unspecified, and eval resolves staleness by
|
||||
// validity rather than by payload before this kernel runs, so what is pinned is what identifies
|
||||
// the sample: the payload of a stale NaN survives the negation.
|
||||
// Multiplication keeps the NaN's sign and sets the quiet bit (IEEE leaves both unspecified);
|
||||
// what is pinned is that the stale NaN's payload survives.
|
||||
assert!(negated.is_nan(), "a NaN stayed a NaN: {negated}");
|
||||
const PAYLOAD: u64 = (1 << 51) - 1;
|
||||
assert_eq!(
|
||||
|
||||
@@ -307,7 +307,7 @@ fn time_varying_scalar_preflight_rejects_unsupported_data_even_outside_overlap()
|
||||
}
|
||||
}
|
||||
|
||||
/// F: a vector–scalar operation between two sparse operands aligns by shared runs, not by
|
||||
/// A vector–scalar operation between two sparse operands aligns by shared runs, not by
|
||||
/// subtracting first positions, and reports the surviving positions as their own runs.
|
||||
///
|
||||
/// Vector positions 1, 5 and 9; scalar positions 5 and 9. Only 5 and 9 are evaluated, and the
|
||||
|
||||
@@ -209,7 +209,7 @@ fn comparisons_reject_raw_axes_and_drop_histogram_positions() {
|
||||
}
|
||||
}
|
||||
|
||||
/// F: a filter over a series of several runs keeps a scattered subset, and the result is a
|
||||
/// A filter over a series of several runs keeps a scattered subset, and the result is a
|
||||
/// fragmented axis of exactly the kept runs -- not a padded envelope from the first kept position
|
||||
/// to the last.
|
||||
///
|
||||
@@ -323,7 +323,7 @@ fn a_filter_over_runs_keeps_exactly_the_runs_that_pass() {
|
||||
);
|
||||
}
|
||||
|
||||
/// F: a bool comparison keeps every position the input carries, so the output is the input's axis
|
||||
/// A bool comparison keeps every position the input carries, so the output is the input's axis
|
||||
/// again -- and a comparison against NaN is false everywhere but `!=`.
|
||||
#[test]
|
||||
fn a_bool_comparison_keeps_the_axis_of_a_sparse_input() {
|
||||
|
||||
@@ -73,11 +73,8 @@ fn rewrite_all(
|
||||
merge_same_labelset(schema, series)
|
||||
}
|
||||
|
||||
/// The label change of `label_replace` or `label_join`, checked and compiled once and applied to
|
||||
/// each series on its own. Series that end up with one label set are the caller's to merge.
|
||||
///
|
||||
/// Built only through [`Self::replace`] and [`Self::join`], so the expression is anchored and the
|
||||
/// label names are checked.
|
||||
/// The validated, compiled label change of `label_replace` or `label_join`, applied per series.
|
||||
/// Merging series that end up with one label set is left to the caller.
|
||||
#[derive(Debug)]
|
||||
pub struct LabelRewrite(Change);
|
||||
impl serde::Serialize for LabelRewrite {
|
||||
@@ -248,20 +245,15 @@ impl std::hash::Hash for LabelRewrite {
|
||||
}
|
||||
|
||||
impl LabelRewrite {
|
||||
/// The label this rewrite writes, which is the one whose routing key may change.
|
||||
/// The label this rewrite writes.
|
||||
pub fn destination(&self) -> &str {
|
||||
match &self.0 {
|
||||
Change::Replace { dst, .. } | Change::Join { dst, .. } => dst,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this change can write a nonempty value.
|
||||
///
|
||||
/// An empty value removes the destination instead ([`set_label`]), so a change whose value is
|
||||
/// necessarily empty only deletes a label and publishes none that its input did not carry.
|
||||
/// `label_replace`'s template is judged as written: `$1` can expand to nothing for one series and
|
||||
/// to a value for another, so it may write. A `label_join` with no source labels joins nothing
|
||||
/// and is always empty.
|
||||
/// Whether this change can write a nonempty value. When it cannot, it only removes the
|
||||
/// destination label. Judged from the template as written, since `$1` may expand to nothing.
|
||||
pub fn writes_value(&self) -> bool {
|
||||
match &self.0 {
|
||||
Change::Replace { replacement, .. } => !replacement.is_empty(),
|
||||
@@ -309,13 +301,9 @@ impl LabelRewrite {
|
||||
}))
|
||||
}
|
||||
|
||||
/// An upper bound on the bytes the label this change writes to `metric` takes, read before it
|
||||
/// is built.
|
||||
///
|
||||
/// The written value can be far larger than the input: `label_join` concatenates its sources,
|
||||
/// listed any number of times, and every `$` reference of a `label_replace` template can expand
|
||||
/// to the whole source value. The bound counts each source once per listing and each `$` as
|
||||
/// one whole source value.
|
||||
/// An upper bound on the bytes of the label this change writes to `metric`, computable before
|
||||
/// applying it. Each `$` in a template counts as one whole source value, and each `label_join`
|
||||
/// source once per listing.
|
||||
pub fn written_bytes(&self, metric: &SeriesLabels) -> usize {
|
||||
let value = |name: &str| metric.get(name).map_or(0, str::len);
|
||||
match &self.0 {
|
||||
@@ -342,7 +330,6 @@ impl LabelRewrite {
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes `metric` the way the function changes one series.
|
||||
pub fn apply(&self, metric: &mut SeriesLabels) -> Result<()> {
|
||||
let mut value = String::new();
|
||||
match &self.0 {
|
||||
|
||||
@@ -111,7 +111,7 @@ fn replacements_expand_like_go() {
|
||||
}
|
||||
}
|
||||
|
||||
/// F: a label function over a series of several runs rewrites the labels and leaves the rows and
|
||||
/// A label function over a series of several runs rewrites the labels and leaves the rows and
|
||||
/// their positions untouched.
|
||||
///
|
||||
/// A label function has no kernel at all, so the only thing that can go wrong is the axis: it must
|
||||
|
||||
@@ -120,7 +120,6 @@ const UNIX_TO_ABSOLUTE: i64 = (1969 * 365 + 1969 / 4 - 1969 / 100 + 1969 / 400)
|
||||
+ (ABSOLUTE_YEARS as i64 / 400 * 146_097 + MARCH_THRU_DECEMBER as i64) * 86_400;
|
||||
|
||||
impl DateFunction {
|
||||
/// The PromQL name of the function.
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::DayOfMonth => "day_of_month",
|
||||
|
||||
@@ -14,37 +14,16 @@
|
||||
|
||||
//! The run-time state of an aggregate node.
|
||||
//!
|
||||
//! An aggregate folds a whole vector into one series per group, so its node is the one that cannot
|
||||
//! answer as its input arrives: a group's value at a grid point is the fold of every value every
|
||||
//! member of the group has there, and the last member to arrive is the one that decides it. What the
|
||||
//! node keeps between chunks is therefore the fold's states and nothing else -- a chunk is folded as
|
||||
//! it arrives and dropped -- and it produces once, when the input ends.
|
||||
//! An aggregate folds each chunk into per-group state as it arrives and produces once, when the
|
||||
//! input ends. It cannot tell an incomplete group from a complete one: a
|
||||
//! [`AggregateStage::Complete`] aggregate is correct only if the plan routes every contribution to
|
||||
//! each group into this execution. Partitioned plans use [`AggregateStage::Partial`] and
|
||||
//! [`AggregateStage::Final`], which carry kernel accumulator state between executions.
|
||||
//!
|
||||
//! That is also why this runtime cannot tell an incomplete group from a complete one: it folds what
|
||||
//! it is handed. A [`AggregateStage::Complete`] aggregate is correct only if every contribution to
|
||||
//! each group lies within the streams this execution reads, which is the physical plan's job -- the
|
||||
//! caller that schedules scans and exchanges guarantees it, and a plan that ran a `Complete`
|
||||
//! aggregate once per partition and then combined the answers would be combining values that were
|
||||
//! each missing the other partitions' contributions. The stages that exist for that shape are
|
||||
//! [`AggregateStage::Partial`] and [`AggregateStage::Final`], which carry kernel accumulator
|
||||
//! state between executions.
|
||||
//!
|
||||
//! `quantile` is the one aggregate here that is not a fold of each point's values. Its answer is the
|
||||
//! φ-quantile of the group's whole sample set at that point, so there is no fixed-width accumulator
|
||||
//! that answers it, and no state that combines two partitions' quantiles into the quantile of their
|
||||
//! union. What the node keeps instead is its input: every series it was handed, until the input
|
||||
//! ends, when [`crate::aggregate::aggregate_quantile`] answers from all of it at once. That is also
|
||||
//! why `quantile` exists only as [`AggregateStage::Complete`] here, and why a plan that would have
|
||||
//! to fold it per partition has to keep the previous route instead of splitting it.
|
||||
//!
|
||||
//! There is no spill either: a `quantile` keeps the whole input of every group, at once, until the
|
||||
//! last chunk arrives, so what it holds is not bounded by the number of groups the way a fixed-width
|
||||
//! accumulator's is -- it is bounded by the pool. Each chunk is admitted before it is kept and the
|
||||
//! reservation settles on the input retained so far ([`AggregateRuntime::accumulate`]), so a
|
||||
//! statement whose groups' samples do not fit the pool is refused rather than served from disk, and
|
||||
//! a caller that needs an answer in bounded memory needs a wider pool rather than a wider node.
|
||||
//! Everything else in this runtime trades memory for the width of a point: a fold's state per group
|
||||
//! and point, this one's whole input.
|
||||
//! `quantile` has no fixed-width accumulator and no mergeable state, so it exists only as
|
||||
//! `Complete` and keeps its whole input until the input ends, when
|
||||
//! [`crate::aggregate::aggregate_quantile`] answers from it. There is no spill: each retained chunk
|
||||
//! is reserved before it is kept, so an input that does not fit the pool is refused.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
@@ -81,10 +60,6 @@ pub(crate) enum AggregateOutput {
|
||||
}
|
||||
|
||||
/// What a `Complete` aggregate keeps while its input arrives.
|
||||
///
|
||||
/// The eight point-wise aggregates fold each grid point's values into fixed-width state; `quantile`
|
||||
/// keeps the samples themselves, because the φ-quantile of a group is not a value its members' values
|
||||
/// fold to.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Fold {
|
||||
/// One fixed-width accumulator per point and field.
|
||||
@@ -93,85 +68,33 @@ enum Fold {
|
||||
Quantile,
|
||||
}
|
||||
|
||||
/// The input a `quantile` aggregate keeps, until it has all of it.
|
||||
///
|
||||
/// The members are the series the node was handed, in the order they arrived: that order is the order
|
||||
/// [`aggregate_quantile`] folds a group's members in, and a series delivered in several chunks
|
||||
/// contributes at each position it holds, so the pieces of one series answer what the whole series
|
||||
/// would have. Nothing here is grouped: the kernel groups, and it groups the same way for a chunk as
|
||||
/// for a series of its own.
|
||||
/// The input a `quantile` aggregate keeps until it ends, ungrouped and in arrival order; the
|
||||
/// kernel groups when it answers.
|
||||
struct QuantileInput {
|
||||
/// The φ the query wrote, when the query wrote it: a fold that bound its argument folds with
|
||||
/// this one number at every point. The kernel reads it as Prometheus does, so a value outside
|
||||
/// `[0, 1]` answers `-Infinity` or `+Infinity` rather than being refused here. `None` for a fold
|
||||
/// whose φ is read per point, which is what `parameter` holds instead.
|
||||
/// The literal φ, or `None` when φ is read per point from `parameter`. As in Prometheus, a
|
||||
/// value outside `[0, 1]` answers `±Inf` rather than being refused.
|
||||
quantile: Option<f64>,
|
||||
/// The φ read per point, when the query left it to the statement's own evaluation: the one
|
||||
/// unlabelled scalar series the node held from its parameter child, on this node's grid.
|
||||
///
|
||||
/// It is kept beside the retained input because the kernel reads it per point, exactly as the
|
||||
/// parameter a bound φ is turned into is read: `q` with no sample at a point leaves the point
|
||||
/// unanswered, as it does for the built one.
|
||||
/// The per-point φ: the unlabelled scalar series handed over by the parameter child, on this
|
||||
/// node's grid. A point it has no sample at is unanswered.
|
||||
parameter: Option<Series>,
|
||||
/// One entry per series this node was handed.
|
||||
series: Vec<Series>,
|
||||
/// The histogram tables the retained chunks index into, by the address of the allocation behind
|
||||
/// their `Arc`.
|
||||
///
|
||||
/// A table is one allocation however many chunks of a series index into it, so it is billed once
|
||||
/// -- by the first chunk that references it -- exactly as a binary operand bills the tables of
|
||||
/// the chunks it retains. That is what keeps a series delivered in a thousand chunks from costing
|
||||
/// a thousand tables, and what keeps a table from costing nothing: the per-chunk figure leaves
|
||||
/// its tables out ([`chunk_bytes_beside_samples`]), so a table in neither this set nor a
|
||||
/// reservation is a table nothing covers.
|
||||
/// Addresses of the histogram tables already billed, so each table is billed once, by the first
|
||||
/// retained chunk that references it.
|
||||
tables: HashSet<usize>,
|
||||
/// The Arrow allocations the retained chunks' samples live in, by the address of the allocation
|
||||
/// behind their `Buffer`.
|
||||
///
|
||||
/// The chunks of one Arrow batch are the same story as its tables one level down, and the same
|
||||
/// answer: what a retainer keeps is the allocation its slices point into, and one allocation is
|
||||
/// one however many chunks slice it, so it is billed once -- by the first chunk that references
|
||||
/// it ([`unbilled_sample_buffers`]) -- rather than once per chunk. That is what keeps a series
|
||||
/// handed over as a thousand slices of one buffer from costing that buffer a thousand times. A
|
||||
/// chunk that holds a small slice of a large allocation is charged the allocation, because the
|
||||
/// allocation is what stays resident; its rows would be the smaller and wrong figure.
|
||||
/// Addresses of the Arrow sample buffers already billed. A retained slice keeps its whole
|
||||
/// allocation resident, so each allocation is billed in full, once.
|
||||
buffers: HashSet<usize>,
|
||||
/// The bytes the retained chunks hold, folded in as they arrive.
|
||||
///
|
||||
/// Each chunk is measured once, by what it holds on its own ([`chunk_bytes_beside_samples`]):
|
||||
/// its axis, its descriptors and its labels, beside the allocations it is the first to reference
|
||||
/// -- the Arrow buffers its samples live in and the histogram tables they index into, each
|
||||
/// billed once as [`unbilled_sample_buffers`] and [`unbilled_tables`] report them. Neither the
|
||||
/// allocation those samples are slices of nor the struct that carries the chunk is part of the
|
||||
/// figure: the first is billed as the allocation it is and not as the rows a chunk holds of it,
|
||||
/// and the second is the slot the vector holds the chunk in. [`Self::bytes`] adds that vector
|
||||
/// from the capacity it holds, which is why the struct is not counted here as well.
|
||||
/// Bytes of the retained chunks beside their `Series` structs: [`chunk_bytes_beside_samples`]
|
||||
/// plus newly referenced buffers and tables. The structs are counted by [`Self::bytes`] from
|
||||
/// the vector's capacity.
|
||||
held: usize,
|
||||
}
|
||||
|
||||
impl QuantileInput {
|
||||
/// The bytes this input holds: the chunks it retained and the vector that carries them.
|
||||
///
|
||||
/// The retained figure is [`Self::held`], which is folded in chunk by chunk, and the vector is
|
||||
/// counted by the capacity it really holds -- the capacity `retain_quantile` reserved before it
|
||||
/// grew -- so this is what the node has to reserve rather than a second estimate of it.
|
||||
///
|
||||
/// The two do not overlap. A chunk's `Series` is carried inside one slot of that vector, so
|
||||
/// `held` counts what the chunk holds beside the struct ([`chunk_bytes_beside_samples`]) and the
|
||||
/// capacity here counts every slot the vector owns, occupied or not. Counting the struct in both
|
||||
/// would charge each occupied slot twice; counting it in neither would leave every slot the
|
||||
/// vector holds uncovered.
|
||||
///
|
||||
/// The parameter is the third figure: a φ read per point is one series this node holds from the
|
||||
/// moment its parameter child hands it over until the kernel reads it, so it is counted from
|
||||
/// [`series_bytes`] however long it stays. A φ the query bound is not held at all - it is
|
||||
/// rebuilt from the binding's one number when the fold answers.
|
||||
///
|
||||
/// That series sits inline, in the `Option<Series>` slot of this struct, so the descriptor is
|
||||
/// what `size_of::<Self>()` above already counts: the parameter adds the heap beside it and not
|
||||
/// a second descriptor. [`series_bytes`] measures a series it takes by reference, so it counts
|
||||
/// the struct as well; the subtraction here is what keeps one held series from being billed one
|
||||
/// descriptor twice.
|
||||
/// The bytes this input holds: itself, every slot of the series vector, [`Self::held`], and
|
||||
/// the held parameter's heap. The parameter's `Series` struct sits inline in `Self`, so it is
|
||||
/// subtracted from [`series_bytes`] to avoid billing it twice.
|
||||
fn bytes(&self) -> usize {
|
||||
std::mem::size_of::<Self>()
|
||||
.saturating_add(
|
||||
@@ -188,36 +111,24 @@ impl QuantileInput {
|
||||
|
||||
/// One aggregate node's states, from the first chunk it is handed to the series it finishes with.
|
||||
pub(crate) struct AggregateRuntime {
|
||||
/// What the node computes, as the tree bound it: the kind it folds by and the stage it reports.
|
||||
op: BoundAggregate,
|
||||
/// The layout its input and output share: the fields every chunk has and the grid they are
|
||||
/// addressed on. A `Complete` aggregate neither adds nor drops a field, and it evaluates on its
|
||||
/// input's grid, so one schema describes both sides.
|
||||
/// The layout input and output share: an aggregate keeps its input's fields and grid.
|
||||
schema: Arc<SeriesSchema>,
|
||||
/// What this node keeps between chunks, as the runtime's own enum, so the chunk check can ask
|
||||
/// what the operation accepts.
|
||||
fold: Fold,
|
||||
/// The query's annotation collector, once the driver installed it. Only an operation that skips
|
||||
/// histogram samples has anything to say, and it says it once.
|
||||
/// Taken after the first annotation, so each node reports at most once.
|
||||
annotations: Option<PromqlAnnotationCollector>,
|
||||
/// The fold. `None` once [`Self::compute`] has taken it, which is also what says the node has
|
||||
/// nothing left to fold into.
|
||||
/// `None` for `Final` and `quantile`, and once [`Self::compute`] has taken it.
|
||||
accumulator: Option<FloatAggregator>,
|
||||
/// The whole input of a `quantile` aggregate. `None` for every other kind, and `None` once the
|
||||
/// kernel has answered from it.
|
||||
/// The whole input of a `quantile`; `None` for other kinds and once the kernel has answered.
|
||||
retained: Option<QuantileInput>,
|
||||
merger: Option<FloatMerger>,
|
||||
state_schema: Option<Arc<AggregateStateSchema>>,
|
||||
/// Whether the fold has been finished and its series handed over. A node computes once: a second
|
||||
/// pull finds the series it queued rather than a fold that ran again.
|
||||
///
|
||||
/// The driver reads this to decide whether the node settled: an aggregate answers only once its
|
||||
/// fold has run, so a child with nothing left to hand over is not an answer.
|
||||
/// Whether [`Self::compute`] has run. The driver reads it to decide whether the node settled.
|
||||
pub(crate) computed: bool,
|
||||
}
|
||||
|
||||
impl AggregateRuntime {
|
||||
/// The PromQL name of the aggregate this node folds, as an annotation names it.
|
||||
/// The PromQL name used in annotations.
|
||||
fn aggregate_name(&self) -> &'static str {
|
||||
match self.fold {
|
||||
Fold::Pointwise(AggregateOp::Sum) => "sum",
|
||||
@@ -232,24 +143,18 @@ impl AggregateRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives this node the query's collector, so it can report what it skipped.
|
||||
/// Installs the query's annotation collector.
|
||||
pub(crate) fn set_annotations(&mut self, collector: PromqlAnnotationCollector) {
|
||||
self.annotations = Some(collector);
|
||||
}
|
||||
|
||||
/// What this node computes, for a rejection that has to say what it refused.
|
||||
///
|
||||
/// It names the kind this node computes, which distinguishes it from another node in the tree.
|
||||
/// The aggregate kind, for error messages.
|
||||
fn describe(&self) -> String {
|
||||
format!("{:?}", self.op.kind)
|
||||
}
|
||||
|
||||
/// The states of a `Complete` aggregate over `schema`.
|
||||
///
|
||||
/// A stage other than `Complete` and a kind without a supported kernel are refused here, before a single
|
||||
/// chunk is folded: a node this runtime cannot compute must not start, because a partial answer
|
||||
/// would be one the caller never asked for. The rejection names what was found, so a reader can
|
||||
/// tell a tree this runtime cannot run from one it cannot run correctly.
|
||||
/// The state of an aggregate over `schema`, in any stage. A kind with no mergeable state is
|
||||
/// refused before any chunk is folded.
|
||||
pub(crate) fn new(
|
||||
op: BoundAggregate,
|
||||
schema: Arc<SeriesSchema>,
|
||||
@@ -264,9 +169,6 @@ impl AggregateRuntime {
|
||||
AggregateKind::Group => AggregateOp::Group,
|
||||
AggregateKind::Stddev => AggregateOp::Stddev,
|
||||
AggregateKind::Stdvar => AggregateOp::Stdvar,
|
||||
// The one kind with no accumulator: it keeps its input instead, which is a state of its
|
||||
// own and is built by [`Self::new_quantile`]. The φ is the only parameter an aggregate
|
||||
// carries, and the arm that names the kind is the one place it is read.
|
||||
AggregateKind::Quantile { quantile } => {
|
||||
return Self::new_quantile(op, Some(quantile), schema, buffer);
|
||||
}
|
||||
@@ -332,20 +234,9 @@ impl AggregateRuntime {
|
||||
})
|
||||
}
|
||||
|
||||
/// The states of a `Complete` `quantile` aggregate over `schema`, whose φ is `quantile`.
|
||||
///
|
||||
/// A `quantile` is answered from its group's whole sample set, so a stage that saw only part of
|
||||
/// a group would answer the quantile of a subset of it: the quantile of two partitions'
|
||||
/// quantiles is not the quantile of their union, and there is no state to export or merge
|
||||
/// either. That is a property of the operation and not of this runtime, so what refuses a
|
||||
/// `Partial` or a `Final` one is the tree's own check -- [`aggregate_state_binding`] has no
|
||||
/// binding for a `quantile`, which [`crate::native::plan::NativeNode::validate`] reports, and
|
||||
/// [`crate::native::split`] declines a `quantile` for the same reason -- and this starts the one
|
||||
/// stage that is left.
|
||||
///
|
||||
/// The same check is what puts the input on a grid: a `Complete` aggregate is validated to
|
||||
/// answer its input's values on its input's grid, and `schema` is the layout the node reports,
|
||||
/// so the grid the kernel reads its parameter on is there before this runs.
|
||||
/// The state of a `Complete` `quantile` over `schema`. The stage is not checked here:
|
||||
/// [`crate::native::plan::NativeNode::validate`] already rejects a `Partial` or `Final`
|
||||
/// `quantile`, which has no state binding.
|
||||
fn new_quantile(
|
||||
op: BoundAggregate,
|
||||
quantile: Option<f64>,
|
||||
@@ -374,13 +265,8 @@ impl AggregateRuntime {
|
||||
})
|
||||
}
|
||||
|
||||
/// The states of a `Complete` aggregate whose one argument is read at every grid point.
|
||||
///
|
||||
/// Only `quantile` has such an argument, and its fold keeps no number of its own: the φ arrives
|
||||
/// as a series from the node's parameter child ([`Self::hold_parameter`]), so the binding's
|
||||
/// constant is not read here at all. Everything else about the fold is the bound one's -- the
|
||||
/// stage, the layout, and the sample set it keeps until the input ends -- which is why this is
|
||||
/// [`Self::new_quantile`] with no constant to fall back on rather than a second kind of state.
|
||||
/// The state of a `quantile` whose φ arrives per point through [`Self::hold_parameter`]; the
|
||||
/// binding's constant is ignored. Any other kind is refused.
|
||||
pub(crate) fn new_parameterized(
|
||||
op: BoundAggregate,
|
||||
schema: Arc<SeriesSchema>,
|
||||
@@ -395,15 +281,9 @@ impl AggregateRuntime {
|
||||
Self::new_quantile(op, None, schema, buffer)
|
||||
}
|
||||
|
||||
/// Keeps the φ this node reads at every grid point, in the one unlabelled scalar series its
|
||||
/// parameter child handed over.
|
||||
///
|
||||
/// The series is already reserved: it arrives through the driver's `hold_scalar`, which grows the
|
||||
/// same reservation by [`series_bytes`] before the chunk is kept, exactly as it does for a
|
||||
/// broadcast scalar or a `topk` parameter. Adopting it therefore only settles on what the node
|
||||
/// holds -- which counts it once, from [`QuantileInput::bytes`] -- rather than growing for a
|
||||
/// second allocation that was never made: a pool that holds the handoff must not refuse a
|
||||
/// handoff that allocates nothing.
|
||||
/// Keeps the per-point φ series. The driver's `hold_scalar` has already grown this reservation
|
||||
/// by [`series_bytes`], so this only settles on [`QuantileInput::bytes`] instead of growing
|
||||
/// again.
|
||||
pub(crate) fn hold_parameter(
|
||||
&mut self,
|
||||
parameter: Series,
|
||||
@@ -421,22 +301,10 @@ impl AggregateRuntime {
|
||||
buffer.resize(retained.bytes())
|
||||
}
|
||||
|
||||
/// What consuming `chunk` reserves while it is consumed.
|
||||
///
|
||||
/// A point-wise fold drops the chunk at the end of the call and keeps only its states, so the
|
||||
/// charge is the chunk's own bytes -- the figure [`evaluated_bytes`] reports, which is one pass
|
||||
/// over the chunk and no state between chunks -- and not the `operand_chunk_bytes` figure a
|
||||
/// binary operand keeps, which exists because such an operand holds a series for the whole
|
||||
/// execution and so must count the slices of one buffer instead of the buffer once per chunk.
|
||||
///
|
||||
/// A `quantile` keeps the chunk instead, and what it holds is not the chunk alone: it is the
|
||||
/// allocations the chunk's samples live in, billed once each, beside the chunk's own descriptors
|
||||
/// ([`Self::retain_quantile`], which is [`chunk_bytes_beside_samples`] plus
|
||||
/// [`unbilled_sample_buffers`] plus [`unbilled_tables`]). That figure is read from the chunk by
|
||||
/// the retainer itself, before it retains it, so nothing is held before it is reserved. Booking
|
||||
/// the chunk again here would reserve the same backing twice -- once for the chunk being handed
|
||||
/// over and once for the allocations it points into -- which is not a safer estimate but a
|
||||
/// refusal of an input whose own figure the pool admits.
|
||||
/// What consuming `chunk` reserves while it is consumed: its [`evaluated_bytes`] for a
|
||||
/// point-wise fold, which drops it after folding. A `quantile` returns 0 because
|
||||
/// [`Self::retain_quantile`] reserves the retained chunk itself; booking it here as well would
|
||||
/// bill it twice.
|
||||
pub(crate) fn pending(&self, chunk: &EvaluatedChunk) -> usize {
|
||||
match self.fold {
|
||||
Fold::Pointwise(_) => evaluated_bytes(chunk),
|
||||
@@ -444,14 +312,8 @@ impl AggregateRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds one chunk into its group.
|
||||
///
|
||||
/// A chunk that closes its series closes nothing here: a group is not a series, so the last
|
||||
/// contribution of one member says nothing about the group. The fold keeps its states, which is
|
||||
/// what makes a group's answer its whole group's answer once the input ends.
|
||||
///
|
||||
/// A `quantile` keeps the chunk itself, for the same reason: the answer is the group's sample set,
|
||||
/// so the samples have to survive until the input does.
|
||||
/// Folds one chunk into its group, or retains it for a `quantile`. A chunk's `is_last` closes a
|
||||
/// member, not a group, so it is ignored.
|
||||
pub(crate) fn accumulate(
|
||||
&mut self,
|
||||
chunk: EvaluatedChunk,
|
||||
@@ -461,22 +323,19 @@ impl AggregateRuntime {
|
||||
let Fold::Pointwise(kind) = self.fold else {
|
||||
return self.retain_quantile(chunk, buffer);
|
||||
};
|
||||
// `Series` keeps its fields public, so a chunk can be built by struct literal against
|
||||
// another schema; the states are indexed by absolute position on this node's grid, so a
|
||||
// chunk of another field count or another grid would be folded into the wrong places.
|
||||
// States are indexed by field and absolute grid position, so a chunk on another schema
|
||||
// would fold into the wrong slots.
|
||||
validate_aggregate_series(&self.schema, &chunk.series, kind)
|
||||
.map_err(|error| folded_chunk(&self.describe(), error))?;
|
||||
if histogram_samples(kind) == HistogramSamples::Ignored
|
||||
&& !crate::map::is_float_series(&chunk.series)
|
||||
&& let Some(collector) = &self.annotations
|
||||
{
|
||||
// Prometheus reports once that it skipped samples it cannot order or average over; the
|
||||
// fold keeps going on the float samples it can read.
|
||||
// Prometheus reports the skipped histogram samples once and folds the floats.
|
||||
collector.record_info(format!(
|
||||
"{}: ignored native histogram samples",
|
||||
self.aggregate_name()
|
||||
));
|
||||
// The collector keeps the message, so the node has said its piece.
|
||||
self.annotations = None;
|
||||
}
|
||||
let Some(accumulator) = self.accumulator.as_mut() else {
|
||||
@@ -490,29 +349,17 @@ impl AggregateRuntime {
|
||||
buffer.resize(accumulator.state_bytes())
|
||||
}
|
||||
|
||||
/// Keeps one chunk of a `quantile`'s input until the input ends.
|
||||
///
|
||||
/// The chunk is kept whole rather than folded: the answer is the φ-quantile of the group's sample
|
||||
/// set, and no fixed-width state holds a sample set. What it costs is measured the way a binary
|
||||
/// operand measures the chunks it retains, and for the same reason: what a `quantile` keeps is a
|
||||
/// series for the rest of the execution, so the allocation one buffer its chunks are slices of is
|
||||
/// counted once rather than once per chunk -- and counted at all when the chunk holds a small
|
||||
/// slice of it, because the allocation is what stays resident. It is the chunk's own descriptors
|
||||
/// ([`chunk_bytes_beside_samples`]) beside those allocations: the Arrow buffers its samples live
|
||||
/// in, once each ([`unbilled_sample_buffers`]), and the histogram tables they index into, once
|
||||
/// each ([`unbilled_tables`]). The figure is reserved before the push -- the push is what makes
|
||||
/// the node hold it -- and the reservation then settles on the whole input, which is what this
|
||||
/// node holds between chunks.
|
||||
/// Retains one chunk of a `quantile`'s input. The chunk's descriptors plus the buffers and
|
||||
/// tables it is first to reference are reserved before the push, then the reservation settles
|
||||
/// on [`QuantileInput::bytes`].
|
||||
fn retain_quantile(&mut self, chunk: EvaluatedChunk, buffer: &mut NodeBuffer) -> Result<()> {
|
||||
// A quantile reads float values and skips a histogram sample, so a chunk only has to fit the
|
||||
// schema and the grid -- exactly what the kernel's own input check asks for.
|
||||
// Same check as the kernel's: histogram samples are skipped, not rejected.
|
||||
validate_grid_series(&self.schema, &chunk.series)
|
||||
.map_err(|error| folded_chunk(&self.describe(), error))?;
|
||||
if !crate::map::is_float_series(&chunk.series)
|
||||
&& let Some(collector) = &self.annotations
|
||||
{
|
||||
// Prometheus reports once that it skipped samples it cannot order; the kernel folds the
|
||||
// float samples it can read.
|
||||
// Prometheus reports the skipped histogram samples once.
|
||||
collector.record_info(format!(
|
||||
"{}: ignored native histogram samples",
|
||||
self.aggregate_name()
|
||||
@@ -522,21 +369,14 @@ impl AggregateRuntime {
|
||||
let Some(retained) = self.retained.as_mut() else {
|
||||
return Err(no_fold(&self.describe()));
|
||||
};
|
||||
// What this chunk adds to what the node holds: the allocations its samples live in and the
|
||||
// histogram tables it is the first chunk to reference -- each billed once, because one
|
||||
// allocation is one however many chunks slice it -- plus the descriptors the chunk keeps.
|
||||
let (buffers, buffer_bytes) = unbilled_sample_buffers(&chunk.series, &retained.buffers);
|
||||
let (tables, table_bytes) = unbilled_tables(&chunk.series, &retained.tables);
|
||||
let bytes = chunk_bytes_beside_samples(&chunk.series)
|
||||
.saturating_add(buffer_bytes)
|
||||
.saturating_add(table_bytes);
|
||||
buffer.grow(bytes)?;
|
||||
// The slot the chunk is about to take, and - when the vector has to grow for it - the
|
||||
// capacity it grows to. `Vec::push` doubles, so booking one slot would let the real
|
||||
// allocation outrun what the pool admitted; the target is booked instead, and the settle
|
||||
// below then reads back the exact capacity the vector holds. The vector's slots are not part
|
||||
// of `held`: [`QuantileInput::bytes`] counts them from that capacity, so booking them here
|
||||
// and folding them there would charge them twice.
|
||||
// Grow the vector explicitly so the reservation covers the doubled capacity before the
|
||||
// allocation; `QuantileInput::bytes` counts slots from capacity, not from `held`.
|
||||
let needed = retained.series.len().saturating_add(1);
|
||||
if needed > retained.series.capacity() {
|
||||
let target = retained.series.capacity().saturating_mul(2).max(needed);
|
||||
@@ -555,22 +395,15 @@ impl AggregateRuntime {
|
||||
})?;
|
||||
}
|
||||
retained.series.push(chunk.series);
|
||||
// From here the node keeps those tables and allocations alive itself, so a chunk arriving
|
||||
// later that references one is charged its own descriptors and not the allocation again.
|
||||
retained.tables.extend(tables);
|
||||
retained.buffers.extend(buffers);
|
||||
retained.held = retained.held.saturating_add(bytes);
|
||||
buffer.resize(retained.bytes())
|
||||
}
|
||||
|
||||
/// Merges one state chunk into this final aggregate.
|
||||
///
|
||||
/// State reaches a `Final` from exactly two places and is merged here, once: a producer in this
|
||||
/// process hands over the groups it folded ([`StateChunk::Series`]), and a region's exported
|
||||
/// frame is decoded into the row it carries ([`StateChunk::Row`], which a merge scan reads
|
||||
/// across processes). Both are read as the rows the merge kernel takes, so there is one merge
|
||||
/// and not one per source; the series form is turned into those rows here, inside the kernel,
|
||||
/// instead of by a caller that would have to know what the kernel eats.
|
||||
/// Merges one state chunk into this `Final` aggregate: either groups a local `Partial` folded
|
||||
/// ([`StateChunk::Series`]) or a decoded exported row ([`StateChunk::Row`]). Both are converted
|
||||
/// to the rows the merge kernel takes.
|
||||
pub(crate) fn accumulate_state(
|
||||
&mut self,
|
||||
chunk: StateChunk,
|
||||
@@ -580,11 +413,6 @@ impl AggregateRuntime {
|
||||
let expected = self.state_schema.as_ref().ok_or_else(|| {
|
||||
DataFusionError::NotImplemented("this runtime does not merge aggregate state".into())
|
||||
})?;
|
||||
// The one conversion this edge performs, and it is here rather than at the API boundary: a
|
||||
// producer hands over the groups it folded, and the kernel merges rows. Each source is
|
||||
// validated once, where its rows are made: the series form by the row layout it is built
|
||||
// against, a decoded row by the checks that layout makes of a group, so the merge below only
|
||||
// merges and a group costs its own encoding.
|
||||
let rows = match chunk {
|
||||
StateChunk::Row(row) => {
|
||||
if row.fields.kind() != expected.kind
|
||||
@@ -615,11 +443,7 @@ impl AggregateRuntime {
|
||||
state_schema: _,
|
||||
reservation: _reservation,
|
||||
} => {
|
||||
// The state layout and the Arrow shape a row is encoded against depend on the chunk,
|
||||
// not on the group, so they are resolved once for all of its groups. The grid is
|
||||
// checked here for the same reason: every row of this chunk lands on the series grid
|
||||
// the layout encodes against, so comparing it once says what a comparison per row
|
||||
// said before.
|
||||
// Layout and grid depend on the chunk, not the group, so they are checked once.
|
||||
if self.schema.eval_grid.as_ref().map(|grid| grid.spec())
|
||||
!= Some(expected.grid.spec())
|
||||
{
|
||||
@@ -637,9 +461,7 @@ impl AggregateRuntime {
|
||||
.map_err(|error| DataFusionError::Execution(error.to_string()))?;
|
||||
let mut rows = Vec::with_capacity(series.len());
|
||||
for group in series {
|
||||
// A group a `Partial` hands over is whole: it folded the group's contribution of
|
||||
// its partition, and the merge above joins partitions rather than continuing a
|
||||
// chain.
|
||||
// A `Partial` hands over its partition's complete contribution to the group.
|
||||
let row = layout
|
||||
.row(group, true)
|
||||
.map_err(|error| DataFusionError::Execution(error.to_string()))?;
|
||||
@@ -665,12 +487,8 @@ impl AggregateRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of retained groups, for budgeting the output queue backing storage.
|
||||
///
|
||||
/// A point-wise fold knows its groups because it keyed them. A `quantile` has not grouped
|
||||
/// anything: the kernel does that when it answers. What it reports here is therefore the number
|
||||
/// of members it retained, which is an upper bound -- every group has at least one member -- and
|
||||
/// only ever sizes a reservation.
|
||||
/// The number of groups, for sizing the output queue. A `quantile` has not grouped yet and
|
||||
/// reports its retained member count, an upper bound.
|
||||
pub(crate) fn groups(&self) -> usize {
|
||||
if let Some(input) = self.retained.as_ref() {
|
||||
return input.series.len();
|
||||
@@ -678,11 +496,8 @@ impl AggregateRuntime {
|
||||
self.accumulator.as_ref().map_or(0, FloatAggregator::groups)
|
||||
}
|
||||
|
||||
/// Finishes the fold and returns one series per group, or `None` if the fold already ran.
|
||||
///
|
||||
/// `None` is what a node reports after it has queued its series: the caller reads them from the
|
||||
/// queue, exactly as it reads the chunks a binary node queued, so a second pull does not finish
|
||||
/// a fold whose states are gone.
|
||||
/// Finishes the fold and returns one series per group (or the state chunk of a `Partial`), or
|
||||
/// `None` if it already ran.
|
||||
pub(crate) fn compute(
|
||||
&mut self,
|
||||
buffer: &mut NodeBuffer,
|
||||
@@ -699,8 +514,6 @@ impl AggregateRuntime {
|
||||
if let Some(accumulator) = self.accumulator.take() {
|
||||
return match self.op.stage {
|
||||
AggregateStage::Complete => {
|
||||
// What the fold recorded about its inputs is reported here, where this node's
|
||||
// answer is the whole answer.
|
||||
let evidence = accumulator.evidence_summary();
|
||||
let output = accumulator.finish_budgeted(|total| {
|
||||
buffer.resize(total.saturating_add(queue_bytes))
|
||||
@@ -717,13 +530,7 @@ impl AggregateRuntime {
|
||||
.state_schema
|
||||
.clone()
|
||||
.ok_or_else(|| no_fold(&self.describe()))?;
|
||||
// The fold builds the chunk's own representation, so handing it over costs no
|
||||
// second copy and no second charge: what was admitted for the groups is what
|
||||
// the chunk now holds.
|
||||
//
|
||||
// What the fold recorded travels in that state instead of being reported here:
|
||||
// one partition's evidence is a claim about a point the merge has not decided
|
||||
// yet, and a message cannot be taken back.
|
||||
// Evidence travels in the state; only the `Final` merge can report it.
|
||||
let partial = accumulator
|
||||
.finish_partial_budgeted(|bytes| buffer.resize(bytes + queue_bytes))?;
|
||||
let chunk = state_chunk_from_partial(partial, state_schema, &self.op)?;
|
||||
@@ -733,8 +540,6 @@ impl AggregateRuntime {
|
||||
};
|
||||
}
|
||||
if let Some(merger) = self.merger.take() {
|
||||
// The merge saw every partition's state, so this node is where the point's outcome is
|
||||
// final and where its evidence is reported.
|
||||
let evidence = merger.evidence_summary();
|
||||
let output =
|
||||
merger.finish_budgeted(|total| buffer.resize(total.saturating_add(queue_bytes)))?;
|
||||
@@ -748,16 +553,8 @@ impl AggregateRuntime {
|
||||
Err(no_fold(&self.describe()))
|
||||
}
|
||||
|
||||
/// Reports what the fold or merge recorded about its inputs, once, where the answer is final.
|
||||
///
|
||||
/// Only a `Complete` or a `Final` node reports: a `Partial` node hands its evidence on in the
|
||||
/// state it exports, because a point's outcome is not decided until every partition has been
|
||||
/// merged and a message cannot be withdrawn once it has been collected. The collector is the
|
||||
/// node's own handle, so its children keep theirs.
|
||||
///
|
||||
/// A poisoned point answers nothing, and the reconciliation its inputs needed is not reported
|
||||
/// for it: the summary already dropped that bit, which is what makes the message set the same
|
||||
/// whichever order the partitions arrived in.
|
||||
/// Reports histogram evidence once. A `Partial` reports nothing: a point's outcome is decided
|
||||
/// only after the `Final` merge, and a collected message cannot be withdrawn.
|
||||
fn report_evidence(&mut self, evidence: HistogramEvidence) {
|
||||
if self.op.stage == AggregateStage::Partial {
|
||||
return;
|
||||
@@ -778,31 +575,11 @@ impl AggregateRuntime {
|
||||
collector.record_warning(format!("{name}: contradictory reset hints"));
|
||||
}
|
||||
}
|
||||
/// Answers a `quantile` from the input it kept, and hands the series over.
|
||||
///
|
||||
/// The kernel reads `q` per point from an unlabelled single-field scalar on the aggregate's own
|
||||
/// grid, and a point that scalar has no value at is a point with no result. Which scalar that is
|
||||
/// depends on what the query wrote: the φ the node held from its parameter child, or -- for a
|
||||
/// number bound on the tree -- one built over the points the input holds, so that every point it
|
||||
/// covers carries it. (A point the held series has no sample at is unanswered, exactly as a
|
||||
/// missing `q` is in the kernel; `scalar(...)`, the shape that produces one per point, answers
|
||||
/// NaN rather than no sample, so a statement whose `foo` holds nothing answers NaN there.)
|
||||
///
|
||||
/// A built parameter covers the points the input holds and not the window they sit in: the
|
||||
/// kernel reads `q` only where a member has a sample, so a sparse input's parameter is as wide
|
||||
/// as its rows. A parameter over the envelope would instead allocate every position between two
|
||||
/// far-apart points -- a span sized by the statement's range rather than by the data it reads,
|
||||
/// which the pool never admitted. The parameter is booked from the bound its rows give before it
|
||||
/// exists, and settles on its exact figure once it is built. A held parameter is not built here
|
||||
/// and needs no such bound: it was reserved when the node adopted it, which is what
|
||||
/// [`QuantileInput::bytes`] counts ever since.
|
||||
///
|
||||
/// The reservation covers what is held while the kernel runs -- the input, that parameter, and
|
||||
/// the kernel's workspace -- and then settles on the series the kernel answered, exactly as a
|
||||
/// point-wise fold's finish does. The input is what stops being held when the kernel is done with
|
||||
/// it, so it is dropped before the settle rather than when this call returns: a settle read
|
||||
/// beside a live input would name a set that is never held, and the figure it left behind would
|
||||
/// be the one the next node's admission had to fit into.
|
||||
|
||||
/// Answers a `quantile` from its retained input. φ is the held per-point series, or for a
|
||||
/// literal φ a series built over only the positions the input holds (not the span between
|
||||
/// them, which could be as wide as the grid). The reservation covers input, parameter and
|
||||
/// workspace while the kernel runs, then settles on the output after the input is dropped.
|
||||
fn finish_quantile(
|
||||
&self,
|
||||
input: QuantileInput,
|
||||
@@ -814,19 +591,13 @@ impl AggregateRuntime {
|
||||
"a `quantile` aggregate needs an evaluated grid to read its parameter on".into(),
|
||||
)
|
||||
})?;
|
||||
// The points the kernel copies the parameter over. A held `φ` covers the grid the statement
|
||||
// evaluated it on, which the input's rows say nothing about: one row of input beside a
|
||||
// `time()` over a million grid points is a million pairs, not one. A built one covers the
|
||||
// points the input holds, and the input's rows bound those.
|
||||
// A held φ may cover far more points than the input has rows (e.g. `time()`).
|
||||
let parameter_points = match &input.parameter {
|
||||
Some(parameter) => parameter.time.len(),
|
||||
None => input.series.iter().map(|series| series.time.len()).sum(),
|
||||
};
|
||||
let workspace = quantile_workspace_bytes(&self.schema, &input, parameter_points);
|
||||
// A built parameter is admitted before it exists, because building it is what makes this
|
||||
// node hold it: the bound is what a parameter over the input's points can take, and the
|
||||
// resize below settles on what it did take. A held one is already counted by
|
||||
// `input.bytes()`, so reserving for it again would charge the same series twice.
|
||||
// Reserve an upper bound for a parameter not built yet; a held one is in `input.bytes()`.
|
||||
let built_bound = match (&input.parameter, input.quantile) {
|
||||
(None, Some(_)) => quantile_parameter_bound_bytes(&input),
|
||||
_ => 0,
|
||||
@@ -838,8 +609,6 @@ impl AggregateRuntime {
|
||||
.saturating_add(workspace)
|
||||
.saturating_add(queue_bytes),
|
||||
)?;
|
||||
// The φ the kernel reads: the series this node held from its parameter child, or -- when the
|
||||
// query bound the number -- one built over the points the input holds.
|
||||
let mut built = None;
|
||||
if input.parameter.is_none() {
|
||||
let Some(quantile) = input.quantile else {
|
||||
@@ -849,8 +618,6 @@ impl AggregateRuntime {
|
||||
};
|
||||
let positions = quantile_positions(&input);
|
||||
built = Some(quantile_parameter(&grid, quantile, &positions)?);
|
||||
// The collected positions are what the bound above covered and what this node no longer
|
||||
// holds, so they go before the figure settles.
|
||||
drop(positions);
|
||||
}
|
||||
let parameter = input
|
||||
@@ -879,15 +646,8 @@ impl AggregateRuntime {
|
||||
let output = aggregate_quantile(&self.schema, &input.series, parameter, grouping)
|
||||
.map_err(|error| folded_chunk(&self.describe(), error))?;
|
||||
drop(names);
|
||||
// The parameter's use ends with the kernel call, and a built one is dropped here for the
|
||||
// same reason the input is: the settle below names what the node holds from then on. A
|
||||
// held one goes with the input it is part of.
|
||||
// Free the input before settling on the output; the output copies what it keeps.
|
||||
drop(built);
|
||||
// The input is what this node held until the kernel answered, and it is given back before
|
||||
// the reservation settles on the answer: the settle below is what the node holds from then
|
||||
// on, so it must be read from the set that is really alive -- the answer and the queue --
|
||||
// rather than from the answer beside an input this call only drops on its way out. The
|
||||
// kernel's answer holds nothing of the input: the builder copies the samples it keeps.
|
||||
drop(input);
|
||||
let output_vec_bytes = output
|
||||
.capacity()
|
||||
@@ -900,27 +660,14 @@ impl AggregateRuntime {
|
||||
/// The field the `quantile` parameter is bound under, which the kernel reads as its scalar.
|
||||
const QUANTILE_PARAMETER_FIELD: &str = "scalar";
|
||||
|
||||
/// The points the retained input holds, once each, in ascending order.
|
||||
///
|
||||
/// A group's answer is decided at the points at least one of its members holds a sample at, and its
|
||||
/// members are drawn from the input, so these are every point the kernel can ask its parameter for.
|
||||
/// They are the positions the input's rows sit at -- not the window they span, which two far-apart
|
||||
/// points make as wide as the grid.
|
||||
/// The positions the retained input holds, deduplicated and ascending: every point the kernel can
|
||||
/// ask φ for.
|
||||
fn quantile_positions(input: &QuantileInput) -> Vec<usize> {
|
||||
union_positions(input.series.iter().map(|series| &series.time)).collect()
|
||||
}
|
||||
|
||||
/// The parameter a `quantile` reads at each point: the φ the query wrote, unlabelled and single
|
||||
/// field, at `positions` and nowhere else.
|
||||
///
|
||||
/// The kernel reads `q` per point and treats a point it has no value at as a point with no result,
|
||||
/// so the parameter has to cover exactly the points that can be asked for and may omit every other
|
||||
/// one. [`GridSeriesBuilder`] is what makes that cheap: the axis keeps the runs of consecutive
|
||||
/// positions rather than a row per position, so two far-apart points cost two rows and two spans
|
||||
/// instead of every position between them.
|
||||
///
|
||||
/// An input holding no point has nothing to decide, which the kernel answers with no output: an
|
||||
/// empty scalar over the grid says the same thing and costs nothing.
|
||||
/// An unlabelled single-field series holding `quantile` at `positions` only, or an empty scalar
|
||||
/// when there are none.
|
||||
fn quantile_parameter(grid: &Arc<EvalGrid>, quantile: f64, positions: &[usize]) -> Result<Series> {
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: Arc::from([FieldSpec {
|
||||
@@ -945,13 +692,8 @@ fn quantile_parameter(grid: &Arc<EvalGrid>, quantile: f64, positions: &[usize])
|
||||
}
|
||||
}
|
||||
|
||||
/// The most a `quantile` parameter over `input` can cost, before it is built.
|
||||
///
|
||||
/// The parameter holds one value and one position per point it covers, and one span per run of
|
||||
/// them; a run is at least one point long, so the input's rows bound all of those. The figure is
|
||||
/// what the pool admits ahead of the allocation, and [`series_bytes`] is what it settles on once
|
||||
/// the parameter exists: what is admitted is what the parameter really takes, wherever its points
|
||||
/// sit on the grid.
|
||||
/// An upper bound on the bytes of the parameter [`quantile_parameter`] builds over `input`,
|
||||
/// reserved before it is built. The input's row count bounds its points and runs.
|
||||
fn quantile_parameter_bound_bytes(input: &QuantileInput) -> usize {
|
||||
let rows: usize = input.series.iter().map(|series| series.time.len()).sum();
|
||||
let per_point = std::mem::size_of::<usize>() // its position, while the points are collected
|
||||
@@ -963,22 +705,10 @@ fn quantile_parameter_bound_bytes(input: &QuantileInput) -> usize {
|
||||
.saturating_add(rows.saturating_mul(per_point))
|
||||
}
|
||||
|
||||
/// The bytes the `quantile` kernel needs beside its retained input while it answers.
|
||||
///
|
||||
/// [`aggregate_quantile`] reports no workspace as it allocates, so this is an estimate reserved once
|
||||
/// before it runs, in the same spirit as the whole-vector kernels'. What it covers: the state it
|
||||
/// keeps per member (one position list, one heap entry and one cursor per field), its own copy of the
|
||||
/// parameter, the temporaries of one grid point (its members' values, the copy the kernel sorts, and
|
||||
/// one row of the width it folds), and the rows it builds -- the group being built and the groups it
|
||||
/// has already handed over. The row count is the input's own: a group's rows are the points at least
|
||||
/// one of its members holds a sample at, so the input's rows bound every group's rows and their sum.
|
||||
///
|
||||
/// The parameter copy is `parameter_points` pairs and not the input's rows: the kernel reads the
|
||||
/// whole parameter into one `(position, φ)` per point it covers before it folds anything, so a dense
|
||||
/// `time()` read against one row of input copies every point of the grid, and sizing that copy from
|
||||
/// the input's one row would reserve a pair for a million points. What the kernel iterates are the
|
||||
/// parameter's own positions -- the points a bound `φ` was built over and the points a held one
|
||||
/// covers -- so the caller reports that count rather than this reading the input for it.
|
||||
/// An estimate of the workspace [`aggregate_quantile`] allocates beside its input, reserved once
|
||||
/// because the kernel does not report allocations: per-member cursors, one point's temporaries,
|
||||
/// the output rows (bounded by the input's rows), and the kernel's `(position, φ)` copy of all
|
||||
/// `parameter_points`.
|
||||
fn quantile_workspace_bytes(
|
||||
schema: &SeriesSchema,
|
||||
input: &QuantileInput,
|
||||
@@ -993,13 +723,12 @@ fn quantile_workspace_bytes(
|
||||
let per_point = members
|
||||
.saturating_mul(2 * std::mem::size_of::<f64>())
|
||||
.saturating_add(width.saturating_mul(std::mem::size_of::<Option<f64>>()));
|
||||
// One row, charged twice: the builder holds one group at a time and the series it has already
|
||||
// handed over are held beside it.
|
||||
// Twice: the group being built plus the groups already finished.
|
||||
let per_row = 2 * width
|
||||
.saturating_mul(std::mem::size_of::<f64>())
|
||||
.saturating_add(2 * std::mem::size_of::<usize>())
|
||||
.saturating_add(1);
|
||||
// The parameter copy, charged twice for the capacity a growing vector keeps over its length.
|
||||
// Twice, for a growing vector's spare capacity.
|
||||
let parameter_copy = 2 * parameter_points.saturating_mul(std::mem::size_of::<(usize, f64)>());
|
||||
members
|
||||
.saturating_mul(per_member)
|
||||
@@ -1009,11 +738,7 @@ fn quantile_workspace_bytes(
|
||||
.saturating_add(members.saturating_mul(std::mem::size_of::<Series>()))
|
||||
}
|
||||
|
||||
/// Charges the series a finished aggregate hands over, plus the queue they enter.
|
||||
///
|
||||
/// The queue's own backing is counted by the caller that appends to it, so what is added here is
|
||||
/// the series themselves and the vector that carries them; the two are charged together because
|
||||
/// the vector outlives the call that built it.
|
||||
/// Settles the reservation on the output series, their vector, and `queue_bytes`.
|
||||
fn charge_samples(
|
||||
buffer: &mut NodeBuffer,
|
||||
output: &[Series],
|
||||
@@ -1030,17 +755,8 @@ fn charge_samples(
|
||||
)
|
||||
}
|
||||
|
||||
/// The rejection of a chunk that is not the layout this node folds.
|
||||
///
|
||||
/// The fold indexes its states by absolute grid position and by field, so a chunk of another field
|
||||
/// count or another grid would be folded into states that mean something else. `error` is what the
|
||||
/// series check reported, which says which of the two disagreed.
|
||||
/// Wraps the error of a chunk this node cannot fold.
|
||||
///
|
||||
/// Only a chunk that does not fit the schema is the node's own refusal; anything else is the
|
||||
/// kernel saying it does not compute this shape at all -- exporting native histogram state, for
|
||||
/// instance -- and a caller that falls back to another planner on `NotImplemented` still can.
|
||||
/// Wrapping that one in an `Execution` would deny it.
|
||||
/// Wraps a chunk-validation or kernel error as an `Execution` error naming the aggregate.
|
||||
/// `NotImplemented` passes through unchanged so callers can still recognise an unsupported shape.
|
||||
fn folded_chunk(aggregate: &str, error: DataFusionError) -> DataFusionError {
|
||||
match error {
|
||||
DataFusionError::NotImplemented(_) => error,
|
||||
@@ -1101,8 +817,6 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The φ this node folds is a series over `points` grid points, as `time()` or `scalar()`
|
||||
/// hands one over.
|
||||
fn parameter_series(points: usize) -> Series {
|
||||
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1, 4).unwrap()).unwrap());
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
@@ -1115,23 +829,11 @@ mod tests {
|
||||
constant_series(&schema, GridRange::try_new(grid, 0, points).unwrap(), 0.5).unwrap()
|
||||
}
|
||||
|
||||
/// Adopting the parameter transfers the charge it arrived with, and bills it once.
|
||||
///
|
||||
/// The series is grown onto this node's reservation before it is handed over, because it
|
||||
/// outlives the child that produced it; `hold_scalar` is what does that, and it does it on this
|
||||
/// node's buffer. Adopting it allocates nothing, so the node settles on what it holds -- the
|
||||
/// series once, its descriptor counted by the state that holds it inline -- and a pool of
|
||||
/// exactly that figure admits the handoff. Growing for the same series again would ask for the
|
||||
/// double of what arrived, and a pool that holds the handoff would refuse it.
|
||||
#[test]
|
||||
fn adopting_a_parameter_charges_it_once() {
|
||||
let parameter = parameter_series(4);
|
||||
let held = series_bytes(¶meter);
|
||||
// What the node holds once the series arrived and was grown onto it, and what it holds with
|
||||
// the same series adopted: the second is the first less the descriptor the state carries
|
||||
// inline, because a series held in a slot costs the slot and the heap and not the slot
|
||||
// twice. The pool holds exactly the handoff, so an admission that asks for the series a
|
||||
// second time has nowhere to put it.
|
||||
// The pool fits the handoff exactly, so growing for the series a second time would fail.
|
||||
let handoff = std::mem::size_of::<QuantileInput>() + held;
|
||||
let adopted = handoff - std::mem::size_of::<Series>();
|
||||
let pool: Arc<dyn datafusion::execution::memory_pool::MemoryPool> = Arc::new(
|
||||
@@ -1153,8 +855,7 @@ mod tests {
|
||||
&mut buffer,
|
||||
)
|
||||
.unwrap();
|
||||
// The handoff the parameter child makes: the series is reserved on this node's buffer
|
||||
// before it is kept, exactly as `hold_scalar` does for every scalar operand.
|
||||
// What `hold_scalar` does before handing the series over.
|
||||
buffer.grow(held).unwrap();
|
||||
runtime
|
||||
.hold_parameter(parameter, &mut buffer)
|
||||
@@ -1172,14 +873,9 @@ mod tests {
|
||||
(warnings, infos)
|
||||
}
|
||||
|
||||
/// Only the node that finishes the answer reports what the fold recorded, and it says each thing
|
||||
/// once. A `Partial` node reports nothing: one partition's evidence is a claim about a point the
|
||||
/// merge has not decided yet, and a message cannot be taken back.
|
||||
#[test]
|
||||
fn only_the_finishing_node_reports_histogram_evidence() {
|
||||
let evidence = HistogramEvidence {
|
||||
// The summary a poisoned point produces keeps its reconciliation bit out, so this is
|
||||
// what a merge hands over when a point is removed for its layout.
|
||||
poisoned: true,
|
||||
incompatible_layout: true,
|
||||
custom_bounds_reconciled: false,
|
||||
@@ -1202,8 +898,6 @@ mod tests {
|
||||
let collector = PromqlAnnotationCollector::default();
|
||||
finishing.set_annotations(collector.clone());
|
||||
finishing.report_evidence(evidence);
|
||||
// A second report is not a second message: the node handed its collector on with the
|
||||
// first one.
|
||||
finishing.report_evidence(evidence);
|
||||
let (warnings, infos) = collected(&collector);
|
||||
assert!(
|
||||
@@ -1223,10 +917,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The two reset-hint bits are OR-ed over every point the fold saw, so between them they say
|
||||
/// only what the inputs reported -- two groups can each hold one of them. Whether they
|
||||
/// contradict is a per-point decision, which the summary carries in `counter_reset_collision`,
|
||||
/// and that bit is what the reporter warns about.
|
||||
/// The two reset-hint bits are OR-ed across points, so both set means nothing on its own; only
|
||||
/// the per-point `counter_reset_collision` warns.
|
||||
#[test]
|
||||
fn a_reset_hint_held_by_one_group_each_is_not_a_collision() {
|
||||
let mut quiet = runtime(AggregateStage::Complete);
|
||||
@@ -1243,7 +935,6 @@ mod tests {
|
||||
"two points that each saw one hint contradict nothing"
|
||||
);
|
||||
|
||||
// One point that saw both is the collision, and it is what the message is for.
|
||||
let mut colliding = runtime(AggregateStage::Complete);
|
||||
let collector = PromqlAnnotationCollector::default();
|
||||
colliding.set_annotations(collector.clone());
|
||||
@@ -1260,7 +951,6 @@ mod tests {
|
||||
assert!(infos.is_empty(), "{infos:?}");
|
||||
}
|
||||
|
||||
/// A reconciled point that answered reports its reconciliation as information, once.
|
||||
#[test]
|
||||
fn a_live_point_reports_its_reconciliation() {
|
||||
let mut runtime = runtime(AggregateStage::Complete);
|
||||
|
||||
@@ -12,28 +12,10 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The batches native nodes hand to each other.
|
||||
//! The chunk native nodes hand to each other by call; see [`EvaluatedChunk`] for the protocol.
|
||||
//!
|
||||
//! These are ordinary Rust values passed by call, not DataFusion streams and not encoded messages:
|
||||
//! the Arrow arrays, buffers and shared schemas inside them are reused as they are.
|
||||
//!
|
||||
//! Two rules make a chunk self-describing:
|
||||
//!
|
||||
//! - A grid position is absolute on the chunk's grid. Batch-local row numbers never stand in for
|
||||
//! one, and an inner grid is never addressed with an outer grid's index.
|
||||
//! - A series closes exactly once, on the chunk that carries [`EvaluatedChunk::is_last`]. A closed
|
||||
//! prefix still has to be followed by a final chunk even when that chunk holds no values, so a
|
||||
//! consumer can tell "nothing more here" from "no more input". This is per input series, not per
|
||||
//! label set: a node that rewrites labels can hand two input series over under one label set, and
|
||||
//! each of them still closes on its own chunk, so a label set may be closed more than once. A
|
||||
//! series that produced values closes it, and a later input series with no result at all closes it
|
||||
//! again on the chunk that ends it; a node that can merge two inputs into one series must not read
|
||||
//! the second close as a defect.
|
||||
|
||||
//!
|
||||
//! The chunk type itself is [`crate::evaluated::EvaluatedChunk`]: one chunk protocol serves both the
|
||||
//! evaluator that produces chunks and the native nodes that consume them. Defining a second one
|
||||
//! here would let the two drift apart, and a chunk produced by the evaluator could not be handed to
|
||||
//! a node without translation.
|
||||
//! A series closes once per input series, not per label set: a node that rewrites labels can emit
|
||||
//! two input series under one label set, so a consumer that merges inputs must accept a second
|
||||
//! close of the same label set.
|
||||
|
||||
pub use crate::evaluated::EvaluatedChunk;
|
||||
|
||||
@@ -12,87 +12,28 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Puts a canonical merge where a label rewrite made one necessary.
|
||||
//! Puts a canonical [`NativeExpr::Merge`] where a label rewrite or a metadata-label drop can give
|
||||
//! two series one label set.
|
||||
//!
|
||||
//! A fused input hands over the pieces of a metric one scan partition holds, and a label rewrite in
|
||||
//! the tree can give two of those pieces one label set. Every consumer that answers a whole label
|
||||
//! set - a fold, a ranking, a vector match, the statement's own output - then reads two series where
|
||||
//! Prometheus reads one, or answers the sum of a group twice. [`NativeExpr::Merge`] is the node that
|
||||
//! collects the pieces of one label set into one series, and this module decides where one is
|
||||
//! needed.
|
||||
//! A fused input hands over the series one scan partition holds. A node that writes an existing
|
||||
//! label or drops `__name__`/`__type__`/`__unit__` can make two of them share a canonical label set
|
||||
//! ([`duplicates_canonical_labels`]); a consumer that reads whole label sets then needs a merge
|
||||
//! below it:
|
||||
//!
|
||||
//! # What decides it
|
||||
//! | consumer | merge below it? |
|
||||
//! | --- | --- |
|
||||
//! | the root | yes |
|
||||
//! | `Aggregate`, `ParameterizedAggregate`, `Vector`, `ParameterizedTopK`, `ParameterizedHistogram`, `ScalarOf` | yes |
|
||||
//! | `Binary`, `Set`, `Info` | yes, on each evaluated-vector side (a scalar broadcast's vector side included) |
|
||||
//! | `Window` | yes |
|
||||
//! | `Map`, `ParameterizedMap` | yes, below it: a map can empty a point (histogram functions drop floats, math skips histograms), so a merge above it would judge occupancy the map already erased |
|
||||
//! | `Timestamp`, `Instant`, `VectorOf` | no |
|
||||
//!
|
||||
//! Only a rewrite can alias, and only one that writes a label its input already carries or drops one
|
||||
//! its output would still be told apart by: [`duplicates_canonical_labels`] is that fact, derived
|
||||
//! from the tree and the tags each source reports. A tree with no such rewrite gains no merge at
|
||||
//! all, so a per-series query keeps every scan partition and pays nothing for this pass.
|
||||
//! The `NULL`/`''` key-column pair is not collected; see
|
||||
//! [`leaves_a_drop_to_the_storage_keys`](crate::native::plan::leaves_a_drop_to_the_storage_keys).
|
||||
//!
|
||||
//! Where a merge is added is a property of the consumer, and of what the operations between the
|
||||
//! consumer and the rewrite do to one sample:
|
||||
//!
|
||||
//! | consumer | merge below it? | why |
|
||||
//! | --- | --- | --- |
|
||||
//! | the root | yes | the answer names one series per label set, so two rows sharing one set are the error Prometheus reports |
|
||||
//! | `Aggregate` | yes | a fold sums the values it is handed at a point, so two pieces of one series are summed as if the query said so twice |
|
||||
//! | `Vector` | yes | ranking, presence checks and folds must read canonical series rather than duplicate fragments |
|
||||
//! | `Binary`/`Set` over two vectors | yes, on both sides | each side is matched by label, and the kernel refuses two values of one field at a point only after the pair was matched |
|
||||
//! | `Info` | yes, on both sides | it looks the info series up by identifying labels, so the pieces of one label set have to be one series first |
|
||||
//! | `Window` over an evaluated vector | yes | a window folds a range of one series, so it reads the series whole |
|
||||
//! | `Map`, `ParameterizedMap` | yes, below it | point-wise, but not sample-preserving: the histogram functions drop float samples, math ignores native histograms, and a parameterized clamp can empty a point - and the label set a point's occupancy is judged under is the rewritten one, so a merge above such a map would be handed the occupancy that is already gone |
|
||||
//! | `Timestamp`, `Instant`, a scalar broadcast | no | each rewrites the value of a sample it read and keeps that sample's position, so no occupancy is lost and the pieces are still told apart where the rewrite left them |
|
||||
//!
|
||||
//! A merge is never added below a raw scan, a scalar or aggregate state: it binds samples evaluated
|
||||
//! on a grid, and no consumer asks for one over those.
|
||||
//!
|
||||
//! A node can be a source of duplicates without rewriting a label its input carries: a range
|
||||
//! function that computes its result and `timestamp` in both of its forms drop the metadata labels -
|
||||
//! the metric name, `__type__` and `__unit__` - and hand out a set those no longer tell apart. What
|
||||
//! they produce is collected by their consumer - the root included - exactly as a rewrite of an
|
||||
//! existing label is, unless
|
||||
//! [`duplicates_canonical_labels`](crate::native::plan::duplicates_canonical_labels) proves from the
|
||||
//! labels alone that nothing they drop was telling two of their series apart: a source bound to one
|
||||
//! metric names every series it hands over, and a source whose tags carry neither `__type__` nor
|
||||
//! `__unit__` holds no series those two tell apart either. `rate(some_metric[5m])` over such a scan
|
||||
//! is then a window that streams its scan, and the same query over a selector that discovered
|
||||
//! several metrics keeps the collection it needs. The same rule is what a math or histogram map, a
|
||||
//! parameterized map and an arithmetic or `bool` scalar broadcast are judged by.
|
||||
//!
|
||||
//! The labels are the whole of that proof, and the scan's key columns are not part of it. A key
|
||||
//! column that holds `NULL` in one stored series and `''` in another decodes to an absent and to an
|
||||
//! empty label, and the drop removes the empty one with the name, leaving both under one label set -
|
||||
//! a pair that no label can state and that is deliberately outside the proof, because every tag
|
||||
//! column of a metric-engine table is nullable and collecting every name-dropping kernel over one
|
||||
//! for it costs every such statement a canonical merge. The fact is still counted
|
||||
//! ([`leaves_a_drop_to_the_storage_keys`](crate::native::plan::leaves_a_drop_to_the_storage_keys)),
|
||||
//! so the statements the pair can hide stay observable. Its other reader is the physical per-series
|
||||
//! scan, which asks it of its own binding to decide whether its partitions hand over whole series
|
||||
//! ([`keys_survive_metadata_drop`](crate::extension_plan::keys_survive_metadata_drop)) - a
|
||||
//! partition-identity question at execution, never a reason to insert a `Merge`.
|
||||
//!
|
||||
//! A drop above a merge is not asked about the empty value it removes, which is what keeps a chain of
|
||||
//! drops to one collection: [`NativeExpr::Merge`] hands over one series per canonical label set - the
|
||||
//! comparison that treats an empty label value as no label - so no drop above it can fold two of its
|
||||
//! series by dropping an empty one. The metadata labels a drop removes are another matter: a merge
|
||||
//! keeps two series that differ in `__name__`, `__type__` or `__unit__`, so the labels half of the
|
||||
//! proof is still asked above it. With that, a chain of drops - `abs(abs(rate(x[5m])))` - pays for
|
||||
//! the one merge at the bottom of the chain rather than one per drop.
|
||||
//!
|
||||
//! Canonicalizing a map's input is what makes the histogram case work: in
|
||||
//! `histogram_count(label_replace(x, "host", "same", "host", ".*"))` two scan partitions each
|
||||
//! rewrite one series to `{host="same"}` and `histogram_count` drops both - they are float samples -
|
||||
//! before anything could report that the two now share a label set at one point. The merge is
|
||||
//! inserted between the rewrite and `histogram_count`, so the canonical router judges the occupancy
|
||||
//! the rewrite created and reports the collision instead of an empty answer.
|
||||
//!
|
||||
//! Running the pass over its own output changes nothing: the node that gained a merge then answers
|
||||
//! one series per label set, so [`duplicates_canonical_labels`] is `false` for it and a second run
|
||||
//! finds nothing to add. That also makes the pass safe to apply at every segment boundary rather
|
||||
//! than only at the statement root.
|
||||
//!
|
||||
//! What this pass does *not* decide is placement: whether the merge can be answered inside one
|
||||
//! execution is the lowering's question. A merge that spans partitions uses a producer and the
|
||||
//! existing canonical router; downstream consumers read ordinary evaluated frames.
|
||||
//! The pass is idempotent: a merge answers `false` to [`duplicates_canonical_labels`], so it is
|
||||
//! safe to run at every segment boundary. Placement of the merge is the lowering's decision.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -107,41 +48,21 @@ mod tests;
|
||||
|
||||
/// Rewrites `tree` so that every consumer of a whole canonical series is handed one.
|
||||
///
|
||||
/// `source_tags` is what the caller knows about each fused input's tags, indexed by the
|
||||
/// `source_index` of the [`BoundInput`](crate::native::plan::BoundInput) each leaf was bound to; a
|
||||
/// source the caller says nothing about proves nothing, and a rewrite over it is collected. The
|
||||
/// index is what a leaf reads, so a tree with several sources is judged source by source.
|
||||
///
|
||||
/// `source_metrics` is the other half of that knowledge, indexed the same way: the one metric each
|
||||
/// source is bound to, or `None` when it may hand over several. It is what lets a kernel that drops
|
||||
/// the metadata labels keep every partition - see
|
||||
/// [`duplicates_canonical_labels`](crate::native::plan::duplicates_canonical_labels) - and a caller
|
||||
/// that cannot say collects instead.
|
||||
///
|
||||
/// Every operation binding and every `source_index` stays where it was, so the rewrite changes which
|
||||
/// series a consumer reads and not what the query computes. The result is checked by
|
||||
/// [`NativeTree::try_new`], because a merge has to sit over an evaluated vector and the pass may
|
||||
/// only put it there.
|
||||
/// `source_tags` and `source_metrics` are indexed by each leaf's `source_index`: the label names a
|
||||
/// source reports, and the one metric it is bound to (`None` when it may hand over several). A
|
||||
/// source without facts proves nothing, so a rewrite over it is collected. Bindings and
|
||||
/// `source_index`es are unchanged.
|
||||
pub fn merge_label_rewrites(
|
||||
tree: &NativeTree,
|
||||
source_tags: &[Vec<String>],
|
||||
source_metrics: &[Option<Arc<str>>],
|
||||
) -> DfResult<NativeTree> {
|
||||
let root = rewrite(tree.root(), source_tags, source_metrics)?;
|
||||
// The root is a consumer too: whatever reads this tree reads one series per label set.
|
||||
NativeTree::try_new(canonical(root, source_tags, source_metrics))
|
||||
}
|
||||
|
||||
/// Wraps `node` in a [`NativeExpr::Merge`] when its pieces can share a label set.
|
||||
///
|
||||
/// Three things have to hold, and each is asked rather than assumed:
|
||||
///
|
||||
/// - the node's output is an evaluated vector, because a merge binds samples on a grid and a raw
|
||||
/// scan, a scalar and aggregate state have nothing it could take;
|
||||
/// - the node can hand over two series of one label set
|
||||
/// ([`duplicates_canonical_labels`]), because collecting pieces that are already distinct is a
|
||||
/// barrier that buys nothing;
|
||||
/// - it is not already a merge, which would collect what is already collected.
|
||||
/// Wraps `node` in a [`NativeExpr::Merge`] when it is an evaluated vector, not already a merge, and
|
||||
/// may hand over two series of one label set.
|
||||
fn canonical(
|
||||
node: NativeNode,
|
||||
source_tags: &[Vec<String>],
|
||||
@@ -156,7 +77,6 @@ fn canonical(
|
||||
if !duplicates_canonical_labels(&node, source_tags, source_metrics) {
|
||||
return node;
|
||||
}
|
||||
// A merge reports its input's layout: the same fields on the same grid.
|
||||
let output = node.output.clone();
|
||||
NativeNode {
|
||||
expr: NativeExpr::Merge {
|
||||
@@ -166,22 +86,16 @@ fn canonical(
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites `node` bottom-up: its children first, then the merge its own consumer contract needs of
|
||||
/// them.
|
||||
fn rewrite(
|
||||
node: &NativeNode,
|
||||
source_tags: &[Vec<String>],
|
||||
source_metrics: &[Option<Arc<str>>],
|
||||
) -> DfResult<NativeNode> {
|
||||
let expr = match &node.expr {
|
||||
// A source is the boundary it was bound to and there is nothing below it to rewrite. A
|
||||
// constant reads nothing.
|
||||
NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {
|
||||
node.expr.clone()
|
||||
}
|
||||
// A selection reads raw samples, one whole storage series at a time, and stamps them onto a
|
||||
// grid; a timestamp replaces each value with its sample's time. Both read each piece as it
|
||||
// is, so neither collects what it reads.
|
||||
// Both keep each sample's position, so no occupancy is lost by not collecting here.
|
||||
NativeExpr::Instant { input, op } => NativeExpr::Instant {
|
||||
input: Box::new(rewrite(input, source_tags, source_metrics)?),
|
||||
op: op.clone(),
|
||||
@@ -189,14 +103,9 @@ fn rewrite(
|
||||
NativeExpr::Timestamp { input } => NativeExpr::Timestamp {
|
||||
input: Box::new(rewrite(input, source_tags, source_metrics)?),
|
||||
},
|
||||
// A merge is the canonicalizer itself, so it asks nothing of its input: fragments are what it
|
||||
// was written to receive.
|
||||
NativeExpr::Merge { input } => NativeExpr::Merge {
|
||||
input: Box::new(rewrite(input, source_tags, source_metrics)?),
|
||||
},
|
||||
// A window folds a range of one series' samples and hands the answer over as that series, so
|
||||
// it reads the series whole. Over a raw scan the pieces are whole storage series already and
|
||||
// the merge above is a no-op; over an evaluated vector a rewrite can have aliased them.
|
||||
NativeExpr::Window { input, op } => NativeExpr::Window {
|
||||
input: Box::new(canonical(
|
||||
rewrite(input, source_tags, source_metrics)?,
|
||||
@@ -205,11 +114,6 @@ fn rewrite(
|
||||
)),
|
||||
op: op.clone(),
|
||||
},
|
||||
// A map is point-wise, but a point can drop out of its output: the histogram functions drop
|
||||
// float samples, math drops native histograms, and a parameterized clamp can empty a point.
|
||||
// The occupancy that tells two pieces of one label set apart is the rewritten frame's, so a
|
||||
// merge above this map would be handed an occupancy the map may already have erased - the
|
||||
// pieces have to be collected where they still hold their samples, below it.
|
||||
NativeExpr::Map { input, op } => NativeExpr::Map {
|
||||
input: Box::new(canonical(
|
||||
rewrite(input, source_tags, source_metrics)?,
|
||||
@@ -218,9 +122,7 @@ fn rewrite(
|
||||
)),
|
||||
op: op.clone(),
|
||||
},
|
||||
// A parameterized map's parameters are scalars, rewritten but never collected - a scalar
|
||||
// carries no label set. Its input is read point-wise like a map's and, for the same reason,
|
||||
// its pieces are collected below it rather than above it.
|
||||
// Scalar parameters carry no label set, so only the input is collected.
|
||||
NativeExpr::ParameterizedMap {
|
||||
input,
|
||||
op,
|
||||
@@ -237,8 +139,6 @@ fn rewrite(
|
||||
.map(|parameter| rewrite(parameter, source_tags, source_metrics))
|
||||
.collect::<DfResult<Vec<_>>>()?,
|
||||
},
|
||||
// A fold answers its groups, so two pieces of one series in a group are summed as if the
|
||||
// query had written them twice: the merge is what makes one series arrive as one.
|
||||
NativeExpr::Aggregate { input, op } => NativeExpr::Aggregate {
|
||||
input: Box::new(canonical(
|
||||
rewrite(input, source_tags, source_metrics)?,
|
||||
@@ -247,9 +147,6 @@ fn rewrite(
|
||||
)),
|
||||
op: op.clone(),
|
||||
},
|
||||
// The same fold with its argument read per point: the pieces of one series in a group are
|
||||
// as much a problem for a quantile as for a sum, and its parameter is a scalar, rewritten
|
||||
// but never collected - a scalar carries no label set.
|
||||
NativeExpr::ParameterizedAggregate {
|
||||
input,
|
||||
op,
|
||||
@@ -263,8 +160,6 @@ fn rewrite(
|
||||
op: op.clone(),
|
||||
parameter: Box::new(rewrite(parameter, source_tags, source_metrics)?),
|
||||
},
|
||||
// Vector operations consume canonical series: ranking counts them, and presence checks and
|
||||
// folds must not silently consume overlapping fragments that a merge would reject.
|
||||
NativeExpr::Vector { input, op } => NativeExpr::Vector {
|
||||
input: Box::new(canonical(
|
||||
rewrite(input, source_tags, source_metrics)?,
|
||||
@@ -273,9 +168,7 @@ fn rewrite(
|
||||
)),
|
||||
op: op.clone(),
|
||||
},
|
||||
// Each side of a binary or set operation is matched by label on its own, so each is
|
||||
// canonicalized on its own. A constant side has nothing to canonicalize and a merge could not
|
||||
// sit over one, which `canonical` leaves it as.
|
||||
// `canonical` leaves a scalar side alone.
|
||||
NativeExpr::Binary {
|
||||
left,
|
||||
right,
|
||||
@@ -306,9 +199,6 @@ fn rewrite(
|
||||
)),
|
||||
op: op.clone(),
|
||||
},
|
||||
// `info` pairs each base series with the info series that share its identifying labels, so it
|
||||
// reads both sides whole: the pieces of one label set have to be one series before they are
|
||||
// matched.
|
||||
NativeExpr::Info {
|
||||
base,
|
||||
info,
|
||||
@@ -326,12 +216,9 @@ fn rewrite(
|
||||
)),
|
||||
selector: selector.clone(),
|
||||
},
|
||||
// `vector(s)` builds its series from a scalar, which carries no label set to collect.
|
||||
NativeExpr::VectorOf { input } => NativeExpr::VectorOf {
|
||||
input: Box::new(rewrite(input, source_tags, source_metrics)?),
|
||||
},
|
||||
// `scalar()` answers from the whole vector: a series that arrives in pieces would be seen
|
||||
// as several samples, so the pieces are collected where they still hold their samples.
|
||||
NativeExpr::ScalarOf { input } => NativeExpr::ScalarOf {
|
||||
input: Box::new(canonical(
|
||||
rewrite(input, source_tags, source_metrics)?,
|
||||
@@ -339,8 +226,6 @@ fn rewrite(
|
||||
source_metrics,
|
||||
)),
|
||||
},
|
||||
// `topk` ranks the whole vector, so it counts canonical series; its parameter is a scalar,
|
||||
// rewritten but never collected - a scalar carries no label set.
|
||||
NativeExpr::ParameterizedTopK {
|
||||
input,
|
||||
op,
|
||||
@@ -354,8 +239,6 @@ fn rewrite(
|
||||
op: op.clone(),
|
||||
parameter: Box::new(rewrite(parameter, source_tags, source_metrics)?),
|
||||
},
|
||||
// A histogram function folds the bucket series of one histogram, so overlapping fragments
|
||||
// must not reach it; its parameters are scalars and only need rewriting.
|
||||
NativeExpr::ParameterizedHistogram {
|
||||
input,
|
||||
op,
|
||||
|
||||
@@ -12,15 +12,6 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! What the canonical-merge pass has to get right: it collects exactly where a rewrite could give
|
||||
//! two series one label set, it never collects a shape a merge cannot take, and running it twice
|
||||
//! changes nothing.
|
||||
//!
|
||||
//! The trees are built node by node over the one-field schemas of a `rate(x[5m])`-style fixture, and
|
||||
//! the labels each source reports are supplied by the test: the pass's whole decision is whether a
|
||||
//! rewrite writes a label its input already carries, so a test that says nothing about the input's
|
||||
//! labels is testing the conservative branch and has to say so.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datatypes::series::SeriesOrdering;
|
||||
@@ -63,7 +54,6 @@ fn evaluated(schema_fields: Arc<[FieldSpec]>, grid: Arc<EvalGrid>) -> NativeType
|
||||
}))
|
||||
}
|
||||
|
||||
/// A scan of raw samples, the leaf every tree here is built over.
|
||||
fn raw_input(source_index: usize) -> NativeNode {
|
||||
let output = NativeType::Samples(Arc::new(SeriesSchema {
|
||||
fields: fields(1),
|
||||
@@ -79,7 +69,6 @@ fn raw_input(source_index: usize) -> NativeNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// A constant, which a binary operation broadcasts.
|
||||
fn scalar(value: f64, out: Arc<EvalGrid>) -> NativeNode {
|
||||
NativeNode {
|
||||
expr: NativeExpr::Scalar(BoundScalar { value }),
|
||||
@@ -87,7 +76,6 @@ fn scalar(value: f64, out: Arc<EvalGrid>) -> NativeNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// An instant selection over `inner` that reports what `value` says it reports, on `out`.
|
||||
fn selection(inner: NativeNode, out: Arc<EvalGrid>, value: InstantValue) -> NativeNode {
|
||||
NativeNode {
|
||||
expr: NativeExpr::Instant {
|
||||
@@ -109,7 +97,6 @@ fn selected(out: &Arc<EvalGrid>) -> NativeNode {
|
||||
selection(raw_input(0), Arc::clone(out), InstantValue::Sample)
|
||||
}
|
||||
|
||||
/// A map that applies `ops` to `inner`, keeping its layout.
|
||||
fn map_ops(inner: NativeNode, ops: Vec<MapOp>) -> NativeNode {
|
||||
let output = inner.output.clone();
|
||||
NativeNode {
|
||||
@@ -131,12 +118,12 @@ fn rewrite(inner: NativeNode, dst: &str, src: &str) -> NativeNode {
|
||||
)
|
||||
}
|
||||
|
||||
/// `abs(inner)`: a point-wise map that keeps the label set's primary key.
|
||||
/// `abs(inner)`.
|
||||
fn abs_map(inner: NativeNode) -> NativeNode {
|
||||
map_ops(inner, vec![MapOp::Math(MathOp::Abs)])
|
||||
}
|
||||
|
||||
/// `histogram_count(inner)`: point-wise over the grid, but it drops every float sample it reads.
|
||||
/// `histogram_count(inner)`, which drops every float sample it reads.
|
||||
fn histogram_count(inner: NativeNode) -> NativeNode {
|
||||
map_ops(
|
||||
inner,
|
||||
@@ -144,7 +131,7 @@ fn histogram_count(inner: NativeNode) -> NativeNode {
|
||||
)
|
||||
}
|
||||
|
||||
/// `clamp_min(inner, argument)`: a point-wise function whose bound argument is a scalar on its grid.
|
||||
/// `clamp_min(inner, argument)`.
|
||||
fn clamp_min(inner: NativeNode, argument: NativeNode) -> NativeNode {
|
||||
let output = inner.output.clone();
|
||||
NativeNode {
|
||||
@@ -163,8 +150,6 @@ fn aggregate_over(inner: NativeNode, out: Arc<EvalGrid>, stage: AggregateStage)
|
||||
AggregateStage::Partial => {
|
||||
NativeType::AggregateState(Arc::new(crate::native::plan::AggregateStateSchema {
|
||||
group: Grouping::By(Arc::from([])),
|
||||
// The state family this branch carries: the kind and its components come from the
|
||||
// kernel binding, not from a second mapping.
|
||||
kind: datatypes::series::aggregate_state::AggregateStateKind::Sum,
|
||||
components: Arc::from(
|
||||
crate::native::plan::aggregate_state_binding(
|
||||
@@ -194,7 +179,6 @@ fn aggregate_over(inner: NativeNode, out: Arc<EvalGrid>, stage: AggregateStage)
|
||||
}
|
||||
}
|
||||
|
||||
/// A vector operation over `inner`, laid out as `inner` is.
|
||||
fn vector_over(inner: NativeNode, op: BoundVectorOp) -> NativeNode {
|
||||
let output = inner.output.clone();
|
||||
NativeNode {
|
||||
@@ -214,7 +198,7 @@ fn topk(k: f64) -> BoundVectorOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// An `adding` match with no `on`/`ignoring`, which is `x + y`.
|
||||
/// `x + y` with no `on`/`ignoring`.
|
||||
fn add() -> BinaryMatching {
|
||||
BinaryMatching {
|
||||
op: BinaryOp::Add,
|
||||
@@ -225,7 +209,6 @@ fn add() -> BinaryMatching {
|
||||
}
|
||||
}
|
||||
|
||||
/// A binary operation over `left` and `right` on `out`, one value per input field.
|
||||
fn binary_over(left: NativeNode, right: NativeNode, out: Arc<EvalGrid>) -> NativeNode {
|
||||
NativeNode {
|
||||
expr: NativeExpr::Binary {
|
||||
@@ -237,7 +220,6 @@ fn binary_over(left: NativeNode, right: NativeNode, out: Arc<EvalGrid>) -> Nativ
|
||||
}
|
||||
}
|
||||
|
||||
/// A set operation over `left` and `right` on `out`.
|
||||
fn set_over(left: NativeNode, right: NativeNode, out: Arc<EvalGrid>) -> NativeNode {
|
||||
NativeNode {
|
||||
expr: NativeExpr::Set {
|
||||
@@ -252,7 +234,7 @@ fn set_over(left: NativeNode, right: NativeNode, out: Arc<EvalGrid>) -> NativeNo
|
||||
}
|
||||
}
|
||||
|
||||
/// `last_over_time(inner[5m])`, a window that folds `inner` onto `out` and keeps the metric name.
|
||||
/// `last_over_time(inner[5m])`, which keeps the metric name.
|
||||
fn keeping_window_over(
|
||||
inner: NativeNode,
|
||||
input_grid: Option<Arc<EvalGrid>>,
|
||||
@@ -277,7 +259,7 @@ fn keeping_window_over(
|
||||
}
|
||||
}
|
||||
|
||||
/// `rate(inner[5m])`, a window that folds `inner` onto `out` and drops the metric name.
|
||||
/// `rate(inner[5m])`, which drops the metric name.
|
||||
fn window_over(
|
||||
inner: NativeNode,
|
||||
input_grid: Option<Arc<EvalGrid>>,
|
||||
@@ -302,7 +284,7 @@ fn window_over(
|
||||
}
|
||||
}
|
||||
|
||||
/// `info(base, {})`: the base series with the data labels of the info series that share theirs.
|
||||
/// `info(base, {})`.
|
||||
fn info_over(base: NativeNode, info: NativeNode) -> NativeNode {
|
||||
let output = base.output.clone();
|
||||
NativeNode {
|
||||
@@ -319,7 +301,6 @@ fn info_over(base: NativeNode, info: NativeNode) -> NativeNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many merges `tree` holds.
|
||||
fn merges(tree: &NativeTree) -> usize {
|
||||
fn visit(node: &NativeNode) -> usize {
|
||||
let children = match &node.expr {
|
||||
@@ -355,20 +336,12 @@ fn merges(tree: &NativeTree) -> usize {
|
||||
visit(tree.root())
|
||||
}
|
||||
|
||||
/// Runs the pass over `root`, whose sources report `source_tags`.
|
||||
///
|
||||
/// Nothing is stated about which metric each source reads, so a kernel that drops the metadata
|
||||
/// labels over one of them proves nothing and is collected.
|
||||
/// Runs the pass over `root` with no metric facts, so every metadata drop is unproved.
|
||||
fn passed(root: NativeNode, source_tags: &[Vec<String>]) -> NativeTree {
|
||||
passed_over(root, source_tags, &[])
|
||||
}
|
||||
|
||||
/// Runs the pass over `root`, whose sources report `source_tags` and read the metric each of
|
||||
/// `source_metrics` names, indexed the way `merge_label_rewrites` takes it.
|
||||
///
|
||||
/// The scans below these fixtures key their series by columns that always decode a value, which is
|
||||
/// not what the pass reads: the labels are the whole of a metadata drop's proof, and the nullable-key
|
||||
/// fixtures state the pair it leaves outside itself.
|
||||
/// Runs the pass over `root` with `source_tags` and `source_metrics` indexed by `source_index`.
|
||||
fn passed_over(
|
||||
root: NativeNode,
|
||||
source_tags: &[Vec<String>],
|
||||
@@ -379,8 +352,7 @@ fn passed_over(
|
||||
.expect("the pass produces a legal tree")
|
||||
}
|
||||
|
||||
/// The labels a scan bound to one metric reports: its tag, and the name the binding gives every
|
||||
/// series it hands over, which is not a tag column.
|
||||
/// A named scan's runtime labels: its tag and `__name__`, which is not a tag column.
|
||||
fn named_scan_tags() -> Vec<Vec<String>> {
|
||||
vec![tags(&["host", "__name__"])]
|
||||
}
|
||||
@@ -389,7 +361,7 @@ fn tags(names: &[&str]) -> Vec<String> {
|
||||
names.iter().map(|name| name.to_string()).collect()
|
||||
}
|
||||
|
||||
/// The labels each fixture source reports, which is what decides whether a rewrite can alias.
|
||||
/// One tag, `host`, and no metric name.
|
||||
fn scan_tags() -> Vec<Vec<String>> {
|
||||
vec![tags(&["host"])]
|
||||
}
|
||||
@@ -397,7 +369,6 @@ fn scan_tags() -> Vec<Vec<String>> {
|
||||
#[test]
|
||||
fn a_fresh_destination_needs_no_collection() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// `dst` names no label the scan reports, so no two series can end under one label set.
|
||||
let tree = passed(rewrite(selected(&out), "dst", "host"), &scan_tags());
|
||||
assert_eq!(0, merges(&tree), "a fresh destination cannot alias");
|
||||
assert!(
|
||||
@@ -409,7 +380,6 @@ fn a_fresh_destination_needs_no_collection() {
|
||||
#[test]
|
||||
fn a_rewrite_of_a_scan_tag_is_collected_at_the_root() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// Writing `host` - the label that told the scan's series apart - can fold them into one set.
|
||||
let tree = passed(rewrite(selected(&out), "host", "host"), &scan_tags());
|
||||
assert_eq!(1, merges(&tree));
|
||||
let NativeExpr::Merge { input } = &tree.root().expr else {
|
||||
@@ -473,7 +443,6 @@ fn presence_and_folding_vector_operations_collect_aliasing_inputs() {
|
||||
},
|
||||
];
|
||||
for op in ops {
|
||||
// Distinct host values can become the same label set, including at an overlapping point.
|
||||
let aliasing = map_ops(
|
||||
selected(&out),
|
||||
vec![MapOp::Label(Arc::new(
|
||||
@@ -554,10 +523,8 @@ fn rewrites_after_ranking_or_grouping_are_collected() {
|
||||
#[test]
|
||||
fn a_rewrite_above_a_match_collects_the_matches_own_labels() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// A match answers one series per label set, but those labels are its operands': renaming `host`
|
||||
// to a constant above it puts both sides' results under one set, so the consumer above the
|
||||
// rewrite is the one that has to collect them. The match itself reads its operands as they are;
|
||||
// the one on the right drops the metadata labels, so its own answer is collected.
|
||||
// Renaming `host` to a constant above the match folds its results, so the root collects them.
|
||||
// The right operand drops the metadata labels, so it is collected too.
|
||||
let matched = binary_over(selected(&out), abs_map(selected(&out)), Arc::clone(&out));
|
||||
let renamed = map_ops(
|
||||
matched,
|
||||
@@ -589,8 +556,6 @@ fn a_rewrite_above_a_match_collects_the_matches_own_labels() {
|
||||
#[test]
|
||||
fn a_rewrite_of_the_label_count_values_writes_is_collected() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// `count_values` answers one series per distinct value under the label it writes, so renaming
|
||||
// that label to a constant folds every one of them into one label set.
|
||||
let counted = vector_over(
|
||||
selected(&out),
|
||||
BoundVectorOp::CountValues {
|
||||
@@ -618,9 +583,6 @@ fn a_rewrite_of_the_label_count_values_writes_is_collected() {
|
||||
#[test]
|
||||
fn a_fresh_destination_above_count_values_needs_no_collection() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// `dst` is not a label `count_values` reports - its grouping's are, and so is the one it writes
|
||||
// - so no two of its series can end under one label set, and deriving that set is what says a
|
||||
// fresh destination above it has nothing to collect.
|
||||
let counted = vector_over(
|
||||
selected(&out),
|
||||
BoundVectorOp::CountValues {
|
||||
@@ -643,8 +605,7 @@ fn a_pointwise_map_reads_each_piece_as_it_is() {
|
||||
abs_map(rewrite(selected(&out), "host", "host")),
|
||||
&scan_tags(),
|
||||
);
|
||||
// Two collections: one below the map, because a map reads pieces point-wise and a point it
|
||||
// reads can be one it drops, and one above it, for the metadata labels the map itself drops.
|
||||
// One merge below the map, for the rewrite, and one above it, for the map's own name drop.
|
||||
assert_eq!(2, merges(&tree), "{tree}");
|
||||
let NativeExpr::Merge { input } = &tree.root().expr else {
|
||||
panic!("the root collects what the map hands out: {tree}");
|
||||
@@ -661,8 +622,8 @@ fn a_pointwise_map_reads_each_piece_as_it_is() {
|
||||
assert_eq!(tree.to_string(), twice.to_string());
|
||||
}
|
||||
|
||||
/// `histogram_count(label_replace(x, "host", "same", "host", ".*"))`: the map that erases the
|
||||
/// samples the collision would be judged on, so the merge has to sit between the rewrite and it.
|
||||
/// `histogram_count(label_replace(x, "host", "same", "host", ".*"))`: the map erases the float
|
||||
/// samples the collision would be judged on, so the merge sits between the rewrite and the map.
|
||||
#[test]
|
||||
fn a_sample_dropping_map_collects_below_itself() {
|
||||
let out = grid(0, 1000, 2);
|
||||
@@ -698,8 +659,6 @@ fn a_sample_dropping_map_collects_below_itself() {
|
||||
matches!(input.expr, NativeExpr::Instant { .. }),
|
||||
"the rewrite still reads the selection it read before"
|
||||
);
|
||||
// A second pass over the collected tree changes nothing: the merge answers one series per label
|
||||
// set, so nothing below the map aliases any more.
|
||||
let twice = merge_label_rewrites(&tree, &scan_tags(), &[]).unwrap();
|
||||
assert_eq!(2, merges(&twice));
|
||||
assert_eq!(tree.to_string(), twice.to_string());
|
||||
@@ -708,11 +667,7 @@ fn a_sample_dropping_map_collects_below_itself() {
|
||||
#[test]
|
||||
fn a_pointwise_map_collects_its_own_name_drop() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// No rewrite anywhere in the tree, so no two pieces were told apart by a label one of them
|
||||
// wrote - but `abs` drops the metadata labels, and the drop is a source of duplicates of its
|
||||
// own: a key column that holds `NULL` in one stored series and `''` in another decodes to an
|
||||
// absent and to an empty label, and both are gone once the empty one goes. Each map's answer is
|
||||
// therefore collected, and both sit above the map that hands them out.
|
||||
// No metric facts, so each `abs` drop is unproved and collected above its map.
|
||||
let tree = passed(abs_map(abs_map(selected(&out))), &scan_tags());
|
||||
assert_eq!(2, merges(&tree), "{tree}");
|
||||
let NativeExpr::Merge { input } = &tree.root().expr else {
|
||||
@@ -733,9 +688,7 @@ fn a_pointwise_map_collects_its_own_name_drop() {
|
||||
#[test]
|
||||
fn a_sample_dropping_map_over_a_fresh_destination_collects_its_own_drop() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// `dst` names no label the scan reports, so the rewrite cannot alias and the map's input needs
|
||||
// no collection even though the map drops samples - but the metadata labels `histogram_count`
|
||||
// drops are a source of duplicates of their own, so its answer is collected.
|
||||
// The fresh `dst` needs no merge below the map; the map's own name drop is collected above it.
|
||||
let tree = passed(
|
||||
histogram_count(rewrite(selected(&out), "dst", "host")),
|
||||
&scan_tags(),
|
||||
@@ -753,8 +706,6 @@ fn a_sample_dropping_map_over_a_fresh_destination_collects_its_own_drop() {
|
||||
#[test]
|
||||
fn a_parameterized_map_collects_below_itself() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// A clamp may empty a point as well, so its input is collected below it exactly as a map's is;
|
||||
// the bound argument is a scalar and carries no label set to collect.
|
||||
let tree = passed(
|
||||
clamp_min(
|
||||
rewrite(selected(&out), "host", "host"),
|
||||
@@ -762,8 +713,7 @@ fn a_parameterized_map_collects_below_itself() {
|
||||
),
|
||||
&scan_tags(),
|
||||
);
|
||||
// One below the map, for the point a clamp can empty, and one above it, for the metadata labels
|
||||
// the kernel drops.
|
||||
// One merge below the clamp, for the rewrite, and one above it, for its name drop.
|
||||
assert_eq!(2, merges(&tree), "{tree}");
|
||||
let NativeExpr::Merge { input } = &tree.root().expr else {
|
||||
panic!("the root collects what the clamp hands out: {tree}");
|
||||
@@ -827,8 +777,6 @@ fn a_set_operation_collects_each_side() {
|
||||
#[test]
|
||||
fn a_window_collects_an_aliasing_child() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// A window over an evaluated vector folds one series' range, so it reads the series whole. The
|
||||
// window keeps the metric name here, so the rewrite below it is the only source of duplicates.
|
||||
let tree = passed(
|
||||
keeping_window_over(
|
||||
rewrite(selected(&out), "host", "host"),
|
||||
@@ -844,131 +792,6 @@ fn a_window_collects_an_aliasing_child() {
|
||||
assert!(matches!(input.expr, NativeExpr::Merge { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_over_a_raw_scan_collects_nothing() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// The scan hands over whole storage series, and a merge cannot take raw samples anyway.
|
||||
let tree = passed(keeping_window_over(raw_input(0), None, out), &scan_tags());
|
||||
assert_eq!(0, merges(&tree));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_dropping_window_is_collected_by_its_consumer() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// `rate` drops the metric name, which is part of the identity a merge groups by: a caller that
|
||||
// says nothing about which metric the scan reads collects what the window hands out.
|
||||
let tree = passed(
|
||||
window_over(raw_input(0), None, Arc::clone(&out)),
|
||||
&named_scan_tags(),
|
||||
);
|
||||
assert_eq!(1, merges(&tree));
|
||||
let NativeExpr::Merge { input } = &tree.root().expr else {
|
||||
panic!("the root collects what the window hands out: {tree}");
|
||||
};
|
||||
assert!(
|
||||
matches!(input.expr, NativeExpr::Window { .. }),
|
||||
"the merge sits above the window, not below it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_dropping_window_over_one_metric_streams() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// The scan is bound to one metric, so every series it hands over is named the same thing:
|
||||
// dropping that name tells none of them apart, and the window keeps every partition.
|
||||
//
|
||||
// The key columns are the other half of that proof, and this fixture states the half that holds:
|
||||
// every one of them always decodes a value, so the empty label value the drop removes with the
|
||||
// name never stood for a second stored series.
|
||||
let tree = passed_over(
|
||||
window_over(raw_input(0), None, Arc::clone(&out)),
|
||||
&named_scan_tags(),
|
||||
&[Some(Arc::from("some_metric"))],
|
||||
);
|
||||
assert_eq!(0, merges(&tree), "{tree}");
|
||||
assert!(
|
||||
matches!(tree.root().expr, NativeExpr::Window { .. }),
|
||||
"the root stays the window: {tree}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Two stored series of one metric that differ only in a tag column holding `NULL` in one and `''`
|
||||
/// in the other: `{host="web-1", zone=""}` and `{host="web-1"}` are two series to the scan, and
|
||||
/// `rate` drops the metric name and the empty `zone` with it, so both leave the window as
|
||||
/// `{host="web-1"}`.
|
||||
///
|
||||
/// The labels alone cannot tell them apart - they share host, zone is about to go, and the name is
|
||||
/// the one every series of the scan shares - but the pair is deliberately outside the drop's proof:
|
||||
/// it is a property of a nullable tag column, and every tag column of a metric-engine table is
|
||||
/// nullable, so collecting for it would put a canonical merge over every statement whose kernel
|
||||
/// drops the metadata labels. Nothing is collected, and the window keeps its partitions; the plan
|
||||
/// time count of the statements this leaves unproved is
|
||||
/// [`leaves_a_drop_to_the_storage_keys`](crate::native::plan::leaves_a_drop_to_the_storage_keys).
|
||||
#[test]
|
||||
fn a_nullable_key_tag_does_not_collect_the_window_that_drops_an_empty_value() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// A scan of one metric whose tags are `host` and `zone`, the second of which is a nullable key
|
||||
// column: the pair above is one storage key away from being two.
|
||||
let scan = [tags(&["host", "zone", "__name__"])];
|
||||
let single = [Some(Arc::<str>::from("some_metric"))];
|
||||
let tree = passed_over(
|
||||
window_over(raw_input(0), None, Arc::clone(&out)),
|
||||
&scan,
|
||||
&single,
|
||||
);
|
||||
assert_eq!(
|
||||
0,
|
||||
merges(&tree),
|
||||
"a nullable key column is not what the drop is proved by, so nothing is collected: {tree}"
|
||||
);
|
||||
assert!(
|
||||
matches!(tree.root().expr, NativeExpr::Window { .. }),
|
||||
"the root stays the window: {tree}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_dropping_window_over_several_metrics_is_collected() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// A selector that discovered several metrics binds no single name, so two of its series can be
|
||||
// told apart by the name alone - and dropping it folds them into one label set.
|
||||
let tree = passed_over(
|
||||
window_over(raw_input(0), None, Arc::clone(&out)),
|
||||
&named_scan_tags(),
|
||||
&[None],
|
||||
);
|
||||
assert_eq!(1, merges(&tree), "{tree}");
|
||||
assert!(
|
||||
matches!(tree.root().expr, NativeExpr::Merge { .. }),
|
||||
"the root collects what the window hands out: {tree}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metadata_tag_in_the_binding_fails_closed() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// `__type__` and `__unit__` go with the name, and a scan that carries one of them as a tag can
|
||||
// hold two series that differ only there. A fixed metric name proves nothing about them, so the
|
||||
// drop stays collected.
|
||||
for metadata in ["__type__", "__unit__"] {
|
||||
let scan = vec![tags(&["host", "__name__", metadata])];
|
||||
let tree = passed_over(
|
||||
window_over(raw_input(0), None, Arc::clone(&out)),
|
||||
&scan,
|
||||
&[Some(Arc::from("some_metric"))],
|
||||
);
|
||||
assert_eq!(1, merges(&tree), "{metadata}: {tree}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The name a name-dropping kernel removes is the one every series of a single-metric scan shares,
|
||||
/// and nothing else it drops tells two of them apart, so a math map, a histogram map, a
|
||||
/// parameterized math kernel and an arithmetic scalar broadcast handed such a source keep every
|
||||
/// partition.
|
||||
///
|
||||
/// A key column that can spell `NULL` in one series and `''` in another is not part of that proof
|
||||
/// (see [`duplicates_canonical_labels`]), so these fixtures answer the same over a metric-engine
|
||||
/// table, whose tag columns are all nullable, as they do over the scans stated here.
|
||||
#[test]
|
||||
fn a_name_dropping_kernel_over_one_metric_keeps_its_partitions() {
|
||||
let out = grid(0, 1000, 2);
|
||||
@@ -981,16 +804,12 @@ fn a_name_dropping_kernel_over_one_metric_keeps_its_partitions() {
|
||||
"`{name}` hands over one series per label set already: {tree}"
|
||||
);
|
||||
};
|
||||
// A math map.
|
||||
kept("abs", abs_map(selected(&out)));
|
||||
// A histogram map.
|
||||
kept("histogram_count", histogram_count(selected(&out)));
|
||||
// A parameterized math kernel.
|
||||
kept(
|
||||
"clamp_min",
|
||||
clamp_min(selected(&out), scalar(0.0, Arc::clone(&out))),
|
||||
);
|
||||
// An arithmetic scalar broadcast, `x * 2`.
|
||||
kept(
|
||||
"x * 2",
|
||||
binary_over(
|
||||
@@ -1001,12 +820,6 @@ fn a_name_dropping_kernel_over_one_metric_keeps_its_partitions() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The same kernels over a binding that carries `__type__` or `__unit__` as a tag are collected at
|
||||
/// the root.
|
||||
///
|
||||
/// Those two go with the name when a kernel drops it, so two series that differ only there meet once
|
||||
/// the drop removes them, whatever the scan's key columns read otherwise: this is the labels half
|
||||
/// failing, not the key half. It is asked before the key columns are.
|
||||
#[test]
|
||||
fn a_name_dropping_kernel_over_a_metadata_tag_is_collected() {
|
||||
let out = grid(0, 1000, 2);
|
||||
@@ -1040,27 +853,16 @@ fn a_name_dropping_kernel_over_a_metadata_tag_is_collected() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A name-dropping kernel above another one asks for no collection of its own, and neither does a
|
||||
/// broadcast above a window that drops the name: `rate(x[5m]) * 2` plans one window and one
|
||||
/// broadcast, and `abs(abs(rate(x[5m])))` one window and two maps, with no merge in either.
|
||||
///
|
||||
/// A key column that can hold `NULL` in one series and `''` in the other is not what the drop is
|
||||
/// proved by (see [`duplicates_canonical_labels`]), so this is the answer over a metric-engine table
|
||||
/// too. What a chain of drops is collected for is a collision the labels do not prove - one
|
||||
/// collection per collision, and none per kernel that repeats a drop nothing can fold: see
|
||||
/// [`a_merge_below_a_drop_does_not_answer_the_metadata_labels`].
|
||||
/// `rate(x[5m]) * 2` and `abs(abs(rate(x[5m])))` over one metric plan no merge.
|
||||
#[test]
|
||||
fn a_drop_above_a_name_dropping_kernel_needs_no_collection() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// What the planner states for a scan of one metric: its tag columns and the name the binding
|
||||
// gives every series it hands over.
|
||||
let scan = [tags(&["host", "zone", "__name__"])];
|
||||
let single = [Some(Arc::<str>::from("some_metric"))];
|
||||
let rate = || window_over(raw_input(0), None, Arc::clone(&out));
|
||||
// `rate(x[5m]) * 2`: the broadcast drops the metadata labels the window dropped already.
|
||||
// `rate(x[5m]) * 2`.
|
||||
let broadcast = binary_over(rate(), scalar(2.0, Arc::clone(&out)), Arc::clone(&out));
|
||||
// `abs(abs(rate(x[5m])))`: two math kernels above the window, neither of which can fold a pair
|
||||
// the window left distinct.
|
||||
// `abs(abs(rate(x[5m])))`.
|
||||
let nested = abs_map(abs_map(rate()));
|
||||
for (query, root) in [
|
||||
("rate(x[5m]) * 2", broadcast),
|
||||
@@ -1071,19 +873,12 @@ fn a_drop_above_a_name_dropping_kernel_needs_no_collection() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A merge below a drop does not answer the metadata labels: a merge keeps two series that differ in
|
||||
/// `__name__`, `__type__` or `__unit__`, and removing those is exactly what a metadata drop does.
|
||||
/// Two metrics whose ordinary labels are equal are therefore still collected above a merge, one
|
||||
/// merge per collision.
|
||||
///
|
||||
/// A selector that discovered several metrics is that shape: each metric's window is collected for
|
||||
/// the name it drops, and the map above the merge is collected again for the name the merge kept.
|
||||
/// A merge keeps series that differ in `__name__`, `__type__` or `__unit__`, so a drop above it is
|
||||
/// still collected when the source may hand over several metrics.
|
||||
#[test]
|
||||
fn a_merge_below_a_drop_does_not_answer_the_metadata_labels() {
|
||||
let out = grid(0, 1000, 2);
|
||||
let scan = [tags(&["host", "__name__"])];
|
||||
// The source may hand over several metrics, which is what leaves the labels half unproved above
|
||||
// the window's merge.
|
||||
let tree = passed_over(
|
||||
abs_map(window_over(raw_input(0), None, Arc::clone(&out))),
|
||||
&scan,
|
||||
@@ -1107,21 +902,12 @@ fn a_merge_below_a_drop_does_not_answer_the_metadata_labels() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A node that only rewrites labels hands its input's identity on, which is what lets a drop above
|
||||
/// it be proved by the labels - except when the rewrite writes the metric name itself.
|
||||
///
|
||||
/// The claim `single_metric_name` makes is that the name the drop removes told none of the node's
|
||||
/// series apart, because every one of them carries the name the scan bound. A rewrite whose
|
||||
/// destination is `__name__` publishes a name of its own, so that claim no longer holds and the drop
|
||||
/// above it is collected; a rewrite of a label the name claim does not read leaves it alone and
|
||||
/// costs nothing.
|
||||
/// A label-only rewrite passes the scan's single name through, unless it writes `__name__`.
|
||||
#[test]
|
||||
fn a_rewrite_of_the_metric_name_leaves_the_drop_unproved() {
|
||||
let out = grid(0, 1000, 2);
|
||||
let single = [Some(Arc::<str>::from("some_metric"))];
|
||||
// `abs(label_replace(x, "dst", "$1", "host", "(.*)"))`: the rewrite writes a label the input
|
||||
// does not carry, so the node still reads the one metric the scan bound and the name the drop
|
||||
// removes told none of its series apart.
|
||||
// `abs(label_replace(x, "dst", "$1", "host", "(.*)"))`.
|
||||
let tree = passed_over(
|
||||
abs_map(rewrite(selected(&out), "dst", "host")),
|
||||
&named_scan_tags(),
|
||||
@@ -1132,9 +918,7 @@ fn a_rewrite_of_the_metric_name_leaves_the_drop_unproved() {
|
||||
merges(&tree),
|
||||
"a rewrite of another label keeps the name the scan bound: {tree}"
|
||||
);
|
||||
// `abs(label_replace(x, "__name__", "$1", "host", "(.*)"))`: the name every series is filed
|
||||
// under is written here, so the rewrite is collected for the names it can fold and the drop above
|
||||
// it is no longer proved - the node below does not hand on the name the scan bound.
|
||||
// `abs(label_replace(x, "__name__", "$1", "host", "(.*)"))`.
|
||||
let tree = passed_over(
|
||||
abs_map(rewrite(selected(&out), "__name__", "host")),
|
||||
&named_scan_tags(),
|
||||
@@ -1147,21 +931,15 @@ fn a_rewrite_of_the_metric_name_leaves_the_drop_unproved() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A `Merge` collects what collided below it, and the drop its consumer performs above it is then
|
||||
/// asked about labels the merge already told apart: a merge keeps the first piece's label set, so
|
||||
/// whether the drop folds two of its series is the labels half alone
|
||||
/// (`a_merge_below_a_drop_does_not_answer_the_metadata_labels`). One collision is one collection,
|
||||
/// rather than one per kernel that repeats the collapse.
|
||||
/// One collision is one collection, not one per kernel that repeats the drop.
|
||||
#[test]
|
||||
fn a_drop_above_a_merge_needs_no_collection_of_its_own() {
|
||||
let out = grid(0, 1000, 2);
|
||||
let single = [Some(Arc::<str>::from("some_metric"))];
|
||||
// `label_replace(x, "host", "$1", "host", "(.*)")`: every host is renamed to one value, so the
|
||||
// rewrite folds the scan's series into one label set and the pass collects it there.
|
||||
// `label_replace(x, "host", "$1", "host", "(.*)")`.
|
||||
let aliasing = || rewrite(selected(&out), "host", "host");
|
||||
|
||||
// `label_replace(x, "host", "$1", "host", "(.*)") * 2`: the broadcast drops the metadata labels
|
||||
// above a merge, which cannot fold two series the merge already told apart.
|
||||
// `label_replace(x, "host", "$1", "host", "(.*)") * 2`.
|
||||
let tree = passed_over(
|
||||
binary_over(aliasing(), scalar(2.0, Arc::clone(&out)), Arc::clone(&out)),
|
||||
&named_scan_tags(),
|
||||
@@ -1179,9 +957,7 @@ fn a_drop_above_a_merge_needs_no_collection_of_its_own() {
|
||||
"the merge sits above the rewrite, and no second one above the match: {tree}"
|
||||
);
|
||||
|
||||
// `abs(abs(rate(label_replace(...)[5m])))`: the rewrite's collision is the one collection, and
|
||||
// neither map above it asks for another - the name each of them drops is the one metric the
|
||||
// scan bound, so it told none of the series the merge holds apart.
|
||||
// `abs(abs(rate(label_replace(...)[5m])))`.
|
||||
let tree = passed_over(
|
||||
abs_map(abs_map(window_over(
|
||||
aliasing(),
|
||||
@@ -1209,23 +985,16 @@ fn a_drop_above_a_merge_needs_no_collection_of_its_own() {
|
||||
matches!(input.expr, NativeExpr::Merge { .. }),
|
||||
"the one merge sits above the rewrite: {tree}"
|
||||
);
|
||||
// A second pass changes nothing: the merge answers one series per label set, and nothing above
|
||||
// it collects again.
|
||||
let twice = merge_label_rewrites(&tree, &named_scan_tags(), &single).unwrap();
|
||||
assert_eq!(1, merges(&twice), "{twice}");
|
||||
assert_eq!(tree.to_string(), twice.to_string());
|
||||
}
|
||||
|
||||
/// A collection below a merge still happens: two series the tree folds into one label set there are
|
||||
/// collected by the merge the pass puts above the rewrite, and the drop above them asks for nothing
|
||||
/// more - the merge is what makes the two arrive as one.
|
||||
#[test]
|
||||
fn a_collision_below_a_merge_is_collected_there() {
|
||||
let out = grid(0, 1000, 2);
|
||||
let single = [Some(Arc::<str>::from("some_metric"))];
|
||||
// `rate(label_replace(x, "host", "$1", "host", "(.*)")[5m])`: every host is renamed to one
|
||||
// value, so the rewrite folds the scan's series into one label set - below the window, whose
|
||||
// `rate` drops the metric name on top of that.
|
||||
// `rate(label_replace(x, "host", "$1", "host", "(.*)")[5m])`.
|
||||
let tree = passed_over(
|
||||
window_over(
|
||||
rewrite(selected(&out), "host", "host"),
|
||||
@@ -1255,20 +1024,12 @@ fn a_collision_below_a_merge_is_collected_there() {
|
||||
assert_eq!(tree.to_string(), twice.to_string());
|
||||
}
|
||||
|
||||
/// A name write is collected even when a merge already holds the series below it: rewriting a name
|
||||
/// can still put two metrics whose ordinary labels are equal under one identity, which is the rule
|
||||
/// the kernels' name-drop proof states.
|
||||
///
|
||||
/// `abs(label_replace(label_replace(x, "__name__", "$1", "host", "(.*)"), "host", "", "", ""))`
|
||||
/// deletes the host the name was derived from, so the name is the only label still telling two
|
||||
/// series apart. `single_metric_name` in `native::plan` is what refuses to carry a written name: it
|
||||
/// would otherwise hand the scan's own name back, and a binding whose key columns always decode a
|
||||
/// value would then make the drop look injective.
|
||||
/// leaves the written name as the only label telling series apart, so `single_metric_name` must not
|
||||
/// hand back the scan's own name.
|
||||
#[test]
|
||||
fn a_written_name_is_not_the_name_the_scan_binds() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// The scan reads one metric, so nothing but the written name is left to tell two of its series
|
||||
// apart.
|
||||
let single = [Some(Arc::<str>::from("some_metric"))];
|
||||
let rewritten = map_ops(
|
||||
map_ops(
|
||||
@@ -1282,9 +1043,6 @@ fn a_written_name_is_not_the_name_the_scan_binds() {
|
||||
))],
|
||||
);
|
||||
let tree = passed_over(abs_map(rewritten), &named_scan_tags(), &single);
|
||||
// The rewrite of the name and the rewrite of the `host` it was derived from are collected in
|
||||
// their own right, and the root merge is the `abs` above them - the node whose answer the
|
||||
// destination check decides.
|
||||
assert_eq!(3, merges(&tree), "{tree}");
|
||||
let NativeExpr::Merge { input: abs_node } = &tree.root().expr else {
|
||||
panic!("the root collects what `abs` hands out: {tree}");
|
||||
@@ -1311,46 +1069,8 @@ fn a_written_name_is_not_the_name_the_scan_binds() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timestamp_is_collected_by_its_consumer() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// `timestamp` reports a sample's own time under the metric name dropped, so a caller that says
|
||||
// nothing about the scan's metric collects its answer at the root as well.
|
||||
let stamped = || NativeNode {
|
||||
expr: NativeExpr::Timestamp {
|
||||
input: Box::new(selected(&out)),
|
||||
},
|
||||
output: evaluated(fields(1), Arc::clone(&out)),
|
||||
};
|
||||
let tree = passed(stamped(), &named_scan_tags());
|
||||
assert_eq!(1, merges(&tree));
|
||||
assert!(
|
||||
matches!(tree.root().expr, NativeExpr::Merge { .. }),
|
||||
"the root collects what the timestamp hands out: {tree}"
|
||||
);
|
||||
|
||||
// The scan reads one metric, so the name it drops told none of its series apart: the timestamp
|
||||
// keeps every partition.
|
||||
let tree = passed_over(
|
||||
stamped(),
|
||||
&named_scan_tags(),
|
||||
&[Some(Arc::from("some_metric"))],
|
||||
);
|
||||
assert_eq!(0, merges(&tree), "{tree}");
|
||||
assert!(
|
||||
matches!(tree.root().expr, NativeExpr::Timestamp { .. }),
|
||||
"the root stays the timestamp: {tree}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The three nodes that drop the metadata labels on their own are judged by the labels: one metric
|
||||
/// name over every series, and no metadata tag among them.
|
||||
///
|
||||
/// A name-dropping window, `timestamp(x)` and a `timestamp` over an evaluated input all drop the
|
||||
/// metadata labels. A source bound to one metric names every series it hands over, so that name told
|
||||
/// none of them apart and the drop is proved; a source that may hand over several is collected, and
|
||||
/// so is one that carries `__type__` or `__unit__` among its tags. A window that keeps the name
|
||||
/// drops nothing and hands its input's identity on.
|
||||
/// A name-dropping window, `timestamp(x)` and `timestamp` over an evaluated input are proved only over
|
||||
/// a single-metric source without `__type__`/`__unit__` tags.
|
||||
#[test]
|
||||
fn a_name_dropping_node_is_proved_by_the_labels_alone() {
|
||||
let out = grid(0, 1000, 2);
|
||||
@@ -1377,8 +1097,6 @@ fn a_name_dropping_node_is_proved_by_the_labels_alone() {
|
||||
"the root stays `{name}`: {tree}"
|
||||
);
|
||||
};
|
||||
// `timestamp(x)` over the scan, `rate(x[5m])`, and `timestamp(rate(x[5m]))` over an evaluated
|
||||
// input: the three nodes that drop the metadata labels themselves.
|
||||
let stamps = || selection(raw_input(0), Arc::clone(&out), InstantValue::Timestamp);
|
||||
let drops = || window_over(raw_input(0), None, Arc::clone(&out));
|
||||
let evaluated_stamps = || NativeNode {
|
||||
@@ -1388,17 +1106,12 @@ fn a_name_dropping_node_is_proved_by_the_labels_alone() {
|
||||
output: evaluated(fields(1), Arc::clone(&out)),
|
||||
};
|
||||
|
||||
// The labels hold: one metric names every series, and no metadata tag is among the tags.
|
||||
kept("timestamp", stamps());
|
||||
kept("rate", drops());
|
||||
kept("timestamp(rate)", evaluated_stamps());
|
||||
// A source that may hand over several metrics is not proved: the name it drops is what tells
|
||||
// two of them apart.
|
||||
collected("timestamp", &named, &[None], stamps());
|
||||
collected("rate", &named, &[None], drops());
|
||||
collected("timestamp(rate)", &named, &[None], evaluated_stamps());
|
||||
// A binding that keys a series by a metadata label is collected: that label goes with the name,
|
||||
// so two series that differ only there meet.
|
||||
for metadata in ["__type__", "__unit__"] {
|
||||
let mut typed = named.clone();
|
||||
typed[0].push(metadata.to_string());
|
||||
@@ -1406,7 +1119,6 @@ fn a_name_dropping_node_is_proved_by_the_labels_alone() {
|
||||
collected("rate", &typed, &single, drops());
|
||||
collected("timestamp(rate)", &typed, &single, evaluated_stamps());
|
||||
}
|
||||
// A window that keeps the name drops nothing, so nothing is asked of it.
|
||||
let tree = passed_over(
|
||||
keeping_window_over(raw_input(0), None, Arc::clone(&out)),
|
||||
&named,
|
||||
@@ -1449,8 +1161,7 @@ fn a_scalar_broadcast_collects_its_own_name_drop() {
|
||||
),
|
||||
&scan_tags(),
|
||||
);
|
||||
// `x + 2` drops the metadata labels, so what it hands out is collected - above the match, not
|
||||
// beside it - and neither operand is collected on its own.
|
||||
// `1 + x`: the merge for the broadcast's name drop sits above it.
|
||||
assert_eq!(1, merges(&tree), "{tree}");
|
||||
let NativeExpr::Merge { input } = &tree.root().expr else {
|
||||
panic!("the root collects what the broadcast hands out: {tree}");
|
||||
@@ -1495,8 +1206,6 @@ fn aggregate_state_is_not_collected() {
|
||||
#[test]
|
||||
fn an_unknown_source_proves_nothing_and_is_collected() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// The caller says nothing about the labels this source reports, so a rewrite over it may well
|
||||
// have written one of them.
|
||||
let tree = passed(rewrite(selected(&out), "dst", "host"), &[]);
|
||||
assert_eq!(1, merges(&tree));
|
||||
}
|
||||
@@ -1520,8 +1229,7 @@ fn the_pass_is_idempotent() {
|
||||
#[test]
|
||||
fn a_later_rewrite_of_an_earlier_destination_is_collected() {
|
||||
let out = grid(0, 1000, 2);
|
||||
// The first rewrite writes `dst`, which is fresh; the second writes the `dst` the first one
|
||||
// created, so it can fold what the first distinguished.
|
||||
// The second rewrite writes the `dst` the first one created.
|
||||
let two = map_ops(
|
||||
selected(&out),
|
||||
vec![
|
||||
|
||||
@@ -14,14 +14,8 @@
|
||||
|
||||
//! One line per node of a [`NativeTree`].
|
||||
//!
|
||||
//! The tree is displayed by recursively visiting its bound expressions. The display is an
|
||||
//! observation of a compiled tree: it runs nothing, and every line reads as the node it is,
|
||||
//! making no claim about whether that node could run.
|
||||
//!
|
||||
//! A node that recorded figures shows them at the end of its own line, and only its own: the walk
|
||||
//! carries the path the runtime registered that node under, so the figures of one node are never
|
||||
//! reported as those of another. A tree whose nodes recorded nothing - one that was never run,
|
||||
//! which is what `EXPLAIN` shows - prints structure only.
|
||||
//! A node's recorded figures are looked up by the path the runtime registered it under and shown
|
||||
//! at the end of its own line. A tree that never ran (`EXPLAIN`) prints structure only.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::{self, Write};
|
||||
@@ -42,31 +36,22 @@ use crate::range_eval::RangeFunction;
|
||||
use crate::select::{MatchOp, SortOrder};
|
||||
use crate::vector_match::{BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp};
|
||||
|
||||
/// The path the runtime registers a tree's root node under.
|
||||
///
|
||||
/// Every other path is this one and the segments of [`child_segments`], so the walk below asks for
|
||||
/// a node's figures by the same key its registration used.
|
||||
/// The path the runtime registers a tree's root node under; descendants append the segments of
|
||||
/// [`child_segments`].
|
||||
pub const ROOT_PATH: &str = "root";
|
||||
|
||||
/// One displayed node: its line, the figures it recorded, and the nodes that consume its output.
|
||||
///
|
||||
/// The same report feeds the tree's text and, through the operator that owns the tree, the
|
||||
/// structure a machine-readable `ANALYZE` publishes, so the two cannot describe different trees.
|
||||
/// One displayed node. It feeds both the text display and the machine-readable `ANALYZE` output.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct NativeNodeReport {
|
||||
/// The node's line without figures, as `<kind>: <what it computes>`.
|
||||
pub line: String,
|
||||
/// The figures this node recorded, in [`crate::native::metrics::NodeMetric::ALL`] order.
|
||||
pub metrics: Vec<(String, usize)>,
|
||||
/// The nodes that consume this one's output, in the order the runtime feeds them.
|
||||
/// The nodes this one reads, in child order.
|
||||
pub children: Vec<NativeNodeReport>,
|
||||
}
|
||||
|
||||
impl From<NativeNodeReport> for NativeTreeMetrics {
|
||||
/// The same nodes, as the plain data a machine-readable `ANALYZE` publishes.
|
||||
///
|
||||
/// The text and that record are built from one report, so a reader of either sees the same
|
||||
/// nodes with the same figures.
|
||||
fn from(report: NativeNodeReport) -> Self {
|
||||
Self {
|
||||
line: report.line,
|
||||
@@ -87,7 +72,6 @@ fn grid_name(grid: &EvalGrid) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// A label list in the order it was bound.
|
||||
fn label_list(labels: &[Arc<str>]) -> String {
|
||||
labels
|
||||
.iter()
|
||||
@@ -98,8 +82,6 @@ fn label_list(labels: &[Arc<str>]) -> String {
|
||||
|
||||
/// The ordering an input guarantees, when it is weaker than the scan's default.
|
||||
fn ordering(ordering: SeriesOrdering) -> &'static str {
|
||||
// `KeyThenTime` is what a scan that orders anything at all provides, so it is the
|
||||
// uninteresting case; a weaker guarantee is what a consumer has to know about.
|
||||
match ordering {
|
||||
SeriesOrdering::KeyThenTime => "",
|
||||
SeriesOrdering::Contiguous => ", contiguous",
|
||||
@@ -218,8 +200,7 @@ fn describe(node: &NativeNode) -> String {
|
||||
}
|
||||
},
|
||||
NativeExpr::Aggregate { op, .. } => describe_aggregate(op, &aggregate_kind(op.kind)),
|
||||
// The `φ` this fold reads is not on its binding, so the line leaves the constant out and
|
||||
// says where the value comes from instead.
|
||||
// The bound `φ` is unused, so it is left out.
|
||||
NativeExpr::ParameterizedAggregate { op, .. } => format!(
|
||||
"{}, parameter per point",
|
||||
describe_aggregate(op, aggregate_name(op.kind))
|
||||
@@ -291,10 +272,7 @@ fn fill(values: FillValues) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// An aggregate: what it folds, how its groups are identified and which stage it reports.
|
||||
///
|
||||
/// `folded` is how the kind is named: with the constant it bound, for a fold that reads one, and
|
||||
/// without it for a fold whose argument is read per point.
|
||||
/// `folded` names the aggregate, with or without its bound argument.
|
||||
fn describe_aggregate(op: &BoundAggregate, folded: &str) -> String {
|
||||
format!(
|
||||
"{} {} [{}] {}",
|
||||
@@ -501,11 +479,8 @@ fn kind(expr: &NativeExpr) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The child nodes of `node` and the path segment each is registered under, in child order.
|
||||
///
|
||||
/// The segments are the ones the runtime registers, not the names the bound tree happens to give
|
||||
/// the operands: `info` binds its operands as `base` and `info`, while the runtime registers them
|
||||
/// as the kernel's `left` and `right`, so the display asks for the figures where they were put.
|
||||
/// The child nodes of `node` and the path segment the runtime registers each under. The runtime
|
||||
/// registers `info`'s `base` and `info` as `left` and `right`.
|
||||
fn child_segments(node: &NativeNode) -> Vec<(&NativeNode, Cow<'static, str>)> {
|
||||
let mut children = Vec::new();
|
||||
fn child<'a>(
|
||||
@@ -579,10 +554,7 @@ fn report_node(node: &NativeNode, path: &str, metrics: &NodeMetricsSnapshot) ->
|
||||
}
|
||||
|
||||
impl NativeTree {
|
||||
/// This tree, one report per node, carrying the figures each node recorded.
|
||||
///
|
||||
/// A snapshot with no entries reports the tree's structure only, which is what a plan that was
|
||||
/// never executed has to show.
|
||||
/// This tree, one report per node, with the figures `metrics` holds for each.
|
||||
pub fn report(&self, metrics: &NodeMetricsSnapshot) -> NativeNodeReport {
|
||||
report_node(self.root(), ROOT_PATH, metrics)
|
||||
}
|
||||
@@ -596,8 +568,8 @@ impl NativeTree {
|
||||
}
|
||||
}
|
||||
|
||||
/// A tree as it appears below the operator line: one node per line, two spaces per depth, and each
|
||||
/// node's figures on its own line.
|
||||
/// A tree as it appears below the operator line: one node per line, two spaces per depth, each
|
||||
/// node's figures at the end of its line.
|
||||
pub struct NativeTreeDisplay<'a> {
|
||||
tree: &'a NativeTree,
|
||||
metrics: &'a NodeMetricsSnapshot,
|
||||
@@ -605,9 +577,7 @@ pub struct NativeTreeDisplay<'a> {
|
||||
|
||||
impl fmt::Display for NativeTreeDisplay<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// The root starts at column zero: the block the caller brackets the tree in carries the
|
||||
// indentation, so each line here is depth-relative to that block rather than to the
|
||||
// caller's own place in the plan.
|
||||
// The caller's enclosing block carries the indentation.
|
||||
write_report(f, &self.tree.report(self.metrics), 0)
|
||||
}
|
||||
}
|
||||
@@ -635,9 +605,7 @@ fn write_report(
|
||||
}
|
||||
|
||||
impl fmt::Display for NativeTree {
|
||||
/// One line per node, outermost first, from column zero with two spaces per depth and without
|
||||
/// figures: this is the tree's own shape, which is what a display that holds no metrics
|
||||
/// snapshot can show.
|
||||
/// One line per node, two spaces per depth, without figures.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write_report(f, &self.report(&NodeMetricsSnapshot::default()), 0)
|
||||
}
|
||||
|
||||
@@ -47,7 +47,6 @@ fn fields() -> Arc<[FieldSpec]> {
|
||||
}])
|
||||
}
|
||||
|
||||
/// The samples a node produces on `grid`.
|
||||
fn evaluated(grid: Arc<EvalGrid>) -> NativeType {
|
||||
NativeType::Samples(Arc::new(SeriesSchema {
|
||||
fields: fields(),
|
||||
@@ -55,11 +54,7 @@ fn evaluated(grid: Arc<EvalGrid>) -> NativeType {
|
||||
}))
|
||||
}
|
||||
|
||||
/// An unqualified scan over raw samples, which is what a compiled query starts from.
|
||||
fn raw_input() -> NativeNode {
|
||||
// One allocation shared by the binding and the output: `validate` checks allocation identity.
|
||||
// The fields are the ones a window over this input reports, because a window keeps its input's
|
||||
// layout and `validate` rejects a node that declares a different count.
|
||||
let output = NativeType::Samples(Arc::new(SeriesSchema {
|
||||
fields: fields(),
|
||||
eval_grid: None,
|
||||
@@ -114,14 +109,10 @@ fn map(inner: NativeNode, ops: Vec<MathOp>) -> NativeNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// The expected display of a tree, one string per line, so a change in wording, order or
|
||||
/// indentation fails the test rather than passing as a substring.
|
||||
fn shown(lines: &[&str]) -> String {
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// A tree is plan lines and nothing else: no header above them and no word beside a node, so every
|
||||
/// line reads as the operator it is, one level in from the operator line it is drawn under.
|
||||
#[test]
|
||||
fn a_tree_is_plan_lines_only() {
|
||||
let tree = NativeTree::try_new(raw_input()).unwrap();
|
||||
@@ -145,31 +136,6 @@ fn a_tree_is_plan_lines_only() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A compiled tree is one line per node, outermost first: the window is the root and the scan it
|
||||
/// folds is shown beneath it.
|
||||
#[test]
|
||||
fn a_window_over_raw_samples_is_shown_once_per_node() {
|
||||
let tree = NativeTree::try_new(window_over(
|
||||
raw_input(),
|
||||
RangeFunction::Rate,
|
||||
300_000,
|
||||
0,
|
||||
None,
|
||||
grid(0, 60_000, 4),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
tree.to_string(),
|
||||
shown(&[
|
||||
"Window: rate [300000ms] offset 0 anchor - on grid 0/60000x4",
|
||||
" Input: raw samples source=0",
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/// A map nests one level deeper than the window it reads, and lists its operations in the order
|
||||
/// they are applied.
|
||||
#[test]
|
||||
fn a_map_nests_below_the_window_it_maps() {
|
||||
let tree = NativeTree::try_new(map(
|
||||
@@ -195,8 +161,6 @@ fn a_map_nests_below_the_window_it_maps() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A parameterised window names the constant it was bound to, and an anchored one names its
|
||||
/// anchor instead of printing the absent case.
|
||||
#[test]
|
||||
fn a_window_names_its_constant_argument_and_its_anchor() {
|
||||
let tree = NativeTree::try_new(window_over(
|
||||
@@ -218,8 +182,6 @@ fn a_window_names_its_constant_argument_and_its_anchor() {
|
||||
);
|
||||
}
|
||||
|
||||
/// An input says whether its samples are raw or already evaluated, and reports the ordering it
|
||||
/// guarantees when that is weaker than the scan default.
|
||||
#[test]
|
||||
fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() {
|
||||
let contiguous = NativeType::Samples(Arc::new(SeriesSchema {
|
||||
@@ -259,8 +221,6 @@ fn an_input_reports_whether_it_is_raw_and_what_ordering_it_guarantees() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A leaf kind renders what it holds, whether or not anything could run it: the line names the
|
||||
/// node it is and makes no claim about executability.
|
||||
#[test]
|
||||
fn a_scalar_and_an_instant_line_show_what_they_hold() {
|
||||
let out = grid(0, 60_000, 4);
|
||||
@@ -294,8 +254,6 @@ fn a_scalar_and_an_instant_line_show_what_they_hold() {
|
||||
);
|
||||
}
|
||||
|
||||
/// An aggregate and a binary operation name the binding they were compiled with, which is what
|
||||
/// makes the line worth reading.
|
||||
#[test]
|
||||
fn an_aggregate_and_a_binary_name_their_binding() {
|
||||
let out = grid(0, 60_000, 4);
|
||||
@@ -328,8 +286,7 @@ fn an_aggregate_and_a_binary_name_their_binding() {
|
||||
])
|
||||
);
|
||||
|
||||
// A scalar broadcast, which is the one binary shape whose matching rules are never consulted:
|
||||
// the display still prints them, because the binding is what the compiler decided.
|
||||
// A broadcast never consults its matching, but the display still prints the binding.
|
||||
let binary = NativeNode {
|
||||
expr: NativeExpr::Binary {
|
||||
left: Box::new(NativeNode {
|
||||
@@ -381,9 +338,8 @@ fn an_aggregate_and_a_binary_name_their_binding() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A set operation names its operator and its matching labels: the logical plan compares fused
|
||||
/// nodes by this rendering, so `and`, `or` and `unless`, and `on` and `ignoring`, must not read
|
||||
/// alike.
|
||||
/// The logical plan compares fused nodes by this rendering, so set operators and `on`/`ignoring`
|
||||
/// must not read alike.
|
||||
#[test]
|
||||
fn a_set_operation_names_its_operator_and_labels() {
|
||||
let out = grid(0, 60_000, 4);
|
||||
@@ -423,11 +379,6 @@ fn a_set_operation_names_its_operator_and_labels() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A `without` grouping reads as `without [...]`, not as `by [...]`.
|
||||
///
|
||||
/// The two are different queries over the same label list: `by(job)` keeps `job` and drops the
|
||||
/// rest, `without(job)` drops `job` and keeps the rest. A rendering that spelled both `by` would
|
||||
/// show two different queries as one.
|
||||
#[test]
|
||||
fn a_without_grouping_does_not_read_as_by() {
|
||||
let out = grid(0, 60_000, 4);
|
||||
@@ -461,7 +412,6 @@ fn a_without_grouping_does_not_read_as_by() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A vector operation names its operator, constant and grouping.
|
||||
#[test]
|
||||
fn instant_at_and_timestamp_are_displayed() {
|
||||
let out = grid(0, 60_000, 4);
|
||||
@@ -555,7 +505,6 @@ fn a_vector_operation_names_its_binding() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A window read with a range modifier names it and the lookback it reads around the window.
|
||||
#[test]
|
||||
fn a_modified_window_names_its_modifier() {
|
||||
let out = grid(0, 60_000, 4);
|
||||
@@ -582,8 +531,6 @@ fn a_modified_window_names_its_modifier() {
|
||||
);
|
||||
}
|
||||
|
||||
/// An aggregate over a window over a scan, which is the shape whose three nodes each record
|
||||
/// something different.
|
||||
fn aggregate_over_window(out: Arc<EvalGrid>) -> NativeTree {
|
||||
NativeTree::try_new(NativeNode {
|
||||
expr: NativeExpr::Aggregate {
|
||||
@@ -607,8 +554,6 @@ fn aggregate_over_window(out: Arc<EvalGrid>) -> NativeTree {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A node's figures end its own line, and only its own: the walk asks for them by the path the
|
||||
/// runtime registered that node under, so one node never reports another's work.
|
||||
#[test]
|
||||
fn each_node_shows_only_the_figures_it_recorded() {
|
||||
let tree = aggregate_over_window(grid(0, 60_000, 4));
|
||||
@@ -636,9 +581,6 @@ fn each_node_shows_only_the_figures_it_recorded() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A tree whose nodes recorded nothing - one that was never run, which is what `EXPLAIN` shows -
|
||||
/// is the same lines without figures. No flag says so: an empty snapshot is what an unexecuted
|
||||
/// registration leaves.
|
||||
#[test]
|
||||
fn a_tree_that_recorded_nothing_shows_no_figures() {
|
||||
let tree = aggregate_over_window(grid(0, 60_000, 4));
|
||||
@@ -651,9 +593,7 @@ fn a_tree_that_recorded_nothing_shows_no_figures() {
|
||||
assert!(!tree.to_string().contains("metrics="));
|
||||
}
|
||||
|
||||
/// A node's figures are read from the path the runtime registers, not from the name the bound tree
|
||||
/// gives the operand: `info` binds its operands as `base` and `info`, and the runtime registers them
|
||||
/// as the kernel's `left` and `right`.
|
||||
/// `info`'s `base` and `info` are registered as `left` and `right`.
|
||||
#[test]
|
||||
fn every_child_is_read_from_the_path_the_runtime_registers() {
|
||||
let out = grid(0, 60_000, 4);
|
||||
|
||||
+362
-1119
File diff suppressed because it is too large
Load Diff
+382
-2522
File diff suppressed because it is too large
Load Diff
@@ -14,23 +14,12 @@
|
||||
|
||||
//! Per-node metric handles for native PromQL execution and their DataFusion registration.
|
||||
//!
|
||||
//! Node metrics retain no names or tree topology: [`NodeMetrics::register`] names the handles for
|
||||
//! one registration, and the set holds them from there. What outlives an execution is therefore its
|
||||
//! counters and gauges, not the nodes that recorded them.
|
||||
//!
|
||||
//! The name carries the node's position in the runtime tree: the whole native tree registers into
|
||||
//! the one [`ExecutionPlanMetricsSet`] the enclosing physical operator (`FusedSeriesExec`) owns, and
|
||||
//! the reader aggregates by name, so two nodes of a kind sharing
|
||||
//! a name would be summed into a single figure. What a consumer can rely on is the grammar
|
||||
//! `native.<path>.<metric>` with the suffixes of [`NodeMetric::ALL`]: splitting off the final
|
||||
//! component leaves the metric, and the path before it keys the node within that operator. That key
|
||||
//! is promised only inside the topology that produced it:
|
||||
//!
|
||||
//! - the path names a node of one runtime topology;
|
||||
//! - queries, plan rewrites, and versions move it, so it is neither a persisted nor a public
|
||||
//! identifier;
|
||||
//! - `peak_reserved_bytes` alone carries `p<partition>`, because the reader sums gauges by name and
|
||||
//! a sum of peaks is not a peak.
|
||||
//! The whole native tree registers into the one [`ExecutionPlanMetricsSet`] of its enclosing
|
||||
//! operator (`FusedSeriesExec`), and readers aggregate by name, so each name carries the node's
|
||||
//! path in the runtime tree: `native.<path>.<metric>`, with a metric from [`NodeMetric::ALL`]. The
|
||||
//! path is valid only within the topology that produced it; it is not a persisted or public
|
||||
//! identifier. `peak_reserved_bytes` alone is named `native.p<partition>.<path>.<metric>`, because
|
||||
//! a sum of peaks is not a peak.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -42,11 +31,9 @@ use datafusion::physical_plan::metrics::{
|
||||
/// The reserved first segment of every native metric name.
|
||||
const NATIVE_PREFIX: &str = "native";
|
||||
|
||||
/// The metric names one node reports.
|
||||
///
|
||||
/// [`Self::ALL`] is the list a reader should treat as complete: [`NodeMetrics::register`] names each
|
||||
/// handle itself, and `registered_metrics_are_exactly_the_declared_set` fails when the two sides
|
||||
/// drift apart.
|
||||
/// The metric names one node reports. [`Self::ALL`] is complete:
|
||||
/// `fresh_exports_register_exactly_the_declared_metrics_without_growth` checks it against
|
||||
/// [`NodeMetrics::register`].
|
||||
pub struct NodeMetric;
|
||||
|
||||
impl NodeMetric {
|
||||
@@ -90,27 +77,19 @@ impl NodeMetric {
|
||||
];
|
||||
}
|
||||
|
||||
/// The figures every node of one execution left, keyed by the path it was registered under.
|
||||
///
|
||||
/// A path is the one [`NodeMetrics::register`] was called with (`root`, `root.left`, ...), which is
|
||||
/// exactly what the runtime builds while it compiles the tree: a reader that walks the *same* tree
|
||||
/// reaches the same path for the same node, so a figure is found rather than guessed.
|
||||
///
|
||||
/// Partitions are combined here because a node is registered once per partition: counts and times
|
||||
/// add up, and `peak_reserved_bytes` — the one figure whose name carries its partition, because a
|
||||
/// sum of peaks is not a peak — is the highest of them.
|
||||
/// The figures every node of one execution recorded, keyed by the path passed to
|
||||
/// [`NodeMetrics::register`] (`root`, `root.left`, ...). A node's partitions are combined: counts
|
||||
/// and times add up, and `peak_reserved_bytes` takes the highest.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct NodeMetricsSnapshot {
|
||||
nodes: HashMap<String, Vec<(String, usize)>>,
|
||||
}
|
||||
|
||||
impl NodeMetricsSnapshot {
|
||||
/// Reads every native node figure in `set`.
|
||||
/// Reads every native node figure in `set`, ignoring other metrics. A plan that never ran
|
||||
/// yields an empty snapshot.
|
||||
///
|
||||
/// `set` may hold other metrics, and holds nothing at all before an execution: a snapshot of a
|
||||
/// plan that never ran is empty, which is how a plain `EXPLAIN` shows a tree without figures.
|
||||
///
|
||||
/// The partitions of one node are combined here rather than by
|
||||
/// Partitions are combined here rather than by
|
||||
/// [`MetricsSet::aggregate_by_name`](datafusion::physical_plan::metrics::MetricsSet::aggregate_by_name),
|
||||
/// which adds at least one nanosecond to every time it touches: a node whose timer never ran
|
||||
/// would then report time it did not spend.
|
||||
@@ -123,8 +102,7 @@ impl NodeMetricsSnapshot {
|
||||
let value = metric.value().as_usize();
|
||||
let figures = nodes.entry(path.to_string()).or_default();
|
||||
match figures.iter_mut().find(|(figure, _)| figure == name) {
|
||||
// A peak is per partition because partitions peak at different moments: the node's
|
||||
// peak is the highest of theirs, never their sum.
|
||||
// Partitions peak at different moments, so the node's peak is the max, not the sum.
|
||||
Some((_, accumulated)) if name == NodeMetric::PEAK_RESERVED_BYTES => {
|
||||
*accumulated = (*accumulated).max(value)
|
||||
}
|
||||
@@ -138,11 +116,8 @@ impl NodeMetricsSnapshot {
|
||||
Self { nodes }
|
||||
}
|
||||
|
||||
/// What this node recorded, as `name: value`, dropping the figures that are zero.
|
||||
///
|
||||
/// A node registers every figure it may record, so a node that did one thing would otherwise
|
||||
/// report ten things it did not: the tree would stop reading as a tree. A node that recorded
|
||||
/// nothing therefore reports nothing, the same way one that never ran does.
|
||||
/// What this node recorded, dropping zero figures: a node registers every metric, so most are
|
||||
/// zero on any one node.
|
||||
pub fn described(&self, path: &str) -> Vec<(String, usize)> {
|
||||
self.of(path)
|
||||
.iter()
|
||||
@@ -158,12 +133,8 @@ impl NodeMetricsSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits a registered metric name into the node path and the figure it reports.
|
||||
///
|
||||
/// A name is `native.<path>.<metric>`, and `native.p<partition>.<path>.<metric>` for a figure that
|
||||
/// is registered per partition. The partition belongs to that registration rather than to the
|
||||
/// node, so it is dropped here and its values are combined by [`NodeMetricsSnapshot::read`]. A name
|
||||
/// that is not one of this module's is not a node figure, and is left to whoever else reads `set`.
|
||||
/// Splits `native.<path>.<metric>` or `native.p<partition>.<path>.<metric>` into path and metric,
|
||||
/// dropping the partition. Returns `None` for any other name.
|
||||
fn split_name(name: &str) -> Option<(&str, &str)> {
|
||||
let rest = name.strip_prefix(NATIVE_PREFIX)?.strip_prefix('.')?;
|
||||
let rest = match rest.strip_prefix('p').and_then(|rest| rest.split_once('.')) {
|
||||
@@ -178,8 +149,7 @@ fn split_name(name: &str) -> Option<(&str, &str)> {
|
||||
NodeMetric::ALL.contains(&metric).then_some((path, metric))
|
||||
}
|
||||
|
||||
/// Where `metric` sits in the declared order, so a node's figures read the same on every node and
|
||||
/// on every run.
|
||||
/// Where `metric` sits in [`NodeMetric::ALL`], so figures print in a stable order.
|
||||
fn node_metric_order(metric: &str) -> usize {
|
||||
NodeMetric::ALL
|
||||
.iter()
|
||||
@@ -187,10 +157,7 @@ fn node_metric_order(metric: &str) -> usize {
|
||||
.unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// The metric handles one node updates as it runs.
|
||||
///
|
||||
/// The node writes these directly; it never looks a metric up by name, and it never formats a path
|
||||
/// on the hot path.
|
||||
/// The metric handles one node in one partition updates as it runs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NodeMetrics {
|
||||
input_batches: Count,
|
||||
@@ -236,20 +203,13 @@ fn named(name: &str, metric: &str) -> String {
|
||||
}
|
||||
|
||||
/// The full metric name for `metric` in `partition` of the node called `name`.
|
||||
///
|
||||
/// A figure that must not be merged across partitions needs the partition in its name: the
|
||||
/// collector aggregates by name first, and a sum of peaks is not a peak.
|
||||
fn partitioned(name: &str, metric: &str, partition: usize) -> String {
|
||||
format!("{NATIVE_PREFIX}.p{partition}.{name}.{metric}")
|
||||
}
|
||||
|
||||
impl NodeMetrics {
|
||||
/// Registers this node's handles under `name` into `set`.
|
||||
///
|
||||
/// A caller registers once per execution, before that execution starts, so what `set` holds
|
||||
/// afterwards follows what this node records as it runs. The name belongs to that registration
|
||||
/// and is not retained here. `partition` is part of the DataFusion registration, and the peak
|
||||
/// name includes it because peaks must not be summed across partitions.
|
||||
/// Registers this node's handles under `name` into `set`. Call once per execution, before it
|
||||
/// starts; `set` then follows what the node records.
|
||||
pub fn register(&self, name: &str, set: &ExecutionPlanMetricsSet, partition: usize) {
|
||||
fn count(set: &ExecutionPlanMetricsSet, partition: usize, name: String, count: &Count) {
|
||||
MetricBuilder::new(set)
|
||||
@@ -310,12 +270,7 @@ impl NodeMetrics {
|
||||
named(name, NodeMetric::CURRENT_RESERVED_BYTES),
|
||||
&self.current_reserved_bytes,
|
||||
);
|
||||
// The peak is the one figure named per partition. The collector groups by name and sums
|
||||
// gauges, and a sum of two peaks is neither peak: partitions peak at different moments.
|
||||
// Summing the other gauges and counts stays meaningful — the memory held now and the
|
||||
// samples seen add up across partitions. `groups` does not: a `Partial` aggregate sees the
|
||||
// same group in every partition it reaches, so the sum is per-partition entries, not
|
||||
// distinct groups.
|
||||
// The collector sums gauges by name; the peak alone must not be summed.
|
||||
gauge(
|
||||
set,
|
||||
partition,
|
||||
@@ -364,26 +319,21 @@ impl NodeMetrics {
|
||||
self.completed_series.add(series);
|
||||
}
|
||||
|
||||
/// Records that this node now reserves `bytes`.
|
||||
///
|
||||
/// The peak is a high-water mark of this node in this partition, never a sum of the peaks of
|
||||
/// different nodes: those peaks can happen at different times.
|
||||
/// Records that this node now reserves `bytes`, raising its peak if higher.
|
||||
pub fn record_reserved_bytes(&self, bytes: usize) {
|
||||
self.current_reserved_bytes.set(bytes);
|
||||
// A high-water mark, not a sum: two nodes peak at different moments.
|
||||
self.peak_reserved_bytes.set_max(bytes);
|
||||
}
|
||||
|
||||
/// Records the size of the grouping and state this node holds.
|
||||
/// Records the size of the grouping and state this node holds. No production node calls this
|
||||
/// yet, so `groups` and `state_entries` report zero.
|
||||
pub fn record_state(&self, groups: usize, entries: usize) {
|
||||
self.groups.set(groups);
|
||||
self.state_entries.set(entries);
|
||||
}
|
||||
|
||||
/// Starts timing this node's own work.
|
||||
///
|
||||
/// The returned timer must be dropped before the node polls its input: a node's self time
|
||||
/// excludes the work its inputs do.
|
||||
/// Starts timing this node's own work. Drop the guard before polling an input: self time
|
||||
/// excludes the inputs' work.
|
||||
pub fn timer(&self) -> datafusion::physical_plan::metrics::ScopedTimerGuard<'_> {
|
||||
self.self_compute_time.timer()
|
||||
}
|
||||
@@ -450,21 +400,12 @@ mod tests {
|
||||
assert_eq!(counter("native.root.output_values"), Some(11));
|
||||
}
|
||||
|
||||
/// Each partition's peak is exported under a name of its own, from handles of its own.
|
||||
///
|
||||
/// A [`NodeMetrics`] belongs to one node in one partition, which is the shape one runtime tree
|
||||
/// per partition gives. Two partitions are therefore two sets of handles that grow
|
||||
/// independently: what the second one records never reaches the figure the first one exported,
|
||||
/// and the peak of each is reported under the partition it belongs to rather than summed under
|
||||
/// one shared name.
|
||||
#[test]
|
||||
fn peak_exports_are_distinct_per_partition() {
|
||||
let first_metrics = NodeMetrics::default();
|
||||
first_metrics.record_reserved_bytes(1024);
|
||||
let first = ExecutionPlanMetricsSet::new();
|
||||
first_metrics.register("root", &first, 0);
|
||||
// The second partition's node is another set of handles, recorded and exported later: the
|
||||
// first export above must not follow it.
|
||||
let second_metrics = NodeMetrics::default();
|
||||
second_metrics.record_reserved_bytes(2048);
|
||||
let second = ExecutionPlanMetricsSet::new();
|
||||
@@ -489,9 +430,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A node is registered once per partition, so one node's figures are the sum of its
|
||||
/// partitions' - except the peak, which is the highest one, because partitions peak at
|
||||
/// different moments.
|
||||
#[test]
|
||||
fn a_node_reports_one_set_of_figures_across_its_partitions() {
|
||||
let set = ExecutionPlanMetricsSet::new();
|
||||
@@ -515,8 +453,6 @@ mod tests {
|
||||
assert_eq!(figure(NodeMetric::PEAK_RESERVED_BYTES), 4096);
|
||||
}
|
||||
|
||||
/// The path is what the registration named, and a partition segment is not part of it: the two
|
||||
/// partitions above file under one node rather than under `p0.root` and `p1.root`.
|
||||
#[test]
|
||||
fn a_partition_belongs_to_the_registration_and_not_to_the_path() {
|
||||
let set = ExecutionPlanMetricsSet::new();
|
||||
@@ -528,7 +464,6 @@ mod tests {
|
||||
assert!(snapshot.of("p7.root.left").is_empty());
|
||||
}
|
||||
|
||||
/// A metric this module did not name is not a node figure, so it is not filed under a node.
|
||||
#[test]
|
||||
fn a_name_outside_the_grammar_is_not_a_node_figure() {
|
||||
let set = ExecutionPlanMetricsSet::new();
|
||||
|
||||
@@ -14,18 +14,11 @@
|
||||
|
||||
//! The native PromQL evaluation model.
|
||||
//!
|
||||
//! A query compiles to a [`plan::NativeTree`]: nodes whose operations, fields and grids are already
|
||||
//! bound. Nodes hand each other [`batch::EvaluatedChunk`]s as ordinary Rust values, so no row batch
|
||||
//! is materialised between them. [`metrics`] names each node after its position in that tree.
|
||||
//!
|
||||
//! Three properties keep this apart from recognising a query shape in a finished physical plan:
|
||||
//!
|
||||
//! - Legality is a type and data-dependency question ([`plan::NativeNode::validate`]), so a new
|
||||
//! combination of supported operations is an ordinary tree, not another matcher.
|
||||
//! - A window binds its input and output grids separately, so a subquery's inner grid is consumed
|
||||
//! as it is instead of being resampled onto the outer grid.
|
||||
//! - A series closes exactly once, on the chunk that says so, so a consumer can tell "nothing more
|
||||
//! here" from "no more input".
|
||||
//! A query compiles to a [`plan::NativeTree`] whose nodes have their operations, fields and grids
|
||||
//! already bound; legality is checked by [`plan::NativeNode::validate`]. Nodes hand each other
|
||||
//! [`batch::EvaluatedChunk`]s as Rust values, and a window binds its input and output grids
|
||||
//! separately, so a subquery's inner grid is consumed without resampling onto the outer grid.
|
||||
//! [`metrics`] names each node after its position in the tree.
|
||||
|
||||
mod aggregate;
|
||||
pub mod batch;
|
||||
|
||||
+244
-1052
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -14,15 +14,13 @@
|
||||
|
||||
//! Segmenting a native tree, so each per-series prefix runs where its input is read.
|
||||
//!
|
||||
//! A tree that reads across series answers one partition and gathers whatever it reads. Its
|
||||
//! per-series prefixes do not need that gather, so each is cut out as a [`FusedSeries`] node of its
|
||||
//! own and keeps the partitions it was scanned with: `cut_as_segment` decides what can be cut,
|
||||
//! [`cut_segments`] rewrites the tree into one segment per cut, and [`segment_tree`] builds the
|
||||
//! nodes, recursing into a cut that wraps a whole-vector consumer.
|
||||
//! A tree that reads across series runs in one partition. Its per-series prefixes are cut out as
|
||||
//! [`FusedSeries`] nodes of their own so they keep their scan partitions: `cut_as_segment` decides
|
||||
//! what is cut, [`cut_segments`] rewrites the tree into one segment per cut, and [`segment_tree`]
|
||||
//! builds the nodes.
|
||||
//!
|
||||
//! Everything here reads the bound tree alone. The columns a node publishes are the planner's
|
||||
//! answer, so the builders ask for them through [`OutputTags`], [`FieldNames`] and [`RootSchema`]
|
||||
//! instead of deriving them a second time.
|
||||
//! Output columns are the planner's answer, read through [`OutputTags`], [`FieldNames`] and
|
||||
//! [`RootSchema`].
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -47,47 +45,27 @@ use crate::native::plan::{
|
||||
};
|
||||
use crate::vector_match::Cardinality;
|
||||
|
||||
/// Derives the output tag columns a node publishes, from the tag columns each source declares.
|
||||
///
|
||||
/// The planner that owns the result layout names those columns with its own walk over the tree. A
|
||||
/// segment only reads that answer - it never renames a column - so it asks through this leaf
|
||||
/// rather than deriving the columns a second time.
|
||||
/// The planner's output tag columns for a node, given each source's tag columns.
|
||||
pub type OutputTags = fn(&NativeNode, &[Vec<String>]) -> Option<Vec<String>>;
|
||||
|
||||
/// Derives the value column names a statement's expression gives the compiled `fields`.
|
||||
///
|
||||
/// Like [`OutputTags`], this is the planner's answer: a segment publishes the values its tree
|
||||
/// computes under the names the statement gave them, so the builders ask through this leaf instead
|
||||
/// of publishing the compiler's own field names. The tree alone does not carry the statement's
|
||||
/// expression, which is why the expression text is an input rather than something derived here.
|
||||
/// The planner's value column names for the compiled `fields` of a statement's expression.
|
||||
pub type FieldNames = fn(&str, &[String]) -> Vec<String>;
|
||||
|
||||
/// The row schema a statement root publishes for `promql`, or `None` when its columns cannot be
|
||||
/// named once.
|
||||
///
|
||||
/// Like [`OutputTags`], this is the caller's answer: a segment that publishes rows publishes
|
||||
/// exactly the columns the planner would have published for the same statement.
|
||||
/// The planner's row schema for a statement root over `promql`, or `None` when its columns cannot
|
||||
/// be named once.
|
||||
pub type RootSchema = fn(&str, &NativeTree, &[Vec<String>], &str, FieldKind) -> Option<DFSchemaRef>;
|
||||
|
||||
/// Whether `node` reads samples point-wise, so that one partitioned execution is one answer.
|
||||
///
|
||||
/// A node's output type is not checked here: [`NativeNode::validate`] already refuses a selection,
|
||||
/// a map or a binary operation whose operands are not evaluated vectors, so every branch below is
|
||||
/// one that produces values rather than raw samples.
|
||||
/// Whether `node` evaluates each series on its own, directly over a scan, so one partitioned
|
||||
/// execution is one answer.
|
||||
pub fn pointwise_operand(node: &NativeNode) -> bool {
|
||||
match &node.expr {
|
||||
// A selection reads the raw samples below it; anything else below it is a value computed
|
||||
// from a whole series, not a scan.
|
||||
NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } => {
|
||||
matches!(input.expr, NativeExpr::Input(_))
|
||||
}
|
||||
NativeExpr::Map { input, .. } | NativeExpr::Timestamp { input } => pointwise_operand(input),
|
||||
// A parameter that reads no data has the same value in every execution.
|
||||
NativeExpr::ParameterizedMap {
|
||||
input, parameters, ..
|
||||
} => pointwise_operand(input) && parameters.iter().all(NativeNode::is_data_free),
|
||||
// A scalar that reads no data is broadcast over the vector side's positions. Two vectors
|
||||
// are a match between two series sets, which is the shape this route cannot split.
|
||||
NativeExpr::Binary {
|
||||
left,
|
||||
right,
|
||||
@@ -101,10 +79,6 @@ pub fn pointwise_operand(node: &NativeNode) -> bool {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
// An aggregate folds a group, a vector operation reads the whole vector, and a bare input or
|
||||
// scalar is not a per-series evaluation. A parameterized topk or histogram reads the whole
|
||||
// vector, `scalar()` answers from it, and a per-point `φ` is read beside the fold over the
|
||||
// whole group.
|
||||
NativeExpr::Input(_)
|
||||
| NativeExpr::Scalar(_)
|
||||
| NativeExpr::EvalTime { .. }
|
||||
@@ -146,56 +120,39 @@ fn scan_operand(node: &NativeNode) -> bool {
|
||||
pointwise_operand(node) || independent_scan_pair(node)
|
||||
}
|
||||
|
||||
/// Whether a segment can hand `node`'s values to another segment.
|
||||
///
|
||||
/// A boundary carries an evaluated series frame: values addressed on a grid, under the labels of
|
||||
/// the series they belong to. A scalar is broadcast rather than carried, aggregate state is
|
||||
/// internal, and raw samples are what a scan produces - none of them is a frame, so a subtree
|
||||
/// producing one stays inside the segment that reads it.
|
||||
/// Whether `node` answers an evaluated vector, the only thing a segment boundary carries.
|
||||
fn exportable(node: &NativeNode) -> bool {
|
||||
node.output
|
||||
.samples()
|
||||
.is_some_and(|schema| schema.eval_grid.is_some())
|
||||
}
|
||||
|
||||
/// Whether `node` is a window over an evaluated input - the shape a subquery over anything but a
|
||||
/// bare selection compiles to.
|
||||
/// Whether `node` is a window over an evaluated input (a subquery).
|
||||
fn evaluated_input_window(node: &NativeNode) -> bool {
|
||||
matches!(&node.expr, NativeExpr::Window { op, .. } if op.input_grid.is_some())
|
||||
}
|
||||
|
||||
/// Whether the dist analyzer places a segment over `node` region-locally.
|
||||
/// Whether the dist analyzer places a segment over `node` below the `MergeScan`.
|
||||
///
|
||||
/// A segment is a `FusedSeries` node the analyzer has to move below the `MergeScan` for the physical
|
||||
/// planner to read the scans it names. The `FusedSeries` arm of `Categorizer::check_extension_plan`
|
||||
/// (`src/query/src/dist_plan/commutativity.rs`) is what decides that, from the bound tree alone: a
|
||||
/// root that [`reads_across_series`] is `NonCommutative` unless it is a per-series evaluation or the
|
||||
/// `Partial` half of a split fold. A segment it refuses stays above the merge, where the physical
|
||||
/// planner finds neither a region scan nor an explicit-label frame below it, so the statement fails
|
||||
/// while being planned instead of keeping the plan it had. Segmentation therefore asks that question
|
||||
/// before it cuts, and `cut_as_segment` declines the nodes this refuses.
|
||||
/// Mirrors the tree-shape check of the `FusedSeries` arm of `Categorizer::check_extension_plan`
|
||||
/// (`src/query/src/dist_plan/commutativity.rs`). A segment left above the merge has no scan the
|
||||
/// physical planner can read, so `cut_as_segment` must not cut it.
|
||||
pub fn region_local_segment(node: &NativeNode) -> bool {
|
||||
!reads_across_series(node) || pointwise_operand(node) || independent_scan_pair(node)
|
||||
}
|
||||
|
||||
/// Whether `node` becomes a segment of its own under a parent that must gather.
|
||||
///
|
||||
/// Cut local prefixes, global consumers and canonical merges separately so the prefix keeps its
|
||||
/// scan width, and every global consumer sees the canonical boundary below it. A pointwise wrapper
|
||||
/// Local prefixes, global consumers and canonical merges are cut separately, so a prefix keeps its
|
||||
/// scan width and every global consumer sees the canonical boundary below it. A pointwise wrapper
|
||||
/// of a global consumer is cut as well, so it cannot hide that consumer from recursive lowering.
|
||||
fn cut_as_segment(node: &NativeNode, canonical_segmentation: bool) -> bool {
|
||||
// A window over an evaluated input answers per series on its own grid, so its own shape says
|
||||
// nothing about where a segment over it can go: it drops the metric name, so two of the series
|
||||
// it answers can end under one label set, and the dist analyzer reads it as cross-series
|
||||
// ([`region_local_segment`]). Cutting one where the analyzer will not place it leaves a
|
||||
// `FusedSeries` above the `MergeScan` that the physical planner cannot build, so the segment is
|
||||
// only taken where the analyzer places it region-locally; otherwise the per-series prefix
|
||||
// inside the window is cut instead, and where there is none the statement keeps the plan it had.
|
||||
// Where the analyzer will not place a subquery window region-locally, the per-series prefix
|
||||
// inside it is cut instead.
|
||||
if evaluated_input_window(node) && !region_local_segment(node) {
|
||||
return false;
|
||||
}
|
||||
// A window over an evaluated input is answered per series on its own grid, so it is not the
|
||||
// global gather a raw window's locality reports.
|
||||
// A subquery window answers per series on its own grid, whatever its locality reports.
|
||||
let evaluated_window = evaluated_input_window(node);
|
||||
if !exportable(node)
|
||||
|| matches!(node.expr, NativeExpr::Input(_))
|
||||
@@ -208,7 +165,7 @@ fn cut_as_segment(node: &NativeNode, canonical_segmentation: bool) -> bool {
|
||||
if canonical_segmentation && (contains_global_consumer(node) || is_canonical_cut(node)) {
|
||||
return true;
|
||||
}
|
||||
// A segment builder needs an input, so data-free subtrees stay with their parent.
|
||||
// Data-free subtrees stay with their parent.
|
||||
let mut sources = Vec::new();
|
||||
collect_segment_inputs(node, &mut sources);
|
||||
!sources.is_empty()
|
||||
@@ -243,14 +200,8 @@ pub fn contains_global_consumer(node: &NativeNode) -> bool {
|
||||
node.any(&is_global_consumer)
|
||||
}
|
||||
|
||||
/// Whole-vector consumers remain global, but can be cut out as evaluated segments so a pointwise
|
||||
/// parent does not inherit their single-partition placement.
|
||||
///
|
||||
/// A per-point `φ` does not make the fold it reads any less of a whole-vector consumer: a
|
||||
/// `quantile` answers from every series of its group whichever node its argument comes from, so the
|
||||
/// parameterized variant is admitted here exactly as the bound one is. Leaving it out would read a
|
||||
/// fold that requires one partition as a node that does not, and the cut below it would be chosen
|
||||
/// as though its parent could run per partition.
|
||||
/// Whole-vector consumers stay global, but are cut out as evaluated segments so a pointwise parent
|
||||
/// does not inherit their single-partition placement.
|
||||
fn is_global_consumer(node: &NativeNode) -> bool {
|
||||
matches!(
|
||||
node.expr,
|
||||
@@ -260,22 +211,19 @@ fn is_global_consumer(node: &NativeNode) -> bool {
|
||||
) && matches!(input_locality(node), InputLocality::SinglePartition)
|
||||
}
|
||||
|
||||
/// Whether a subtree can be cut without inheriting its parent's global gather.
|
||||
///
|
||||
/// A local prefix stays on its source partitions. A canonical merge becomes its own routed
|
||||
/// boundary, and a parent reads the assembled frames rather than gathering the scan.
|
||||
/// Whether a subtree can be cut without inheriting its parent's global gather: a local prefix, or
|
||||
/// a canonical merge that becomes its own routed boundary.
|
||||
fn is_canonical_cut(node: &NativeNode) -> bool {
|
||||
matches!(node.expr, NativeExpr::Merge { .. })
|
||||
|| !matches!(input_locality(node), InputLocality::SinglePartition)
|
||||
|| canonical_local_prefix(node)
|
||||
}
|
||||
|
||||
/// One segment: its tree rewritten to read only its own inputs, the scans it reads, and the
|
||||
/// subtrees cut out of it.
|
||||
/// One segment: its tree rewritten to its own index space, the scans it reads, and the subtrees cut
|
||||
/// out of it.
|
||||
///
|
||||
/// A segment has one index space of its own - the scans it reads first, in the order it first names
|
||||
/// them, then the subtrees cut out of it - because `FusedSeries` requires its source indices to be
|
||||
/// dense over its children.
|
||||
/// `FusedSeries` requires dense source indices, so a segment numbers its scans first, in the order
|
||||
/// it first names them, then its cut subtrees.
|
||||
pub struct Segment {
|
||||
pub node: NativeNode,
|
||||
/// Original scan indices, in the order this segment's indices name them.
|
||||
@@ -410,23 +358,12 @@ pub fn cut_segments(node: &NativeNode, canonical_segmentation: bool) -> Segment
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends the per-row name column to a rows layout's tag list.
|
||||
///
|
||||
/// A scalar root declares no name column: it publishes one value and no series, so the row it
|
||||
/// answers has no name to report. The column is appended, so the layout keeps its order - the time
|
||||
/// index, then the value fields, then the tags - and a label set that already reports the name keeps
|
||||
/// the one column it has.
|
||||
/// Moves or appends `__name__` to the end of a rows layout's tag list. A scalar root gets no name
|
||||
/// column.
|
||||
pub fn with_row_name_column(node: &NativeNode, mut tags: Vec<String>) -> Vec<String> {
|
||||
if !matches!(&node.output, NativeType::Samples(_)) {
|
||||
return tags;
|
||||
}
|
||||
// A layout can already report the name: a set operation takes it from its sides, a discovered
|
||||
// source sorts its tags for the union, and a statement reading more than one metric-bound input
|
||||
// declares the name each of those inputs reports. None of them leaves that column last - `or`
|
||||
// keeps the left operand's order and only appends the right side's unseen tags, and sorting puts
|
||||
// the name wherever its bytes fall - so the existing one is removed and appended instead: every
|
||||
// rows layout then answers one order, the time index, the value fields, the labels, and the name
|
||||
// last.
|
||||
if let Some(index) = tags.iter().position(|tag| tag == METRIC_NAME) {
|
||||
tags.remove(index);
|
||||
}
|
||||
@@ -434,32 +371,13 @@ pub fn with_row_name_column(node: &NativeNode, mut tags: Vec<String>) -> Vec<Str
|
||||
tags
|
||||
}
|
||||
|
||||
/// The ordering this route compiles its trees against: the weakest both scanners provide.
|
||||
///
|
||||
/// A native scan declares `KeyThenTime` and a two-phase scan `Contiguous`, and the logical planner
|
||||
/// cannot read which one a statement will get. `Contiguous` is the weaker of the two - every
|
||||
/// series' samples contiguous, the series themselves unordered - and a native evaluation only
|
||||
/// refuses `Interleaved`, so a tree compiled against this ordering runs on either scanner.
|
||||
/// The ordering trees are compiled against: the weaker of a native scan's `KeyThenTime` and a
|
||||
/// two-phase scan's `Contiguous`, since the logical planner cannot tell which a statement gets.
|
||||
pub const NATIVE_ORDERING: SeriesOrdering = SeriesOrdering::Contiguous;
|
||||
|
||||
/// The columns a [`FusedSeries`] node produces.
|
||||
///
|
||||
/// With `experimental_native_promql` enabled, a value column is named by the caller's [`FieldNames`]
|
||||
/// answer for the statement's expression, not legacy planner expression text. Legacy headers in
|
||||
/// `tests/cases/**` are unaffected because the native route is opt-in and off by default.
|
||||
///
|
||||
/// The shape is the one the existing unary pipeline consumes — the time index, then the series
|
||||
/// fields, then the tags — and each column is declared the way the node's own conversion reads it
|
||||
/// back:
|
||||
/// the time column is a non-nullable millisecond timestamp with no timezone, because every
|
||||
/// evaluated chunk is addressed on the statement's grid and carries one; a field is a nullable
|
||||
/// `Float64`, because a grid point inside the statement's interval can have no sample; and a tag is
|
||||
/// a nullable `Utf8`, because a range function drops the metric name and a series can be missing a
|
||||
/// label entirely.
|
||||
/// The output schema of a fused node: its time index, one column per field, then its tags.
|
||||
///
|
||||
/// `field_kind` says what a field column carries. The physical conversion reads the same kind off
|
||||
/// this schema and dispatches on it, so the schema and the batch it describes cannot disagree.
|
||||
/// The output schema of a fused node: a non-nullable millisecond time index, one nullable column
|
||||
/// of `field_kind` per field, then nullable `Utf8` tags. Value columns are named by the caller's
|
||||
/// [`FieldNames`].
|
||||
pub fn fused_output_schema(
|
||||
fields: &[String],
|
||||
tags: &[String],
|
||||
@@ -471,10 +389,7 @@ pub fn fused_output_schema(
|
||||
FieldKind::Histogram => native_histogram_value_type().as_arrow_type(),
|
||||
};
|
||||
let mut columns = Vec::with_capacity(fields.len() + tags.len() + 1);
|
||||
// The time index is marked as one, the way the existing planner's plans mark the table's own
|
||||
// time index: what a plan publishes is a result either way, and a reader of the marker - a
|
||||
// `RANGE` query over the plan, a schema converted back to GreptimeDB's - has to see the same
|
||||
// column on both routes.
|
||||
// Marked as the existing planner marks it, for `RANGE` queries and schema conversion.
|
||||
columns.push((
|
||||
None,
|
||||
Arc::new(
|
||||
@@ -494,18 +409,13 @@ pub fn fused_output_schema(
|
||||
}
|
||||
for name in tags {
|
||||
let mut field = Field::new(name, ArrowDataType::Utf8, true);
|
||||
// The runtime answers `__name__` from the metric name of the series it reports, so a tag
|
||||
// column of that name is the name of each row rather than one name for the whole result.
|
||||
// Declaring it keeps the response layer from naming every row after the statement.
|
||||
// Tells the response layer each row carries its own name.
|
||||
if name == METRIC_NAME {
|
||||
field = field.with_metadata(datatypes::schema::metric_name_field_metadata());
|
||||
}
|
||||
columns.push((None, Arc::new(field)));
|
||||
}
|
||||
|
||||
// GreptimeDB's schemas carry their version, and a result schema is no different: a schema
|
||||
// read back from this plan is one, exactly as the existing planner's answer for the same
|
||||
// statement is.
|
||||
let metadata = std::collections::HashMap::from([(
|
||||
datatypes::schema::VERSION_KEY.to_string(),
|
||||
datatypes::schema::Schema::INITIAL_VERSION.to_string(),
|
||||
@@ -513,51 +423,24 @@ pub fn fused_output_schema(
|
||||
Ok(Arc::new(DFSchema::new_with_metadata(columns, metadata)?))
|
||||
}
|
||||
|
||||
/// The grid one `FusedSeries` publishes on: the grid its root declares it produces, or the
|
||||
/// statement's grid when the root declares none.
|
||||
///
|
||||
/// A root that produces one value per grid point says which grid that is, and that declared grid is
|
||||
/// the one its consumer reads it on: a window over an evaluated input - a subquery - produces on the
|
||||
/// window's own output grid, and a non-window root inside such a window, like the `Map` an
|
||||
/// expression of a subquery compiles to, produces on the subquery's grid rather than on the
|
||||
/// statement's. A statement root declares the statement's grid, so the two agree there. A root with
|
||||
/// no declared grid - raw samples - is read where it was scanned and keeps the caller's grid.
|
||||
/// Every lowering path binds the effective grid (the subquery's child grid for a matrix root, the
|
||||
/// statement's grid otherwise), so a window root answers that same grid here.
|
||||
/// The grid a `FusedSeries` publishes on: its root's grid, which inside a subquery is the
|
||||
/// subquery's grid, or `statement_grid` for a root without one.
|
||||
fn fused_publish_grid(root: &NativeNode, statement_grid: &Arc<EvalGrid>) -> Arc<EvalGrid> {
|
||||
root.output
|
||||
.grid()
|
||||
.map_or_else(|| Arc::clone(statement_grid), Arc::clone)
|
||||
}
|
||||
|
||||
/// Lowers a tree whose root is a canonical merge into a producer and a canonical router.
|
||||
/// Lowers a tree whose root is a canonical merge into a producer and a canonical router, and
|
||||
/// returns the plan with the tags its frames carry.
|
||||
///
|
||||
/// The tree says the statement answers one series per canonical label set; what it cannot say is
|
||||
/// where the pieces of one set are, because a rewrite created them after the scan split the rows.
|
||||
/// So the pieces have to meet before the answer is written, and there are only two honest ways to
|
||||
/// make them meet: read every partition in one execution, or route each label set to one owner. The
|
||||
/// first takes the caller's parallelism away for the whole query; this is the second.
|
||||
/// - The producer runs the merge on every scan partition, so a same-partition collision fails
|
||||
/// there, and exports one series per label set as a frame.
|
||||
/// - The router is `SeriesRepartitionExec`'s canonical routing: it publishes a label set once every
|
||||
/// producer contributed it or ended, and reports a second piece holding a taken position.
|
||||
///
|
||||
/// Two stages come out of it, and each has one job:
|
||||
///
|
||||
/// - the **producer** runs the tree's root merge on every scan partition. Its merge collects the
|
||||
/// pieces that partition holds - which is what makes a same-partition collision an error here,
|
||||
/// before anything is routed - and it exports one series per label set as a series frame. It is
|
||||
/// explicitly partition-local: the same node without that distinction would gather its inputs and
|
||||
/// answer everything in one execution.
|
||||
/// - the **router** is `SeriesRepartitionExec`'s canonical routing, which collects the pieces of one
|
||||
/// label set from *every* input partition. It is the conservative router - a label set is
|
||||
/// published only once every producer contributed it or ended - because a producer promises one
|
||||
/// series per set *per partition*, not that each set lives in one partition. A second piece of one
|
||||
/// set that holds a position another piece already holds is the same error, reported while that
|
||||
/// label set is assembled, and each output of the router then holds whole label sets: one series
|
||||
/// per set, complementary points joined.
|
||||
///
|
||||
/// `None` when the boundary cannot be built, so the caller keeps the plan it would have chosen.
|
||||
/// The stages of a canonical boundary over `tree`, and the columns its frames carry.
|
||||
///
|
||||
/// `format` says what the caller above reads: a statement root reads the boundary's rows, and
|
||||
/// anything else reads the assembled frames as an ordinary evaluated input.
|
||||
/// `format` is what the caller reads: rows for a statement root, frames otherwise. `None` when the
|
||||
/// boundary cannot be built, so the caller keeps its plan.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn canonical_boundary_stages(
|
||||
promql: Arc<str>,
|
||||
@@ -589,19 +472,11 @@ pub fn canonical_boundary_stages(
|
||||
.map(|field| field.name.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
let output_tags = output_tags_of(tree.root(), source_tags)?;
|
||||
// The terminal rows of this boundary report the name of each row they publish, so the schema
|
||||
// declares it exactly as the other rows layouts do. The tags stay the walk's own: they name the
|
||||
// labels the frames carry, and the binding below is built from them.
|
||||
let row_tags = with_row_name_column(tree.root(), output_tags.clone());
|
||||
// The values are named after the expression, as in every other rows layout of this statement.
|
||||
// A schema this boundary cannot declare declines here: the caller's error type is not one this
|
||||
// crate can build, so a name collision is reported by declining rather than as an internal
|
||||
// error, and the caller keeps the plan it would have chosen.
|
||||
// A column-name collision declines, so the caller keeps its plan.
|
||||
let value_names = field_names(&promql, &fields);
|
||||
let output_schema = fused_output_schema(&value_names, &row_tags, time_index, root_kind).ok()?;
|
||||
|
||||
// The producer: the statement's own tree, run per partition, exporting a frame. It runs above
|
||||
// the regions, where its router collects each label set from every region's contribution.
|
||||
let producer = FusedSeries::try_new_canonical_producer(
|
||||
Arc::clone(&promql),
|
||||
tree.clone(),
|
||||
@@ -618,10 +493,8 @@ pub fn canonical_boundary_stages(
|
||||
node: Arc::new(producer),
|
||||
});
|
||||
|
||||
// What reads the router depends on where this boundary sits. A consumer still above it reads
|
||||
// whole label sets, and the router already merged the pieces of one label set into one series,
|
||||
// so that consumer is an ordinary evaluated input of its own and needs no merge. The statement's
|
||||
// root instead publishes rows, which is this boundary's own frame converted as usual.
|
||||
// A consumer above reads the routed frames as an ordinary evaluated input; the statement root
|
||||
// converts them to rows.
|
||||
if format == FusedOutputFormat::SeriesFrame {
|
||||
return Some((producer, output_tags));
|
||||
}
|
||||
@@ -670,15 +543,8 @@ fn is_raw_series_source(plan: &LogicalPlan) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `plan` already answers raw series frames of its own.
|
||||
///
|
||||
/// A selector naming no metric is prepared as one [`RawSeriesSource`] per discovered metric, or as
|
||||
/// the `Union` of them when it discovered several, and each source names the metric it reads. So
|
||||
/// such a plan is a frame producer in its own right: a segment hands it to the node it builds
|
||||
/// instead of binding it again. Binding it again nests a source in a source, and the physical
|
||||
/// planner reads a source's child as the region scan that source binds - a union is no such child
|
||||
/// either - so the nested input is refused after the statement has already been committed to this
|
||||
/// route.
|
||||
/// Whether `plan` is a discovered selector's [`RawSeriesSource`], or the `Union` of several. It is
|
||||
/// used as is: wrapping it in another source is refused by the physical planner.
|
||||
fn is_sourced_plan(plan: &LogicalPlan) -> bool {
|
||||
matches!(plan, LogicalPlan::Union(_)) || is_raw_series_source(plan)
|
||||
}
|
||||
@@ -689,13 +555,8 @@ fn find_input_node(node: &NativeNode, source_index: usize) -> Option<&BoundInput
|
||||
.find(|input| input.source_index == source_index)
|
||||
}
|
||||
|
||||
/// Whether `plan` is the typed empty input a discovered selector that matched no table gets.
|
||||
///
|
||||
/// It reads no region and holds no scan, so it is not one of the tables a node's binding is derived
|
||||
/// from: two selectors are "of one table" only if the tables they scan are one. The remote
|
||||
/// admission gate reads the same shape back, to tell a node with nothing to ship from one that does
|
||||
/// read regions, so the declared frame is part of the check: an empty relation that does not
|
||||
/// declare the raw explicit-label frame is some other plan, not this input.
|
||||
/// Whether `plan` is the typed empty input of a discovered selector that matched no table: an
|
||||
/// `EmptyRelation` declaring the raw explicit-label frame.
|
||||
pub fn is_empty_discovered_input(plan: &LogicalPlan) -> bool {
|
||||
let LogicalPlan::EmptyRelation(relation) = plan else {
|
||||
return false;
|
||||
@@ -751,15 +612,7 @@ fn build_evaluated_segment(
|
||||
.output
|
||||
.samples()
|
||||
.is_some_and(|schema| schema.eval_grid.is_some())
|
||||
// A selector that discovered one metric is prepared as that metric's source, and one that
|
||||
// discovered several as the union of one source per metric; either way it already
|
||||
// declares the frames this segment reads, since it names each metric's source. So there
|
||||
// is nothing to bind it to and nothing to wrap it in, and binding a source in a source
|
||||
// is what the physical planner refuses. See [`is_sourced_plan`].
|
||||
|| is_sourced_plan(&child)
|
||||
// The typed empty frame of a selector that matched no table is an input in its own
|
||||
// right: it reads no region and carries no metric, so there is nothing to wrap it in.
|
||||
// A segment over it is still an explicit-label frame with no series.
|
||||
|| is_empty_discovered_input(&child)
|
||||
{
|
||||
inputs.push(child);
|
||||
@@ -786,9 +639,6 @@ fn build_evaluated_segment(
|
||||
local_tags.push(tags.clone());
|
||||
}
|
||||
}
|
||||
// A canonical merge is not a segment: it is the middle of a boundary whose two frame nodes and
|
||||
// router are what answer one series per label set across partitions, so it is built as that
|
||||
// boundary and read as a frame.
|
||||
if matches!(tree.root().expr, NativeExpr::Merge { .. }) {
|
||||
let (plan, tags) = canonical_boundary_stages(
|
||||
Arc::clone(&promql),
|
||||
@@ -835,10 +685,8 @@ fn build_evaluated_segment(
|
||||
))
|
||||
}
|
||||
|
||||
/// Builds one segment's plan from a subtree, binding its scan inputs without cutting again.
|
||||
///
|
||||
/// Returns the plan and the output columns the segment reports, which its parent names its own
|
||||
/// columns by. `None` when any part cannot be built, so the statement keeps the plan it had.
|
||||
/// Builds one segment's plan from a subtree without cutting again, and returns it with its output
|
||||
/// tags. `None` when any part cannot be built.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn build_inner_segment(
|
||||
node: &NativeNode,
|
||||
@@ -862,23 +710,17 @@ fn build_inner_segment(
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
let tree = NativeTree::try_new(rewrite_inner_segment(node, &sources)).ok()?;
|
||||
let output_tags = output_tags_of(tree.root(), &source_tags)?;
|
||||
// A segment publishes on the grid its own root declares, which is the grid its parent reads it
|
||||
// on: the segments of a subquery's inner expression are evaluated on the subquery's grid, not on
|
||||
// the statement's, whatever their root computes. The statement's grid is only the fallback for a
|
||||
// root that declares none.
|
||||
let segment_grid = fused_publish_grid(tree.root(), grid);
|
||||
let (inputs, metric, time_index, tags) = if let [index] = sources.as_slice() {
|
||||
let (metric, time_index, tags) = per_source.get(*index)?;
|
||||
(scans, metric.clone(), time_index.clone(), tags.clone())
|
||||
} else {
|
||||
// A binding cannot describe different source identities. Give each child the existing
|
||||
// explicit-label source boundary used for separate metric tables.
|
||||
// One binding cannot describe several sources, so each child gets its own
|
||||
// explicit-label source.
|
||||
let source_fields = tree_source_fields(&tree).ok()?;
|
||||
let mut children = Vec::with_capacity(sources.len());
|
||||
for (local_index, &source_index) in sources.iter().enumerate() {
|
||||
let scan = scans.get(local_index)?;
|
||||
// A scan that is already a source - one metric of a discovery, or the union of several -
|
||||
// is the frame producer this segment reads, so it stays as it is; see [`is_sourced_plan`].
|
||||
if is_sourced_plan(scan) {
|
||||
children.push(scan.clone());
|
||||
continue;
|
||||
@@ -930,14 +772,11 @@ fn build_inner_segment(
|
||||
))
|
||||
}
|
||||
|
||||
/// Plans `tree` as several segments, or `None` when it is one node already.
|
||||
/// Plans `tree` as several segments, or `None` when there is nothing to cut or a segment cannot be
|
||||
/// built; the caller then keeps the unsegmented plan.
|
||||
///
|
||||
/// A tree that reads across series answers one partition and gathers whatever it reads. Its
|
||||
/// per-series prefixes do not need that gather, so each becomes a segment of its own and keeps the
|
||||
/// partitions it was scanned with. Global consumers and canonical merges are cut in their original
|
||||
/// order, and recursive segments publish frames for their parents to consume. Only the statement
|
||||
/// root publishes rows, and it does so under the statement's own value names: [`FieldNames`]
|
||||
/// answers those, and the rows schema asks [`RootSchema`] for the rest of the layout.
|
||||
/// Nested segments publish frames for their parents; only the statement root publishes rows, named
|
||||
/// through [`FieldNames`] and [`RootSchema`].
|
||||
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
|
||||
pub fn segment_tree(
|
||||
promql: Arc<str>,
|
||||
@@ -958,31 +797,13 @@ pub fn segment_tree(
|
||||
field_names: FieldNames,
|
||||
root_schema: RootSchema,
|
||||
) -> Option<LogicalPlan> {
|
||||
// Only a tree the analyzer gathers is worth splitting: its per-series prefixes then run where
|
||||
// their input is read. A window over an evaluated input can need that split even where
|
||||
// [`input_locality`] reports a local tree - it drops the metric name, so [`reads_across_series`]
|
||||
// reads it as cross-series - and the per-series prefix inside it is what keeps the partitions it
|
||||
// scanned. Proceeding only admits the attempt: every cut is admitted by `cut_as_segment`
|
||||
// individually, which is where the analyzer's placement is asked.
|
||||
// A subquery window root may read across series even where `input_locality` reports a local
|
||||
// tree, so it is attempted too; `cut_as_segment` admits each cut.
|
||||
if !matches!(input_locality(tree.root()), InputLocality::SinglePartition)
|
||||
&& !evaluated_input_window(tree.root())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// A segment boundary has to carry something, and the only thing it can carry is a per-series
|
||||
// prefix: a subtree that answers each series on its own and can be recomputed. A tree with no
|
||||
// such subtree inside it has nothing to cut, and cutting anything else - an aggregate's own
|
||||
// state, a constant - is either impossible or a plain recomputation of the same work in one
|
||||
// more node. Cutting on locality alone would accept one here.
|
||||
//
|
||||
// The window this tree may be rooted at is not one of those consumers, but it is no boundary
|
||||
// either: `cut_as_segment` never cuts one, and what keeps its input's partitions is the
|
||||
// per-series prefix below it, which the cuts below are admitted for.
|
||||
//
|
||||
// A grouping by `__name__` needs no refusal of its own here: `source_tags` is the authority on
|
||||
// which labels an input declares, and the planner declares the metric name of every occurrence of
|
||||
// a statement reading more than one input - so a segment's output tags name the label the grouping
|
||||
// keeps, and two groups differing only by metric are published under their own label sets.
|
||||
let mut current_tree = tree.clone();
|
||||
let mut current_children = children.to_vec();
|
||||
let mut current_tags = source_tags.to_vec();
|
||||
@@ -990,8 +811,6 @@ pub fn segment_tree(
|
||||
let mut first_iteration = true;
|
||||
let mut changed = false;
|
||||
loop {
|
||||
// A tree the analyzer keeps partition-local needs no segment; a window over an evaluated
|
||||
// input is still worth attempting one for, so its per-series prefix keeps its partitions.
|
||||
if !matches!(
|
||||
input_locality(current_tree.root()),
|
||||
InputLocality::SinglePartition
|
||||
@@ -1016,9 +835,8 @@ pub fn segment_tree(
|
||||
.map(|&index| current_source_ids.get(index).copied().flatten())
|
||||
.collect::<Vec<_>>();
|
||||
for cut in &segment.cut {
|
||||
// A cut may wrap a global consumer in a pointwise rewrite or a later merge. Segment
|
||||
// that subtree first so its inner canonical boundary stays below the consumer. A local
|
||||
// canonical merge instead goes directly to the boundary builder.
|
||||
// A cut wrapping a global consumer is segmented recursively, so its inner canonical
|
||||
// boundary stays below the consumer.
|
||||
let canonical = matches!(cut.expr, NativeExpr::Merge { .. });
|
||||
let built = if first_iteration && contains_global_consumer(cut) {
|
||||
let cut_tree = NativeTree::try_new(cut.clone()).ok()?;
|
||||
@@ -1056,12 +874,7 @@ pub fn segment_tree(
|
||||
if built.is_none() && contains_global_consumer(cut) {
|
||||
return None;
|
||||
}
|
||||
// A cut the first iteration cannot build from the scans is built from the frames this
|
||||
// loop has already published: the canonical pass inserts a merge under a label rewrite,
|
||||
// and that boundary - rebuilt here as a producer, a frame and a router - is what answers
|
||||
// one series per label set across partitions. Which cuts are taken is
|
||||
// `cut_as_segment`'s decision, and it declines the evaluated-input window the analyzer
|
||||
// will not place region-locally, so this fallback only ever sees the cuts it admitted.
|
||||
// Otherwise the cut is built over the frames this loop has already published.
|
||||
let built = built.or_else(|| {
|
||||
build_evaluated_segment(
|
||||
Arc::clone(&promql),
|
||||
@@ -1094,12 +907,9 @@ pub fn segment_tree(
|
||||
return None;
|
||||
}
|
||||
let parent = current_tree;
|
||||
// Segmentation is useful even when the resulting parent is still single-partition: each
|
||||
// exported per-series subtree remains a separate input and is bound to its own source.
|
||||
let mut inputs = current_children;
|
||||
let mut child_tags = current_tags;
|
||||
// A merge at this segment's root still needs its own boundary. An outer rewrite above a
|
||||
// recursively cut ranking runs after the ranking, then is canonicalized before its caller.
|
||||
// A merge at this segment's root still needs its own boundary.
|
||||
if let NativeExpr::Merge { input } = &parent.root().expr {
|
||||
let source_fields = tree_source_fields(&parent).ok();
|
||||
for index in 0..inputs.len() {
|
||||
@@ -1147,9 +957,7 @@ pub fn segment_tree(
|
||||
)
|
||||
.map(|(plan, _)| plan);
|
||||
}
|
||||
// Nothing below can fall back once physical planning starts, so every tree this route commits
|
||||
// to has to be one the runtime executes. A shape the runtime refuses - a grouping by a value
|
||||
// field, an operation with no kernel - therefore keeps the plan it had.
|
||||
// Physical planning cannot fall back, so refuse here what the runtime would refuse.
|
||||
if !native_tree_supported(&parent) {
|
||||
return None;
|
||||
}
|
||||
@@ -1167,9 +975,7 @@ pub fn segment_tree(
|
||||
Arc::new(schema)
|
||||
}
|
||||
};
|
||||
// A recursively constructed segment still has its original source binding. Its parent may
|
||||
// combine another metric; giving the segment that parent's metric would relabel both inputs.
|
||||
// Direct scan segments keep their established builder and binding unchanged.
|
||||
// A recursive segment keeps its own source's metric; its parent's would relabel both inputs.
|
||||
let segment_binding = |source_ids: &[Option<usize>]| -> (Option<Arc<str>>, String) {
|
||||
let mut sources = source_ids.iter().flatten().copied();
|
||||
let Some(source) = sources.next() else {
|
||||
@@ -1184,11 +990,8 @@ pub fn segment_tree(
|
||||
)
|
||||
};
|
||||
let (segment_metric, segment_time_index) = segment_binding(¤t_source_ids);
|
||||
// A segment publishes on the grid its root declares, which is the grid its consumer reads it
|
||||
// on. Segmentation recurses into a cut subtree with the caller's grid, and that subtree can sit
|
||||
// inside a subquery window: the canonical segmentation of a collapsing rewrite cuts the window's
|
||||
// input while its caller still holds the statement's grid. Binding the caller's grid here
|
||||
// rejects such a segment, and the rejection aborts the whole route.
|
||||
// Recursion reaches a cut inside a subquery window with the statement's grid, not the
|
||||
// subquery's, so the root's own grid is bound.
|
||||
let publish_grid = fused_publish_grid(parent.root(), grid);
|
||||
let Ok(plan) = FusedSeries::try_new_with_format(
|
||||
Arc::clone(&promql),
|
||||
@@ -1229,7 +1032,6 @@ mod tests {
|
||||
Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1, 4).unwrap()).unwrap())
|
||||
}
|
||||
|
||||
/// The evaluated layout of the only field these trees carry.
|
||||
fn evaluated(grid: &Arc<EvalGrid>) -> NativeType {
|
||||
NativeType::Samples(Arc::new(SeriesSchema {
|
||||
fields: vec![FieldSpec {
|
||||
@@ -1240,7 +1042,6 @@ mod tests {
|
||||
}))
|
||||
}
|
||||
|
||||
/// `abs(…)` over `inner`, as a pointwise rewrite above a cut would be.
|
||||
fn map_over(inner: NativeNode) -> NativeNode {
|
||||
let output = inner
|
||||
.output
|
||||
@@ -1258,7 +1059,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `inner` selected at every grid point.
|
||||
fn selection(inner: NativeNode, output: NativeType) -> NativeNode {
|
||||
let grid = output
|
||||
.grid()
|
||||
@@ -1279,15 +1079,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fold that reads its argument at every step is a whole-vector consumer.
|
||||
///
|
||||
/// A `quantile` answers from its group's whole sample set wherever its `φ` comes from, so a
|
||||
/// fold that reads that `φ` per point needs every series of the vector in one place exactly as
|
||||
/// the fold that binds the number does. [`segment_tree`] asks [`contains_global_consumer`]
|
||||
/// where a tree may be cut and whether a cut it cannot build has to be declined, and a parent
|
||||
/// that answers one series at a time -- the `abs` below, as a canonical label rewrite would be
|
||||
/// -- must not hide the gather under it: read as a per-partition node, the cut beneath would be
|
||||
/// chosen for a parent that cannot run there.
|
||||
#[test]
|
||||
fn a_fold_that_reads_its_parameter_is_a_global_consumer() {
|
||||
let grid = grid();
|
||||
@@ -1324,8 +1115,6 @@ mod tests {
|
||||
contains_global_consumer(&map_over(fold)),
|
||||
"a pointwise parent must not hide the fold's gather"
|
||||
);
|
||||
// The predicate is about that fold and not about every subtree: a pointwise rewrite of a
|
||||
// selection answers each series on its own, so it stays cuttable where it stands.
|
||||
assert!(
|
||||
!contains_global_consumer(&map_over(selection(source, output))),
|
||||
"a selection is not a whole-vector consumer"
|
||||
|
||||
+40
-151
@@ -14,16 +14,13 @@
|
||||
|
||||
//! Where a native aggregate is split so two planes can run it.
|
||||
//!
|
||||
//! A `Complete` aggregate folds every contribution to a group, which is only correct when one
|
||||
//! execution reads all of them. A raw-series scan hands its partitions to separate executions, so the
|
||||
//! aggregate is split instead: the per-series prefix of the tree runs below the aggregate in the
|
||||
//! partitions that read series, that aggregate becomes a `Partial` one exporting the state each
|
||||
//! partition folded, and everything above it runs over the merged series.
|
||||
//! A `Complete` aggregate is only correct when one execution reads every contribution. Over a
|
||||
//! partitioned raw-series scan, the innermost aggregate is split: the per-series prefix runs in each
|
||||
//! partition under a `Partial` aggregate, and the suffix above the cut runs over a `Final` aggregate
|
||||
//! of the merged state.
|
||||
//!
|
||||
//! The split is structural. The innermost aggregate of the tree is replaced by an input node at its
|
||||
//! own output - that is where state enters - and the nodes above it become the suffix. What cannot be
|
||||
//! split correctly is refused with [`DataFusionError::NotImplemented`], which the planner reads as
|
||||
//! "plan this query the existing way".
|
||||
//! What cannot be split correctly is refused with [`DataFusionError::NotImplemented`], which the
|
||||
//! planner reads as "plan this query the existing way".
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -38,13 +35,12 @@ use crate::native::plan::{
|
||||
};
|
||||
|
||||
pub(crate) struct Split {
|
||||
/// The per-series tree below the cut aggregate, which the producer runs.
|
||||
/// The per-series tree below the cut aggregate.
|
||||
prefix: NativeNode,
|
||||
/// The tree above it, starting at the input the merged values enter at.
|
||||
/// The tree above the cut, with an input node where the merged values enter.
|
||||
suffix: NativeNode,
|
||||
/// The aggregate that was cut out.
|
||||
op: BoundAggregate,
|
||||
/// What that aggregate produces: the layout the exported state is indexed by.
|
||||
/// The cut aggregate's output, which the exported state is indexed by.
|
||||
schema: Arc<SeriesSchema>,
|
||||
/// The suffix reads whole histograms rather than individual groups.
|
||||
histogram: bool,
|
||||
@@ -59,21 +55,12 @@ pub(crate) fn histogram_group_is_single(group: &Grouping) -> bool {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Splits the innermost aggregate out of `node`.
|
||||
/// Splits the innermost aggregate out of `node`; `Ok(None)` when `node` holds no aggregate.
|
||||
///
|
||||
/// `Ok(None)` is a subtree holding no aggregate. Point-wise operations can run where their groups
|
||||
/// are owned. Histogram functions can also run there when the state router co-locates every bucket
|
||||
/// and every histogram whose output labels collide. A label rewrite may change that key, so it is
|
||||
/// only admitted alongside a partitioned histogram when it cannot change a label in the cut's
|
||||
/// routing key. A single-owner histogram needs no such restriction. A histogram parameter is
|
||||
/// answered above the cut, so it has to read no series: one that does would be silently replaced by
|
||||
/// the merged values. `topk`, a second aggregate and vector-vector matching still need a whole-vector
|
||||
/// boundary.
|
||||
///
|
||||
/// An instant selection or a window over raw samples above the cut cannot be applied to the merged
|
||||
/// values under the tree's current binding: the cut output is evaluated, whereas these nodes consume
|
||||
/// raw samples. A subquery window instead reads an evaluated input, so it is admitted when its
|
||||
/// declared grid equals its direct input's grid.
|
||||
/// The suffix may hold maps, constant-sided binaries, subquery windows and one histogram function.
|
||||
/// A label rewrite that changes a label of the cut's routing key is refused alongside a partitioned
|
||||
/// histogram, because the state router co-locates buckets by that key. A histogram parameter must
|
||||
/// read no series (see [`suffix_carries`]).
|
||||
pub(crate) fn split(
|
||||
node: &NativeNode,
|
||||
fields: &[FieldSpec],
|
||||
@@ -118,9 +105,6 @@ pub(crate) fn split(
|
||||
NativeExpr::Aggregate { input, op } => {
|
||||
check_cut(op, fields, time_index)?;
|
||||
match split(input, fields, time_index)? {
|
||||
// A second aggregate above the cut folds the merged values of every group, which
|
||||
// no partition owns on its own: it would have to be replanned as its own
|
||||
// `Partial`/`Final` pair above the first one's result.
|
||||
Some(_) => Err(declined("an aggregate above a split aggregate")),
|
||||
None => {
|
||||
admit_prefix(input)?;
|
||||
@@ -132,11 +116,7 @@ pub(crate) fn split(
|
||||
}
|
||||
Ok(Some(Split {
|
||||
prefix: (**input).clone(),
|
||||
// The merged values enter the suffix as the aggregate's own output: the same
|
||||
// binding and the same value, which is what the tree validates, at source
|
||||
// `0` of the suffix's own execution - a source index is local to one
|
||||
// execution, so the suffix names its one input rather than inheriting the
|
||||
// prefix's.
|
||||
// Source indices are local to one execution; the suffix has one input.
|
||||
suffix: NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
@@ -180,10 +160,6 @@ pub(crate) fn split(
|
||||
};
|
||||
Ok(Some(inner))
|
||||
}
|
||||
// The same histogram operation with a parameter evaluated at every grid point instead of
|
||||
// bound as a constant. The parameter is a per-point scalar - an expression of `time()` and
|
||||
// literals - so it reads no series and means the same thing above the merged values, and
|
||||
// the suffix carries it unchanged.
|
||||
NativeExpr::ParameterizedHistogram {
|
||||
input,
|
||||
op,
|
||||
@@ -192,8 +168,6 @@ pub(crate) fn split(
|
||||
let Some(mut inner) = split(input, fields, time_index)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
// The same two refusals as the literal form: successive calls may drop different labels,
|
||||
// so only the first call's partition key is known, and a rewrite may change that key.
|
||||
if inner.histogram {
|
||||
return Err(declined("nested histograms above a split aggregate"));
|
||||
}
|
||||
@@ -202,9 +176,6 @@ pub(crate) fn split(
|
||||
"a routing-label rewrite around a partitioned histogram",
|
||||
));
|
||||
}
|
||||
// A parameter is answered at its own grid point rather than from the merged values, so
|
||||
// one that reads the series the prefix reads has no source above the cut: applying it
|
||||
// there would silently answer it from the merged state instead.
|
||||
if parameters
|
||||
.iter()
|
||||
.any(|parameter| !suffix_carries(parameter))
|
||||
@@ -224,33 +195,18 @@ pub(crate) fn split(
|
||||
};
|
||||
Ok(Some(inner))
|
||||
}
|
||||
// TopK ranks the whole vector, not one histogram or aggregation group at a time.
|
||||
NativeExpr::Vector {
|
||||
op: BoundVectorOp::TopK { .. },
|
||||
..
|
||||
} => Err(declined("a whole-vector operation above a split aggregate")),
|
||||
// A per-point `φ` does not make the fold splittable: `check_cut` declines every `quantile`,
|
||||
// whose state is its group's samples however its argument is read. A `ParameterizedAggregate`
|
||||
// is only ever that fold, so there is nothing here to admit.
|
||||
// Always a `quantile`, which `check_cut` declines.
|
||||
NativeExpr::ParameterizedAggregate { .. } => Err(declined("a `quantile` aggregate")),
|
||||
// A canonical merge answers one series per canonical label set from every piece of that set,
|
||||
// and the pieces of one set are not in one partition: a label rewrite created them after the
|
||||
// scan split the rows. A split keeps that merge in the prefix, where it sees one partition's
|
||||
// pieces - so two colliding series that landed in different partitions are each collected
|
||||
// apart, the state router folds their partial states, and the statement answers a value
|
||||
// where Prometheus reports `vector cannot contain metrics with the same labelset`.
|
||||
//
|
||||
// The merge therefore has to stay above every partition, and the tree keeps the plan the
|
||||
// lowering gives a collected subtree: the merge is the boundary (`canonical_boundary_stages`
|
||||
// builds its producer and the canonical router collects one label set from every partition),
|
||||
// and the fold above it reads the whole series that boundary assembled. Refusing the split
|
||||
// here is what sends the statement there instead of answering it per partition.
|
||||
// A merge in the prefix would see one partition's pieces only, so colliding series in
|
||||
// different partitions would be folded instead of reported as
|
||||
// `vector cannot contain metrics with the same labelset`. The merge must stay a boundary
|
||||
// above every partition (`canonical_boundary_stages`).
|
||||
NativeExpr::Merge { .. } => Err(declined("an aggregate split across a canonical merge")),
|
||||
// A window whose input is already evaluated - a subquery - applies to the merged values the
|
||||
// suffix reads, provided it evaluates on a grid. The declared grid and the input's grid are
|
||||
// already required to be the same one when the window is bound, so the cut's grid need not be
|
||||
// that grid: a window between them may already have re-gridded the values. A raw-sample
|
||||
// window cannot sit above the cut.
|
||||
// Only a subquery window, whose input is evaluated, can sit above the cut.
|
||||
NativeExpr::Window { input, op } => {
|
||||
let Some(mut inner) = split(input, fields, time_index)? else {
|
||||
return Ok(None);
|
||||
@@ -271,12 +227,9 @@ pub(crate) fn split(
|
||||
};
|
||||
Ok(Some(inner))
|
||||
}
|
||||
// These read values the merged state does not answer: an instant selection or window reads
|
||||
// raw samples, `scalar`/`vector` answers one value or one series instead of the vector, and a
|
||||
// parameterized map reads the whole vector at a point. `ParameterizedTopK` declines here
|
||||
// exactly like the literal `topk` above does: a per-point `k` ranks the whole vector just as
|
||||
// a bound one does, so it needs the same whole-vector boundary. Admitting the one and
|
||||
// refusing the other would be an inconsistency rather than a capability.
|
||||
// None of these is rebuilt above the cut by `enter_suffix`: an instant selection reads raw
|
||||
// samples, `scalar()` and a ranking read the whole vector, and the rest are not supported
|
||||
// there.
|
||||
NativeExpr::Instant { input, .. }
|
||||
| NativeExpr::Timestamp { input }
|
||||
| NativeExpr::Vector { input, .. }
|
||||
@@ -294,16 +247,11 @@ pub(crate) fn split(
|
||||
right,
|
||||
matching,
|
||||
} => {
|
||||
// Each side is split once, and at most one of them may hold the innermost aggregate: two
|
||||
// would be two cuts, which this node cannot merge.
|
||||
let (left_split, right_split) = (
|
||||
split(left, fields, time_index)?,
|
||||
split(right, fields, time_index)?,
|
||||
);
|
||||
// A constant operand is broadcast over whatever the other side answers, so applying the
|
||||
// same operation to the merged values is the operation the query wrote. Any other sibling
|
||||
// would have to be matched with those values by label, which nothing below this node
|
||||
// gathers.
|
||||
// Only a broadcast against a literal applies unchanged to the merged values.
|
||||
let (mut inner, constant_on_the_left) = match (left_split, right_split) {
|
||||
(None, None) => return Ok(None),
|
||||
(Some(inner), None) if matches!(right.expr, NativeExpr::Scalar(_)) => {
|
||||
@@ -316,9 +264,6 @@ pub(crate) fn split(
|
||||
));
|
||||
}
|
||||
};
|
||||
// The cut side's own suffix takes the place of the aggregate, on the side the query wrote
|
||||
// it: a non-commutative operator means what that order says, and the matching and the
|
||||
// output are the ones the compiler bound.
|
||||
let (left, right) = if constant_on_the_left {
|
||||
((**left).clone(), inner.suffix)
|
||||
} else {
|
||||
@@ -334,8 +279,6 @@ pub(crate) fn split(
|
||||
};
|
||||
Ok(Some(inner))
|
||||
}
|
||||
// A set operation keeps samples by whether their match group is present on the other side,
|
||||
// which the merged values of one side cannot answer.
|
||||
NativeExpr::Set { left, right, .. } => {
|
||||
match (
|
||||
split(left, fields, time_index)?,
|
||||
@@ -345,8 +288,6 @@ pub(crate) fn split(
|
||||
_ => Err(declined("an aggregate under a set operation")),
|
||||
}
|
||||
}
|
||||
// The suffix above a split aggregate reads the merged state alone, so it has no source for
|
||||
// the info series.
|
||||
NativeExpr::Info { base, info, .. } => {
|
||||
match (
|
||||
split(base, fields, time_index)?,
|
||||
@@ -359,13 +300,8 @@ pub(crate) fn split(
|
||||
}
|
||||
}
|
||||
|
||||
/// The field names of the raw series the prefix reads, in source order.
|
||||
///
|
||||
/// Read off the tree's own raw input node, which is the one authority on what the prefix is
|
||||
/// compiled against: the root is already evaluated on the statement's grid, so its fields are the
|
||||
/// statement's value columns rather than the raw ones a `by(...)` clause would name. The prefix is
|
||||
/// one series at a time and the tree reads exactly one source, so the first raw input answers for
|
||||
/// all of them.
|
||||
/// The fields of the first raw input in `tree`, which a `by(...)` naming a value field would name.
|
||||
/// The split tree reads exactly one source.
|
||||
pub(crate) fn prefix_fields(tree: &NativeTree) -> DfResult<Vec<FieldSpec>> {
|
||||
tree.root()
|
||||
.inputs()
|
||||
@@ -380,13 +316,8 @@ pub(crate) fn prefix_fields(tree: &NativeTree) -> DfResult<Vec<FieldSpec>> {
|
||||
.ok_or_else(|| declined("a tree that reads no raw series"))
|
||||
}
|
||||
|
||||
/// Refuses an aggregate whose state the split cannot carry, and one grouped by a value field.
|
||||
///
|
||||
/// Only the eight fixed-width accumulators are carried: a quantile's state is the group's samples, and
|
||||
/// a non-`Complete` stage is a state or a merge rather than an answer. A `by(...)` naming a value field
|
||||
/// or the time index cannot be kept either - the state rows are indexed by field and by grid point,
|
||||
/// so a group that varies with either is not a group - while a label the input does not have is
|
||||
/// simply absent, exactly as it is in the existing planner.
|
||||
/// Refuses a non-`Complete` aggregate, a `quantile` (no fixed-width state), and a `by(...)` naming
|
||||
/// a value field or the time index.
|
||||
pub(crate) fn check_cut(
|
||||
op: &BoundAggregate,
|
||||
fields: &[FieldSpec],
|
||||
@@ -411,16 +342,10 @@ pub(crate) fn check_cut(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks that the per-series prefix is a tree one partition can evaluate on its own.
|
||||
/// Checks that the prefix answers one series from one series' samples: maps and constant-sided
|
||||
/// binaries over a window or instant selection of a raw input.
|
||||
///
|
||||
/// The producer runs one execution per partition and folds exactly the series that partition's scan
|
||||
/// returned, so the prefix has to answer one series from one series' samples: maps are point-wise, a
|
||||
/// binary operation with a constant side applies that constant to each series its other side answers,
|
||||
/// and a window or an instant selection reads the raw input itself. A raw input means no evaluation
|
||||
/// grid - a tree whose input is already evaluated is a subquery's, which one partition cannot evaluate.
|
||||
///
|
||||
/// A `clamp` whose maximum is below its minimum answers no value at all, so the fold would see a group
|
||||
/// with no sample of that field rather than the query the reader wrote.
|
||||
/// A `clamp` whose maximum is below its minimum answers no value, so it is refused too.
|
||||
pub(crate) fn admit_prefix(root: &NativeNode) -> DfResult<()> {
|
||||
let mut node = root;
|
||||
loop {
|
||||
@@ -435,10 +360,6 @@ pub(crate) fn admit_prefix(root: &NativeNode) -> DfResult<()> {
|
||||
}
|
||||
node = input;
|
||||
}
|
||||
// Only a constant side is broadcast: it reaches each series the other side answers, so
|
||||
// that side is the one the fold runs. Two constants answer one value per grid point and
|
||||
// read no series, and two vectors are a label match over the whole vector, which is not
|
||||
// what either half of the split produces.
|
||||
NativeExpr::Binary { left, right, .. } => {
|
||||
node = match (&left.expr, &right.expr) {
|
||||
(NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => {
|
||||
@@ -453,9 +374,6 @@ pub(crate) fn admit_prefix(root: &NativeNode) -> DfResult<()> {
|
||||
}
|
||||
};
|
||||
}
|
||||
// A canonical merge is a `merge_same_labelset` over the pieces one scan returned, so it
|
||||
// reads across series even inside one partition: a prefix holding one cannot promise
|
||||
// one series per label set, which is why the split refuses it above as well.
|
||||
NativeExpr::Merge { .. } => {
|
||||
return Err(declined("a per-series prefix that collects a label set"));
|
||||
}
|
||||
@@ -485,23 +403,16 @@ pub(crate) fn declined(reason: &str) -> DataFusionError {
|
||||
))
|
||||
}
|
||||
|
||||
/// A split aggregate as the two trees that run it, and the state they exchange between them.
|
||||
///
|
||||
/// The prefix runs where the series are read and ends at a `Partial` aggregate exporting the state
|
||||
/// each partition folded. The suffix runs where every partition's state has arrived and starts at a
|
||||
/// `Final` aggregate consuming it, so nothing above the cut sees a partial contribution.
|
||||
/// A split aggregate as the two trees that run it.
|
||||
pub struct SplitTrees {
|
||||
/// The prefix, with the cut aggregate bound over it as `Partial`; it answers aggregate state.
|
||||
/// The prefix under a `Partial` aggregate, answering aggregate state per partition.
|
||||
pub partial: NativeTree,
|
||||
/// The `Final` aggregate over that state, and everything the split moved above the cut.
|
||||
/// The suffix over a `Final` aggregate of every partition's state.
|
||||
pub final_tree: NativeTree,
|
||||
}
|
||||
|
||||
impl Split {
|
||||
/// Binds this split as the two trees that run it.
|
||||
///
|
||||
/// `Ok(None)` is an aggregate whose kernel keeps no mergeable state, which cannot cross a
|
||||
/// partition boundary at all.
|
||||
/// `Ok(None)` when the aggregate has no mergeable state.
|
||||
pub fn into_trees(self) -> DfResult<Option<SplitTrees>> {
|
||||
let Self {
|
||||
prefix,
|
||||
@@ -561,11 +472,7 @@ impl Split {
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts `merged` at the cut and returns the suffix above it.
|
||||
///
|
||||
/// A suffix is the spine of point-wise maps, constant-sided binaries, evaluated-input windows and at
|
||||
/// most one histogram operation between the cut and the root, with scalar constants and the
|
||||
/// evaluation time preserved. Other whole-vector operations are refused by `split`.
|
||||
/// Replaces the suffix's input node with `merged`.
|
||||
fn enter_suffix(node: NativeNode, merged: &NativeNode) -> DfResult<NativeNode> {
|
||||
let NativeNode { expr, output } = node;
|
||||
let rejected = || {
|
||||
@@ -573,13 +480,9 @@ fn enter_suffix(node: NativeNode, merged: &NativeNode) -> DfResult<NativeNode> {
|
||||
};
|
||||
let expr = match expr {
|
||||
NativeExpr::Input(_) => return Ok(merged.clone()),
|
||||
// A constant carries no state: the suffix keeps it as it is, beside the merged values. The
|
||||
// evaluation time is such a constant - it answers the grid's own timestamps, and the suffix
|
||||
// runs on the statement's grid, so it answers the same per-point value there.
|
||||
NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {
|
||||
return Ok(NativeNode { expr, output });
|
||||
}
|
||||
// A subquery window above the cut is rebuilt over the merged values, on its own grid.
|
||||
NativeExpr::Window { input, op } => NativeExpr::Window {
|
||||
input: Box::new(enter_suffix(*input, merged)?),
|
||||
op,
|
||||
@@ -595,9 +498,7 @@ fn enter_suffix(node: NativeNode, merged: &NativeNode) -> DfResult<NativeNode> {
|
||||
input: Box::new(enter_suffix(*input, merged)?),
|
||||
op,
|
||||
},
|
||||
// The parameters are per-point scalars that read no series - `split` refuses the split
|
||||
// otherwise - so they mean the same above the merged values and are handed over untouched
|
||||
// while only the input is rebuilt.
|
||||
// `split` checked the parameters read no series, so they are kept as they are.
|
||||
NativeExpr::ParameterizedHistogram {
|
||||
input,
|
||||
op,
|
||||
@@ -621,29 +522,17 @@ fn enter_suffix(node: NativeNode, merged: &NativeNode) -> DfResult<NativeNode> {
|
||||
Ok(NativeNode { expr, output })
|
||||
}
|
||||
|
||||
/// Whether [`enter_suffix`] rebuilds this subtree without reading `merged`.
|
||||
///
|
||||
/// This is the question the histogram arm of [`split`] asks of every parameter before it is carried
|
||||
/// above the cut: a parameter that `enter_suffix` rebuilds from constants alone means the same thing
|
||||
/// there, and one that reads the series has no source above the cut. Keeping the answer exactly the
|
||||
/// set of shapes `enter_suffix` builds is what keeps a misplaced tree a decline rather than an
|
||||
/// `Internal` error: a subtree that claims to carry but does not would reach `rejected()`.
|
||||
/// Whether [`enter_suffix`] rebuilds this subtree from constants alone. It accepts a subset of the
|
||||
/// shapes `enter_suffix` builds; a shape outside them would become an `Internal` error there.
|
||||
fn suffix_carries(node: &NativeNode) -> bool {
|
||||
match &node.expr {
|
||||
// Constants: they answer their own values on the statement's grid.
|
||||
NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => true,
|
||||
// Point-wise spines over something that carries: the map and the histogram application
|
||||
// reach each series the way they are rebuilt.
|
||||
NativeExpr::Map { input, .. }
|
||||
| NativeExpr::Vector {
|
||||
input,
|
||||
op: BoundVectorOp::Histogram(_),
|
||||
} => suffix_carries(input),
|
||||
// A binary operation carries when both sides do: a constant broadcast over a constant is
|
||||
// still a constant.
|
||||
NativeExpr::Binary { left, right, .. } => suffix_carries(left) && suffix_carries(right),
|
||||
// Everything else reads a source: the cut's own values (`Input`), the whole vector at a
|
||||
// point (`ScalarOf`, a vector operation), or the series a parameter reads.
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,12 +14,10 @@
|
||||
|
||||
//! The aggregate-state chunk a native `Partial`/`Final` aggregate passes between executions.
|
||||
//!
|
||||
//! A state chunk is not a query value. It names the group a partition folded and the grid
|
||||
//! positions that group has contributions at, and it carries the accumulator components its
|
||||
//! aggregate declared -- nothing else. The conversions here are the only place kernel state
|
||||
//! ([`PartialAggregate`]) and frame state ([`StateSeries`]) meet, so a hole in one is a hole in the
|
||||
//! other: a field with no contribution at a carried position stays absent through both directions
|
||||
//! rather than being filled in with a zero that a later merge would count.
|
||||
//! A state chunk carries a group's labels, the grid positions it has contributions at, and the
|
||||
//! accumulator components its aggregate declares. Converting between kernel state
|
||||
//! ([`PartialAggregate`]) and frame state ([`StateSeries`]) keeps a field with no contribution
|
||||
//! absent rather than zero, so a later merge does not count it.
|
||||
|
||||
use std::mem::{size_of, size_of_val};
|
||||
use std::sync::Arc;
|
||||
@@ -42,23 +40,15 @@ pub enum StateChunk {
|
||||
Series {
|
||||
series: Vec<StateSeries>,
|
||||
state_schema: Arc<AggregateStateSchema>,
|
||||
/// The producer charge this chunk carries once it has left its node's queue.
|
||||
///
|
||||
/// A state chunk is charged to the node that folded it until the chunk is handed over. The
|
||||
/// consumer keeps the batch across polls while it packs rows from it, so the charge travels
|
||||
/// with those series rather than being returned the moment the producer lets go.
|
||||
/// The producer's charge, moved here when the chunk leaves its node's queue: the consumer
|
||||
/// keeps the series across polls, so the charge travels with them.
|
||||
reservation: Option<MemoryReservation>,
|
||||
},
|
||||
Row(crate::aggregate::state::StateRow),
|
||||
}
|
||||
|
||||
/// Rejects a bound state whose kind or component layout is not what this node binds.
|
||||
///
|
||||
/// Both halves matter. A frame carries its kind so a `sum` state is never merged as an `avg` one, and
|
||||
/// it carries the component list so a merge reads exactly the columns the producer wrote. The
|
||||
/// expected pair comes from the same binding the node was built from, so a histogram aggregate
|
||||
/// exports and accepts histogram state and a numeric one numeric state, with no second table to
|
||||
/// drift from the first.
|
||||
/// Rejects a state whose kind or component list differs from what `op`'s binding produces, so a
|
||||
/// `sum` state is never merged as `avg` and a merge reads exactly the columns the producer wrote.
|
||||
fn ensure_bound_state(op: &BoundAggregate, state_schema: &AggregateStateSchema) -> Result<()> {
|
||||
let Some((expected_kind, expected_components)) =
|
||||
aggregate_state_binding(op.kind, op.field_kind)
|
||||
@@ -83,11 +73,8 @@ fn ensure_bound_state(op: &BoundAggregate, state_schema: &AggregateStateSchema)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hands one partition's kernel state over as the frame state a consumer reads.
|
||||
///
|
||||
/// The fold already builds the frame's own representation - field-major states on sparse absolute
|
||||
/// grid positions - so this moves the groups. It copies nothing: the charge the fold reported for
|
||||
/// those groups is the charge the chunk keeps.
|
||||
/// Hands one partition's kernel state over as frame state. The fold already builds the frame
|
||||
/// representation, so this moves the groups without copying.
|
||||
pub(crate) fn state_chunk_from_partial(
|
||||
partial: PartialAggregate,
|
||||
state_schema: Arc<AggregateStateSchema>,
|
||||
@@ -101,11 +88,8 @@ pub(crate) fn state_chunk_from_partial(
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds the executor's state row for one exported row, as its producer declared it.
|
||||
///
|
||||
/// A producer hands a row over without knowing which binding will fold it: the kind and the columns
|
||||
/// it was written with travel in the row, and the consumer checks them against its own binding. So
|
||||
/// this converts the row's columns and keeps the layout they were validated against.
|
||||
/// Builds a state row keeping the kind and components its producer declared; the consumer checks
|
||||
/// them against its own binding.
|
||||
pub(crate) fn state_row_of(row: StateFrameRow) -> Result<crate::aggregate::state::StateRow> {
|
||||
let fields = row
|
||||
.fields()
|
||||
@@ -149,10 +133,8 @@ pub(crate) fn state_row_from_frame_row(
|
||||
})
|
||||
}
|
||||
|
||||
/// The aggregate a state kind is the state of.
|
||||
///
|
||||
/// A histogram kind is the state of the same aggregate over a histogram input, so it merges with the
|
||||
/// same rules; what differs is the payload, which the merge reads from the kind itself.
|
||||
/// The aggregate a state kind is the state of. A histogram kind maps to the same aggregate; the
|
||||
/// merge reads the payload type from the kind.
|
||||
pub(crate) fn op_of_state(kind: AggregateStateKind) -> AggregateOp {
|
||||
match kind {
|
||||
AggregateStateKind::Sum | AggregateStateKind::HistogramSum => AggregateOp::Sum,
|
||||
@@ -217,9 +199,8 @@ pub(crate) fn state_row_bytes(row: &crate::aggregate::state::StateRow) -> usize
|
||||
|
||||
/// Bytes a state chunk holds: labels, axis runs, and one sparse state vector per field.
|
||||
///
|
||||
/// Like [`crate::grid_series::series_bytes`] this is a work estimate rather than a heap
|
||||
/// measurement -- it counts vector capacities, not allocator overhead -- which is what the
|
||||
/// reservation it feeds needs: a figure that never under-counts what the executor holds.
|
||||
/// Like [`crate::grid_series::series_bytes`], an estimate from vector capacities that must not
|
||||
/// under-count what the executor holds.
|
||||
pub(crate) fn state_bytes(chunk: &StateChunk) -> usize {
|
||||
let StateChunk::Series {
|
||||
series,
|
||||
@@ -252,9 +233,7 @@ pub(crate) fn state_bytes(chunk: &StateChunk) -> usize {
|
||||
.capacity()
|
||||
.saturating_mul(size_of::<Vec<Option<StatePayload>>>());
|
||||
let states = series.states.iter().fold(fields, |bytes, field| {
|
||||
// The slot is sized for the payload family it holds; a histogram payload also owns its
|
||||
// boxed state and both histograms' Arrow buffers, so its buckets are charged by width
|
||||
// rather than estimated at a fixed size.
|
||||
// A histogram payload owns boxed state and Arrow buffers, charged by bucket width.
|
||||
bytes
|
||||
.saturating_add(
|
||||
field
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//!An extended "array" based on [DictionaryArray].
|
||||
//! An extended "array" based on [DictionaryArray].
|
||||
|
||||
use datafusion::arrow::datatypes::Field;
|
||||
use datatypes::arrow::array::{Array, ArrayData, ArrayRef, DictionaryArray, Int64Array};
|
||||
@@ -23,12 +23,11 @@ use crate::error::{EmptyRangeSnafu, IllegalRangeSnafu, Result};
|
||||
|
||||
pub type RangeTuple = (u32, u32);
|
||||
|
||||
/// An compound logical "array" type. Represent serval ranges (slices) of one array.
|
||||
/// It's useful to use case like compute sliding window, or range selector from promql.
|
||||
/// A compound logical "array" type representing several ranges (slices) of one array, used for
|
||||
/// sliding windows such as PromQL range selectors.
|
||||
///
|
||||
/// It's build on top of Arrow's [DictionaryArray]. [DictionaryArray] contains two
|
||||
/// sub-arrays, one for dictionary key and another for dictionary value. Both of them
|
||||
/// can be arbitrary types, but here the key array is fixed to u32 type.
|
||||
/// It's built on top of Arrow's [DictionaryArray], which holds a key array and a value array.
|
||||
/// The value array can be any type; the key array is fixed to i64.
|
||||
///
|
||||
/// ```text
|
||||
/// │ ┌─────┬─────┬─────┬─────┐
|
||||
@@ -242,8 +241,6 @@ impl std::fmt::Debug for RangeArray {
|
||||
}
|
||||
}
|
||||
|
||||
// util functions
|
||||
|
||||
fn pack(offset: u32, length: u32) -> i64 {
|
||||
bytemuck::cast::<[u32; 2], i64>([offset, length])
|
||||
}
|
||||
|
||||
+73
-216
@@ -136,11 +136,8 @@ pub(crate) struct FloatWindows<'a> {
|
||||
}
|
||||
|
||||
impl FloatWindows<'_> {
|
||||
/// The resets inside window `index`.
|
||||
///
|
||||
/// `windows` index the retained arrays as they stand in this batch, not absolutely: each
|
||||
/// span is relative to `timestamps` and `values`, which is why `base` plus a span start is
|
||||
/// the absolute position of the sample the span starts at.
|
||||
/// The resets inside window `index`. Spans are relative to this batch's retained arrays, so
|
||||
/// `base + span.start` is the absolute position of the span's first sample.
|
||||
pub(crate) fn resets_of(&self, index: usize) -> &[CounterReset] {
|
||||
let span = &self.windows[index];
|
||||
resets_between(
|
||||
@@ -158,19 +155,14 @@ pub(crate) type BatchKernel = Box<dyn FnMut(&FloatWindows<'_>, &mut Vec<Option<f
|
||||
/// 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, handing out its results as they
|
||||
/// become final.
|
||||
/// Evaluates range windows over series pushed one at a time, chunk by chunk.
|
||||
///
|
||||
/// Each series is pushed as its chunks in order. A push evaluates the grid points whose windows
|
||||
/// the pushed samples complete, and hands them out as one [`EvaluatedChunk`], so a consumer can
|
||||
/// stream a long series instead of waiting for its last chunk. One chunk may hold several runs of
|
||||
/// positions, separated by stretches holding no value, and the axis names them. The series closes
|
||||
/// on a chunk marked `is_last`, which is handed out even when it holds no position.
|
||||
/// Each push hands out the grid points its samples completed as one [`EvaluatedChunk`]. A series
|
||||
/// closes exactly once, on a chunk marked `is_last`, which is handed out even when empty.
|
||||
///
|
||||
/// Fields are evaluated independently over their own valid samples; a row holding a stale
|
||||
/// marker in any field is dropped, as the ordinary range selector does. Only the samples later
|
||||
/// windows can still use are retained. Native histogram samples need a [`RangeFunction`]; an
|
||||
/// evaluator built from a bare kernel rejects them.
|
||||
/// Fields are evaluated independently over their own valid samples; a raw row holding a stale
|
||||
/// marker in any field is dropped. Native histogram samples need a [`RangeFunction`]; an evaluator
|
||||
/// built from a bare kernel rejects them.
|
||||
pub struct RangeEvaluator {
|
||||
grid: Arc<EvalGrid>,
|
||||
/// The window with `offset_ms` replaced by the offset samples are shifted by.
|
||||
@@ -190,8 +182,6 @@ pub struct RangeEvaluator {
|
||||
drops_metric_name: bool,
|
||||
/// Raised by the first non-empty window, where Prometheus validates function arguments.
|
||||
window_error: Option<String>,
|
||||
/// Chunks appended by the bulk path, so a test can prove that path is reached rather than
|
||||
/// only that the output is right, which the per-sample path would also produce.
|
||||
#[cfg(test)]
|
||||
bulk_ingests: usize,
|
||||
/// The batch form of `function`, when it has one and the input allows it. Present only for
|
||||
@@ -200,11 +190,8 @@ pub struct RangeEvaluator {
|
||||
batch: Option<BatchKernel>,
|
||||
/// Windows accumulated for the next batch call.
|
||||
pending: PendingBatch,
|
||||
/// Buffers the bulk ingest shifts and compacts a chunk into, kept between chunks so a series
|
||||
/// that needs them does not allocate per push.
|
||||
/// Kept between chunks so the bulk ingest does not allocate per push.
|
||||
bulk_scratch: BulkScratch,
|
||||
/// 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,
|
||||
}
|
||||
@@ -351,8 +338,6 @@ fn flush_batch(
|
||||
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;
|
||||
@@ -399,11 +384,8 @@ struct SeriesState {
|
||||
impl SeriesState {
|
||||
/// The bytes this series' identity holds, which the rows handed out do not cover.
|
||||
fn identity_bytes(&self) -> usize {
|
||||
// A scan slices the primary key out of a decoded buffer, so the bytes the key shows are not
|
||||
// the bytes it keeps: a key of a few bytes pins the allocation it was sliced out of.
|
||||
// Charging the slice length instead would show a handful of bytes for an allocation the
|
||||
// size of a decoded batch. One evaluator holds one series at a time, and an evaluated input
|
||||
// holds no key at all, so there is no second slice of the same allocation to dedupe.
|
||||
// The key is sliced out of a decoded scan buffer and pins that whole allocation, so charge
|
||||
// its capacity. One series is held at a time, so no other slice shares the allocation.
|
||||
let primary_key = self
|
||||
.primary_key
|
||||
.as_ref()
|
||||
@@ -444,24 +426,16 @@ struct FieldSamples {
|
||||
/// Histograms before `histogram_head` are behind every remaining window; their payloads are
|
||||
/// released by [`advance_histograms`](Self::advance_histograms).
|
||||
histogram_head: usize,
|
||||
/// Estimated payload of the histograms this field still holds: the bucket lists and other
|
||||
/// buffers the samples own, which no `size_of` of a slot shows.
|
||||
///
|
||||
/// Measured for a histogram when it is admitted and released with it, so a retained sample is
|
||||
/// not walked again on every push. A histogram is never modified once admitted, so the payload
|
||||
/// its release subtracts is the one its admission added. Samples already behind every window
|
||||
/// keep their payload in the figure until the drain releases them.
|
||||
/// Heap payload of the histograms in `histograms`, behind `histogram_head` included. Added on
|
||||
/// admission and subtracted on drain; a histogram is never modified in between, so both
|
||||
/// measurements agree.
|
||||
histogram_bytes: usize,
|
||||
/// Sequence number of `values[0]`. Absolute and monotonic across the series this evaluator
|
||||
/// evaluates, so a reset keeps its position when `head` samples are dropped instead of every
|
||||
/// index being renumbered. An empty field holds the number of samples already dropped, which
|
||||
/// keeps positions increasing when the next series starts.
|
||||
/// Absolute sequence number of `values[0]`, monotonic across series, so dropping samples
|
||||
/// does not renumber the reset positions.
|
||||
base: u64,
|
||||
/// Resets between consecutive retained samples, ascending by position: exactly the ones a
|
||||
/// window over these samples can still contain. Maintained only for the counter-correcting
|
||||
/// functions, and released as the samples they reach back to are dropped.
|
||||
/// Resets between consecutive retained samples, ascending by position. Maintained only when
|
||||
/// `index_resets` is set.
|
||||
resets: Vec<CounterReset>,
|
||||
/// Whether `resets` is maintained for this field.
|
||||
index_resets: bool,
|
||||
}
|
||||
|
||||
@@ -504,16 +478,12 @@ impl FieldSamples {
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends one valid sample, recording a counter reset when it dropped below the sample
|
||||
/// before it.
|
||||
/// Appends one valid sample, recording a counter reset when it dropped below the previous
|
||||
/// float.
|
||||
///
|
||||
/// "Before it" means the previous entry of `values`, which leaves native histogram samples
|
||||
/// out. A drop across an intervening histogram is therefore recorded as a reset of two
|
||||
/// samples that are not neighbours. That is unobservable: a window holding both floats also
|
||||
/// holds the histogram between them, so it is a mixed window, whose counter functions report
|
||||
/// nothing; and a window starting after the earlier float excludes a reset on its first
|
||||
/// sample. Should the mixed-window rules ever start reading the float resets, this has to
|
||||
/// compare timestamps instead.
|
||||
/// The previous float may sit before an intervening native histogram. That is unobservable:
|
||||
/// a window holding both floats also holds the histogram, and counter functions report
|
||||
/// nothing for a mixed window.
|
||||
fn push(&mut self, timestamp: i64, value: f64) {
|
||||
if self.index_resets
|
||||
&& let Some(&previous_value) = self.values.last()
|
||||
@@ -528,11 +498,7 @@ impl FieldSamples {
|
||||
self.values.push(value);
|
||||
}
|
||||
|
||||
/// Appends samples that are all present, in bulk.
|
||||
///
|
||||
/// Same result as calling [`push`](Self::push) once per sample, including the reset scan,
|
||||
/// which stays per-sample for a field that maintains the index; the two appends become two
|
||||
/// `memcpy`s.
|
||||
/// Same as calling [`push`](Self::push) once per sample.
|
||||
fn push_bulk(&mut self, timestamps: &[i64], values: &[f64]) {
|
||||
debug_assert_eq!(timestamps.len(), values.len());
|
||||
if self.index_resets {
|
||||
@@ -571,9 +537,6 @@ impl FieldSamples {
|
||||
}
|
||||
|
||||
/// Drops the histograms before `histogram_head`, releasing the payload they held.
|
||||
///
|
||||
/// The dropped samples are measured as they go, which costs one measurement per dropped
|
||||
/// histogram in total: the retained ones are never scanned again.
|
||||
fn advance_histograms(&mut self) {
|
||||
let head = std::mem::take(&mut self.histogram_head);
|
||||
if head == 0 {
|
||||
@@ -594,12 +557,8 @@ impl FieldSamples {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes the histograms a row holds box, beyond the slots they sit in.
|
||||
///
|
||||
/// A slot is an `Option<GridSample>`: a pointer and a tag. A result that is a native histogram
|
||||
/// points at a [`FloatHistogram`] on the heap, which owns its bucket lists in turn, and both stay
|
||||
/// alive between pushes. Only slots the last evaluated point left in place are counted: a push
|
||||
/// clears the row.
|
||||
/// The heap bytes of the histograms boxed in `row`, beyond the slots themselves. The row survives
|
||||
/// between pushes holding the last evaluated point.
|
||||
fn boxed_bytes(row: &[Option<GridSample>]) -> usize {
|
||||
row.iter()
|
||||
.flatten()
|
||||
@@ -716,24 +675,20 @@ impl RangeEvaluator {
|
||||
})
|
||||
}
|
||||
|
||||
/// The evaluation grid this evaluator decides points of.
|
||||
///
|
||||
/// Every window ends at a point of it and is read at that point's timestamp, so a caller
|
||||
/// reserving for what the evaluator is about to allocate reserves this grid's timestamps.
|
||||
/// The evaluation grid the output is addressed on.
|
||||
pub fn grid(&self) -> &Arc<EvalGrid> {
|
||||
&self.grid
|
||||
}
|
||||
|
||||
/// Chunks appended without the per-sample loop. Test-only: both paths produce the same
|
||||
/// output by construction, so a test that only compared output could not tell whether the
|
||||
/// bulk path ran at all.
|
||||
/// Chunks taken by the bulk path. Both paths produce the same output, so only this shows
|
||||
/// which one ran.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn bulk_ingest_count(&self) -> usize {
|
||||
self.bulk_ingests
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Batch kernel calls made so far; like [`Self::bulk_ingest_count`], output alone cannot
|
||||
/// show which dispatch ran.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn batch_call_count(&self) -> usize {
|
||||
self.batch_calls
|
||||
@@ -744,23 +699,10 @@ impl RangeEvaluator {
|
||||
self.annotations = collector;
|
||||
}
|
||||
|
||||
/// An estimate of the bytes this evaluator keeps between pushes.
|
||||
///
|
||||
/// Counted by capacity, so it is what the storage holds rather than what it uses: the retained
|
||||
/// samples per field (timestamps, values, the reset index and the native histograms with the
|
||||
/// payload each of them owns), the row a push fills with the histograms it boxes, the identity
|
||||
/// of the open series, the pending batch's own vectors and the buffers the bulk ingest shifts
|
||||
/// and compacts into. Left out are the kernel's scratch buffers, this struct's `Vec` headers
|
||||
/// and the grid, which every chunk addressed on it shares.
|
||||
///
|
||||
/// The figure is an estimate, not a ledger of every allocation: a histogram's payload is
|
||||
/// measured once when it is admitted and released with it, so neither the retained samples nor
|
||||
/// the transient allocations of a push are walked again.
|
||||
///
|
||||
/// A push is the only caller that also holds the incoming chunk, and it charges that itself for
|
||||
/// as long as the call runs. The figure must not be per-chunk either: charging every chunk
|
||||
/// consumed would make the charge grow with the chunk count, so a fixed window over a long
|
||||
/// series would read as an allocation failure even though the window holds no more samples.
|
||||
/// An estimate, by capacity, of the bytes this evaluator keeps between pushes: retained
|
||||
/// samples and histograms, the output row, the open series' identity, the pending batch and
|
||||
/// the bulk scratch. Excludes kernel scratch, the shared grid and the incoming chunk, which
|
||||
/// the caller charges for the duration of a push.
|
||||
pub(crate) fn retained_bytes(&self) -> usize {
|
||||
let fields: usize = self.fields.iter().map(FieldSamples::bytes).sum();
|
||||
let row = self.row.capacity() * std::mem::size_of::<Option<GridSample>>();
|
||||
@@ -775,11 +717,8 @@ impl RangeEvaluator {
|
||||
/// An upper bound of the rows the next push hands out, for input whose last sample is at
|
||||
/// `last_ts` (`None` when it holds none) and which closes its series when `last`.
|
||||
///
|
||||
/// A push writes at most one row per point it decides, from the series' cursor -- the first
|
||||
/// point for a series not started yet. Unless the series closes, it decides no point past the
|
||||
/// time the input has reached; and a point holds a row only while its window still reaches the
|
||||
/// latest sample, so the points after that one's window are decided empty. A replayed `@`
|
||||
/// result fills every grid point from the one window it evaluates first.
|
||||
/// Points past the window of the latest sample are empty, and unless the series closes no
|
||||
/// point past the input time is decided. A replayed `@` result fills the whole grid at once.
|
||||
pub(crate) fn output_rows_bound(&self, last_ts: Option<i64>, last: bool) -> usize {
|
||||
let spec = self.grid.spec();
|
||||
let len = usize::try_from(spec.len).unwrap_or(usize::MAX);
|
||||
@@ -860,20 +799,11 @@ impl RangeEvaluator {
|
||||
self.close_series()
|
||||
}
|
||||
|
||||
/// Evaluates one run of an evaluated series, such as the inner result of a subquery: the
|
||||
/// value at each grid point is a sample at that time. Stale markers are kept as values,
|
||||
/// since the input is computed.
|
||||
/// Evaluates one delivery of an evaluated series, such as the inner result of a subquery.
|
||||
/// Stale markers are kept as values, since the input is computed.
|
||||
///
|
||||
/// `last` says whether this delivery closes its series. A stream hands over the same logical
|
||||
/// series more than once -- a prefix now, its closing chunk later -- and the windows of a later
|
||||
/// delivery read the samples of the earlier ones, so the state a series retains lives on across
|
||||
/// them: only the `last` call ends it. Handing the deliveries over without saying which is last
|
||||
/// would close the series early and lose exactly the samples a window across the boundary
|
||||
/// needs.
|
||||
///
|
||||
/// One delivery may hold several runs of positions, separated by stretches holding no value;
|
||||
/// they all reach the caller in one chunk, addressed by the axis. A delivery that holds no
|
||||
/// position at all is a legal close when it is `last`, and an error otherwise.
|
||||
/// A series may arrive in several deliveries; retained samples carry across them and only the
|
||||
/// `last` one closes it. An empty delivery is legal only when it is `last`.
|
||||
pub fn push_series(&mut self, series: &Series, last: bool) -> Result<Option<EvaluatedChunk>> {
|
||||
let time = &series.time;
|
||||
let Some(grid) = time.grid() else {
|
||||
@@ -889,13 +819,9 @@ impl RangeEvaluator {
|
||||
"evaluated series does not match the input schema".into(),
|
||||
));
|
||||
}
|
||||
// The input may skip positions: it is ingested by the positions it carries, and the points
|
||||
// it skips hold no sample, which is exactly what a hole means.
|
||||
let timestamps = time.timestamps().map_err(external)?;
|
||||
let last_ts = timestamps.last().copied();
|
||||
if !last && last_ts.is_none() {
|
||||
// An empty delivery inside a series decides nothing: it is indistinguishable from a
|
||||
// stall, so only the closing `is_last` one is a legal close.
|
||||
return Err(DataFusionError::Execution(
|
||||
"evaluated range input holds no position before its last run".into(),
|
||||
));
|
||||
@@ -913,7 +839,6 @@ impl RangeEvaluator {
|
||||
});
|
||||
}
|
||||
Some(state) => {
|
||||
// A run continues its series; the earlier runs' samples stay retained for it.
|
||||
if state.primary_key.is_some() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"evaluated series pushed inside a raw series".into(),
|
||||
@@ -948,24 +873,17 @@ impl RangeEvaluator {
|
||||
return self.close_series();
|
||||
}
|
||||
// Later runs only hold samples after `last_ts`, so every point up to it is decided.
|
||||
// The samples are shifted onto the evaluation timeline by the selector offset, so the
|
||||
// ready point is on that timeline too.
|
||||
self.evaluate(Some(
|
||||
i128::from(last_ts) + i128::from(self.window.offset_ms),
|
||||
))?;
|
||||
return self.emit();
|
||||
}
|
||||
// A closing chunk holding no position: there is nothing to ingest, but the samples the
|
||||
// earlier deliveries left retained still decide the windows that follow them, so the close
|
||||
// finishes them rather than ending the series on the spot.
|
||||
// An empty close still has to evaluate the windows over earlier deliveries' samples.
|
||||
debug_assert!(last, "an empty chunk that is not last is rejected above");
|
||||
self.close_series()
|
||||
}
|
||||
|
||||
/// Evaluates the rest of the series of the last input chunk and closes it.
|
||||
///
|
||||
/// The rows still buffered are handed out here as one chunk, and the chunk that sees nothing
|
||||
/// behind it carries `is_last`.
|
||||
/// Evaluates the rest of the current series and hands out its closing chunk.
|
||||
fn close_series(&mut self) -> Result<Option<EvaluatedChunk>> {
|
||||
self.evaluate(None)?;
|
||||
self.series
|
||||
@@ -975,14 +893,8 @@ impl RangeEvaluator {
|
||||
self.emit()
|
||||
}
|
||||
|
||||
/// Hands out the rows buffered so far as one chunk, and closes the series when nothing is left.
|
||||
///
|
||||
/// The chunk holds every row decided since the last hand-out, in one go and in one [`Series`]:
|
||||
/// several runs of positions may sit inside it, separated by stretches holding no value, and
|
||||
/// the axis names them. A position decided to hold none costs no row, so it lies between the
|
||||
/// runs rather than inside one. `is_last` closes the series, and a series always closes exactly
|
||||
/// once: on the chunk that carries its last rows, or on an empty chunk after it when no row is
|
||||
/// left.
|
||||
/// Hands out the rows buffered since the last hand-out as one chunk. When the series is
|
||||
/// closing, that chunk carries `is_last`, and is empty if no row is left.
|
||||
fn emit(&mut self) -> Result<Option<EvaluatedChunk>> {
|
||||
let Some(state) = self.series.as_ref() else {
|
||||
return Ok(None);
|
||||
@@ -1000,8 +912,6 @@ impl RangeEvaluator {
|
||||
Ok(None)
|
||||
};
|
||||
};
|
||||
// The builder addresses every position it hands out, so the chunk's bounds come from the
|
||||
// axis itself: `first_position` is where it starts, and `last_position` where it ends.
|
||||
let start = series
|
||||
.time
|
||||
.first_position()
|
||||
@@ -1009,7 +919,6 @@ impl RangeEvaluator {
|
||||
let end = series.time.last_position().map_or(start, |last| last + 1);
|
||||
debug_assert!(start >= emitted_end, "a chunk never goes back");
|
||||
if closing {
|
||||
// The buffer was drained into this chunk, so nothing of the series is left behind it.
|
||||
self.series = None;
|
||||
EvaluatedChunk::try_new(series, true).map(Some)
|
||||
} else {
|
||||
@@ -1101,25 +1010,15 @@ impl RangeEvaluator {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Appends the chunk in bulk when every field is an entirely present float column.
|
||||
///
|
||||
/// Returns `false` when a condition of the per-sample path applies, so the caller can run it.
|
||||
/// Only the shapes that path alone can read do: a field holding native histogram samples or
|
||||
/// mixed floats and histograms -- `dense()` reports [`DenseSamplesRef::Mixed`] for the latter,
|
||||
/// keeping its windows on the histogram path where the mixed-window rules decide the result --
|
||||
/// and a column with missing samples, which are absent rows rather than values.
|
||||
///
|
||||
/// A selector offset and a stale marker do not: the shift and the rows the marker drops are
|
||||
/// applied here, over the columns, instead of handing the chunk to the per-sample loop. The
|
||||
/// search for a marker is one short-circuiting pass, the same pass the loop would have made.
|
||||
/// Appends the chunk in bulk when every field is a float column without missing samples.
|
||||
/// Returns `false`, appending nothing, when the per-sample path has to run instead: a field
|
||||
/// holds histograms (including [`DenseSamplesRef::Mixed`]) or missing samples.
|
||||
fn ingest_in_bulk(
|
||||
&mut self,
|
||||
timestamps: &[i64],
|
||||
fields: &SeriesFields,
|
||||
drop_stale: bool,
|
||||
) -> Result<bool> {
|
||||
// Lengths are checked by `check_chunk` for raw input and by `push_series` for evaluated
|
||||
// input, so only the shape of the columns is decided here.
|
||||
let mut columns = Vec::with_capacity(fields.len());
|
||||
for field in fields.iter() {
|
||||
let Some(DenseSamplesRef::Float(values)) = field.dense() else {
|
||||
@@ -1130,9 +1029,7 @@ impl RangeEvaluator {
|
||||
}
|
||||
columns.push(values.values().as_ref());
|
||||
}
|
||||
// A stale marker drops its whole row, so which rows go is decided before anything is
|
||||
// retained. A chunk holding none -- the common case -- is judged by one scan that stops at
|
||||
// the first marker and then leaves the columns as they are.
|
||||
// A stale marker in any field drops its whole row.
|
||||
let stale_rows = if drop_stale
|
||||
&& columns
|
||||
.iter()
|
||||
@@ -1156,11 +1053,8 @@ impl RangeEvaluator {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Retains one chunk of entirely present float columns.
|
||||
///
|
||||
/// `stale` marks the rows a stale marker drops, `None` when the chunk holds none. The retained
|
||||
/// samples are the chunk's rows less those, on the evaluation timeline: the selector offset
|
||||
/// shifts them, and only a chunk that needs neither keeps the incoming timestamps as they are.
|
||||
/// Retains one chunk of entirely present float columns, shifted by the selector offset and
|
||||
/// without the rows `stale` marks.
|
||||
fn append_float_chunk(
|
||||
&mut self,
|
||||
timestamps: &[i64],
|
||||
@@ -1169,9 +1063,6 @@ impl RangeEvaluator {
|
||||
) -> Result<()> {
|
||||
let offset_ms = self.window.offset_ms;
|
||||
if offset_ms == 0 && stale.is_none() {
|
||||
// The source timestamps, which `RawTimestamps` already validated as increasing and
|
||||
// which the frame widened into this array without narrowing: nothing to shift, nothing
|
||||
// to check, and the two appends become two `memcpy`s.
|
||||
for (field, values) in self.fields.iter_mut().zip(columns) {
|
||||
field.push_bulk(timestamps, values);
|
||||
}
|
||||
@@ -1187,8 +1078,7 @@ impl RangeEvaluator {
|
||||
if stale.is_some_and(|stale| stale[row]) {
|
||||
continue;
|
||||
}
|
||||
// Like RangeManipulate, any kept sample whose shifted time leaves i64 fails the series,
|
||||
// whichever path retains it.
|
||||
// Like RangeManipulate, any kept sample whose shifted time leaves i64 fails the series.
|
||||
let Some(shifted_timestamp) = timestamp.checked_add(offset_ms) else {
|
||||
self.bulk_scratch = BulkScratch {
|
||||
timestamps: shifted,
|
||||
@@ -1306,9 +1196,8 @@ impl RangeEvaluator {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a sample at `timestamp` on the evaluation timeline lies in the window of a point
|
||||
/// this evaluator decides: a window ending at `E` reads `(E - range - before, E + after]`, and
|
||||
/// only the first point's window is read when the result is replayed.
|
||||
/// Whether a sample at `timestamp` on the evaluation timeline lies in the window of a grid
|
||||
/// point this evaluator reads: a window ending at `E` reads `(E - range - before, E + after]`.
|
||||
fn decided_window_reads(&self, timestamp: i64) -> bool {
|
||||
let (before, after) = self.window.modifier.map_or((0, 0), |modifier| {
|
||||
(
|
||||
@@ -1322,8 +1211,6 @@ impl RangeEvaluator {
|
||||
Replay::Once | Replay::EveryPoint => 1,
|
||||
};
|
||||
let (start, step) = (i128::from(spec.start_ms), i128::from(spec.step_ms));
|
||||
// The window ends that read the sample are those in `[timestamp - after, timestamp +
|
||||
// range + before)`; the first grid point at or after the lower bound decides.
|
||||
let lowest = i128::from(timestamp) - after;
|
||||
let highest = i128::from(timestamp) + i128::from(self.window.range_ms) + before;
|
||||
let first = if lowest <= start {
|
||||
@@ -1341,16 +1228,13 @@ impl RangeEvaluator {
|
||||
let state = self.series.as_mut().expect("checked by check_chunk");
|
||||
let spec = self.grid.spec();
|
||||
let grid = self.grid.timestamps().map_err(external)?;
|
||||
// A modifier also reads samples up to the lookback ahead of the window start, so they are
|
||||
// kept that much longer.
|
||||
let before = self
|
||||
.window
|
||||
.modifier
|
||||
.map_or(0, |modifier| i128::from(modifier.before_ms()));
|
||||
// `smoothed` interpolates the window end with the first sample at or after it, which can
|
||||
// arrive up to the lookback later. A point is decided once every field holds a sample at
|
||||
// or after it, or once the lookback past it has arrived. The input's last row does not say
|
||||
// that alone: a stale row is dropped, and a field can hold no value in it.
|
||||
// `smoothed` interpolates the window end with the first sample at or after it, so a point
|
||||
// is ready once every field holds such a sample or the input is a lookback past it. The
|
||||
// input's last row alone does not tell: a stale row is dropped and a field may be missing.
|
||||
let ready = match (ready, self.window.modifier) {
|
||||
(Some(ready), Some(RangeModifier::Smoothed { lookback_ms })) => {
|
||||
let held = self
|
||||
@@ -1394,16 +1278,14 @@ impl RangeEvaluator {
|
||||
if ready.is_some_and(|ready| i128::from(eval_ts) > ready) {
|
||||
break;
|
||||
}
|
||||
// No retained sample: every point from here on is decided too. A sample that still
|
||||
// has to arrive lies beyond the window of every one of them, so none can gain a value.
|
||||
// No retained sample: no later point can gain a value either.
|
||||
let Some(earliest) = earliest else {
|
||||
empty_tail = true;
|
||||
break;
|
||||
};
|
||||
if earliest > eval_ts {
|
||||
// Skip the points whose windows end before the earliest sample. A smoothed window
|
||||
// reads past its end, but without a sample at or before its end it has no result,
|
||||
// as Prometheus returns nothing when the first sample is after the end.
|
||||
// has no result then either: Prometheus needs a sample at or before its end.
|
||||
let step = i128::from(spec.step_ms);
|
||||
let steps = (i128::from(earliest) - i128::from(spec.start_ms) + step - 1) / step;
|
||||
state.cursor = usize::try_from(steps).map_or(grid.len(), |i| i.min(grid.len()));
|
||||
@@ -1424,14 +1306,9 @@ 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.
|
||||
//
|
||||
// Histograms are retained in time order, so the first one still ahead of the
|
||||
// window head decides: a later one cannot be inside this window if this one
|
||||
// is not. The check runs only when a batch kernel is set, so a function
|
||||
// without one never pays for it.
|
||||
// The batch kernel reads floats only, so a window holding a native histogram
|
||||
// flushes the batch and goes through the per-window path. Histograms are in
|
||||
// time order, so checking the first one past the head is enough.
|
||||
let histogram_window = self.batch.is_some()
|
||||
&& self.fields.iter().any(|field| {
|
||||
field.histograms.get(field.histogram_head).is_some_and(
|
||||
@@ -1499,11 +1376,8 @@ impl RangeEvaluator {
|
||||
&mut self.batch_calls,
|
||||
)?;
|
||||
}
|
||||
// A point is decided once it has been evaluated, once its window can no longer gain a
|
||||
// sample, or -- at the end of the series or of what the input has reached -- once no
|
||||
// retained sample reaches it. The last case is what keeps a long empty stretch cheap: the
|
||||
// loop stops at the first such point instead of walking the rest of the grid, and none of
|
||||
// the points behind it can gain a value, so the cursor skips them.
|
||||
// With nothing retained, the ready points after the cursor are all empty; skip them
|
||||
// instead of walking the grid.
|
||||
if empty_tail && matches!(self.replay, Replay::PerPoint) {
|
||||
let mut decided = state.cursor;
|
||||
if let Some(ready) = ready {
|
||||
@@ -1522,9 +1396,8 @@ impl RangeEvaluator {
|
||||
);
|
||||
let mut drains_samples = false;
|
||||
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.
|
||||
// An anchored selector can skip past the one point it reads.
|
||||
// Past the last window read, samples are still ingested so the overflow and
|
||||
// histogram checks do not depend on chunking, but none are kept.
|
||||
if state.cursor >= points_read {
|
||||
field.head = field.timestamps.len();
|
||||
field.histogram_head = field.histograms.len();
|
||||
@@ -1604,13 +1477,9 @@ impl RowEvaluator<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rejects a modifier on a function Prometheus does not allow it with, as Prometheus rejects the
|
||||
/// query (`AnchoredSafeFunctions`, `SmoothedSafeFunctions`), and on evaluated input, which reads
|
||||
/// no raw samples around its windows.
|
||||
///
|
||||
/// `pub(crate)` because it is a rule about the input's schema and the window alone, so the native
|
||||
/// route's admission predicate (`native_tree_supported`) asks it rather than a second copy of it,
|
||||
/// the way it asks [`fold_offset`].
|
||||
/// Rejects a modifier on a function Prometheus does not allow it with
|
||||
/// (`AnchoredSafeFunctions`, `SmoothedSafeFunctions`), and on evaluated input. Shared with the
|
||||
/// native admission predicate.
|
||||
pub(crate) fn check_modifier(
|
||||
input: &SeriesSchema,
|
||||
modifier: RangeModifier,
|
||||
@@ -1656,10 +1525,7 @@ pub(crate) fn check_modifier(
|
||||
}
|
||||
|
||||
/// The offset samples are shifted by: the selector offset, or for `@` the offset that places
|
||||
/// the anchored window at the first grid point.
|
||||
///
|
||||
/// `pub(crate)` because whether it fits is decided from the grid and the window alone, so the
|
||||
/// native route's admission predicate asks the same arithmetic rather than a second copy of it.
|
||||
/// the anchored window at the first grid point. Shared with the native admission predicate.
|
||||
pub(crate) fn fold_offset(grid: GridSpec, window: RangeWindow) -> Result<i64> {
|
||||
let Some(anchor) = window.anchor_ms else {
|
||||
return Ok(window.offset_ms);
|
||||
@@ -1675,18 +1541,9 @@ pub(crate) fn fold_offset(grid: GridSpec, window: RangeWindow) -> Result<i64> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks that `predict_linear` can read the instant of every point of `grid` once shifted by
|
||||
/// `fold_offset`.
|
||||
///
|
||||
/// Unlike every other range function, which reads the window a grid point opens alone,
|
||||
/// `predict_linear` reads the instant it reports as well, and reports it shifted by the fold
|
||||
/// offset. The first and the last point are the ones checked: the shift is the same at every point
|
||||
/// and the grid's points are ordered, so what fits at both ends fits between them.
|
||||
///
|
||||
/// The refusal is arithmetic rather than shape, but it is decided by the grid and the window alone,
|
||||
/// which is why the native route's admission predicate reaches it too
|
||||
/// (`native_tree_supported`): a query refused only here has to keep the plan it had instead of
|
||||
/// failing while its runtime is built.
|
||||
/// Checks that every evaluation instant of `grid`, shifted by `fold_offset`, fits in i64;
|
||||
/// `predict_linear` reads it. Checking both ends suffices. Shared with the native admission
|
||||
/// predicate, so a query refused here keeps its legacy plan instead of failing at runtime.
|
||||
pub(crate) fn predict_linear_instants(grid: GridSpec, fold_offset: i64) -> Result<()> {
|
||||
let last = i128::from(grid.start_ms) + i128::from(grid.step_ms) * (i128::from(grid.len) - 1);
|
||||
for eval_ts in [i128::from(grid.start_ms), last] {
|
||||
|
||||
@@ -12,11 +12,8 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Float range-vector functions as window kernels.
|
||||
//!
|
||||
//! Each kernel follows the Prometheus function of the same name, including its floating point
|
||||
//! operation order. Arithmetic that GreptimeDB's range UDFs compute the same way is shared with
|
||||
//! them.
|
||||
//! Float range-vector functions as window kernels. Each kernel follows the Prometheus function
|
||||
//! of the same name, including its floating point operation order.
|
||||
|
||||
use crate::functions::{EdgeKind, count_edges, extremum, instant_delta, kahan_inc};
|
||||
use crate::go_sort;
|
||||
@@ -89,26 +86,15 @@ impl RangeFunction {
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the evaluator has to index counter resets for this function.
|
||||
///
|
||||
/// This must hold for exactly the kernels that read [`FloatWindow::counter_resets`], which is
|
||||
/// the same as saying `IS_COUNTER` in `extrapolated_rate`: `rate` and `increase`. A kernel
|
||||
/// that corrects counters without the index being maintained would silently drop every
|
||||
/// correction, so a new counter function has to be added here as well.
|
||||
///
|
||||
/// It governs both readers of the index: the per-window kernel above, and the batch kernel,
|
||||
/// which reads [`FloatWindows::resets_of`]. When it returns `false`, `resets` stays empty and
|
||||
/// `resets_of` yields nothing, so a batch kernel for a counter function would skip every
|
||||
/// correction and report `delta`-like values.
|
||||
/// Whether the evaluator has to index counter resets for this function. Must hold for
|
||||
/// exactly the kernels that read [`FloatWindow::counter_resets`] or
|
||||
/// [`FloatWindows::resets_of`]; otherwise they see no resets and silently skip corrections.
|
||||
pub(crate) fn indexes_counter_resets(self) -> bool {
|
||||
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.
|
||||
/// The batch form of this function, when it has one; otherwise the evaluator uses
|
||||
/// [`Self::kernel`] per window.
|
||||
pub(crate) fn batch_kernel(self) -> Option<BatchKernel> {
|
||||
match self {
|
||||
Self::Rate => Some(Box::new(extrapolated_rate_batch::<true, true>)),
|
||||
@@ -194,10 +180,8 @@ impl RangeFunction {
|
||||
|
||||
impl RangeFunction {
|
||||
/// Returns the kernel computing this function over windows read with `modifier`, for the
|
||||
/// functions the modifier is allowed with (`RangeEvaluator::try_new` checks that).
|
||||
///
|
||||
/// The window holds the samples the modifier reads around it as well, on the evaluation
|
||||
/// timeline, so the window itself is `(eval_ts - range_ms, eval_ts]`.
|
||||
/// functions the modifier is allowed with (`RangeEvaluator::try_new` checks that). The window
|
||||
/// also holds the samples the modifier reads around `(eval_ts - range_ms, eval_ts]`.
|
||||
pub(crate) fn modified_kernel(self, modifier: RangeModifier) -> WindowKernel {
|
||||
let smoothed = matches!(modifier, RangeModifier::Smoothed { .. });
|
||||
match self {
|
||||
@@ -398,11 +382,7 @@ fn extrapolated_rate<const IS_COUNTER: bool, const IS_RATE: bool>(
|
||||
}
|
||||
|
||||
/// The arithmetic of [`extrapolated_rate`], over a window's endpoints and the previous values of
|
||||
/// its resets.
|
||||
///
|
||||
/// Both callers reach it: the per-window form with a slice of the field, the batch form with the
|
||||
/// field's own arrays. Keeping it in one place is what holds their results equal; the two differ
|
||||
/// only in how they find the endpoints.
|
||||
/// its resets. Shared by the per-window and batch forms so their results stay equal.
|
||||
fn extrapolated_rate_of(
|
||||
(first_t, last_t): (i64, i64),
|
||||
(first, last): (f64, f64),
|
||||
@@ -414,8 +394,7 @@ fn extrapolated_rate_of(
|
||||
) -> Option<f64> {
|
||||
let mut result = last - first;
|
||||
if is_counter {
|
||||
// The same additions in the same order as scanning the window for resets, reached
|
||||
// through the evaluator's per-field reset index instead of the whole window.
|
||||
// Same additions in the same order as scanning the window for resets.
|
||||
result = resets.fold(result, |result, previous_value| result + previous_value);
|
||||
}
|
||||
let zero_point = (is_counter && result > 0.0 && first >= 0.0).then(|| first / result);
|
||||
@@ -437,12 +416,8 @@ fn extrapolated_rate_of(
|
||||
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.
|
||||
/// The batch form of [`extrapolated_rate`] over consecutive windows of one field; bit-identical
|
||||
/// to calling the per-window form once per point.
|
||||
pub(crate) fn extrapolated_rate_batch<const IS_COUNTER: bool, const IS_RATE: bool>(
|
||||
batch: &FloatWindows<'_>,
|
||||
out: &mut Vec<Option<f64>>,
|
||||
@@ -470,12 +445,9 @@ pub(crate) fn extrapolated_rate_batch<const IS_COUNTER: bool, const IS_RATE: boo
|
||||
}
|
||||
}
|
||||
|
||||
/// The span one window's extrapolation factor is measured over.
|
||||
///
|
||||
/// A float window has one anchor: its first sample starts both the interval the increase was
|
||||
/// sampled over and the interval the average sample distance is measured over. A native histogram
|
||||
/// counter can have two, because a `start_timestamp` inside the window is a synthetic zero the
|
||||
/// sampled interval starts at, while the average sample distance still belongs to the real samples.
|
||||
/// The span one window's extrapolation factor is measured over. A float window starts both
|
||||
/// intervals at its first sample; a native histogram counter with a `start_timestamp` inside the
|
||||
/// window starts the sampled interval at that synthetic zero instead.
|
||||
pub(super) struct ExtrapolationSpan {
|
||||
/// The first sample, or a native histogram's synthetic zero.
|
||||
pub sampled_from: i64,
|
||||
@@ -488,18 +460,10 @@ pub(super) struct ExtrapolationSpan {
|
||||
pub samples_minus_one: usize,
|
||||
}
|
||||
|
||||
/// 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: it is the share of
|
||||
/// the sampled interval that lies before `span.sampled_from`, so `0` says the counter's zero point
|
||||
/// is `span.sampled_from` itself, which is what a synthetic zero is.
|
||||
///
|
||||
/// Floats and native histograms both come through here, and this is the only place the factor is
|
||||
/// computed; the two routes differ in the anchors they read, never in the arithmetic. The one
|
||||
/// deliberate difference is not in the formula: a zero `sampled_interval` makes this function
|
||||
/// answer `1.0` (`1 / range` for a rate), which is the identity a float window wants to multiply
|
||||
/// its increase by, while the histogram caller answers no value at all before calling this. Its
|
||||
/// buckets are all zero there, and an `Inf` or `NaN` rate would only poison what consumes it
|
||||
/// downstream; a float window has no such leftovers to hand on.
|
||||
/// The factor `extrapolatedRate` scales the sampled increase by, for floats and native
|
||||
/// histograms alike. `zero_point` is the first value over the increase, given only when a counter
|
||||
/// is extrapolated to zero; `0` puts the zero point at `span.sampled_from`, as a synthetic zero
|
||||
/// does. A zero sampled interval answers `1.0` (`1 / range` for a rate).
|
||||
pub(super) fn extrapolation_factor(
|
||||
span: ExtrapolationSpan,
|
||||
eval_ts: i64,
|
||||
@@ -514,11 +478,7 @@ pub(super) fn extrapolation_factor(
|
||||
last,
|
||||
samples_minus_one,
|
||||
} = span;
|
||||
// Millisecond differences in 64-bit arithmetic: widening to `i128` and narrowing back with
|
||||
// `as f64` compiles to a call to the `__floattidf` builtin instead of an instruction, once per
|
||||
// grid point per series. The subtractions wrap, which is what Go's `int64` arithmetic does, so
|
||||
// an out-of-range window start produces the same value Prometheus computes rather than a
|
||||
// clamped one; real timestamps are nowhere near that range, where both agree.
|
||||
// Wrapping i64 arithmetic matches Go's int64 and avoids the slow i128-to-f64 conversion.
|
||||
let range_start = eval_ts.wrapping_sub(range_ms);
|
||||
let mut duration_to_start = average_from.wrapping_sub(range_start) as f64 / 1000.0;
|
||||
let mut duration_to_end = eval_ts.wrapping_sub(last) as f64 / 1000.0;
|
||||
@@ -693,10 +653,6 @@ impl std::hash::Hash for RangeFunction {
|
||||
mod tests {
|
||||
use super::{ExtrapolationSpan, extrapolation_factor};
|
||||
|
||||
/// One window as both range-function routes read it: `sampled_from` starts the interval the
|
||||
/// increase was sampled over, `average_from` the interval the average sample distance is
|
||||
/// measured over. They are the same timestamp except for a native histogram counter with a
|
||||
/// synthetic zero, whose sampled interval starts at the zero.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Window {
|
||||
sampled_from: i64,
|
||||
@@ -711,8 +667,7 @@ mod tests {
|
||||
}
|
||||
|
||||
impl Window {
|
||||
/// The factor the float route computes. A float sample carries no start timestamp, so its
|
||||
/// single anchor starts both intervals and `sampled_from` plays no part.
|
||||
/// The float route ignores `sampled_from`: it has no start timestamp.
|
||||
fn as_float(self) -> f64 {
|
||||
extrapolation_factor(
|
||||
ExtrapolationSpan {
|
||||
@@ -729,8 +684,6 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
/// The factor the native histogram route computes, with both anchors as its call site
|
||||
/// builds them.
|
||||
fn as_histogram(self) -> f64 {
|
||||
extrapolation_factor(
|
||||
ExtrapolationSpan {
|
||||
@@ -748,15 +701,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Both routes reach one function, so their factors can only differ in how each fills the span.
|
||||
/// A window without a synthetic zero is filled the same way by both, and the factors have to
|
||||
/// agree to the bit. A window whose sampled anchor is a synthetic zero is the one shape the two
|
||||
/// fills answer differently, and pinning both answers there is what puts the anchors, not only
|
||||
/// the arithmetic, under the assertions.
|
||||
#[test]
|
||||
fn both_routes_compute_one_extrapolation_factor() {
|
||||
// Evaluation at 6500ms over a 6000ms range: the window opens at 500ms and the last sample
|
||||
// sits 1500ms inside its closed end.
|
||||
let windows = [
|
||||
Window {
|
||||
sampled_from: 2_000,
|
||||
@@ -831,15 +777,9 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// A synthetic zero at 2000ms with real samples at 2500ms and 4500ms, evaluated at 7000ms
|
||||
// over a 6000ms range, gives the histogram route a sampled interval of 2500ms and the
|
||||
// 2000ms average interval between the real samples. The end is 2500ms from the range end,
|
||||
// past 1.1 * 2000ms, so it falls back to half the average interval; the start is 1500ms
|
||||
// from the range start, inside that threshold, and the counter's zero point then takes it
|
||||
// to 0: (2500 + 0 + 1000) / 2500 = 1.4. A float sample carries no start timestamp, so the
|
||||
// float route samples the same 2000ms it measures its average over and answers
|
||||
// (2000 + 0 + 1000) / 2000 = 1.5. The two fills disagree, which is what makes reading one
|
||||
// anchor for the other observable rather than a change of arguments with no effect.
|
||||
// Synthetic zero at 2000ms, samples at 2500ms and 4500ms: the end falls back to half the
|
||||
// 2000ms average interval and the zero point takes the start to 0, so the histogram route
|
||||
// answers (2500 + 0 + 1000) / 2500 = 1.4 and the float route (2000 + 0 + 1000) / 2000.
|
||||
let two_anchor = Window {
|
||||
sampled_from: 2_000,
|
||||
average_from: 2_500,
|
||||
@@ -853,14 +793,8 @@ mod tests {
|
||||
};
|
||||
assert_eq!(two_anchor.as_histogram().to_bits(), 1.4f64.to_bits());
|
||||
assert_eq!(two_anchor.as_float().to_bits(), 1.5f64.to_bits());
|
||||
// Both directions an anchor can be replaced in are pinned, so neither the divisor nor the
|
||||
// end's fallback can absorb the swap. Reading the average anchor for the sampled one
|
||||
// shortens the sampled interval to 2000ms and answers 1.5; reading the sampled anchor for
|
||||
// the average one widens the average interval to 2500ms, which puts the end back inside the
|
||||
// threshold so it stays at 2500ms, and answers 2.0. The zero point takes the start to 0
|
||||
// whatever the average interval says, so the end has to fall past one threshold and inside
|
||||
// the other for that: an end falling back under both average intervals, or under neither,
|
||||
// answers the same either way and pins nothing.
|
||||
// Each swapped anchor gives a distinct answer: 1.5 with the average anchor read for the
|
||||
// sampled one, 2.0 the other way round (the end stays inside the wider threshold).
|
||||
assert_eq!(
|
||||
Window {
|
||||
sampled_from: two_anchor.average_from,
|
||||
@@ -881,21 +815,11 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A synthetic zero puts the sampled anchor before the average anchor, and no float window
|
||||
/// describes that: a float window starting at the zero would move its average interval there
|
||||
/// too. The geometry is chosen so the two answers differ -- measuring the average from the
|
||||
/// synthetic zero answers 1.75 where the real samples answer 1.25 -- so a swapped anchor cannot
|
||||
/// pass by agreeing with itself.
|
||||
#[test]
|
||||
fn a_synthetic_zero_moves_only_the_sampled_anchor() {
|
||||
// A zero at 1000ms, real samples at 2000ms and 3000ms, evaluated at 4500ms over a 4000ms
|
||||
// range: the window opens at 500ms and the range ends 1500ms past the last sample. The
|
||||
// sampled interval runs 2000ms from the zero, the average interval is the 1000ms between
|
||||
// the real samples, so both ends lie past 1.1 * 1000ms and fall back to half of it, and the
|
||||
// counter's zero point then takes the start to 0: (2000 + 0 + 500) / 2000 = 1.25. Measuring
|
||||
// the average from the synthetic zero instead makes the average interval 2000ms, leaves
|
||||
// both ends inside 1.1 * 2000ms and answers (2000 + 0 + 1500) / 2000 = 1.75. Both are
|
||||
// pinned below, so swapping the anchors fails here instead of agreeing with itself.
|
||||
// Zero at 1000ms, samples at 2000ms and 3000ms: both ends fall back to half the 1000ms
|
||||
// average interval and the zero point takes the start to 0: (2000 + 0 + 500) / 2000.
|
||||
// Averaging from the zero instead gives (2000 + 0 + 1500) / 2000 = 1.75.
|
||||
let window = Window {
|
||||
sampled_from: 1_000,
|
||||
average_from: 2_000,
|
||||
@@ -917,8 +841,6 @@ mod tests {
|
||||
.to_bits(),
|
||||
(1.25f64 / 4.0).to_bits()
|
||||
);
|
||||
// The answer a swapped average anchor gives, pinned so that this geometry stays one the
|
||||
// assertions above can tell apart.
|
||||
assert_eq!(
|
||||
Window {
|
||||
average_from: 1_000,
|
||||
@@ -928,12 +850,9 @@ mod tests {
|
||||
.to_bits(),
|
||||
1.75f64.to_bits()
|
||||
);
|
||||
// The float route on the same numbers starts its sampled interval at the first sample,
|
||||
// which is a different window: 1.5 rather than 1.25.
|
||||
assert_eq!(window.as_float().to_bits(), 1.5f64.to_bits());
|
||||
|
||||
// One real sample behind the zero leaves no average interval, so neither end is
|
||||
// extrapolated and the factor is the identity.
|
||||
// One real sample leaves no average interval: the factor is the identity.
|
||||
let single = Window {
|
||||
sampled_from: 1_000,
|
||||
average_from: 2_000,
|
||||
|
||||
@@ -80,10 +80,10 @@ pub(super) fn evaluate(
|
||||
),
|
||||
);
|
||||
}
|
||||
// The functions that read only the floats of a mixed window ignore its histograms, which is
|
||||
// what the existing planner tells the client with an info. The set is the one that path lists
|
||||
// as `FloatOnly`; the experimental functions this crate also has carry no message there, so
|
||||
// they stay silent rather than inventing one.
|
||||
// Float-only functions ignore the histograms of a mixed window and say so with an info, as
|
||||
// the legacy planner's `FloatOnly` set does. `mad_over_time` and `ts_of_{min,max}_over_time`
|
||||
// also ignore them but record nothing here, although Prometheus emits
|
||||
// HistogramIgnoredInMixedRange for them too (`funcMadOverTime`, `compareOverTime`).
|
||||
if floats.is_some()
|
||||
&& matches!(
|
||||
function,
|
||||
@@ -158,9 +158,6 @@ pub(super) fn evaluate(
|
||||
} else {
|
||||
HistogramAggregate::Avg
|
||||
};
|
||||
// The hints are read from the window's own histograms, so nothing is cloned for the
|
||||
// check; the fold below copies each histogram in turn and folds it into the
|
||||
// accumulator it keeps.
|
||||
if has_contradictory_reset_hints(histograms.iter().map(|(_, h)| h)) {
|
||||
record_warning(
|
||||
collector,
|
||||
@@ -170,9 +167,7 @@ pub(super) fn evaluate(
|
||||
),
|
||||
);
|
||||
}
|
||||
// The fold reports both answers itself: a `None` is the mixed-bucket drop, and the
|
||||
// flag is the reconciliation its own adds already observed. Re-walking the pairs to
|
||||
// learn either would double the histogram work of every window.
|
||||
// `None` is the mixed-bucket drop; the flag reports a custom-bucket reconciliation.
|
||||
let (result, custom_reconciled) =
|
||||
sum_or_avg(op, histograms.iter().map(|(_, h)| Ok(h.clone())))?;
|
||||
if result.is_none() {
|
||||
@@ -245,19 +240,15 @@ pub(super) fn evaluate(
|
||||
if *last_ts <= effective_first_ts {
|
||||
return Ok(None);
|
||||
}
|
||||
// A synthetic zero *is* the counter's zero point, so nothing is extrapolated before it
|
||||
// and `zero_point` says so with `0`; the counter instead extrapolates towards zero from
|
||||
// its first real sample, and only when that sample is not itself negative.
|
||||
// A synthetic zero is the counter's zero point, so nothing is extrapolated before it.
|
||||
let zero_point = if synthetic_zero.is_some() {
|
||||
Some(0.0)
|
||||
} else {
|
||||
(is_counter && result.count > 0.0 && first.count >= 0.0)
|
||||
.then(|| first.count / result.count)
|
||||
};
|
||||
// The sampled interval runs from the synthetic zero while the average interval is
|
||||
// measured between the real samples, as `native_extrapolated_rate` does: they are two
|
||||
// different spans, and taking one for the other shifts the average by a whole sample
|
||||
// interval.
|
||||
// The sampled interval starts at the synthetic zero; the average interval stays
|
||||
// between the real samples.
|
||||
let factor = extrapolation_factor(
|
||||
ExtrapolationSpan {
|
||||
sampled_from: effective_first_ts,
|
||||
@@ -285,7 +276,6 @@ pub(super) fn evaluate(
|
||||
Some(GridSample::Histogram(Box::new(result)))
|
||||
}
|
||||
Irate | Idelta => {
|
||||
// The annotations read the window before `last_two` consumes it.
|
||||
let had_floats = floats.is_some();
|
||||
record_mixed_last_two(collector, function, floats.as_ref(), histograms);
|
||||
let tail_histograms = &histograms[histograms.len().saturating_sub(2)..];
|
||||
@@ -311,8 +301,7 @@ pub(super) fn evaluate(
|
||||
}
|
||||
result
|
||||
}
|
||||
// Mixed windows, and rates over fewer than two histograms. The mixed warning was already
|
||||
// recorded above for every function that reaches here, so this branch only answers.
|
||||
// Mixed windows (already warned about above), and rates over too few histograms.
|
||||
SumOverTime | AvgOverTime | Rate | Increase | Delta => None,
|
||||
})
|
||||
}
|
||||
@@ -371,12 +360,8 @@ fn has_contradictory_reset_hints<'a>(
|
||||
saw_counter && saw_not_counter
|
||||
}
|
||||
|
||||
/// The info a `rate`/`increase`/`delta` window owes when adjacent histograms carry different
|
||||
/// custom bucket bounds and the fold has to reconcile them.
|
||||
///
|
||||
/// The check compares bounds; it does not add the pair. The fold that follows does that work, and
|
||||
/// repeating it here would double the histogram arithmetic of every window. This is the same
|
||||
/// per-pair check the existing planner's counter UDF makes.
|
||||
/// Warns when a counter function reads a gauge histogram, or a gauge function reads a counter
|
||||
/// histogram at either end of the window.
|
||||
fn record_histogram_flavor_warning(
|
||||
collector: Option<&PromqlAnnotationCollector>,
|
||||
function: RangeFunction,
|
||||
@@ -437,8 +422,6 @@ fn record_mixed_last_two(
|
||||
floats: Option<&FloatWindow<'_>>,
|
||||
histograms: &Histograms,
|
||||
) {
|
||||
// Nothing is recorded without a collector, and the walk below exists only to decide whether
|
||||
// something would be.
|
||||
if collector.is_none() {
|
||||
return;
|
||||
}
|
||||
@@ -532,18 +515,9 @@ fn edges(
|
||||
count += match (previous, current) {
|
||||
(Sample::Float(a), Sample::Float(b)) => count_edges(&[a, b], kind),
|
||||
(Sample::Histogram(a), Sample::Histogram(b)) => u64::from(match kind {
|
||||
// `resets` counts the restarts the payload alone does not show. A start
|
||||
// timestamp inside the window witnesses a counter that began again, whose
|
||||
// counts may have grown across the restart, which is the rule `rate` and
|
||||
// `increase` already read.
|
||||
//
|
||||
// A gauge-to-counter edge is deliberately NOT counted, although the existing
|
||||
// planner counts one (`NativeHistogramRangeFloatKind::Resets`). Prometheus
|
||||
// does not: the golden case `resets 25000 0` in `histogram_cases.txt` holds a
|
||||
// gauge sample followed by a counter sample with identical payloads and
|
||||
// expects 0. Where the two disagree the golden wins, because the existing
|
||||
// planner's count there is not a behaviour this route can reproduce and stay
|
||||
// correct.
|
||||
// A start timestamp inside the window also witnesses a reset. A
|
||||
// gauge-to-counter edge is not one, unlike in the legacy planner: Prometheus
|
||||
// answers 0 for golden case `resets 25000 0` in `histogram_cases.txt`.
|
||||
EdgeKind::Resets => {
|
||||
b.detect_counter_reset_shifted(a, previous_ts, timestamp, offset_ms)
|
||||
}
|
||||
@@ -584,9 +558,8 @@ fn last_two<const IS_RATE: bool>(
|
||||
(Sample::Histogram(prev), Sample::Histogram(last)) => {
|
||||
let interval = last_ts - prev_ts;
|
||||
let mut result = last.clone();
|
||||
// `irate` drops the counter's accumulations on a reset the way the existing planner's
|
||||
// `idelta_value` does, start timestamp included; `idelta` is a plain difference and
|
||||
// reads no reset at all.
|
||||
// On a reset (start timestamp included) `irate` takes the last histogram as is;
|
||||
// `idelta` is a plain difference.
|
||||
if !IS_RATE || !last.detect_counter_reset_shifted(prev, prev_ts, last_ts, offset_ms) {
|
||||
if result.uses_custom_buckets() != prev.uses_custom_buckets() {
|
||||
return Ok(None);
|
||||
@@ -614,9 +587,8 @@ fn histogram_rate(
|
||||
let last = &points[points.len() - 1].1;
|
||||
let mut prev = Cow::Borrowed(&points[0].1);
|
||||
let mut uses_custom_buckets = prev.uses_custom_buckets();
|
||||
// A reset between the first two samples makes the first one irrelevant, layout included.
|
||||
// The start timestamps witness a reset the counts alone do not, which is what a restarted
|
||||
// counter looks like when it is already above the previous value.
|
||||
// A reset between the first two samples, by counts or start timestamps, makes the first one
|
||||
// irrelevant, layout included.
|
||||
if is_counter {
|
||||
let (second_ts, second) = &points[1];
|
||||
if second.detect_counter_reset_shifted(&prev, points[0].0, *second_ts, offset_ms) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+29
-98
@@ -62,10 +62,8 @@ pub enum SortOrder {
|
||||
/// `topk(k, ...)` (`top`) or `bottomk(k, ...)` with a constant `k`.
|
||||
///
|
||||
/// At every point each group keeps the `k` largest (or smallest) values, NaN ranking last for
|
||||
/// both; the selected samples keep their series' labels and values. Histogram samples are not
|
||||
/// ranked, as Prometheus ignores them here. Prometheus breaks ties by
|
||||
/// the order its storage returns series in, which is not a property of the series; here ties
|
||||
/// go to the series whose label set sorts first.
|
||||
/// both; histogram samples are ignored, as in Prometheus. Prometheus breaks ties by storage order;
|
||||
/// here ties go to the series whose label set sorts first.
|
||||
pub fn topk(
|
||||
k: f64,
|
||||
top: bool,
|
||||
@@ -86,12 +84,9 @@ pub fn topk_at(
|
||||
series: &[Series],
|
||||
) -> Result<Vec<Series>> {
|
||||
single_field(schema, "topk/bottomk")?;
|
||||
// Validates the series against the schema and its grid; the walk below visits the carried
|
||||
// positions, not the whole grid.
|
||||
grid_points(schema, series)?;
|
||||
let mut order: Vec<usize> = (0..series.len()).collect();
|
||||
// The label pairs of a series are built once: a comparator that compared two metrics would
|
||||
// rebuild both lists per comparison, and the groups read the same lists again.
|
||||
// Built once per series and shared by the sort and the grouping.
|
||||
let mut label_sets: Vec<Vec<(Arc<str>, Arc<str>)>> = series
|
||||
.iter()
|
||||
.map(|item| labels_with_name(&item.metric))
|
||||
@@ -104,18 +99,12 @@ pub fn topk_at(
|
||||
.or_default()
|
||||
.push(index);
|
||||
}
|
||||
// The groups hold what they need, so the label lists are freed before the point walk.
|
||||
label_sets.clear();
|
||||
|
||||
let mut selected: Vec<Vec<(usize, usize)>> = vec![Vec::new(); series.len()];
|
||||
let mut candidates: Vec<(usize, usize, f64)> = Vec::new();
|
||||
// The values of one point, for the partial selection below: ranking them there leaves the
|
||||
// candidates in member order, which is what hands ties to the earlier label set.
|
||||
let mut values: Vec<f64> = Vec::new();
|
||||
for members in groups.values() {
|
||||
// A point no member carries holds no candidate, so only the union of the members'
|
||||
// positions is visited: a hole in the grid never reaches the ranking. Each member reads
|
||||
// through one forward cursor, whose rows only increase as the union walk advances.
|
||||
let mut cursors: Vec<RowCursor<'_>> = members
|
||||
.iter()
|
||||
.map(|&member| series[member].fields.as_slice()[0].cursor())
|
||||
@@ -136,10 +125,7 @@ pub fn topk_at(
|
||||
let Some(k) = k_at(point)? else {
|
||||
continue;
|
||||
};
|
||||
// Which candidates win is the result; the order they were found in is not. The ranking
|
||||
// is a partial selection of the k best values rather than an ordering of the whole
|
||||
// group, and it runs on a copy of the values so that the candidates keep the member
|
||||
// order the ties are resolved in.
|
||||
// Select the k-th value on a copy so `candidates` stays in label order for tie-breaking.
|
||||
let k = k.min(candidates.len());
|
||||
if k == 0 {
|
||||
continue;
|
||||
@@ -150,9 +136,8 @@ pub fn topk_at(
|
||||
values.select_nth_unstable_by(k, |a, b| rank(*a, *b, top));
|
||||
values[k]
|
||||
});
|
||||
// The partition splits the run of values equal to its boundary, while ties go to the
|
||||
// earlier label set: the ones equal to the boundary inside the front are the slots left
|
||||
// for them, and the scan below fills those slots in member order, which is label order.
|
||||
// Values equal to the boundary inside the front are the slots left for ties; the scan
|
||||
// fills them in label order.
|
||||
let mut tied = match boundary {
|
||||
Some(boundary) => values[..k]
|
||||
.iter()
|
||||
@@ -182,10 +167,7 @@ pub fn topk_at(
|
||||
}
|
||||
let mut sorted = points;
|
||||
sorted.sort_unstable();
|
||||
// One builder serves every result series, so each one starts explicitly: only
|
||||
// `begin_series` resets the positions it accepts.
|
||||
builder.begin_series();
|
||||
// The selected positions of one series only increase, so one cursor reads their rows.
|
||||
let mut cursor = series[index].fields.as_slice()[0].cursor();
|
||||
for (point, row) in sorted {
|
||||
builder.push(point, &[cursor_value(&mut cursor, row)?])?;
|
||||
@@ -198,10 +180,9 @@ pub fn topk_at(
|
||||
/// `limitk(k, ...)` with a constant `k`.
|
||||
///
|
||||
/// At every point each group keeps the first `k` series in input order that hold a sample there,
|
||||
/// float or histogram, with their labels and values. Prometheus takes them in the order its
|
||||
/// storage returns series: label order once a query reads several queriers (the head and a
|
||||
/// block), creation order when the TSDB head alone answers it. A caller that wants Prometheus'
|
||||
/// result over persisted data passes the series in label order.
|
||||
/// float or histogram. Prometheus uses storage order: label order across several queriers,
|
||||
/// creation order when the TSDB head alone answers. Callers pass series in label order to match
|
||||
/// Prometheus over persisted data.
|
||||
pub fn limitk(
|
||||
k: f64,
|
||||
grouping: &Grouping,
|
||||
@@ -255,10 +236,8 @@ pub fn limitk(
|
||||
continue;
|
||||
}
|
||||
builder.begin_series();
|
||||
// A series belongs to one group, whose points are visited in order.
|
||||
let mut cursor = series[index].fields.as_slice()[0].cursor();
|
||||
for (point, row) in points {
|
||||
// The sample is moved, not computed, so it goes straight into the result.
|
||||
let sample = cursor.at(row).expect("the axis and the fields are aligned");
|
||||
builder.push_refs(point, &[sample])?;
|
||||
}
|
||||
@@ -271,8 +250,8 @@ pub fn limitk(
|
||||
///
|
||||
/// Keeps whole series: Prometheus derives an offset in `[0, 1)` from the hash of a series' labels
|
||||
/// and keeps the series when the offset is below `r`, or, for a negative `r`, at least `1 + r`.
|
||||
/// Which series are kept does not depend on the grouping, so it is not a parameter. The hash is
|
||||
/// the one of Prometheus' default `stringlabels` build; the other label builds hash differently.
|
||||
/// The result does not depend on the grouping. The hash matches Prometheus' default `stringlabels`
|
||||
/// build; other label builds hash differently.
|
||||
pub fn limit_ratio(ratio: f64, schema: &SeriesSchema, series: &[Series]) -> Result<Vec<Series>> {
|
||||
grid_points(schema, series)?;
|
||||
if ratio.is_nan() {
|
||||
@@ -298,7 +277,6 @@ pub fn limit_ratio(ratio: f64, schema: &SeriesSchema, series: &[Series]) -> Resu
|
||||
item.fields.iter().map(|field| field.cursor()).collect();
|
||||
for (point, index) in item.time.positions() {
|
||||
row.clear();
|
||||
// The samples are moved, not computed, so the row is read and pushed as it stands.
|
||||
for cursor in &mut cursors {
|
||||
row.push(
|
||||
cursor
|
||||
@@ -337,27 +315,16 @@ fn sample_offset(metric: &SeriesLabels) -> f64 {
|
||||
|
||||
/// `scalar(v)`: the value of the only float sample present at each point, NaN otherwise.
|
||||
///
|
||||
/// Native histogram samples are ignored, as Prometheus' `funcScalar` ignores them: they hold no
|
||||
/// float value, and they are not an element either, so they never make a point hold more than one
|
||||
/// sample. A point whose only sample is a histogram therefore answers NaN, a histogram beside one
|
||||
/// float answers that float, and two floats answer NaN.
|
||||
/// Native histogram samples are ignored, as in Prometheus' `funcScalar`: a histogram alone answers
|
||||
/// NaN, a histogram beside one float answers that float.
|
||||
///
|
||||
/// A scalar holds a value at every point of the grid, so its value array is written where the input
|
||||
/// is read rather than staged and rebuilt: the one buffer of values becomes the result's array, and
|
||||
/// the counts that decide between a value and a NaN are dropped before it is handed over. Building
|
||||
/// it therefore costs one `f64` and one count per point and nothing else per point -- no optional
|
||||
/// value, no row index, no second copy of the answer -- which is what the caller reserves for it.
|
||||
/// Costs one `f64` and one count per grid point; the caller reserves exactly that.
|
||||
pub fn scalar(schema: &SeriesSchema, series: &[Series]) -> Result<Series> {
|
||||
single_field(schema, "scalar")?;
|
||||
let (grid, points) = grid_and_points(schema, series)?;
|
||||
// A point no float has reached answers the Go NaN, which is where it starts. The first float of
|
||||
// a point writes its value there; the second takes the point back to NaN, and so does any float
|
||||
// after it, so a point holding more than one float never reads as holding one.
|
||||
let mut values = vec![GO_NAN; points];
|
||||
let mut counts = vec![0u8; points];
|
||||
for item in series {
|
||||
// Walk the rows this series carries: a sparse axis must not be read as its envelope, and
|
||||
// a forward cursor keeps the read proportional to them.
|
||||
let mut field = item.fields.as_slice()[0].cursor();
|
||||
for (point, row) in item.time.positions() {
|
||||
match field.at(row).expect("the axis and the fields are aligned") {
|
||||
@@ -366,17 +333,12 @@ pub fn scalar(schema: &SeriesSchema, series: &[Series]) -> Result<Series> {
|
||||
values[point] = if *count == 0 { value } else { GO_NAN };
|
||||
*count = count.saturating_add(1);
|
||||
}
|
||||
// Neither a histogram nor a position holding no sample is an element of the
|
||||
// vector, so neither decides what the point answers.
|
||||
SampleRef::Histogram(_) | SampleRef::Missing => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The counts have decided every value above; handing them back first leaves the values as the
|
||||
// only per-point buffer alive when the answer is built.
|
||||
drop(counts);
|
||||
let fields = SeriesFields::one(Samples::from_float(Float64Array::from(values)));
|
||||
// Every point of the grid holds a value, so the axis is the whole grid as one run.
|
||||
let time = TimeAxis::Grid(GridRange::try_new(grid, 0, points).map_err(external)?);
|
||||
let empty = SeriesLabels::try_new(None, Vec::new()).map_err(external)?;
|
||||
Series::try_new(schema, empty, time, fields).map_err(external)
|
||||
@@ -388,10 +350,8 @@ pub fn scalar(schema: &SeriesSchema, series: &[Series]) -> Result<Series> {
|
||||
/// a range selector, `labels` come from its matchers as for `absent(v)`; for a subquery
|
||||
/// Prometheus derives no labels.
|
||||
///
|
||||
/// All of it is one label set, so the result is one series. A point where one field is present and
|
||||
/// another is absent keeps its row, with a null in the field that is present; a point where every
|
||||
/// field is present contributes no row, and the axis names the runs of points that do. `None` means
|
||||
/// no point is absent in any field, so no row survives.
|
||||
/// Each field is absent on its own: a field present at a point gets a null there. `None` means
|
||||
/// every field is present at every point.
|
||||
pub fn absent(
|
||||
schema: &SeriesSchema,
|
||||
series: &[Series],
|
||||
@@ -399,11 +359,9 @@ pub fn absent(
|
||||
) -> Result<Option<Series>> {
|
||||
let points = grid_points(schema, series)?;
|
||||
let fields = schema.fields.len();
|
||||
// Each field is absent on its own.
|
||||
let mut present = vec![false; points * fields];
|
||||
for item in series {
|
||||
for (field, samples) in item.fields.iter().enumerate() {
|
||||
// One cursor per field, driven by the positions the axis carries.
|
||||
let mut cursor = samples.cursor();
|
||||
for (point, row) in item.time.positions() {
|
||||
if !matches!(
|
||||
@@ -450,10 +408,9 @@ pub enum MatchOp {
|
||||
/// the first equality matcher of a name sets that label, any other matcher of the name removes
|
||||
/// it, and `__name__` is skipped.
|
||||
///
|
||||
/// Prometheus reads the matchers after TSDB's `PostingsForMatchers` has reordered them in place,
|
||||
/// moving the matchers that narrow the result before those that only subtract from it; that is
|
||||
/// the order users see whenever the storage holds data, and the order used here. It changes the
|
||||
/// result only when a name has both an equality and another matcher.
|
||||
/// The matchers are first reordered as TSDB's `PostingsForMatchers` does in place (narrowing
|
||||
/// matchers before subtracting ones), which Prometheus shows whenever storage holds data. The order
|
||||
/// matters only when a name has both an equality and another matcher.
|
||||
pub fn absent_labels(matchers: &[LabelMatcher]) -> Result<SeriesLabels> {
|
||||
let must_be_set: Vec<&str> = matchers
|
||||
.iter()
|
||||
@@ -610,15 +567,10 @@ pub(crate) fn k_param(k: f64, series: usize) -> Result<Option<usize>> {
|
||||
Ok(Some(k.trunc().min(series as f64) as usize))
|
||||
}
|
||||
|
||||
/// Validates the complete parameter series for Prometheus topk/bottomk/limitk semantics.
|
||||
///
|
||||
/// The values are read where the node holds them, in one pass. The caller keeps both the series the
|
||||
/// parameter arrived as and the values it was read into, so a second copy of the present ones would
|
||||
/// be memory neither of them is charged for.
|
||||
/// Validates the complete parameter series for Prometheus topk/bottomk/limitk semantics. Values are
|
||||
/// read in place; copying them would be unaccounted memory.
|
||||
pub(crate) fn validate_topk_parameters(values: &[Option<f64>]) -> Result<()> {
|
||||
// A position the series decided nothing at is no parameter value, so only the present ones are
|
||||
// read. NaN is tracked rather than folded into the bounds: it is a value Prometheus refuses
|
||||
// outright, not the largest one, and it is refused even where every value is below 1.
|
||||
// Prometheus refuses NaN even when every other value is below 1.
|
||||
let (mut max, mut min, mut nan) = (f64::NEG_INFINITY, f64::INFINITY, false);
|
||||
for value in values.iter().flatten() {
|
||||
if value.is_nan() {
|
||||
@@ -655,7 +607,6 @@ fn group_key(metric: &SeriesLabels, grouping: &Grouping) -> GroupKey {
|
||||
group_key_from(&labels_with_name(metric), grouping)
|
||||
}
|
||||
|
||||
/// The group `labels` belong to, for callers that already hold the series' label pairs.
|
||||
fn group_key_from(labels: &[(Arc<str>, Arc<str>)], grouping: &Grouping) -> GroupKey {
|
||||
let mut key: Vec<_> = labels
|
||||
.iter()
|
||||
@@ -747,16 +698,12 @@ fn grid_points(schema: &SeriesSchema, series: &[Series]) -> Result<usize> {
|
||||
Ok(grid_and_points(schema, series)?.1)
|
||||
}
|
||||
|
||||
/// Checks every series against `schema` and returns the grid it validated them on, with its length.
|
||||
///
|
||||
/// An operator that addresses points on the grid needs the grid itself, not just its length, and
|
||||
/// resolving it twice would let the two answers disagree.
|
||||
/// Checks every series against `schema` and returns the grid with its length.
|
||||
fn grid_and_points(schema: &SeriesSchema, series: &[Series]) -> Result<(Arc<EvalGrid>, usize)> {
|
||||
let grid = schema.eval_grid.as_ref().ok_or_else(|| {
|
||||
DataFusionError::Execution("select operators need an evaluation grid".into())
|
||||
})?;
|
||||
for item in series {
|
||||
// Both grid axes are addressed on a grid; what matters is that it is this schema's.
|
||||
let matches = match item.time.grid() {
|
||||
Some(item_grid) => {
|
||||
item_grid.spec() == grid.spec() && item.fields.len() == schema.fields.len()
|
||||
@@ -772,26 +719,16 @@ fn grid_and_points(schema: &SeriesSchema, series: &[Series]) -> Result<(Arc<Eval
|
||||
Ok((Arc::clone(grid), grid.spec().len as usize))
|
||||
}
|
||||
|
||||
/// The first field's value of `series` at grid `point`, looked up by position.
|
||||
///
|
||||
/// A point read: its only caller, `sort_instant`, reads one point of each instant series, so there
|
||||
/// is no walk for a cursor to follow. The row of a position is searched for, not counted from the
|
||||
/// first one, and a position the axis does not carry answers `None` rather than a row read from
|
||||
/// another offset.
|
||||
/// The first field's value of `series` at grid `point`; `None` when the axis does not carry it.
|
||||
fn value_at(series: &Series, point: usize) -> Result<Option<f64>> {
|
||||
let Some(row) = series.time.row_of(point) else {
|
||||
return Ok(None);
|
||||
};
|
||||
// `Samples::sample` walks the chunk descriptors, not the rows, which is what a random read
|
||||
// costs; a cursor would have to replay every row before this one.
|
||||
into_value(series.fields.as_slice()[0].sample(row))
|
||||
}
|
||||
|
||||
/// A sample as a value for an operator that ranks or sorts reads it.
|
||||
///
|
||||
/// The callers read floats only -- `sort` drops the histogram samples before it keys a series by a
|
||||
/// value, and `topk` collects float candidates -- so a histogram here is a broken invariant rather
|
||||
/// than an input.
|
||||
/// Callers filter histograms out first (`sort` drops them, `topk` selects only float candidates),
|
||||
/// so a histogram here is a broken invariant.
|
||||
fn into_value(sample: SampleRef<'_>) -> Result<Option<f64>> {
|
||||
match sample {
|
||||
SampleRef::Missing => Ok(None),
|
||||
@@ -807,36 +744,30 @@ fn cursor_value(cursor: &mut RowCursor<'_>, row: usize) -> Result<Option<f64>> {
|
||||
into_value(cursor.at(row).expect("the axis and the fields are aligned"))
|
||||
}
|
||||
|
||||
/// How often this thread built a series' label list or compared two candidates, so a test can hold
|
||||
/// `topk` to the work it should not do rather than to the result, which every shape produces.
|
||||
/// Test-only: a decorated sort and a partial selection select the same candidates.
|
||||
/// Per-thread counts of label lists built and candidates compared, so tests can bound `topk`'s work.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod calls {
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
/// Label lists [`super::labels_with_name`] built on this thread.
|
||||
static LABEL_LISTS: Cell<usize> = const { Cell::new(0) };
|
||||
/// Candidate pairs [`super::rank`] looked at on this thread.
|
||||
static RANKS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Records one label list.
|
||||
pub(crate) fn record_label_list() {
|
||||
LABEL_LISTS.with(|lists| lists.set(lists.get() + 1));
|
||||
}
|
||||
|
||||
/// Records one comparison of two candidates.
|
||||
pub(crate) fn record_rank() {
|
||||
RANKS.with(|ranks| ranks.set(ranks.get() + 1));
|
||||
}
|
||||
|
||||
/// The label lists built on this thread since the last call, which starts a new count.
|
||||
/// Returns and resets the count.
|
||||
pub(crate) fn take_label_lists() -> usize {
|
||||
LABEL_LISTS.with(|lists| lists.replace(0))
|
||||
}
|
||||
|
||||
/// The candidate comparisons made on this thread since the last call, which starts a new count.
|
||||
/// Returns and resets the count.
|
||||
pub(crate) fn take_ranks() -> usize {
|
||||
RANKS.with(|ranks| ranks.replace(0))
|
||||
}
|
||||
|
||||
+11
-130
@@ -77,10 +77,7 @@ fn dense(points: usize, values: &str) -> Dense {
|
||||
dense
|
||||
}
|
||||
|
||||
/// The `dense` matrix as one trimmed series, `None` when every row is missing.
|
||||
///
|
||||
/// An *input*, so the holes stay nulls inside one series: the builder would cut them into pieces,
|
||||
/// and the operators under test take one series per input.
|
||||
/// The `dense` matrix as one trimmed series with holes as nulls, `None` when every row is missing.
|
||||
fn build(schema: &SeriesSchema, metric: SeriesLabels, dense: &Dense) -> Option<Series> {
|
||||
let start = dense
|
||||
.iter()
|
||||
@@ -221,8 +218,7 @@ fn sample_offset_hashes_labels_like_prometheus() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `limitk` and `limit_ratio` select series, so histogram samples pass through, and
|
||||
/// `limit_ratio` keeps every field of the series it keeps.
|
||||
/// `limit_ratio` keeps every field of a kept series, histograms included.
|
||||
#[test]
|
||||
fn limit_operators_keep_histogram_samples() {
|
||||
let histogram =
|
||||
@@ -269,8 +265,6 @@ fn limit_operators_keep_histogram_samples() {
|
||||
assert_eq!(kinds(&kept[0], 0), [(1, "histogram")]);
|
||||
}
|
||||
|
||||
/// `topk` ranks floats only: a histogram sample is skipped, as Prometheus ignores it, and the
|
||||
/// float below it is kept in its place.
|
||||
#[test]
|
||||
fn topk_skips_histogram_samples() {
|
||||
let histogram =
|
||||
@@ -294,8 +288,7 @@ fn topk_skips_histogram_samples() {
|
||||
assert_eq!(kept[0].metric.name(), Some("b"));
|
||||
}
|
||||
|
||||
/// `sort` drops histogram samples at every step, as Prometheus' `filterFloats` does, while
|
||||
/// `sort_by_label` keeps them.
|
||||
/// Prometheus' `filterFloats` drops histograms before `sort`, not before `sort_by_label`.
|
||||
#[test]
|
||||
fn sort_drops_histogram_samples() {
|
||||
let histogram =
|
||||
@@ -339,9 +332,6 @@ fn sort_drops_histogram_samples() {
|
||||
assert_eq!(positions, [1]);
|
||||
}
|
||||
|
||||
/// `scalar` reads float samples only, as Prometheus' `funcScalar` does: a point whose only sample
|
||||
/// is a histogram holds no float value, so it answers NaN; a histogram beside one float leaves
|
||||
/// that float; and two floats are more than one sample, so they answer NaN.
|
||||
#[test]
|
||||
fn scalar_ignores_histogram_samples() {
|
||||
let histogram =
|
||||
@@ -362,7 +352,6 @@ fn scalar_ignores_histogram_samples() {
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
};
|
||||
// A scalar exists at every grid point, so the one point of this grid is the whole answer.
|
||||
let value = |series: &[Series]| -> f64 {
|
||||
let result = scalar(&schema, series).unwrap();
|
||||
assert_eq!(result.time.len(), 1, "a scalar exists at every point");
|
||||
@@ -390,11 +379,6 @@ fn scalar_ignores_histogram_samples() {
|
||||
);
|
||||
}
|
||||
|
||||
/// `scalar` answers one dense run of values over the whole grid: one value per point and no null,
|
||||
/// so the value buffer the input is read into is the result's array.
|
||||
///
|
||||
/// The answer is the only thing a scalar can be -- a value at every point of the grid -- which is
|
||||
/// why it is written directly rather than staged as optional values and rebuilt from a row index.
|
||||
#[test]
|
||||
fn scalar_answers_one_dense_run_over_the_grid() {
|
||||
let schema = schema(3, 1);
|
||||
@@ -437,28 +421,16 @@ fn scalar_answers_one_dense_run_over_the_grid() {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -498,8 +470,6 @@ fn limit_operators_keep_the_start_timestamp_of_a_selected_sample() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The selections that only move samples hand them from the field to the builder: no owned
|
||||
/// histogram is built on the way, and the payload arrives as it was read.
|
||||
#[test]
|
||||
fn limit_operators_pass_histograms_through_without_an_owned_form() {
|
||||
let histogram =
|
||||
@@ -529,7 +499,6 @@ fn limit_operators_pass_histograms_through_without_an_owned_form() {
|
||||
"a selection built an owned histogram of a sample it only moved"
|
||||
);
|
||||
|
||||
// Both selections hand on the samples they kept, unchanged and in the same place.
|
||||
let kept = |series: &Series| -> Vec<(usize, bool)> {
|
||||
let samples = &series.fields.as_slice()[0];
|
||||
series
|
||||
@@ -549,14 +518,10 @@ fn limit_operators_pass_histograms_through_without_an_owned_form() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `topk` builds one label list per series and ranks each point with a partial selection: the
|
||||
/// comparisons it makes grow with the candidates rather than with their logarithm, which is what
|
||||
/// ordering the whole group at every point cost.
|
||||
#[test]
|
||||
fn topk_ranks_a_point_with_a_partial_selection() {
|
||||
let schema = schema(1, 1);
|
||||
// Every series is one group, and the input arrives in reverse label order, so nothing about it
|
||||
// is inherited from the order the members were built in.
|
||||
// Reverse label order, so the result cannot inherit the input order.
|
||||
let series: Vec<Series> = (0..256)
|
||||
.rev()
|
||||
.map(|index| {
|
||||
@@ -596,8 +561,7 @@ fn topk_ranks_a_point_with_a_partial_selection() {
|
||||
series.len(),
|
||||
"topk rebuilt a series' label list instead of reading the one it built"
|
||||
);
|
||||
// Ordering the whole group at the point would take the candidates' logarithm per candidate;
|
||||
// the partial selection takes a small constant.
|
||||
// A full sort would make O(n log n) comparisons.
|
||||
assert!(
|
||||
comparisons <= 4 * series.len(),
|
||||
"topk compared {comparisons} candidate pairs to select 8 of {}",
|
||||
@@ -605,16 +569,14 @@ fn topk_ranks_a_point_with_a_partial_selection() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Ties go to the label set that sorts first, whatever order the input arrived in: the value the
|
||||
/// partial selection stops at falls inside a run of equal values, and the run is resolved by label
|
||||
/// order rather than by the order the ranking left the group in.
|
||||
/// The k-th value falls inside a run of ties, which must be resolved by label order rather than by
|
||||
/// the order the partial selection left the group in.
|
||||
#[test]
|
||||
fn topk_breaks_ties_by_label_order() {
|
||||
let names: Vec<String> = (0..40)
|
||||
.map(|index| format!("__name__=s{index:02}"))
|
||||
.collect();
|
||||
// The ten series that sort first carry the top value, and the input arrives in reverse label
|
||||
// order, so a tie can only be resolved by the labels.
|
||||
// The ten series that sort first carry the top value; input in reverse label order.
|
||||
let values: Vec<(&str, Option<f64>)> = names
|
||||
.iter()
|
||||
.rev()
|
||||
@@ -633,7 +595,6 @@ fn topk_breaks_ties_by_label_order() {
|
||||
kept.sort();
|
||||
assert_eq!(kept, ["__name__=s00", "__name__=s01", "__name__=s02"]);
|
||||
|
||||
// `bottomk` ties the same way, and its run of equal values holds the whole group.
|
||||
let kept = topk(3.0, false, &Grouping::By(Vec::new()), &schema, &series).unwrap();
|
||||
let mut kept = rendered(&kept);
|
||||
kept.sort();
|
||||
@@ -692,8 +653,6 @@ fn check_cases(
|
||||
(actual, expected) => panic!("{case}\ngot {actual:?}, expected error {expected:?}"),
|
||||
};
|
||||
|
||||
// A result arrives as one series over the runs of valued positions; the fixtures pin the
|
||||
// dense values, so each result is expanded over the grid before comparing.
|
||||
let actual: BTreeMap<String, Series> = fold_pieces(actual)
|
||||
.into_iter()
|
||||
.map(|series| (render(&series.metric), series))
|
||||
@@ -868,22 +827,16 @@ fn absent_evaluates_fields_independently() {
|
||||
let result = absent(&schema, &series, metric("-"))
|
||||
.unwrap()
|
||||
.expect("both positions are absent in one field");
|
||||
// The two fields take turns holding a value, but a row is kept when either field has one, so
|
||||
// both positions stay in one run; the missing field carries a null there.
|
||||
// A row is kept when either field has a value, so both positions form one run.
|
||||
assert_eq!(piece_ranges(std::slice::from_ref(&result)), vec![(0, 2)]);
|
||||
let expected = vec![vec![None, Some(1.0)], vec![Some(1.0), None]];
|
||||
assert_pieces_eq(std::slice::from_ref(&result), &expected, &metric("-"));
|
||||
}
|
||||
|
||||
/// `absent` and `scalar` read a series of several runs by its positions.
|
||||
///
|
||||
/// The rows of a sparse input are neither adjacent nor starting where the series says, so an
|
||||
/// operator that counted rows from the first position would report presence at the wrong points.
|
||||
#[test]
|
||||
fn select_operators_read_a_sparse_axis_by_its_positions() {
|
||||
let schema = Arc::new(schema(8, 1));
|
||||
let labels = Labels::from([("host".to_string(), "a".to_string())]);
|
||||
// Positions 1, 2 and 6 hold a value; 0, 3, 4, 5 and 7 hold none.
|
||||
let mut points = Points::new();
|
||||
for position in [1, 2, 6] {
|
||||
points.insert(position, f64::to_bits(1.0));
|
||||
@@ -891,7 +844,6 @@ fn select_operators_read_a_sparse_axis_by_its_positions() {
|
||||
let sparse = sparse_series(&schema, &labels, &points).unwrap();
|
||||
assert_eq!(sparse.time.len(), 3);
|
||||
|
||||
// `absent` reports 1 at every point nothing is present: the five positions the axis skips.
|
||||
let absent_series = absent(&schema, std::slice::from_ref(&sparse), metric("-"))
|
||||
.unwrap()
|
||||
.expect("the sparse series holds five absent positions");
|
||||
@@ -907,7 +859,6 @@ fn select_operators_read_a_sparse_axis_by_its_positions() {
|
||||
"absent must hold a value exactly where the sparse series holds none"
|
||||
);
|
||||
|
||||
// `scalar` reads the same sparse rows and reports NaN where nothing is present.
|
||||
let scalar_series = scalar(&schema, std::slice::from_ref(&sparse)).unwrap();
|
||||
assert_eq!(
|
||||
scalar_series.time.len(),
|
||||
@@ -930,72 +881,8 @@ fn select_operators_read_a_sparse_axis_by_its_positions() {
|
||||
assert!(matches!(values[3].1, SampleRef::Float(value) if value.is_nan()));
|
||||
}
|
||||
|
||||
/// F: `topk` selects a winner sitting in a later run, so its result is a fragmented axis of the
|
||||
/// selected positions, not a contiguous piece from the earliest winner.
|
||||
///
|
||||
/// Three series each carry one position: a=7 at 1, b=9 at 4 and c=2 at 9. `topk` ranks per point,
|
||||
/// so each point holds the one candidate its series carries -- and every survivor sits at its own
|
||||
/// position, never shifted to the start of an envelope.
|
||||
#[test]
|
||||
fn topk_keeps_a_winner_sitting_in_a_later_run() {
|
||||
let schema = Arc::new(schema(10, 1));
|
||||
let operand = |name: &str, position: usize, value: f64| -> Series {
|
||||
let labels = Labels::from([("host".to_string(), name.to_string())]);
|
||||
let points = Points::from([(position, f64::to_bits(value))]);
|
||||
sparse_series(&schema, &labels, &points).expect("one position holds a value")
|
||||
};
|
||||
let series = vec![
|
||||
operand("a", 1, 7.0),
|
||||
operand("b", 4, 9.0),
|
||||
operand("c", 9, 2.0),
|
||||
];
|
||||
for operand in &series {
|
||||
assert_eq!(
|
||||
run_ranges(operand),
|
||||
vec![(operand.time.first_position().expect("one row"), 1)]
|
||||
);
|
||||
assert_eq!(operand.time.len(), 1, "each series carries one row");
|
||||
}
|
||||
|
||||
// `topk(1)` over the empty grouping: at each point the only candidate wins, so all three
|
||||
// series survive, each at its own position.
|
||||
let result = topk(1.0, true, &Grouping::By(Vec::new()), &schema, &series).unwrap();
|
||||
assert_eq!(result.len(), 3, "one candidate per point: {result:?}");
|
||||
let mut ranges = piece_ranges(&result);
|
||||
ranges.sort_unstable();
|
||||
assert_eq!(
|
||||
ranges,
|
||||
vec![(1, 1), (4, 1), (9, 1)],
|
||||
"every winner sits at its own position, not at the start of an envelope"
|
||||
);
|
||||
let mut expected = vec![vec![None]; 10];
|
||||
expected[4] = vec![Some(9.0)];
|
||||
let middle = result
|
||||
.iter()
|
||||
.find(|series| series.metric.get("host") == Some("b"))
|
||||
.expect("series b wins at position 4")
|
||||
.clone();
|
||||
assert_result_eq(Some(&middle), &expected, &metric("host=b"));
|
||||
|
||||
// `topk(2)` is evaluated per point, and each point holds one candidate, so it selects the
|
||||
// same three series the `k=1` case did.
|
||||
let result = topk(2.0, true, &Grouping::By(Vec::new()), &schema, &series).unwrap();
|
||||
assert_eq!(result.len(), 3, "one candidate per point: {result:?}");
|
||||
let mut ranges = piece_ranges(&result);
|
||||
ranges.sort_unstable();
|
||||
assert_eq!(ranges, vec![(1, 1), (4, 1), (9, 1)]);
|
||||
for series in &result {
|
||||
assert_eq!(series.time.len(), 1, "one row, one position");
|
||||
}
|
||||
}
|
||||
|
||||
/// F: `topk` ranks each point on its own, so a winner can sit in a later run, and a tie is broken
|
||||
/// by label order rather than by position.
|
||||
///
|
||||
/// Series `a` holds 5 at 0 and 5 at 6; series `b` holds 5 at 0 and 4 at 6. The two tie at 0, and
|
||||
/// the earlier label set wins there; at 6 the larger value wins. So `topk(1)` selects `a` twice, at
|
||||
/// two positions with a hole between -- a winner in a later run. `bottomk(1)` flips the second
|
||||
/// point to `b`, so the two winners sit in different runs of the two inputs.
|
||||
/// Sparse inputs: `a` holds 5 at 0 and 6, `b` holds 5 at 0 and 4 at 6. The tie at 0 goes to `a`;
|
||||
/// `bottomk(1)` picks `b` at 6, a winner in a later run.
|
||||
#[test]
|
||||
fn topk_breaks_ties_across_a_gap_by_label_order() {
|
||||
let schema = Arc::new(schema(10, 1));
|
||||
@@ -1007,15 +894,12 @@ fn topk_breaks_ties_across_a_gap_by_label_order() {
|
||||
.collect();
|
||||
sparse_series(&schema, &labels, &points).expect("the series holds a value")
|
||||
};
|
||||
// Each series carries two positions with a hole between them.
|
||||
let a = operand("a", &[(0, 5.0), (6, 5.0)]);
|
||||
let b = operand("b", &[(0, 5.0), (6, 4.0)]);
|
||||
assert_eq!(run_ranges(&a), vec![(0, 1), (6, 1)]);
|
||||
assert_eq!(run_ranges(&b), vec![(0, 1), (6, 1)]);
|
||||
let series = vec![a, b];
|
||||
|
||||
// `topk(1)`: `a` wins at both points -- the tie at 0 goes to the earlier label set, and 5 beats
|
||||
// 4 at 6. The winner is one series whose two rows are two runs.
|
||||
let result = topk(1.0, true, &Grouping::By(Vec::new()), &schema, &series).unwrap();
|
||||
assert_eq!(
|
||||
result.len(),
|
||||
@@ -1033,7 +917,6 @@ fn topk_breaks_ties_across_a_gap_by_label_order() {
|
||||
expected[6] = vec![Some(5.0)];
|
||||
assert_result_eq(Some(&result[0]), &expected, &metric("host=a"));
|
||||
|
||||
// `topk(2)`: both series are selected wherever they hold a value.
|
||||
let result = topk(2.0, true, &Grouping::By(Vec::new()), &schema, &series).unwrap();
|
||||
assert_eq!(result.len(), 2, "both series are selected: {result:?}");
|
||||
let mut all = piece_ranges(&result);
|
||||
@@ -1055,8 +938,6 @@ fn topk_breaks_ties_across_a_gap_by_label_order() {
|
||||
let winner = by_label(&result, "b");
|
||||
assert_result_eq(Some(&winner), &second, &metric("host=b"));
|
||||
|
||||
// `bottomk(1)`: the tie at 0 still goes to `a`, but 4 beats 5 at 6, so `b` wins in the later
|
||||
// run. The two winners sit in different series and at different positions.
|
||||
let result = topk(1.0, false, &Grouping::By(Vec::new()), &schema, &series).unwrap();
|
||||
assert_eq!(result.len(), 2, "each series wins one point: {result:?}");
|
||||
let mut ranges = piece_ranges(&result);
|
||||
|
||||
@@ -34,13 +34,9 @@ use store_api::region_engine::{RawLabelSource, RawSeriesStream, SendableRawSerie
|
||||
|
||||
/// Materializes complete metric labels from a raw-series frame stream.
|
||||
///
|
||||
/// The labels are decoded from the stream's own label decode description, so a consumer that holds
|
||||
/// only the frame needs no scan-bound binding; a stream that carries complete labels already, and
|
||||
/// so declares no description, needs no decoder and is forwarded as supplied. Adjacent-chunk
|
||||
/// pack/unpack validation remains the caller's responsibility, and nonadjacent key recurrence is
|
||||
/// governed by the producer contract. Explicit labels are retained as supplied; their completeness
|
||||
/// cannot be inferred from the schema. No authorization or cross-stream completion is performed
|
||||
/// here.
|
||||
/// Labels are decoded with the stream's own label decode description; a stream without one already
|
||||
/// carries complete labels and is forwarded as supplied. Explicit labels are kept as supplied.
|
||||
/// Adjacent-chunk pack/unpack validation stays with the caller.
|
||||
pub fn materialize_raw_labels(
|
||||
source: SendableRawSeriesStream,
|
||||
) -> Result<SendableRawSeriesStream, BoxedError> {
|
||||
|
||||
@@ -25,12 +25,9 @@ use datatypes::series::samples::{SampleRef, Samples, SeriesFields, SeriesSchema}
|
||||
|
||||
use crate::grid_series::{label_set, render_label_set};
|
||||
|
||||
/// Rebuilds one raw series from every piece of one complete physical identity, reporting each
|
||||
/// allocation before it happens.
|
||||
///
|
||||
/// Reconstruction holds three intermediate vectors whose sizes depend on how the pieces interleave,
|
||||
/// so what it needs cannot be known up front. The caller charges `reserve` as the work grows
|
||||
/// instead of reserving a worst case it may never reach.
|
||||
/// Rebuilds one raw series from every piece of one complete physical identity. Calls `reserve`
|
||||
/// before each allocation, since the sizes depend on how the pieces interleave, and `shrink` once
|
||||
/// the transient workspaces are freed.
|
||||
pub(crate) fn merge_raw_identity_charging(
|
||||
schema: &SeriesSchema,
|
||||
chunks: &[RawSeriesChunk],
|
||||
@@ -209,7 +206,6 @@ pub(crate) fn merge_raw_identity_charging(
|
||||
true,
|
||||
)
|
||||
.map_err(|error| DataFusionError::External(Box::new(error)))?;
|
||||
// Only the general merge path allocates transient row-index workspaces.
|
||||
shrink(transient_workspace_bytes);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -43,34 +43,6 @@ fn schema(count: usize) -> SeriesSchema {
|
||||
}
|
||||
}
|
||||
|
||||
fn histogram(sum: f64, threshold: f64) -> Samples {
|
||||
let mut builder = HistogramBatchBuilder::new();
|
||||
let side = BucketSideView {
|
||||
span_offsets: &[],
|
||||
span_lengths: &[],
|
||||
buckets: &[],
|
||||
};
|
||||
let index = builder
|
||||
.push(datatypes::series::histogram::HistogramView {
|
||||
schema: 1,
|
||||
zero_threshold: threshold,
|
||||
sum,
|
||||
count: 1.0,
|
||||
zero_count: 0.0,
|
||||
reset_hint: CounterResetHint::Unknown,
|
||||
start_timestamp: None,
|
||||
custom_values: &[],
|
||||
positive: side,
|
||||
negative: side,
|
||||
})
|
||||
.unwrap();
|
||||
Samples::try_from_histogram(
|
||||
UInt32Array::from(vec![Some(index)]),
|
||||
builder.finish().unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn labels(value: &str) -> SeriesLabels {
|
||||
SeriesLabels::try_new(
|
||||
Some(Arc::from("metric")),
|
||||
@@ -281,40 +253,6 @@ fn rejects_different_keys_labels_and_internal_duplicates() {
|
||||
assert!(merge_raw_identity(&schema(1), &[no_labels]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_duplicates_compare_every_float_property() {
|
||||
let schema = schema(1);
|
||||
let make = |sample| RawSeriesChunk {
|
||||
primary_key: Buffer::from(b"k".to_vec()),
|
||||
metric: Some(labels("v")),
|
||||
time: RawTimestamps::try_new(vec![1].into()).unwrap(),
|
||||
fields: SeriesFields::one(sample),
|
||||
is_last: false,
|
||||
};
|
||||
assert!(
|
||||
merge_raw_identity(
|
||||
&schema,
|
||||
&[make(histogram(2.0, 0.5)), make(histogram(2.0, 0.5))]
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
merge_raw_identity(
|
||||
&schema,
|
||||
&[make(histogram(2.0, 0.5)), make(histogram(3.0, 0.5))]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
merge_raw_identity(
|
||||
&schema,
|
||||
&[make(histogram(2.0, 0.5)), make(histogram(2.0, -0.0))]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds a histogram with configurable comparison properties for duplicate-conflict tests.
|
||||
fn histogram_with(view: datatypes::series::histogram::HistogramView<'_>) -> Samples {
|
||||
let mut builder = HistogramBatchBuilder::new();
|
||||
let index = builder.push(view).unwrap();
|
||||
@@ -325,12 +263,8 @@ fn histogram_with(view: datatypes::series::histogram::HistogramView<'_>) -> Samp
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Two histograms are duplicates only when every property matches.
|
||||
///
|
||||
/// Bucket values are independently free within a valid layout and are compared directly. The
|
||||
/// span/cursor layout cannot be varied independently of bucket count: each layout must have
|
||||
/// nonnegative lengths summing to the bucket count and a valid cursor. The cases below vary each
|
||||
/// offset and length while preserving valid layouts and equal bucket counts.
|
||||
/// Two histograms are duplicates only when every property matches. Span offsets and lengths are
|
||||
/// varied while keeping the layout valid and the bucket count equal.
|
||||
#[test]
|
||||
fn histogram_duplicates_compare_every_property() {
|
||||
let schema = schema(1);
|
||||
@@ -401,7 +335,6 @@ fn histogram_duplicates_compare_every_property() {
|
||||
buckets: &[3.0, 4.5],
|
||||
..negative
|
||||
};
|
||||
// Same span count and lengths as the baseline, different cursors: only the offsets differ.
|
||||
let positive_offsets_changed = BucketSideView {
|
||||
span_offsets: &[1, 0],
|
||||
..positive
|
||||
@@ -410,8 +343,6 @@ fn histogram_duplicates_compare_every_property() {
|
||||
span_offsets: &[1, 0],
|
||||
..negative
|
||||
};
|
||||
// Same cursors and same total bucket count (2), different split into spans. A zero-length
|
||||
// span is a valid layout, so only the lengths differ here.
|
||||
let positive_lengths_changed = BucketSideView {
|
||||
span_lengths: &[2, 0],
|
||||
..positive
|
||||
|
||||
@@ -91,8 +91,8 @@ fn metadata(encoding: PrimaryKeyEncoding) -> Arc<RegionMetadata> {
|
||||
column_id: id,
|
||||
});
|
||||
}
|
||||
// main's `fix!: enforce sparse primary key schema` requires sparse primary keys to start
|
||||
// with `(__table_id, __tsid)`, and every primary-key column id must exist in the schema.
|
||||
// Sparse primary keys must start with `(__table_id, __tsid)`, and every primary-key column id
|
||||
// must exist in the schema.
|
||||
let mut primary_key = vec![8, 2, 41];
|
||||
if encoding == PrimaryKeyEncoding::Sparse {
|
||||
builder.push_column_metadata(ColumnMetadata {
|
||||
@@ -891,8 +891,7 @@ async fn constructor_and_mode_errors_drop_input_without_polling_ahead() {
|
||||
fields: SeriesFields::one(Samples::from_float(Float64Array::from(Vec::<f64>::new()))),
|
||||
is_last: false,
|
||||
};
|
||||
// `RawTimestamps` rejects duplicate or descending axes at construction, so a chunk
|
||||
// carrying an out-of-order time axis can no longer be constructed.
|
||||
// An out-of-order time axis cannot be constructed.
|
||||
assert!(RawTimestamps::try_new(ScalarBuffer::from(vec![100, 100, 90])).is_err());
|
||||
for malformed in [malformed_shape, malformed_empty_time] {
|
||||
let (raw, polls, drops) = mock(
|
||||
@@ -1072,9 +1071,8 @@ async fn dense_and_sparse_sources_materialize_complete_labels() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A consumer that received only the raw series frame decodes labels with no scan-bound source:
|
||||
/// the producer's description travels inside the frame schema, so unpacking needs no binding and
|
||||
/// materialization builds its decoder from that description alone.
|
||||
/// The label decode description travels in the frame schema, so a consumer holding only the frame
|
||||
/// decodes labels without a binding.
|
||||
#[tokio::test]
|
||||
async fn materializes_labels_from_a_frame_with_no_supplied_binding() {
|
||||
for encoding in [PrimaryKeyEncoding::Dense, PrimaryKeyEncoding::Sparse] {
|
||||
@@ -1100,8 +1098,6 @@ async fn materializes_labels_from_a_frame_with_no_supplied_binding() {
|
||||
"{encoding:?}: the frame schema is the producer's only label statement"
|
||||
);
|
||||
|
||||
// Everything the consumer keeps is the frame stream: no expected schema, no binding, no
|
||||
// region metadata anywhere on the decode path.
|
||||
let framed = unpack_raw_series(framed, None).unwrap();
|
||||
assert_eq!(
|
||||
framed.label_decode_spec(),
|
||||
|
||||
+158
-406
File diff suppressed because it is too large
Load Diff
@@ -32,7 +32,7 @@ use super::{
|
||||
};
|
||||
use crate::grid_series::reference::{
|
||||
Dense, OwnedHistogram, Points, assert_histogram_close, assert_result_eq, golden_cases,
|
||||
mixed_series, piece_ranges, random_dense, run_ranges, sparse_series,
|
||||
mixed_series, random_dense, run_ranges, sparse_series,
|
||||
};
|
||||
use crate::grid_series::{GridSample, GridSeriesBuilder};
|
||||
use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
@@ -1510,277 +1510,6 @@ fn an_incompatible_bucket_layout_drops_the_reset_collision_warning() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A binary pairing walks two operands of many single-position runs and still reports every
|
||||
/// position exactly once.
|
||||
///
|
||||
/// The rows of a pairing only increase -- `intersect_runs` merges the two run lists forward and
|
||||
/// each shared run carries the row of each side -- which is what lets one cursor per operand serve
|
||||
/// every run of the pairing. This pins that order and the values under heavy fragmentation; it
|
||||
/// does not measure cost, since a cursor rebuilt per run returns the same values.
|
||||
#[test]
|
||||
fn a_pairing_reads_many_single_position_runs_once() {
|
||||
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 10_000, 8).unwrap()).unwrap());
|
||||
let schema = Arc::new(schema(1, &grid));
|
||||
let points: Points = (0..8)
|
||||
.step_by(2)
|
||||
.map(|position| (position, f64::to_bits(position as f64)))
|
||||
.collect();
|
||||
let operand = |name: &str, offset: f64| -> Series {
|
||||
let labels = Labels::from([
|
||||
("__name__".to_string(), name.to_string()),
|
||||
("job".to_string(), "x".to_string()),
|
||||
]);
|
||||
// Every other position is its own run: eight positions become four one-row runs.
|
||||
let points: Points = points
|
||||
.iter()
|
||||
.map(|(&position, &bits)| (position, (f64::from_bits(bits) + offset).to_bits()))
|
||||
.collect();
|
||||
sparse_series(&schema, &labels, &points).unwrap()
|
||||
};
|
||||
let lhs = operand("a", 0.0);
|
||||
let rhs = operand("b", 100.0);
|
||||
assert_eq!(run_ranges(&lhs), vec![(0, 1), (2, 1), (4, 1), (6, 1)]);
|
||||
assert_eq!(run_ranges(&rhs), vec![(0, 1), (2, 1), (4, 1), (6, 1)]);
|
||||
|
||||
let matching = BinaryMatching {
|
||||
op: BinaryOp::Add,
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::On(vec![Arc::from("job")]),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(
|
||||
&matching,
|
||||
&schema,
|
||||
std::slice::from_ref(&lhs),
|
||||
&schema,
|
||||
std::slice::from_ref(&rhs),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(run_ranges(&result[0]), vec![(0, 1), (2, 1), (4, 1), (6, 1)]);
|
||||
let expected: Points = (0..8)
|
||||
.step_by(2)
|
||||
.map(|position| (position, f64::to_bits((2 * position) as f64 + 100.0)))
|
||||
.collect();
|
||||
assert_eq!(points_of(&result[0]), expected);
|
||||
}
|
||||
|
||||
/// F: a binary operation between two sparse operands evaluates only the shared positions, and its
|
||||
/// output's runs are exactly those positions -- never the envelope of the pairing.
|
||||
///
|
||||
/// LHS carries 1 and 8, RHS carries 8 and 10, so the only shared position is 8. A pairing that
|
||||
/// offset one side's rows by its first position would evaluate 1 against 8 and 8 against 10.
|
||||
#[test]
|
||||
fn a_binary_pairing_of_sparse_operands_keeps_the_shared_positions() {
|
||||
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1_000, 12).unwrap()).unwrap());
|
||||
let schema = Arc::new(schema(1, &grid));
|
||||
let operand = |name: &str, points: &[(usize, f64)]| -> Series {
|
||||
let labels = Labels::from([
|
||||
("__name__".to_string(), name.to_string()),
|
||||
("job".to_string(), "x".to_string()),
|
||||
]);
|
||||
let points: Points = points
|
||||
.iter()
|
||||
.map(|&(position, value)| (position, f64::to_bits(value)))
|
||||
.collect();
|
||||
sparse_series(&schema, &labels, &points).expect("the operand holds a value")
|
||||
};
|
||||
let lhs = operand("l", &[(1, 10.0), (8, 20.0)]);
|
||||
let rhs = operand("r", &[(8, 2.0), (10, 5.0)]);
|
||||
assert_eq!(run_ranges(&lhs), vec![(1, 1), (8, 1)]);
|
||||
assert_eq!(run_ranges(&rhs), vec![(8, 1), (10, 1)]);
|
||||
|
||||
let matching = BinaryMatching {
|
||||
op: BinaryOp::Add,
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(
|
||||
&matching,
|
||||
&schema,
|
||||
std::slice::from_ref(&lhs),
|
||||
&schema,
|
||||
std::slice::from_ref(&rhs),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.len(), 1, "one matched pair: {result:?}");
|
||||
assert_eq!(
|
||||
run_ranges(&result[0]),
|
||||
vec![(8, 1)],
|
||||
"only position 8 is shared, so the result holds exactly one row"
|
||||
);
|
||||
assert_eq!(result[0].time.len(), 1);
|
||||
let mut expected: Dense = vec![vec![None]; 12];
|
||||
expected[8] = vec![Some(22.0)];
|
||||
// Arithmetic drops the metric name, as Prometheus does.
|
||||
assert_result_eq(
|
||||
Some(&result[0]),
|
||||
&expected,
|
||||
&metric(&Labels::from([("job".to_string(), "x".to_string())])),
|
||||
);
|
||||
|
||||
// A filtered comparison keeps the left value where it holds, at the same positions.
|
||||
let filtered = BinaryMatching {
|
||||
op: BinaryOp::Gt,
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(
|
||||
&filtered,
|
||||
&schema,
|
||||
std::slice::from_ref(&lhs),
|
||||
&schema,
|
||||
std::slice::from_ref(&rhs),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(run_ranges(&result[0]), vec![(8, 1)]);
|
||||
let mut expected: Dense = vec![vec![None]; 12];
|
||||
expected[8] = vec![Some(20.0)];
|
||||
// A filtered comparison keeps the left value and its metric, name included.
|
||||
assert_result_eq(
|
||||
Some(&result[0]),
|
||||
&expected,
|
||||
&metric(&Labels::from([
|
||||
("__name__".to_string(), "l".to_string()),
|
||||
("job".to_string(), "x".to_string()),
|
||||
])),
|
||||
);
|
||||
|
||||
// A `bool` comparison emits 0/1 at every shared position, so the axis is the intersection's.
|
||||
let booled = BinaryMatching {
|
||||
op: BinaryOp::Gt,
|
||||
return_bool: true,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
};
|
||||
let result = binary_vectors(
|
||||
&booled,
|
||||
&schema,
|
||||
std::slice::from_ref(&lhs),
|
||||
&schema,
|
||||
std::slice::from_ref(&rhs),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(run_ranges(&result[0]), vec![(8, 1)]);
|
||||
let mut expected: Dense = vec![vec![None]; 12];
|
||||
expected[8] = vec![Some(1.0)];
|
||||
assert_result_eq(
|
||||
Some(&result[0]),
|
||||
&expected,
|
||||
&metric(&Labels::from([("job".to_string(), "x".to_string())])),
|
||||
);
|
||||
}
|
||||
|
||||
/// F: a set operator keeps each series' own positions, so a sparse operand comes back with the
|
||||
/// runs it had and a dense one is cut to the sparse side's positions.
|
||||
///
|
||||
/// `and`: the positions both sides carry. `or`: the union. `unless`: the LHS positions the RHS
|
||||
/// does not carry.
|
||||
#[test]
|
||||
fn set_operators_of_sparse_operands_keep_their_own_positions() {
|
||||
let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1_000, 12).unwrap()).unwrap());
|
||||
let schema = Arc::new(schema(1, &grid));
|
||||
let operand = |name: &str, points: &[(usize, f64)]| -> Series {
|
||||
let labels = Labels::from([
|
||||
("__name__".to_string(), name.to_string()),
|
||||
("job".to_string(), "x".to_string()),
|
||||
]);
|
||||
let points: Points = points
|
||||
.iter()
|
||||
.map(|&(position, value)| (position, f64::to_bits(value)))
|
||||
.collect();
|
||||
sparse_series(&schema, &labels, &points).expect("the operand holds a value")
|
||||
};
|
||||
let lhs = operand("l", &[(1, 10.0), (5, 50.0), (9, 90.0)]);
|
||||
let rhs = operand("r", &[(3, 30.0), (5, 55.0)]);
|
||||
assert_eq!(run_ranges(&lhs), vec![(1, 1), (5, 1), (9, 1)]);
|
||||
assert_eq!(run_ranges(&rhs), vec![(3, 1), (5, 1)]);
|
||||
let labels = MatchingLabels::Ignoring(Vec::new());
|
||||
let input = |side: &[Series]| side.to_vec();
|
||||
|
||||
// `and`: only position 5, where both sides hold a value.
|
||||
let result = set_vectors(
|
||||
SetOp::And,
|
||||
&labels,
|
||||
&schema,
|
||||
&input(std::slice::from_ref(&lhs)),
|
||||
&schema,
|
||||
&input(std::slice::from_ref(&rhs)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.len(), 1, "an `and` keeps the left side: {result:?}");
|
||||
assert_eq!(run_ranges(&result[0]), vec![(5, 1)]);
|
||||
let mut expected: Dense = vec![vec![None]; 12];
|
||||
expected[5] = vec![Some(50.0)];
|
||||
assert_result_eq(Some(&result[0]), &expected, &lhs.metric);
|
||||
|
||||
// `or`: both sides' positions, each with the value it had.
|
||||
let result = set_vectors(
|
||||
SetOp::Or,
|
||||
&labels,
|
||||
&schema,
|
||||
&input(std::slice::from_ref(&lhs)),
|
||||
&schema,
|
||||
&input(std::slice::from_ref(&rhs)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.len(), 2, "an `or` keeps the series: {result:?}");
|
||||
let mut ranges = piece_ranges(&result);
|
||||
ranges.sort_unstable();
|
||||
assert_eq!(ranges, vec![(1, 1), (3, 1), (5, 1), (9, 1)]);
|
||||
// Results come back by label set, not in input order, so each side is found by its labels.
|
||||
let side = |name: &str| -> Series {
|
||||
result
|
||||
.iter()
|
||||
.find(|series| series.metric.name() == Some(name))
|
||||
.unwrap_or_else(|| panic!("no series {name}: {result:?}"))
|
||||
.clone()
|
||||
};
|
||||
let left = side("l");
|
||||
assert_eq!(
|
||||
left.time.len(),
|
||||
3,
|
||||
"the left side keeps its three rows: {left:?}"
|
||||
);
|
||||
assert_eq!(run_ranges(&left), vec![(1, 1), (5, 1), (9, 1)]);
|
||||
let right = side("r");
|
||||
assert_eq!(
|
||||
right.time.len(),
|
||||
1,
|
||||
"`or` keeps only the right side's positions the left side does not carry: {right:?}"
|
||||
);
|
||||
assert_eq!(run_ranges(&right), vec![(3, 1)]);
|
||||
|
||||
// `unless`: the LHS positions the RHS does not carry, so 5 is dropped.
|
||||
let result = set_vectors(
|
||||
SetOp::Unless,
|
||||
&labels,
|
||||
&schema,
|
||||
&input(std::slice::from_ref(&lhs)),
|
||||
&schema,
|
||||
&input(std::slice::from_ref(&rhs)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.len(), 1, "{result:?}");
|
||||
assert_eq!(
|
||||
run_ranges(&result[0]),
|
||||
vec![(1, 1), (9, 1)],
|
||||
"the dropped position costs no row and splits the run"
|
||||
);
|
||||
let mut expected: Dense = vec![vec![None]; 12];
|
||||
expected[1] = vec![Some(10.0)];
|
||||
expected[9] = vec![Some(90.0)];
|
||||
assert_result_eq(Some(&result[0]), &expected, &lhs.metric);
|
||||
}
|
||||
|
||||
/// One filed row, counted from what the row holds: the point it answers, the match group it belongs
|
||||
/// to and the value it keeps. It is an independent unit of account -- the three things a row is made
|
||||
/// of, not the figure the operation charges for one -- so a reservation that grew with something
|
||||
@@ -2532,62 +2261,6 @@ fn a_filtered_comparison_files_a_row_that_carries_no_value() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Fields that hold different positions of one label set are merged into one series: the triples
|
||||
/// arrive field by field, so the merge sorts them before it writes the series out.
|
||||
#[test]
|
||||
fn fields_holding_different_positions_merge_into_one_series() {
|
||||
let grid = budget_grid(2);
|
||||
let schema = Arc::new(schema(2, &grid));
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap();
|
||||
// The left side holds its first field at the later point and its second at the earlier one.
|
||||
builder.begin_series();
|
||||
builder.push(0, &[None, Some(10.0)]).unwrap();
|
||||
builder.push(1, &[Some(1.0), None]).unwrap();
|
||||
let lhs: Vec<Series> = builder
|
||||
.finish(metric(&Labels::from([(
|
||||
"job".to_string(),
|
||||
"x".to_string(),
|
||||
)])))
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.collect();
|
||||
let labels = Labels::from([
|
||||
("__name__".to_string(), "b".to_string()),
|
||||
("job".to_string(), "x".to_string()),
|
||||
]);
|
||||
builder.begin_series();
|
||||
builder.push(0, &[Some(2.0), Some(20.0)]).unwrap();
|
||||
builder.push(1, &[Some(3.0), Some(30.0)]).unwrap();
|
||||
let rhs: Vec<Series> = builder
|
||||
.finish(metric(&labels))
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.collect();
|
||||
let matching = budget_matching(BinaryOp::Add, MatchingLabels::Ignoring(Vec::new()));
|
||||
let (output, _) = budgeted(&matching, &schema, &lhs, &schema, &rhs, usize::MAX);
|
||||
let output = output.expect("the fields merge");
|
||||
assert_eq!(output.len(), 1, "{output:?}");
|
||||
let series = &output[0];
|
||||
let mut first = series.fields.as_slice()[0].cursor();
|
||||
let mut second = series.fields.as_slice()[1].cursor();
|
||||
let value = |cursor: &mut RowCursor<'_>, row: usize| -> Option<f64> {
|
||||
match cursor.at(row).expect("a row never goes back") {
|
||||
SampleRef::Missing => None,
|
||||
SampleRef::Float(value) => Some(value),
|
||||
SampleRef::Histogram(_) => panic!("a float field holds no histogram"),
|
||||
}
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for (point, row) in series.time.positions() {
|
||||
rows.push((point, [value(&mut first, row), value(&mut second, row)]));
|
||||
}
|
||||
assert_eq!(
|
||||
rows,
|
||||
vec![(0, [None, Some(30.0)]), (1, [Some(4.0), None])],
|
||||
"each field keeps its own point"
|
||||
);
|
||||
}
|
||||
|
||||
/// Only the field that matches keeps storage: a second field whose operands share no value files
|
||||
/// nothing, and the match slots of the first field are released with it.
|
||||
#[test]
|
||||
@@ -2772,16 +2445,12 @@ fn the_budget_charges_the_matching_names_it_collects() {
|
||||
);
|
||||
// A limit the run without the names admits is refused once they are collected.
|
||||
let matching = budget_matching(BinaryOp::Add, labels(absent(2_000)));
|
||||
let (output, admitted) = budgeted(&matching, &schema, &lhs, &schema, &rhs, none_peak);
|
||||
let (output, _) = budgeted(&matching, &schema, &lhs, &schema, &rhs, none_peak);
|
||||
let error = output.expect_err("the names are charged before the rewrite");
|
||||
assert!(
|
||||
matches!(error, DataFusionError::ResourcesExhausted(_)),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
admitted.iter().all(|&total| total <= none_peak),
|
||||
"{admitted:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2866,10 +2535,9 @@ fn a_budget_below_the_workspace_stops_the_operation() {
|
||||
limits.dedup();
|
||||
assert!(!limits.is_empty(), "{seen:?}");
|
||||
for limit in limits {
|
||||
let (output, admitted) = budgeted(&matching, &schema, &lhs, &schema, &rhs, limit);
|
||||
let (output, _) = budgeted(&matching, &schema, &lhs, &schema, &rhs, limit);
|
||||
let error = output.unwrap_err().to_string();
|
||||
assert!(error.contains("more than the"), "{error}");
|
||||
assert!(admitted.iter().all(|&total| total <= limit), "{admitted:?}");
|
||||
}
|
||||
// A budget of zero admits nothing, so the first step already fails.
|
||||
let (output, admitted) = budgeted(&matching, &schema, &lhs, &schema, &rhs, 0);
|
||||
@@ -3986,6 +3654,23 @@ fn duplicate_evidence_candidate_survives_false_gate_until_late_presence() {
|
||||
assert_eq!(evidence.verdict().unwrap().point, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_evidence_separates_node_field_pairs() {
|
||||
use datafusion::execution::memory_pool::{MemoryPool, UnboundedMemoryPool};
|
||||
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
|
||||
let evidence = super::DuplicateEvidence::new(&pool, 1);
|
||||
evidence.publish(0, 0, &[true], &[true], false).unwrap();
|
||||
evidence
|
||||
.record_candidate(0, 0, 0, Arc::new(vec![]), "left", 0)
|
||||
.unwrap();
|
||||
evidence.publish(0, 1, &[false], &[false], false).unwrap();
|
||||
evidence
|
||||
.record_candidate(0, 1, 0, Arc::new(vec![]), "left", 0)
|
||||
.unwrap();
|
||||
assert_eq!(evidence.verdict().unwrap().point, 0);
|
||||
assert!(evidence.verdict().unwrap().group.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_evidence_skips_ineligible_earlier_point() {
|
||||
use datafusion::execution::memory_pool::{MemoryPool, UnboundedMemoryPool};
|
||||
@@ -4004,23 +3689,6 @@ fn duplicate_evidence_skips_ineligible_earlier_point() {
|
||||
assert_eq!(evidence.verdict().unwrap().point, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_evidence_separates_node_field_pairs() {
|
||||
use datafusion::execution::memory_pool::{MemoryPool, UnboundedMemoryPool};
|
||||
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
|
||||
let evidence = super::DuplicateEvidence::new(&pool, 1);
|
||||
evidence.publish(0, 0, &[true], &[true], false).unwrap();
|
||||
evidence
|
||||
.record_candidate(0, 0, 0, Arc::new(vec![]), "left", 0)
|
||||
.unwrap();
|
||||
evidence.publish(0, 1, &[false], &[false], false).unwrap();
|
||||
evidence
|
||||
.record_candidate(0, 1, 0, Arc::new(vec![]), "left", 0)
|
||||
.unwrap();
|
||||
assert_eq!(evidence.verdict().unwrap().point, 0);
|
||||
assert!(evidence.verdict().unwrap().group.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_evidence_charges_memory_and_reports_refusal() {
|
||||
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, UnboundedMemoryPool};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user