diff --git a/src/promql/AGENTS.md b/src/promql/AGENTS.md index 03804148b72..08f7638a91d 100644 --- a/src/promql/AGENTS.md +++ b/src/promql/AGENTS.md @@ -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 diff --git a/src/promql/src/aggregate.rs b/src/promql/src/aggregate.rs index 730e09e7e8f..9bdc79b7830 100644 --- a/src/promql/src/aggregate.rs +++ b/src/promql/src/aggregate.rs @@ -75,10 +75,9 @@ pub enum Grouping<'a> { /// Groups are returned in the order their first input appears, as in Prometheus: a nested /// aggregation folds them in that order. /// -/// Evaluated inputs on the shared schema/grid are admitted. An operation that reads a value takes -/// float samples only; `count` and `group` ask whether a sample is present, so they also accept a -/// histogram. `by` on a value field needs per-point labels and an output schema adapter, and is -/// rejected. There is no fallback. +/// Inputs must be evaluated series on the schema's grid. `sum` and `avg` fold histogram samples, +/// `count` and `group` count them, and the other operations skip them. `by` naming a value field is +/// rejected. pub fn aggregate_float( schema: &Arc, input: &[Series], @@ -92,11 +91,8 @@ pub fn aggregate_float( aggregator.finish() } -/// [`aggregate_float`] fed one series at a time, for a caller that does not hold all its input -/// at once. Series are folded in the order they arrive, with the same semantics. -/// -/// The grouping labels are copied in, so the aggregator borrows nothing and can live in the -/// state of a stream. +/// [`aggregate_float`] fed one series at a time, in arrival order. Owns its grouping labels, so it +/// can live in a stream's state. pub struct FloatAggregator { schema: Arc, op: AggregateOp, @@ -111,26 +107,23 @@ pub struct FloatAggregator { /// What an aggregate does with a native histogram sample. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum HistogramSamples { - /// Counts it as one present sample: `count` counts every present sample, and `group` answers - /// `1` for a non-empty group, whatever the sample's type is. + /// `count` and `group`: counts as one present sample. Presence, - /// Ignores it and reports that it did: `min`, `max`, `stddev`, `stdvar` and `quantile` read a - /// float value, and Prometheus skips the histogram samples instead of refusing the statement. + /// `min`, `max`, `stddev`, `stdvar`: skipped and reported, as Prometheus does. Ignored, - /// Folds the payload and answers a histogram: `sum` adds native histograms bucket by bucket - /// and `avg` adds them and divides, as Prometheus does, so one group's result is a native - /// histogram. + /// `sum` and `avg`: folded bucket by bucket into a histogram result. Folded, } impl AggregateOp { - /// The words of `f64` one field's state of this aggregation keeps for one grid point. + /// The `f64` words one field's state keeps per grid point. The last word is the presence + /// word: the count where the state has one, else a `0`/`1` flag. Layouts: /// - /// The last word is the presence word: the op's own count where its state carries one, so a - /// zero count reads as unseen, and a `0`/`1` flag where it does not. The words before it are - /// the components the op folds, in [`Self::state_fields`] order. A state therefore costs what - /// its own operation needs instead of what the widest operation needs: a block holds - /// `BLOCK_POINTS * fields * state_words * size_of::()` bytes however wide the op is. + /// - `sum`: value, compensation, presence + /// - `avg`: value, compensation, mean, incremental-mean flag, count + /// - `min`/`max`: value, presence + /// - `stddev`/`stdvar`: sum of squared deviations, mean, count + /// - `count`: count; `group`: presence pub(crate) const fn state_words(self) -> usize { match self { Self::Count | Self::Group => 1, @@ -152,11 +145,8 @@ pub(crate) fn histogram_samples(op: AggregateOp) -> HistogramSamples { } } -/// Checks a series for the aggregate `op` folds, and returns its evaluated axis. -/// -/// Every operation this route folds takes a histogram series: it counts the sample, skips it, or -/// folds the payload. What a series must satisfy is therefore its axis, not its sample type -- the -/// fold itself is where a payload an operation cannot use is refused or dropped. +/// Checks a series against the schema and grid and returns its axis. Every op accepts histogram +/// samples here; the fold decides what to do with them. pub(crate) fn validate_aggregate_series<'a>( schema: &SeriesSchema, series: &'a Series, @@ -220,11 +210,8 @@ impl FloatAggregator { /// Folds `series` into its group. A series that fails validation leaves the state unchanged. /// - /// A budget refusal is not a validation failure: the fold may have opened a group or filled - /// blocks before the allocation it could not admit, so a failed [`Self::update_budgeted`] - /// leaves the state half folded and its retained figure stale. The runtime stops the execution - /// and drops the aggregator on that error, which is why no rollback is kept; a caller holding - /// one must drop it rather than fold into it again. + /// A budget refusal in [`Self::update_budgeted`] can leave the state half folded, with no + /// rollback; the caller must drop the aggregator after one. pub fn update(&mut self, series: &Series) -> Result<()> { self.update_budgeted(series, |_| Ok(())) } @@ -238,16 +225,10 @@ impl FloatAggregator { let existing_bytes = self.state_bytes(); let group_capacity = self.groups.capacity(); let map_capacity = self.group_index.capacity(); - // One admission for everything the fold can allocate before it writes a sample: the copy of - // this series' metric the grouping makes, the group's own copy of those labels and its - // key, the labels vector, and the group vector and index that may grow. What only a new - // group pays for is admitted whether or not this series opens one, so a chunk costs one - // pool call here instead of one per step, and a refusal still arrives before any of it is - // allocated. - // - // The grouping copy, the second workspace the copy is grouped into, and the group's - // retained labels and key are each a copy or a subset of this series' labels, so three - // copies of the one workspace bound all of them. + // One admission, before any allocation, for everything the fold may allocate before + // writing samples, including new-group costs whether or not a group opens. The grouping + // copy with its workspace, the group's labels, and its key are each bounded by one label + // workspace, hence three. let label_workspace = grouping_workspace_bytes(&series.metric); budget( existing_bytes @@ -258,9 +239,8 @@ impl FloatAggregator { .len() .saturating_mul(std::mem::size_of::<&str>()), ) - // 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 the retained - // state already holds. The map is admitted the same way. + // A realloc keeps both buffers alive while it copies, so growth admits the new + // buffer beside the old one already in `retained`. Same for the map. .saturating_add(if self.groups.len() == group_capacity { group_capacity .saturating_mul(2) @@ -340,25 +320,19 @@ impl FloatAggregator { Ok(()) } - /// Number of groups currently retained by this fold. pub(crate) fn groups(&self) -> usize { self.groups.len() } - /// The evidence the fold recorded, for the node that finishes the answer to report. pub(crate) fn evidence_summary(&self) -> HistogramEvidence { evidence_summary(&self.groups) } - /// Bytes reserved for this fold, using bounded allowances for its maps and group payloads. + /// Bytes admitted for this fold; an upper bound on what it holds. pub(crate) fn state_bytes(&self) -> usize { self.retained } - /// The evidence the histogram fold recorded for one position, for a fold test. - /// - /// It is the state the fold keeps beside its payload, so a test reads the bits where the state - /// export would read them rather than from a value the answer happens to imply. #[cfg(test)] pub(crate) fn histogram_evidence( &self, @@ -471,9 +445,7 @@ fn finish_groups_budgeted( let words = op.state_words(); let point_words = width.saturating_mul(words); for group in groups { - // A group that folded histogram samples answers histogram columns; one that folded floats - // keeps the float path below, so a group without a single histogram payload is built - // exactly as before. + // A group that folded histogram samples answers histogram columns. if !group.histograms.is_empty() { let finish_bytes = histogram_finish_bytes(&group, width); budget( @@ -496,7 +468,6 @@ fn finish_groups_budgeted( )?; continue; } - // One builder serves every group, so each result series starts explicitly. builder.begin_series(); let (rows, runs) = group_rows_runs(&group, width, op); let finish_bytes = finish_working_bytes(rows, runs, width); @@ -543,19 +514,16 @@ fn finish_groups_budgeted( /// Builds one group's histogram result, or `None` when it has nothing left to answer. /// -/// A position's answer is its live sum plus the compensation paired with it -- what the kernel's own -/// `sum` does at the end of its fold -- with the start timestamp cleared and the empty buckets -/// dropped. A poisoned position was removed, so it contributes no value; a position that is -/// poisoned in one field and answered in another still carries the row. +/// A poisoned position yields no value in its field; the row survives if another field answers. fn finish_histogram_group( op: AggregateOp, schema: &Arc, group: Group, width: usize, ) -> Result> { - // A field's column is one type. The fold already refuses a histogram where it had folded a - // float at that position; a float folded after a histogram is caught here, where the column - // type is chosen for the whole group. + // The output column type is chosen per group: any float state in a group that also folded + // histograms is refused, even when it is in another field or position. The fold itself only + // refuses the two kinds meeting in one field. if group.blocks.values().any(|states| { states .chunks_exact(op.state_words()) @@ -580,8 +548,7 @@ fn finish_histogram_group( let mut spans: Vec = Vec::new(); let mut row: Vec> = vec![None; width]; for position in positions { - // A poisoned position has no answer, so the row it would have made is dropped whole: every - // column is written once per *answered* position, or the columns and the axis would drift. + // Every column is written once per answered position, or the columns and the axis drift. let mut answered = false; for (field, value) in row.iter_mut().enumerate() { *value = match group.histograms.get(&(position, field)) { @@ -596,7 +563,6 @@ fn finish_histogram_group( if !answered { continue; } - // A gap between two answered positions ends a run, and a row belongs to the run it opens. match spans.last_mut() { Some(span) if span.start() + span.len() == position => { *span = GridSpan::new(span.start(), span.len() + 1); @@ -620,8 +586,6 @@ fn finish_histogram_group( Samples::try_from_histogram(UInt32Array::from(indices), batch).map_err(external)?, ); } - // The result is addressed by the runs that carry a histogram, not by the span between the first - // and the last one: the nulls padding them stay inside a run, never between two. let time = TimeAxis::from_grid_spans(grid, spans).map_err(external)?; Series::try_new( schema, @@ -633,12 +597,9 @@ fn finish_histogram_group( .map_err(external) } -/// One position's answer, compacted, or `None` when the point was poisoned. -/// -/// A sum answers its live value with the compensation folded in. An average in mean mode answers its -/// mean with the compensation folded in; one that never switched divides the sum and the compensation -/// by the sample count and then folds the compensation in, which is what `sum_or_avg` does at the end -/// of both paths. +/// One position's answer with the compensation folded in and empty buckets dropped, or `None` +/// when the point was poisoned. An average that never switched to mean mode divides the sum and +/// the compensation by the count first, as Prometheus `sum_or_avg` does. pub(crate) fn finished_histogram( op: AggregateOp, accumulator: &HistogramAccumulator, @@ -671,14 +632,11 @@ pub(crate) fn finished_histogram( value } }; - // The answer's empty buckets are dropped the way the kernel's own aggregate drops them. It also - // carries no start timestamp of its own, which every derivation above clears along with - // `compact`. value.compact(); Ok(Some(value)) } -/// Bytes [`finish_histogram_group`] works in while it builds one group's result. +/// Bytes [`finish_histogram_group`] allocates for one group's result. fn histogram_finish_bytes(group: &Group, width: usize) -> usize { let payload = group .histograms @@ -692,8 +650,7 @@ fn histogram_finish_bytes(group: &Group, width: usize) -> usize { .saturating_add(size_of::>>()) .saturating_add(size_of::()), ); - // Twice the fold's payload: the answer is one derived histogram per position, and an average - // divides a copy of its live value before it adds the compensation in. + // Twice the payload: one derived histogram per position, plus the copy an average divides. payload .saturating_mul(2) .saturating_add(rows.saturating_mul(size_of::>())) @@ -702,8 +659,7 @@ fn histogram_finish_bytes(group: &Group, width: usize) -> usize { .saturating_add(size_of::().saturating_add(size_of::())) } -/// The result of every group, without a budget: the entry the partial-state merger takes, which -/// does not hold a query pool to admit against. +/// [`finish_groups_budgeted`] without a budget. fn finish_groups( schema: Arc, op: AggregateOp, @@ -769,9 +725,9 @@ fn finish_working_bytes(rows: usize, runs: usize, width: usize) -> usize { .saturating_add(std::mem::size_of::() + std::mem::size_of::()) } -/// `quantile(q, v)`, with `q` read at each grid point from an unlabelled single-field scalar on -/// the same grid, as Prometheus evaluates the parameter at every step. A point where `q` has no -/// value has no result; `q` outside `[0, 1]` or NaN gives what Prometheus' `quantile` gives. +/// `quantile(q, v)` with `q` a time-varying scalar on the same grid. A point where `q` has no value +/// has no result; `q` outside `[0, 1]` or NaN behaves as in Prometheus. Histogram samples are +/// skipped. pub fn aggregate_quantile( schema: &Arc, input: &[Series], @@ -805,14 +761,12 @@ pub fn aggregate_quantile( let (mut values, mut sorted, mut row) = (Vec::new(), Vec::new(), Vec::with_capacity(width)); for (metric, members) in groups { builder.begin_series(); - // Each member's next position waits in a min-heap, so a point costs the members present - // there and not the whole group: a group of short-lived series stays linear in its - // samples. Ties pop in member order, the input order Prometheus appends values in. + // A min-heap of each member's next position keeps a point's cost proportional to the + // members present there. Ties pop in member order, the order Prometheus appends values. let mut positions: Vec<_> = members .iter() .map(|series| series.time.positions()) .collect(); - // Indexed by field, then member. let mut cursors: Vec> = (0..width) .map(|field| { members @@ -866,7 +820,7 @@ pub fn aggregate_quantile( Ok(output) } -/// Validates the schema-only requirements shared by the kernel and native runtime construction. +/// The schema checks of [`count_values`], shared with native runtime construction. pub(crate) fn validate_count_values( schema: &SeriesSchema, label: &str, @@ -906,7 +860,6 @@ pub fn count_values( grouping: Grouping<'_>, ) -> Result> { validate_count_values(schema, label, grouping)?; - // Unlike the other aggregations, this one reads histogram samples too. for series in input { validate_grid_series(schema, series)?; } @@ -924,8 +877,7 @@ pub fn count_values( // about one group per sample. let mut groups: Counts = Vec::new(); for series in input { - // Equal bits format to the same label value, so each distinct value of a series - // resolves its group once. A histogram is keyed by the text it is written as. + // Each distinct value of a series resolves its group once. let mut group_of_value: HashMap = HashMap::new(); for (field_index, field) in series.fields.iter().enumerate() { for ((point, _), sample) in series.time.positions().zip(field.iter()) { @@ -937,8 +889,6 @@ pub fn count_values( let group = match group_of_value.entry(key) { Entry::Occupied(entry) => *entry.get(), Entry::Vacant(entry) => { - // Prometheus writes a float in Go's `'f'` form and a histogram as - // `FloatHistogram.String` does. let text = match entry.key() { Value::Float(bits) => format_float_f(f64::from_bits(*bits)), Value::Histogram(text) => text.clone(), @@ -963,7 +913,7 @@ pub fn count_values( count_series(schema, groups) } -/// Counts per point and field: one series per label set, a count of 0 being no sample. +/// Counts per point and field for each label set; a count of 0 means no sample. type Counts = Vec<(SeriesLabels, BTreeMap>)>; fn count_series(schema: &Arc, groups: Counts) -> Result> { @@ -982,29 +932,23 @@ fn count_series(schema: &Arc, groups: Counts) -> Result) -> Result<()> { validate_grouping(schema, grouping)?; for series in input { - // `quantile` reads float values and skips a histogram sample the way Prometheus does, so - // the only thing it needs from a series is that it fits this schema and grid. validate_grid_series(schema, series)?; } Ok(()) } -/// Validates the grouping a whole-vector operation addresses its series by. -/// -/// The native route keys `topk`, `bottomk` and `limitk` groups by series labels only, while the -/// existing planner also accepts a value field there, where it varies between samples. Refusing -/// the field here keeps such a statement on the existing plan before native execution is chosen. +/// Validates the grouping of `topk`, `bottomk` and `limitk`. Native groups by series labels only, +/// so `by` a value field is refused, which keeps such a statement on the existing plan. pub(crate) fn validate_vector_grouping( schema: &SeriesSchema, grouping: Grouping<'_>, @@ -1084,15 +1028,10 @@ fn grouping_workspace_bytes(metric: &SeriesLabels) -> usize { .saturating_add(std::mem::size_of::()) } -/// Conservative backing estimate for Rust 1.98.1's insert-only `HashMap` (hashbrown 0.17.1). -/// Bucket count follows its 7/8 load factor; entries, one control byte per bucket and the -/// 16-byte control-group tail are counted. This models requested table storage, not allocator slack. /// An upper bound on the bytes the group index holds for `capacity` entries. /// -/// The table keeps its entries in a power-of-two number of buckets below `16/7` of the usable -/// capacity, with one control byte beside each bucket. Three buckets per entry therefore covers the -/// table whatever exact growth the map uses, which is what keeps this a bound rather than a model of -/// one implementation: a toolchain that changes how the map grows cannot make it under-count. +/// A hash table keeps a power-of-two bucket count below `16/7` of its usable capacity, plus one +/// control byte per bucket, so three buckets per entry bounds it whatever growth policy it uses. fn hash_map_backing_bytes(capacity: usize) -> usize { capacity .saturating_mul(3) @@ -1104,19 +1043,14 @@ fn next_hash_capacity(capacity: usize) -> usize { capacity.saturating_mul(2).max(7) } -/// An upper bound on the bytes one B-tree node holds. -/// -/// A node keeps at most eleven key/value pairs and twelve child pointers, plus a header of a few -/// words; the leaf form is smaller than that. The header allowance is generous on purpose, so the -/// bound does not depend on how a toolchain lays the node out. +/// An upper bound on the bytes one B-tree node holds: at most eleven pairs and twelve child +/// pointers, with a generous header allowance so the bound does not depend on node layout. fn btree_node_bytes() -> usize { 11 * size_of::<(usize, Box<[f64]>)>() + 16 * size_of::() } -/// An upper bound on the bytes a B-tree of `entries` holds. -/// -/// Every node but the root keeps at least five entries, so `entries / 5` nodes is enough to hold -/// them; a tree of one entry is one node. +/// An upper bound on the bytes a B-tree of `entries` holds: every node but the root keeps at +/// least five entries. fn btree_backing_bytes(entries: usize) -> usize { if entries == 0 { return 0; @@ -1124,8 +1058,7 @@ fn btree_backing_bytes(entries: usize) -> usize { entries.div_ceil(5).saturating_mul(btree_node_bytes()) } -/// Transient bytes the fold needs for one field's row while it folds a series. The samples are -/// written straight into their blocks, so a block's staging buffer is no longer part of this. +/// Transient bytes the fold needs for one row while it folds a series. fn pending_bytes(fields: usize) -> usize { fields.saturating_mul(std::mem::size_of::>() + 1) } @@ -1161,13 +1094,11 @@ fn label_key(metric: &SeriesLabels) -> LabelKey { labels } -/// Grid points per state block. A block is allocated only once a sample falls in it, so sparse -/// input never expands to the full grid and dense input costs one allocation per block. +/// Grid points per state block. Blocks are allocated on first sample, so sparse input never +/// expands to the full grid. const BLOCK_POINTS: usize = 64; -/// Bytes one allocated block keeps: a state per point per field, [`AggregateOp::state_words`] -/// words of `f64` each. The fold, the merge and the recount all size a block through this, so what -/// is admitted and what is allocated cannot drift apart. +/// Bytes one block keeps. The fold, the merge and the recount all size blocks through this. fn block_bytes(width: usize, op: AggregateOp) -> usize { BLOCK_POINTS .saturating_mul(width) @@ -1177,56 +1108,33 @@ fn block_bytes(width: usize, op: AggregateOp) -> usize { struct Group { metric: SeriesLabels, - /// Keyed by absolute grid index / `BLOCK_POINTS`; each block holds one state per field for - /// each of its points, point by point, each state as many `f64` words as the op folds. + /// Keyed by absolute grid index / `BLOCK_POINTS`; point-major, then field, then state words. blocks: BTreeMap>, - /// The histogram states of this group, keyed by absolute grid position and field. - /// - /// Only an aggregate that folds a payload allocates one, and only where it saw a histogram - /// sample, so a float fold never touches this map and its state stays the blocks alone. + /// Histogram states of `sum`/`avg`, keyed by (absolute grid position, field). histograms: BTreeMap<(usize, usize), HistogramAccumulator>, } -/// One position's histogram fold: the live payload, the compensation paired with it, the running -/// mean an average switched to, and the evidence the fold recorded beside them. +/// One position's histogram `sum`/`avg` fold. Maps onto the `HistogramState` payload: `value` is +/// `histogram_value`, `compensation` is `histogram_compensation`, `mean` is set in +/// `incremental_mean` mode. A `sum` fold leaves `mean` at `None` and does not update `count`. /// -/// The payload here is the kernel's own owned histogram rather than the state frame's row -/// representation: a fold adds bucket by bucket, and rebuilding a frame row per sample would -/// re-encode the layout it just added into. The state export builds that row from this. -/// -/// The fields are the `HistogramAvg` state layout of the design: `value` is the state's -/// `histogram_value`, `mean` is its `incremental_mean` mode, `count` is its `count`, and -/// `compensation` is its `histogram_compensation`. A `sum` fold leaves `mean` at `None` and only -/// counts for the average's sake. -/// -/// The legacy `prom_native_histogram_agg_sum`/`_avg` accumulators fold through this one as well, so -/// their arithmetic is this arithmetic; only their state frame differs. +/// The legacy `prom_native_histogram_agg_sum`/`_avg` accumulators fold through this type too. #[derive(Debug)] pub(crate) struct HistogramAccumulator { - /// The live value: the running sum, or -- once an average switched -- the sum the switch started - /// from, which the mean is derived from. + /// The running sum; once an average switched to mean mode, the sum at the switch. value: FloatHistogram, - /// The compensation paired with `value`, carrying `value`'s bucket layout. - /// - /// It is `None` only while a [`FloatHistogram::kahan_add`] call owns it, and stays `None` once - /// the position is poisoned: a poisoned point folds nothing more, so there is nothing left to - /// compensate. + /// The compensation of the live value, with its bucket layout. `None` only while + /// [`FloatHistogram::kahan_add`] owns it, and once the position is poisoned. compensation: Option, /// The running mean an average switched to once its sum overflowed; `None` while it still sums. mean: Option, - /// Samples folded into this position, which is the divisor an average's mean uses. + /// Samples folded in; maintained only by `avg`. count: f64, - /// The evidence bits this fold recorded. A legacy accumulator keeps its own copy of the bits its - /// state frame can carry and seeds them in before every operation. pub(crate) evidence: HistogramEvidence, } -/// The evidence bits a histogram fold records beside its payload. -/// -/// These are the Boolean components of the histogram state layout: the fold records them per point -/// so a merge of two partitions can report what the inputs disagreed about. Only `poisoned` steers -/// the fold's own output today -- a poisoned point is removed -- and the rest are carried for that -/// merge, except `counter_reset_collision`, which is decided from them when the answer is finished. +/// Per-point flags a histogram fold records, carried in the state so a merge can report them. +/// Only `poisoned` changes the answer: a poisoned point is removed. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct HistogramEvidence { /// The point cannot be answered because its samples disagreed on their bucket layout. @@ -1239,20 +1147,12 @@ pub(crate) struct HistogramEvidence { pub(crate) counter_reset_seen: bool, /// Some sample reported that no counter reset happened. pub(crate) not_counter_reset_seen: bool, - /// One point saw both a reset hint and its negation, which cannot both hold of its samples. - /// - /// The two bits above are recorded per point and travel through the state, so a summary of them - /// is a claim about the fold rather than about one point. This bit is the per-point decision: - /// [`evidence_summary`] sets it for a point that holds both bits and is not poisoned, so two - /// groups that each saw one of the hints do not contradict each other. + /// One unpoisoned point saw both hints. Set only by [`evidence_summary`]; never carried in + /// the state. pub(crate) counter_reset_collision: bool, } -/// Which field of which layout a fold is writing, and how it folds it. -/// -/// One value carried through the per-block work instead of three separate arguments: the three -/// never vary independently within one series, and the block loop is the only place that reads -/// them. +/// Which field of which block layout a fold is writing. #[derive(Clone, Copy)] struct FieldFold { width: usize, @@ -1261,12 +1161,11 @@ struct FieldFold { } impl FieldFold { - /// Words one point of this fold's block keeps: every field's state, side by side. fn point_words(self) -> usize { self.width.saturating_mul(self.op.state_words()) } - /// Where this field's state of the point at `offset` starts inside a block. + /// Where this field's state for the point at `offset` starts inside a block. fn state_start(self, offset: usize) -> usize { offset .saturating_mul(self.point_words()) @@ -1275,12 +1174,8 @@ impl FieldFold { } impl Group { - /// Folds one series' float samples into this group's blocks, one field at a time. - /// - /// Within a field the samples arrive in position order, so the first sample of a block admits - /// that block and allocates its states, and every following sample of the same block is written - /// into the states just placed. Each block needs one acquisition per field run, and a field - /// with no value in a block leaves that block unallocated. + /// Folds one series into this group, one field at a time. Samples arrive in position order, + /// so a block is looked up (and admitted, if new) once per run of samples inside it. fn accumulate( &mut self, series: &Series, @@ -1289,8 +1184,7 @@ impl Group { mut retained: usize, width: usize, ) -> Result { - // The grouping workspace the caller admitted for this series is gone once the fold starts, - // so only the retained state stays charged while the samples are written. + // Re-admit without the grouping workspace, which is freed by now. budget(retained)?; for (field_index, field) in series.fields.iter().enumerate() { let fold = FieldFold { @@ -1298,10 +1192,8 @@ impl Group { field_index, op, }; - // A payload-folding aggregate keeps its own per-position histogram state, addressed by - // the absolute grid position: histogram samples never enter the block buffer the float - // samples share, and a field that carries them cannot also carry floats. A float field - // of the same aggregate still folds through that buffer, so the branch is per field. + // The branch is per field, but `finish_histogram_group` refuses a group holding both + // float and histogram state in any field. let folds_histograms = histogram_samples(op) == HistogramSamples::Folded && field .iter() @@ -1313,8 +1205,6 @@ impl Group { SampleRef::Histogram(view) => { retained = self.fold_histogram(fold, index, &view, budget, retained)?; } - // The finish step refuses the other order (a float folded after a - // histogram); refusing this one here keeps the column single-typed. SampleRef::Float(_) => { return Err(DataFusionError::Execution( "a native aggregate cannot mix float and histogram samples in one field" @@ -1325,10 +1215,6 @@ impl Group { } continue; } - // The axis says which absolute positions the field holds and the field iterator - // supplies them in order, so a sparse axis never turns into its envelope here. Samples - // that hold nothing never reach a state, and `validate_aggregate_series` has already - // decided how this aggregate treats histogram samples. let mut samples = series .time .positions() @@ -1336,17 +1222,9 @@ impl Group { .filter_map(|((index, _), sample)| match sample { SampleRef::Float(sample) => Some((index, sample)), SampleRef::Histogram(_) => match histogram_samples(op) { - // `count` and `group` ask whether a sample is present, not which payload - // it carries, so a histogram is one contribution. The value is a - // placeholder: `FloatState` counts the contributions for `count` and only - // records that it saw one for `group`. + // The value is a placeholder: `count` and `group` never read it. HistogramSamples::Presence => Some((index, 1.0)), - // Prometheus skips a histogram sample where the aggregate reads a float - // value; the runtime reports that it did. HistogramSamples::Ignored => None, - // A payload-folding aggregate never reaches this loop: its samples were - // folded in the histogram branch above, and a field carrying both kinds is - // refused there. HistogramSamples::Folded => { unreachable!("a payload-folding aggregate folds histograms above") } @@ -1373,11 +1251,8 @@ impl Group { Ok(retained) } - /// The states of `block` for this field, admitting and allocating the block if this field has - /// not written there yet, along with the retained bytes after that admission. - /// - /// A new block is admitted before the tree holds it, so a refused allocation leaves no block - /// behind and the retained figure never counts an allocation that was not made. + /// The states of `block`, admitting and allocating it if new, and the retained bytes after. + /// Admission precedes insertion, so a refusal leaves no block behind. fn block_states<'a>( &'a mut self, block: usize, @@ -1412,17 +1287,9 @@ impl Group { impl Group { /// Folds one histogram sample into its position's state, admitting what the fold allocates. /// - /// The first sample of a position establishes the state: it is the live value, and its - /// compensation is the layout-carrying zero `new_compensation` builds -- never an `empty_like` - /// histogram, which has no bucket indices for the compensated add to index. Every later sample - /// is one [`FloatHistogram::kahan_add`] into the live value (an average's mean once it switched), - /// carrying the compensation this position already holds. - /// - /// Two samples whose bucket layouts cannot be added (exponential meeting custom buckets) poison - /// the position instead of failing the statement, and a poisoned position folds nothing more: - /// Prometheus drops the point, so the evidence is what survives. Numeric overflow is not a reason - /// to poison a point -- a saturated sum answers `Inf`, as the kernel's own sum does, and an - /// average switches to its mean instead. + /// Exponential buckets meeting custom buckets poison the position instead of failing the + /// statement, as Prometheus drops the point; a poisoned position folds nothing more. Overflow + /// does not poison: a sum answers `Inf` and an average switches to mean mode. fn fold_histogram( &mut self, fold: FieldFold, @@ -1431,9 +1298,7 @@ impl Group { budget: &mut impl FnMut(usize) -> Result<()>, retained: usize, ) -> Result { - // A field's column is either float or histogram, so a position that already folded a float - // cannot also fold a histogram. The other order is caught when the fold is finished, which - // is where the column type is chosen. + // The reverse order, a float after a histogram, is caught in `finish_histogram_group`. if let Some(states) = self.blocks.get(&(position / BLOCK_POINTS)) { let words = fold.op.state_words(); let start = fold.state_start(position % BLOCK_POINTS); @@ -1453,8 +1318,6 @@ impl Group { 0 }; if vacant { - // Admit the new position before allocating it: a live value, the compensation that - // starts beside it, and the map node holding both. budget( retained .saturating_add(size_of::()) @@ -1466,7 +1329,7 @@ impl Group { .histograms .entry(key) .or_insert_with(|| HistogramAccumulator::from_sample(&sample)); - // The evidence follows the sample's own reset hint, whether or not the point still folds. + // Hints are recorded even for a poisoned point. match sample.reset_hint { CounterResetHint::CounterReset => accumulator.evidence.counter_reset_seen = true, CounterResetHint::NotCounterReset => accumulator.evidence.not_counter_reset_seen = true, @@ -1476,13 +1339,11 @@ impl Group { return Ok(retained); } if vacant { - // The admitted estimate is an upper bound; what the fold keeps is the real figure. return Ok(retained .saturating_add(accumulator_bytes(accumulator)) .saturating_add(backing)); } - // An add can grow both bucket lists, so the incoming sample's payload on top of what the - // position already holds is what is admitted; the figure kept afterwards is the real one. + // An add can grow the buckets by at most the sample's payload. let before = accumulator_bytes(accumulator); budget( retained @@ -1490,8 +1351,6 @@ impl Group { .saturating_add(sample.heap_bytes()), )?; if accumulator.uses_custom_buckets() != sample.uses_custom_buckets() { - // Exponential buckets cannot be added to custom ones: the point is removed rather than - // answered, and the evidence says why. accumulator.poison(); return Ok(retained); } @@ -1507,8 +1366,8 @@ impl Group { } impl HistogramAccumulator { - /// A fold that has taken `sample` and nothing else: the sample is the live value, the - /// compensation is the layout-carrying zero built beside it, and one sample is counted. + /// A fold of `sample` alone. The compensation must come from `new_compensation`: an + /// `empty_like` histogram has no bucket indices for the compensated add. pub(crate) fn from_sample(sample: &FloatHistogram) -> Self { Self { value: sample.clone(), @@ -1519,7 +1378,7 @@ impl HistogramAccumulator { } } - /// Whether the live value -- the mean once an average switched -- uses custom buckets. + /// Whether the live value (the mean once an average switched) uses custom buckets. pub(crate) fn uses_custom_buckets(&self) -> bool { match &self.mean { Some(mean) => mean.uses_custom_buckets(), @@ -1527,15 +1386,14 @@ impl HistogramAccumulator { } } - /// Removes this position: its samples disagreed on their bucket layout, so it answers nothing - /// and the evidence says why. + /// Marks this position as answering nothing because its bucket layouts are incompatible. pub(crate) fn poison(&mut self) { self.evidence.poisoned = true; self.evidence.incompatible_layout = true; self.compensation = None; } - /// Adds one sample into the running sum, one compensated add into the live value. + /// Adds one sample into the running sum. Does not update `count`. pub(crate) fn fold_sum(&mut self, sample: &FloatHistogram) -> Result<()> { let (compensation, outcome) = self.value.kahan_add(sample, self.compensation.take())?; self.compensation = Some(compensation); @@ -1543,24 +1401,16 @@ impl HistogramAccumulator { Ok(()) } - /// Averages one sample in, switching from the running sum to a running mean when the sum would - /// overflow. - /// - /// Each step is Prometheus v3.15's `aggregation`/`sum_or_avg` average in the same order: the - /// trial add is what decides the mode, and once it overflows the trial is discarded, the sum so - /// far becomes the mean of the samples before this one, and every later sample enters as - /// `sample / count` weighted by `(count - 1) / count`. Dividing before adding is what keeps a - /// mean of finite inputs finite: two histograms of `1e308` at one observation each average to - /// `1e308`, while `(1e308 + 1e308) / 2` would be `Inf`. + /// Averages one sample in, following Prometheus `aggregation` for `avg`: sum until a trial + /// add overflows, then switch to an incremental mean where each sample enters as + /// `sample / count` and the mean is weighted by `(count - 1) / count`, so finite inputs keep a + /// finite mean. pub(crate) fn fold_avg(&mut self, sample: &FloatHistogram) -> Result<()> { self.count += 1.0; if self.mean.is_none() { - // The trial runs on a copy, so an overflowing add leaves the sum it started from intact - // -- that sum is what the mean begins at. let mut trial = self.value.clone(); let (compensation, outcome) = trial.kahan_add(sample, self.compensation.clone())?; - // A reconciliation counts whether or not the trial is kept: the two sides' bounds meet - // in it either way. + // Counts whether or not the trial is kept. self.evidence.custom_bounds_reconciled |= outcome.custom_bounds_reconciled; if !trial.has_overflow() { self.value = trial; @@ -1574,8 +1424,7 @@ impl HistogramAccumulator { } self.mean = Some(started); } - // The mean's unit follows the value's: the compensation is scaled by the same weight the - // value is, and the incoming sample is divided before it is added. + // The compensation is scaled with the mean. let q = (self.count - 1.0) / self.count; if let Some(compensation) = self.compensation.as_mut() { compensation.mul(q); @@ -1592,15 +1441,8 @@ impl HistogramAccumulator { } impl HistogramAccumulator { - /// This position's state as the frame payload a `Partial` hands over. - /// - /// The payload is the fold's own state, not its answer: a sum exports the running sum and the - /// compensation beside it, and folding the compensation in belongs to the merge that finishes the - /// answer. An average exports whichever value it is keeping -- the sum it still adds to, or the - /// mean it switched to -- with the count and the mode flag that say how to read them. - /// - /// A poisoned position exports the empty placeholders the state layout reserves for it: it - /// answers nothing, and the merge reads its evidence, not its buckets. + /// This position's state as a `Partial` payload: the value (sum, or mean once switched) and + /// its compensation unfolded. A poisoned position exports empty histograms and its evidence. pub(crate) fn payload(&self, op: AggregateOp) -> Result { if self.evidence.poisoned { let empty = self.value.empty_like(); @@ -1618,7 +1460,6 @@ impl HistogramAccumulator { } let switched = self.mean.is_some(); let value = match op { - // A sum's state is its running sum: adding the compensation in is the merge's job. AggregateOp::Sum => &self.value, AggregateOp::Avg if switched => self.mean.as_ref().expect("checked above"), AggregateOp::Avg => &self.value, @@ -1631,8 +1472,7 @@ impl HistogramAccumulator { Ok(StatePayload::Histogram(Box::new(HistogramState { value: histogram_batch(value)?, compensation: histogram_batch(&compensation)?, - // A sum's state declares no count and no mean mode, so both stay at their defaults: the - // payload cannot claim a component its kind does not carry. + // A sum's state kind carries no count and no mean mode. count: if op == AggregateOp::Avg { self.count } else { @@ -1647,21 +1487,16 @@ impl HistogramAccumulator { }))) } - /// The state a decoded payload carries, as the merge keeps it. pub(crate) fn from_payload(op: AggregateOp, payload: &HistogramState) -> Result { let value = decoded_histogram(&payload.value)?; let compensation = decoded_histogram(&payload.compensation)?; let switched = op == AggregateOp::Avg && payload.incremental_mean; Ok(Self { - // An average that switched keeps its mean in the mean slot; the sum it switched from is - // not part of the state it exported, so the value slot holds the mean too. + // The pre-switch sum is not exported, so a switched average holds the mean in both. value: value.clone(), compensation: Some(compensation), mean: switched.then_some(value), count: payload.count, - // A decoded state is one point's payload, so whether its two hint bits contradict is - // decided where the whole answer is, in `evidence_summary`: the state layout carries the - // bits, not the decision. evidence: HistogramEvidence { poisoned: payload.poisoned, incompatible_layout: payload.incompatible_layout, @@ -1673,12 +1508,8 @@ impl HistogramAccumulator { }) } - /// Merges another partition's state into this position's. - /// - /// The rules are the design's: a sum adds both sides' values and then both sides' compensations - /// into the live value, and an average either adds its sums the same way -- when that stays - /// finite -- or continues in mean mode from the means and the counts, dividing before it adds. - /// Poison is sticky, and both sides' evidence is kept whatever the outcome of the arithmetic. + /// Merges another partition's state into this position's. Poison is sticky and both sides' + /// evidence is kept. pub(crate) fn merge_state(&mut self, op: AggregateOp, other: &HistogramState) -> Result<()> { self.evidence.poisoned |= other.poisoned; self.evidence.incompatible_layout |= other.incompatible_layout; @@ -1686,15 +1517,11 @@ impl HistogramAccumulator { self.evidence.counter_reset_seen |= other.counter_reset_seen; self.evidence.not_counter_reset_seen |= other.not_counter_reset_seen; if self.evidence.poisoned { - // A poisoned point answers nothing, so there is no value to merge into it. return Ok(()); } let right = decoded_histogram(&other.value)?; let right_compensation = decoded_histogram(&other.compensation)?; - // Two partitions can each be valid on their own and still disagree: one folded exponential - // buckets, the other custom ones. The fold removes such a point when both layouts meet - // inside one partition, so the merge reports it the same way instead of letting the add - // refuse the layouts and fail the whole statement. + // Poison, as the fold does, rather than let the add fail the statement. let left_uses_custom = self.uses_custom_buckets(); if left_uses_custom != right.uses_custom_buckets() { self.evidence.poisoned = true; @@ -1713,11 +1540,8 @@ impl HistogramAccumulator { } } - /// Merges two sums: both values and then both compensations go into the live value. - /// - /// The receiver stays the live value for both adds -- the compensation's unit follows the value's - /// -- so the second add folds the other side's compensation into the sum this state carries, not - /// into the compensation the first add returned. + /// Merges two sums: the other value, then the other compensation, are each Kahan-added into + /// the live value. fn merge_sum( &mut self, right: FloatHistogram, @@ -1737,8 +1561,7 @@ impl HistogramAccumulator { Ok(()) } - /// Merges an average: the sums add while they stay finite, and otherwise the means and their - /// counts do. + /// Merges an average: sums add while they stay finite, otherwise count-weighted means do. fn merge_avg( &mut self, right: FloatHistogram, @@ -1759,8 +1582,7 @@ impl HistogramAccumulator { .clone() .unwrap_or_else(|| left_value.new_compensation()); if !left_is_mean && !right_is_mean { - // Sum and sum: steps 1-2 on a copy of the left sum. The trial is what decides the mode, - // and a reconciliation it reports counts whether or not it is kept. + // A reconciliation counts whether or not the trial is kept. let mut trial = left_value.clone(); let (compensation, first) = trial.kahan_add(&right, Some(left_compensation.clone()))?; let (compensation, second) = @@ -1774,10 +1596,8 @@ impl HistogramAccumulator { return Ok(()); } } - // The mean path, written so that no intermediate product or sum can overflow: each side - // becomes a mean, its count becomes a weight, and the weighted means are scaled before they - // are added -- with their compensations scaled the same way, because the compensation's unit - // is the value's. + // Scale each side's mean (and compensation) by its weight before adding, so no + // intermediate overflows. let weight_left = left_count / total; let weight_right = right_count / total; let mut left_mean = left_value; @@ -1810,14 +1630,13 @@ impl HistogramAccumulator { } } -/// One histogram as the frame payload's own one-row batch. +/// One histogram as a one-row batch. pub(crate) fn histogram_batch(histogram: &FloatHistogram) -> Result> { let mut builder = HistogramBatchBuilder::new(); histogram.push_to(&mut builder)?; builder.finish().map_err(external) } -/// The histogram a payload component carries. fn decoded_histogram(batch: &HistogramBatch) -> Result { let view = batch.view(0).ok_or_else(|| { DataFusionError::Execution("a histogram state component carries no histogram".into()) @@ -1825,20 +1644,9 @@ fn decoded_histogram(batch: &HistogramBatch) -> Result { FloatHistogram::try_from_view(&view) } -/// The evidence a fold or a merge has to report, once, wherever it finishes. -/// -/// A poisoned point suppresses its own reconciliation bit: the point answers nothing, so reporting -/// that its bounds were reconciled would report a reconciliation of an answer that is not there. -/// -/// The reset hints are per point too: a point whose samples report a reset and no reset contradicts -/// itself -- Prometheus skips such a point -- while two points that each report one of the two do -/// not contradict each other, and neither does one series whose hint changes from one point to the -/// next. The summary therefore ORs the per-point collision rather than the two bits themselves: a -/// `sum by (job)` whose `job` a only ever resets and whose `job` b never does is two ordinary -/// points, and a point cannot be both poisoned and in contradiction. -/// -/// Everything else is reported if any point recorded it, which is what makes the message set the same -/// whichever order the partitions were merged in. +/// The evidence to report for all groups, independent of merge order. A poisoned point reports +/// neither a reconciliation nor a reset collision. A collision is per point: two points that each +/// saw one hint do not collide. fn evidence_summary(groups: &[Group]) -> HistogramEvidence { let mut summary = HistogramEvidence::default(); for accumulator in groups.iter().flat_map(|group| group.histograms.values()) { @@ -1854,7 +1662,7 @@ fn evidence_summary(groups: &[Group]) -> HistogramEvidence { summary } -/// Bytes one histogram position holds: every histogram it keeps, with buckets, bounds and spans. +/// Bytes one histogram position holds. pub(crate) fn accumulator_bytes(accumulator: &HistogramAccumulator) -> usize { size_of::() .saturating_add(accumulator.value.heap_bytes()) @@ -1885,20 +1693,14 @@ fn histogram_backing_bytes(entries: usize) -> usize { entries.div_ceil(5).saturating_mul(histogram_node_bytes()) } -/// The float part of Prometheus' `groupedAggregation`, as a view of one state's words. -/// -/// A state is [`AggregateOp::state_words`] words of the block it sits in: the components the op -/// folds, then the presence word. The view reads and writes that layout in place, so folding -/// allocates nothing per state and an op that keeps less memory keeps less. +/// The float part of Prometheus' `groupedAggregation`, over one state's words in place; the layout +/// is documented on [`AggregateOp::state_words`]. struct FloatState<'a> { words: &'a mut [f64], op: AggregateOp, } -/// Whether the state in `words` has seen a sample: its presence word is set. -/// -/// The presence word is the last one, which is the op's count where its state carries one - a -/// state that has folded nothing has no count - and a `0`/`1` flag where it does not. +/// Whether the state in `words` has seen a sample. fn state_seen(words: &[f64], op: AggregateOp) -> bool { words[op.state_words() - 1] != 0.0 } @@ -1909,56 +1711,44 @@ fn state_finish(words: &[f64], op: AggregateOp) -> Option { return None; } Some(match op { - // `value`, its compensation, then the presence flag. AggregateOp::Sum => words[0] + words[1], - // `value`, `compensation`, `mean`, the incremental flag, then the count. AggregateOp::Avg if words[3] != 0.0 => words[2] + words[1], AggregateOp::Avg => words[0] / words[4] + words[1] / words[4], AggregateOp::Count => words[0], AggregateOp::Min | AggregateOp::Max => words[0], AggregateOp::Group => 1.0, - // `value`, `mean`, then the count. AggregateOp::Stdvar => words[0] / words[2], AggregateOp::Stddev => (words[0] / words[2]).sqrt(), }) } impl<'a> FloatState<'a> { - /// The state at `words`, which is `op`'s layout: [`AggregateOp::state_words`] words. fn new(words: &'a mut [f64], op: AggregateOp) -> Self { debug_assert_eq!(words.len(), op.state_words()); Self { words, op } } - /// Folds one sample in, initializing the state if it had seen none. fn update(self, sample: f64) { let (op, words) = (self.op, self.words); if !state_seen(words, op) { match op { - // The count is the presence word. AggregateOp::Count => words[0] = 1.0, - // Presence alone: `group` answers 1 for any kind of sample, NaN included, so the - // sample itself is not kept - a zero sample would read as unseen. AggregateOp::Group => words[0] = 1.0, - // `value`, then the presence flag. AggregateOp::Min | AggregateOp::Max => { words[0] = sample; words[1] = 1.0; } - // `value`, its compensation, then the presence flag. AggregateOp::Sum => { words[0] = sample; words[1] = 0.0; words[2] = 1.0; } - // The running sum of squared deviations, which Prometheus starts at NaN for a - // non-finite first sample; then `mean` and the count that says it is seen. + // Prometheus starts the sum of squared deviations at NaN for a non-finite sample. AggregateOp::Stddev | AggregateOp::Stdvar => { words[0] = if sample.is_finite() { 0.0 } else { f64::NAN }; words[1] = sample; words[2] = 1.0; } - // `value`, `compensation`, `mean`, the incremental flag, then the count. AggregateOp::Avg => { words[0] = sample; words[1] = 0.0; @@ -1998,8 +1788,8 @@ impl<'a> FloatState<'a> { } } -/// `avg`'s update: sums directly until the running sum would overflow, then switches to an -/// incremental mean, whose flag is the fourth word. +/// `avg`'s update: sums until the running sum would overflow, then switches to an incremental +/// mean. fn update_avg(words: &mut [f64], sample: f64) { let count = words[4] + 1.0; words[4] = count; diff --git a/src/promql/src/aggregate/state.rs b/src/promql/src/aggregate/state.rs index 5863dac0569..f6a2b6f0508 100644 --- a/src/promql/src/aggregate/state.rs +++ b/src/promql/src/aggregate/state.rs @@ -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 { 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::()); 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 { 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>> = (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, position: usize) { match spans.last_mut() { Some(span) if span.start() + span.len() == position => { @@ -265,25 +239,14 @@ fn extend_spans(spans: &mut Vec, 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::()) } -/// 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, 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 { 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 { ..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, partials: impl IntoIterator, diff --git a/src/promql/src/aggregate/tests.rs b/src/promql/src/aggregate/tests.rs index 3cd19c84dab..91154d274a3 100644 --- a/src/promql/src/aggregate/tests.rs +++ b/src/promql/src/aggregate/tests.rs @@ -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::>(); - 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 = 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 = (0..2) - .map(|index| histogram_series(&schema, &format!("a{index}"), vec![(0, large())])) - .collect(); - let right_input: Vec = (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] diff --git a/src/promql/src/evaluated.rs b/src/promql/src/evaluated.rs index 473c76bf4ba..1b369b1c00f 100644 --- a/src/promql/src/evaluated.rs +++ b/src/promql/src/evaluated.rs @@ -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 { - // 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])); diff --git a/src/promql/src/grid_series.rs b/src/promql/src/grid_series.rs index d3f754a7335..8bede5edeb5 100644 --- a/src/promql/src/grid_series.rs +++ b/src/promql/src/grid_series.rs @@ -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) -> usize { std::mem::size_of::().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::()) } -/// 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, grid: Arc, /// 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, - /// One row per retained row, per field; empty when nothing is buffered. + /// Empty until the first retained row of a hand-out. fields: Vec, } @@ -164,7 +149,7 @@ pub(crate) fn owned(sample: SampleRef<'_>) -> Result> { } 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) -> Result { 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]) -> 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> { 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> { self.collect(metric) } - /// Turns the buffered rows into one series over the runs they make up. fn collect(&mut self, metric: SeriesLabels) -> Result> { 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, series: Vec) -> Result> { let mut groups: HashMap> = HashMap::with_capacity(series.len()); let mut collided = false; @@ -503,31 +455,22 @@ pub fn merge_same_labelset(schema: &Arc, series: Vec) -> 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> = 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)> = 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 = 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, series: Vec) -> 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, series: Vec) -> 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> = 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, series: Vec) -> 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, series: Vec) -> 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 { let mut chunks: Vec = Vec::new(); - // The run of values the last merged row continued, if any. let mut run: Option> = 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) -> 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, missing: &mut usize) { if *missing != 0 { chunks.push(Samples::from_float(Float64Array::new_null(*missing))); diff --git a/src/promql/src/grid_series/reference.rs b/src/promql/src/grid_series/reference.rs index b80d89a20ee..9bdc8b259c1 100644 --- a/src/promql/src/grid_series/reference.rs +++ b/src/promql/src/grid_series/reference.rs @@ -35,9 +35,6 @@ use crate::histogram_eval::float_histogram::FloatHistogram; pub(crate) type Dense = Vec>>; /// 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 = 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) -> std::collections::BTreeMap { 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, 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, 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)), ) diff --git a/src/promql/src/grid_series/tests.rs b/src/promql/src/grid_series/tests.rs index 203de9e9f2c..97c49b1b055 100644 --- a/src/promql/src/grid_series/tests.rs +++ b/src/promql/src/grid_series/tests.rs @@ -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::>(); - // 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::() ); - // 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, Option<&'a str>, Option); -/// 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, 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 { 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, 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, 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 = 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 = 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 { 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> { 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 { let hint = match view.reset_hint { CounterResetHint::Unknown => 0, @@ -1620,8 +1364,7 @@ fn payload(view: &HistogramView<'_>) -> Vec { 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()), diff --git a/src/promql/src/histogram_eval.rs b/src/promql/src/histogram_eval.rs index a10792fb962..e0400f91edf 100644 --- a/src/promql/src/histogram_eval.rs +++ b/src/promql/src/histogram_eval.rs @@ -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>, collector: Option<&PromqlAnnotationCollector>, ) -> Result> { - // 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 = HashMap::new(); let mut groups: Vec> = 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, @@ -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", diff --git a/src/promql/src/histogram_eval/aggregate.rs b/src/promql/src/histogram_eval/aggregate.rs index 7db4a11c6eb..3abbac8e05c 100644 --- a/src/promql/src/histogram_eval/aggregate.rs +++ b/src/promql/src/histogram_eval/aggregate.rs @@ -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>, @@ -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)) } diff --git a/src/promql/src/histogram_eval/float_histogram.rs b/src/promql/src/histogram_eval/float_histogram.rs index 42ed96216e1..ab6012931db 100644 --- a/src/promql/src/histogram_eval/float_histogram.rs +++ b/src/promql/src/histogram_eval/float_histogram.rs @@ -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 = 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, 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 { 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 { 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, diff --git a/src/promql/src/histogram_eval/legacy_bridge.rs b/src/promql/src/histogram_eval/legacy_bridge.rs index a83d47533e2..e2d0c0690f1 100644 --- a/src/promql/src/histogram_eval/legacy_bridge.rs +++ b/src/promql/src/histogram_eval/legacy_bridge.rs @@ -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, @@ -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 { 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::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)> { // 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); diff --git a/src/promql/src/histogram_eval/native.rs b/src/promql/src/histogram_eval/native.rs index cc72515a1d7..4401f515b39 100644 --- a/src/promql/src/histogram_eval/native.rs +++ b/src/promql/src/histogram_eval/native.rs @@ -447,8 +447,6 @@ pub(super) fn variance(h: &HistogramView<'_>, buckets: &mut Vec) - #[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] { diff --git a/src/promql/src/histogram_eval/tests.rs b/src/promql/src/histogram_eval/tests.rs index c6805c7e4d6..05c9bdfe1f5 100644 --- a/src/promql/src/histogram_eval/tests.rs +++ b/src/promql/src/histogram_eval/tests.rs @@ -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, @@ -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> = BTreeMap::new(); let mut kinds: BTreeMap = BTreeMap::new(); let mut samples: BTreeMap> = 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 = 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 , 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 +/// . 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 { .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![(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, diff --git a/src/promql/src/info.rs b/src/promql/src/info.rs index 004b995b77b..90e2c22b627 100644 --- a/src/promql/src/info.rs +++ b/src/promql/src/info.rs @@ -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)>, - /// 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>, - /// 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, 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, 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, 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>>> = 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 = 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> = 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 = 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, Vec>>); -/// 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>> { IDENTIFYING_LABELS .iter() diff --git a/src/promql/src/instant_eval.rs b/src/promql/src/instant_eval.rs index 08e9ce51d3a..998f30c3493 100644 --- a/src/promql/src/instant_eval.rs +++ b/src/promql/src/instant_eval.rs @@ -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> { - // 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, @@ -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, 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, 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> = Vec::with_capacity(fields.len()); let mut last: Option<(i128, usize)> = None; for (&index, ×tamp) in indices.iter().zip(evaluation_timestamps) { diff --git a/src/promql/src/instant_eval/tests.rs b/src/promql/src/instant_eval/tests.rs index 036c948a53a..682221bf4af 100644 --- a/src/promql/src/instant_eval/tests.rs +++ b/src/promql/src/instant_eval/tests.rs @@ -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 diff --git a/src/promql/src/map.rs b/src/promql/src/map.rs index 3a5681d46f5..2e4e654ba54 100644 --- a/src/promql/src/map.rs +++ b/src/promql/src/map.rs @@ -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> { 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 Result { 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 { 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 { let tags = metric.tags(); let reject = |label: &Label| { @@ -378,7 +352,6 @@ pub(crate) fn drop_empty_labels(metric: &SeriesLabels) -> Result { 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>, @@ -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 diff --git a/src/promql/src/map/broadcast.rs b/src/promql/src/map/broadcast.rs index 4aeafc20d99..9b20cdfccf1 100644 --- a/src/promql/src/map/broadcast.rs +++ b/src/promql/src/map/broadcast.rs @@ -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, 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, 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 { 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, 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, 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 diff --git a/src/promql/src/map/comparison.rs b/src/promql/src/map/comparison.rs index 63d62461fa5..ac5aec8ae60 100644 --- a/src/promql/src/map/comparison.rs +++ b/src/promql/src/map/comparison.rs @@ -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, series: &Series, comparison: Comparison, scalar: ScalarOperand, ) -> Result<(Option, 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 { diff --git a/src/promql/src/map/tests.rs b/src/promql/src/map/tests.rs index c6f0eec958f..09b656e16a7 100644 --- a/src/promql/src/map/tests.rs +++ b/src/promql/src/map/tests.rs @@ -84,9 +84,6 @@ fn floats(samples: &[Option]) -> 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"])); diff --git a/src/promql/src/map/tests/arithmetic.rs b/src/promql/src/map/tests/arithmetic.rs index 13e913b7e2e..ad5a463604c 100644 --- a/src/promql/src/map/tests/arithmetic.rs +++ b/src/promql/src/map/tests/arithmetic.rs @@ -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!( diff --git a/src/promql/src/map/tests/broadcast.rs b/src/promql/src/map/tests/broadcast.rs index 97d34b9d8f2..d0a3af1840e 100644 --- a/src/promql/src/map/tests/broadcast.rs +++ b/src/promql/src/map/tests/broadcast.rs @@ -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 diff --git a/src/promql/src/map/tests/comparison.rs b/src/promql/src/map/tests/comparison.rs index 361a13cd51f..f328be7c82a 100644 --- a/src/promql/src/map/tests/comparison.rs +++ b/src/promql/src/map/tests/comparison.rs @@ -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() { diff --git a/src/promql/src/map_label.rs b/src/promql/src/map_label.rs index 9a3f0e4db98..eebee631e6a 100644 --- a/src/promql/src/map_label.rs +++ b/src/promql/src/map_label.rs @@ -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 { diff --git a/src/promql/src/map_label/tests.rs b/src/promql/src/map_label/tests.rs index d16b1b9d52b..bb36e1d31da 100644 --- a/src/promql/src/map_label/tests.rs +++ b/src/promql/src/map_label/tests.rs @@ -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 diff --git a/src/promql/src/map_time.rs b/src/promql/src/map_time.rs index 9f5f9f4fad6..6e8ee2a11a0 100644 --- a/src/promql/src/map_time.rs +++ b/src/promql/src/map_time.rs @@ -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", diff --git a/src/promql/src/native/aggregate.rs b/src/promql/src/native/aggregate.rs index 128ad9b4aa6..ff368079dca 100644 --- a/src/promql/src/native/aggregate.rs +++ b/src/promql/src/native/aggregate.rs @@ -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, - /// 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, /// One entry per series this node was handed. series: Vec, - /// 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, - /// 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, - /// 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` slot of this struct, so the descriptor is - /// what `size_of::()` 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::() .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, - /// 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, - /// 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, - /// 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, merger: Option, state_schema: Option>, - /// 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, @@ -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, @@ -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, @@ -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 { 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, quantile: f64, positions: &[usize]) -> Result { let schema = Arc::new(SeriesSchema { fields: Arc::from([FieldSpec { @@ -945,13 +692,8 @@ fn quantile_parameter(grid: &Arc, 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::() // 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::()) .saturating_add(width.saturating_mul(std::mem::size_of::>())); - // 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::()) .saturating_add(2 * std::mem::size_of::()) .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::())) } -/// 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::() + held; let adopted = handoff - std::mem::size_of::(); let pool: Arc = 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); diff --git a/src/promql/src/native/batch.rs b/src/promql/src/native/batch.rs index 0137bbef658..de3e8959911 100644 --- a/src/promql/src/native/batch.rs +++ b/src/promql/src/native/batch.rs @@ -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; diff --git a/src/promql/src/native/canonicalize.rs b/src/promql/src/native/canonicalize.rs index f5273021294..c37d9d9a6d7 100644 --- a/src/promql/src/native/canonicalize.rs +++ b/src/promql/src/native/canonicalize.rs @@ -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], source_metrics: &[Option>], ) -> DfResult { 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], @@ -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], source_metrics: &[Option>], ) -> DfResult { 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::>>()?, }, - // 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, diff --git a/src/promql/src/native/canonicalize/tests.rs b/src/promql/src/native/canonicalize/tests.rs index a6c520c5213..7027ba65f6e 100644 --- a/src/promql/src/native/canonicalize/tests.rs +++ b/src/promql/src/native/canonicalize/tests.rs @@ -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) -> 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) -> NativeNode { NativeNode { expr: NativeExpr::Scalar(BoundScalar { value }), @@ -87,7 +76,6 @@ fn scalar(value: f64, out: Arc) -> NativeNode { } } -/// An instant selection over `inner` that reports what `value` says it reports, on `out`. fn selection(inner: NativeNode, out: Arc, value: InstantValue) -> NativeNode { NativeNode { expr: NativeExpr::Instant { @@ -109,7 +97,6 @@ fn selected(out: &Arc) -> 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) -> 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, 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, 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) -> NativeNode { NativeNode { expr: NativeExpr::Binary { @@ -237,7 +220,6 @@ fn binary_over(left: NativeNode, right: NativeNode, out: Arc) -> Nativ } } -/// A set operation over `left` and `right` on `out`. fn set_over(left: NativeNode, right: NativeNode, out: Arc) -> NativeNode { NativeNode { expr: NativeExpr::Set { @@ -252,7 +234,7 @@ fn set_over(left: NativeNode, right: NativeNode, out: Arc) -> 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>, @@ -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>, @@ -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]) -> 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], @@ -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![tags(&["host", "__name__"])] } @@ -389,7 +361,7 @@ fn tags(names: &[&str]) -> Vec { 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![tags(&["host"])] } @@ -397,7 +369,6 @@ fn scan_tags() -> Vec> { #[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::::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::::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::::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::::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::::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::::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![ diff --git a/src/promql/src/native/display.rs b/src/promql/src/native/display.rs index 393b8c54522..b721c6cf8ba 100644 --- a/src/promql/src/native/display.rs +++ b/src/promql/src/native/display.rs @@ -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 `: `. 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, } impl From 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]) -> String { labels .iter() @@ -98,8 +82,6 @@ fn label_list(labels: &[Arc]) -> 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) } diff --git a/src/promql/src/native/display/tests.rs b/src/promql/src/native/display/tests.rs index 9dbc48e61bc..66a0caf766d 100644 --- a/src/promql/src/native/display/tests.rs +++ b/src/promql/src/native/display/tests.rs @@ -47,7 +47,6 @@ fn fields() -> Arc<[FieldSpec]> { }]) } -/// The samples a node produces on `grid`. fn evaluated(grid: Arc) -> NativeType { NativeType::Samples(Arc::new(SeriesSchema { fields: fields(), @@ -55,11 +54,7 @@ fn evaluated(grid: Arc) -> 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) -> 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) -> NativeTree { NativeTree::try_new(NativeNode { expr: NativeExpr::Aggregate { @@ -607,8 +554,6 @@ fn aggregate_over_window(out: Arc) -> 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); diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index e6f184d7dd6..59631850d6c 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -14,9 +14,9 @@ //! Running a bound tree, node by node. //! -//! Each execution owns a recursive runtime tree; the compiled [`NativeTree`] stays immutable, so one -//! tree builds independent executions. A caller registers the tree's per-node metric handles into -//! its own metrics set once, before the execution starts. +//! Each execution owns a recursive runtime tree; the compiled [`NativeTree`] stays immutable, so +//! one tree builds independent executions. A caller registers the tree's per-node metric handles +//! into its own metrics set once, before the execution starts. use std::collections::{HashSet, VecDeque}; use std::sync::Arc; @@ -75,9 +75,6 @@ use crate::vector_match::{ mod tests; /// A chunk on an internal edge. -/// -/// A source hands over raw samples; a node above a window hands over evaluated chunks or group -/// state, as the bound tree says. enum NativeChunk { /// Raw source samples, with their own timestamps. Raw(RawSeriesChunk), @@ -100,7 +97,7 @@ impl NativeChunk { } } - /// What this chunk is, for a rejection that has to say which kind arrived. + /// The chunk kind, for error messages. fn describe(&self) -> &'static str { match self { Self::Raw(_) => "raw samples", @@ -109,24 +106,20 @@ impl NativeChunk { } } - /// Whether this chunk closes the source series whose data it carries. - /// - /// Not the label set it holds: two source series can share one output label set, and each ends - /// on its own chunk. + /// Whether this chunk closes its source series (not its label set, which two source series + /// can share). fn is_last(&self) -> bool { match self { Self::Raw(chunk) => chunk.is_last, Self::Evaluated(chunk) => chunk.is_last, - // A state chunk is what a partition's fold produces once its input ended, so it only - // says the producer is done with these groups -- not that a group is complete; a - // `Final` closes a group on the end of its whole input, not on one chunk. + // The producer is done with these groups; a `Final` still closes a group only when + // its whole input ends. Self::AggregateState(_) => true, } } - /// An estimate of the bytes this chunk holds. - /// - /// Only what the chunk alone stands for, so a shared buffer or table is counted once per chunk. + /// An estimate of the bytes this chunk holds; shared buffers and tables are counted in full + /// for every chunk. fn bytes(&self) -> usize { match self { Self::Raw(chunk) => raw_bytes(chunk), @@ -138,8 +131,6 @@ impl NativeChunk { /// The bytes a raw chunk holds: its identity, its timestamps and the Arrow buffers behind its /// fields. -/// -/// A histogram field costs its column of indices, not one float per row. pub(crate) fn raw_bytes(chunk: &RawSeriesChunk) -> usize { std::mem::size_of::() .saturating_add(buffer_bytes(&chunk.primary_key)) @@ -148,71 +139,39 @@ pub(crate) fn raw_bytes(chunk: &RawSeriesChunk) -> usize { .saturating_add(fields_bytes(&chunk.fields)) } -/// The bytes an evaluated chunk holds: its struct and the Arrow buffers behind its fields. -/// -/// The grid is shared by every chunk addressed on it, so it is not counted per chunk. +/// The bytes an evaluated chunk holds: its struct and the Arrow buffers behind its fields, but not +/// the shared grid. pub(super) fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize { std::mem::size_of::().saturating_add(fields_bytes(&chunk.series.fields)) } -/// The bytes one chunk holds beside its samples: its axis, the runs that axis is made of, one -/// descriptor per segment and its labels. -/// -/// It is what is left of [`series_bytes`] once the allocations its samples are slices of are taken -/// out and the `Series` struct itself is left to whatever holds the chunk: the struct is one slot of -/// the container a retainer keeps its chunks in, so a retainer that counts that container -- a -/// `quantile` counts its vector by capacity -- has already counted it, and one that does not count -/// it anywhere would have to add it back. -/// -/// This is the figure of a retainer that bills the allocations its samples live in itself -/// ([`unbilled_sample_buffers`]): what the chunk holds on its own, plus that residency, once each. +/// [`series_bytes`] without the sample buffers and without the `Series` struct: its axis, segment +/// descriptors and labels. For a retainer that bills buffers through [`unbilled_sample_buffers`] +/// and counts the struct in its own container. pub(crate) fn chunk_bytes_beside_samples(series: &Series) -> usize { series_bytes(series) .saturating_sub(fields_bytes(&series.fields)) .saturating_sub(std::mem::size_of::()) } -/// The bytes one chunk a binary operand retains holds on its own. -/// -/// It is [`chunk_bytes_beside_samples`] with the samples a chunk's rows occupy in place of the -/// allocations they are slices of, and with the struct the chunk's `Series` carries: a series -/// delivered in a thousand chunks holds a thousand slices of one buffer, so counting that buffer -/// once per chunk would make the operand's figure grow with the number of chunks rather than with -/// the data in them. The slices of one series add up to the allocation they share, which is the -/// figure a deduplication across the chunks would arrive at. -/// -/// The struct is part of this figure because an operand keeps one entry per retained chunk and -/// counts no container of its own, so the entry and the chunk in it are one figure here. A retainer -/// that does count its container takes [`chunk_bytes_beside_samples`] instead. -/// -/// The histogram tables a chunk's segments reference are not part of the figure: a table is one -/// allocation however many chunks index into it, so it is not a per-chunk cost at all. Dropping it -/// here is therefore only half the story -- it must not become a figure the operand never charges. -/// [`unbilled_tables`] is the other half, and the operand bills each table once through it. +/// The bytes one chunk retained by a binary operand holds: [`chunk_bytes_beside_samples`] plus the +/// `Series` struct plus the rows its sample slices cover, so a series split into many slices of one +/// buffer is not billed that buffer per chunk. Histogram tables are excluded; the operand bills +/// each once through [`unbilled_tables`]. pub(crate) fn operand_chunk_bytes(series: &Series) -> usize { chunk_bytes_beside_samples(series) .saturating_add(std::mem::size_of::()) .saturating_add(sample_slice_bytes(&series.fields)) } -/// The fields of one chunk, one dense segment at a time. -/// -/// A field is one or more dense segments - a merged chunk carries one per source piece it was folded -/// from - and asking such a field for a single dense view answers `None`. Every figure this crate -/// bills for a chunk's samples walks the segments through here, so the two of them cannot drift on -/// which parts of a field they count; only the yardstick differs, and each caller says why. +/// The dense segments of every field of one chunk. A merged field has several, and asking it for a +/// single dense view answers `None`. pub(crate) fn field_segments(fields: &SeriesFields) -> impl Iterator + '_ { fields.iter().flat_map(|field| field.segments()) } -/// The bytes the samples of one series' fields take as the slices they are. -/// -/// A dense segment is counted by its rows and a native-histogram field by its index column; a nested -/// segment is left to the chunks it is made of. The walk over segments is the same one -/// [`raw_chunk_slice_bytes`](crate::extension_plan::series_repartition) makes for a raw chunk - a -/// field is one or more of them, and both walk them with [`field_segments`] - but the yardstick -/// differs on purpose: this figure bills rows and the allocations behind them are counted once by -/// `chunk_bytes_beside_samples`, while a router bills the buffers a slice keeps alive. +/// The bytes the sample slices of one series cover, by rows: floats per value, histograms per +/// index. fn sample_slice_bytes(fields: &SeriesFields) -> usize { field_segments(fields) .map(|segment| match segment.dense() { @@ -240,34 +199,13 @@ fn sample_slice_bytes(fields: &SeriesFields) -> usize { .fold(0usize, usize::saturating_add) } -/// The Arrow allocations `series`' samples live in that `billed` does not hold yet, and the bytes -/// they hold. +/// The Arrow allocations (values and validity bitmaps) `series`' samples live in that neither +/// `billed` nor this chunk has already listed, with their bytes: full capacity plus one identity +/// slot each. A retained slice keeps its whole allocation resident, so it is billed in full, once. /// -/// [`sample_slice_bytes`] counts the rows a chunk holds, which is the figure of a caller that bills -/// the samples without the allocations they are slices of. That is exact only when the chunks of a -/// series are non-overlapping slices that add up to the buffers they point into. It is wrong in both -/// directions otherwise: a chunk holding one row of a large batch keeps the whole buffer resident -/// while its rows are eight bytes, and two chunks whose slices overlap hold the bytes between them -/// once while each is charged for them. What is resident is the allocation, and an allocation is one -/// however many chunks slice it, so it is counted once, by the first chunk to reference it -- -/// exactly as [`unbilled_tables`] counts a histogram table. -/// -/// Counting every chunk for the whole buffer it slices would need no identity at all, but it -/// over-estimates by the number of chunks: a series handed over as a thousand slices of one buffer -/// would be charged that buffer a thousand times, which refuses an input whose buffers do fit the -/// pool. The identity is therefore read, and read from Arrow's own handle on the allocation -/// ([`Buffer::data_ptr`]): every slice of one buffer reports the address of the allocation it points -/// into, whatever its offset inside it, and the address names that allocation for as long as it is -/// remembered -- a chunk referencing a buffer keeps it alive, so no later allocation can be given -/// the same address. The bytes are the buffer's capacity, which is the allocation and not the slice, -/// plus the one slot the identity takes in the set that remembers it. The caller counts the figure -/// as it stands and adds the identities to `billed` once the chunk is retained, which is what makes -/// the two halves agree. -/// -/// Every array a chunk holds samples in contributes: the values of a float segment, the indices of a -/// histogram one, both of a mixed one, and the validity bitmap beside each of them -- a bitmap is an -/// allocation of its own, and no figure that counts rows can see it. A buffer two segments or two -/// fields of the one chunk reference is listed once. +/// The identity is [`Buffer::data_ptr`], shared by every slice of one allocation; it stays unique +/// while remembered because the retained chunk keeps the allocation alive. The caller adds the +/// returned identities to `billed` after retaining the chunk. pub(crate) fn unbilled_sample_buffers( series: &Series, billed: &HashSet, @@ -300,8 +238,7 @@ pub(crate) fn unbilled_sample_buffers( (fresh, bytes) } -/// Adds the allocation a sample array's values live in, and the one its validity bitmap lives in, -/// to `fresh` and `bytes`, skipping the ones `billed` holds and the ones already reported. +/// [`unbilled_buffer`] for a sample array's values and validity bitmap. fn unbilled_array_buffers( values: &PrimitiveArray, fresh: &mut Vec, @@ -323,7 +260,6 @@ fn unbilled_buffer( ) { let held = buffer_bytes(buffer); if held == 0 { - // An array whose values are all valid carries an empty bitmap, which owns nothing. return; } let identity = buffer.data_ptr().as_ptr() as usize; @@ -336,25 +272,10 @@ fn unbilled_buffer( .saturating_add(std::mem::size_of::()); } -/// The histogram tables `series` is the first to reference, and the bytes they hold. -/// -/// A table is one allocation the chunks of a series share, so it is neither a per-chunk cost -- -/// counting it per chunk would make a series delivered in a thousand chunks cost a thousand tables -/// -- nor no cost at all, which is what leaving it out of every chunk leaves the figure at. What it -/// is, is a cost of the operand that first retains a chunk referencing it: the identities it returns -/// are the tables `billed` does not hold yet, and the figure is what those tables hold -/// ([`table_bytes`]). The caller bills the figure as it stands and adds the identities to `billed` -/// once the chunk is retained, which is what makes the two halves of the figure agree. -/// -/// The identity is the address of the allocation behind the `Arc`. It names one table for as long as -/// it is remembered, because a chunk referencing a table keeps it alive and no later allocation can -/// be given the same address. A table two segments or two fields of the one chunk reference is -/// listed once. Each identity is also one slot in the set that remembers it, which is charged as it -/// is written -- one entry at a time, like the boundary list's, and not from the capacity the set -/// grows to -- so remembering a table is paid for beside the table itself. -/// -/// Both nodes that retain chunks instead of folding them read this: a binary operand and a -/// `quantile` input. Neither counts a table per chunk, and neither lets it go unbilled. +/// The histogram tables `series` references that neither `billed` nor this chunk has already +/// listed, with their [`table_bytes`] plus one identity slot each. The identity is the `Arc`'s +/// address, unique while the retained chunk keeps the table alive. The caller adds the identities +/// to `billed` after retaining the chunk. pub(crate) fn unbilled_tables(series: &Series, billed: &HashSet) -> (Vec, usize) { let mut fresh: Vec = Vec::new(); let mut bytes = 0usize; @@ -378,10 +299,8 @@ pub(crate) fn unbilled_tables(series: &Series, billed: &HashSet) -> (Vec< (fresh, bytes) } -/// A rough workspace estimate for merging fragments that hold `rows` rows between them. -/// -/// An estimate, not an allocation bound; the payload of values and histogram tables stays shared -/// with the fragments. +/// A rough workspace estimate for merging fragments that hold `rows` rows between them. Values +/// and histogram tables stay shared with the fragments and are not counted. pub(crate) fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize) -> usize { let sorted_rows = rows.saturating_mul( std::mem::size_of::<(usize, usize, usize)>() + std::mem::size_of::(), @@ -389,8 +308,7 @@ pub(crate) fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize let readers = fragments.saturating_mul( fields.saturating_mul(std::mem::size_of::() + 4 * std::mem::size_of::()), ); - // Allow for run and flattened-field descriptors when rows alternate between fragments or - // missing values; this is an estimate rather than a count of the allocations made. + // Run and field descriptors for rows alternating between fragments or gaps. let merged_field_per_row = 2 * std::mem::size_of::() + 3 * std::mem::size_of::(); let merged_fields = rows @@ -411,10 +329,8 @@ fn buffer_bytes(buffer: &Buffer) -> usize { buffer.capacity().max(buffer.len()) } -/// Which of an execution's inputs a caller's chunk belongs to. -/// -/// The leaf's position among the leaves counted left to right: a routing handle that is stable for -/// one tree and means nothing across trees. +/// Which of an execution's inputs a caller's chunk belongs to: the leaf's position counted left to +/// right. Meaningful only within one tree. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InputId(usize); @@ -431,39 +347,27 @@ impl InputId { } /// The series whose first chunk this buffer received and whose closing chunk it has not seen. -/// -/// A window reads one series at a time, up to the chunk carrying `is_last`, so the chunks of one -/// series arrive together. struct OpenSeries { - /// The identity of the open series, as the chunk that opened it named it. metric: SeriesLabels, - /// The last absolute position the open series decided, when it decided any. last_position: Option, } -/// The input a [`RuntimeOp::Window`] or a [`RuntimeOp::Merge`] collects until its input ends. +/// The input a [`RuntimeOp::Window`] or a [`RuntimeOp::Merge`] collects until its input ends, then +/// merges into one series per label set ([`crate::grid_series::merge_same_labelset`]). /// -/// Neither node can answer one label set at a time: the points a window across the boundary needs, and -/// the fragments a canonical merge combines, are those of closed series. The fragments are kept whole, -/// merged into one series per label set ([`crate::grid_series::merge_same_labelset`]), and only then -/// evaluated or emitted. -/// -/// Collecting is also where the per-series contract is checked: the merge that follows would sort a -/// stream that broke it into a plausible answer. +/// The per-series contract is checked here because the merge would sort a stream that broke it into +/// a plausible answer. struct MergeInput { - /// The schema the fragments are addressed on: their grid and their field count. schema: Arc, - /// The series received so far, in the order they arrived. + /// In arrival order. fragments: Vec, - /// An estimate of the bytes the fragments and the merge that follows them stand for. + /// An estimate of the fragments plus the merge workspace. bytes: usize, - /// The series the next chunk has to continue, if the last chunk this buffer took did not close - /// one. Nothing is kept once a series closed: the next chunk, if any, starts another series. + /// The series the next chunk must continue, if the last chunk did not close it. open: Option, } impl MergeInput { - /// A buffer for the fragments of one window's input, which are addressed on `schema`. fn new(schema: Arc) -> Self { Self { schema, @@ -473,11 +377,9 @@ impl MergeInput { } } - /// Checks one received chunk against the contract a series keeps, and follows the open series. - /// - /// A chunk must match the input grid and schema, hold positions as its axis places rows, - /// continue the open series' identity and only move forward inside it. A chunk carrying `is_last` - /// closes the open series whether or not it holds rows. + /// Checks one chunk against the series contract and tracks the open series: it must match the + /// input grid and schema, continue the open series' labels, and move strictly forward. A chunk + /// with `is_last` closes the series whether or not it holds rows. fn check(&mut self, series: &Series, is_last: bool) -> Result<()> { let on_grid = match (&self.schema.eval_grid, series.time.grid()) { (Some(input), Some(grid)) => input.spec() == grid.spec(), @@ -526,9 +428,7 @@ impl MergeInput { Ok(()) } - /// The bytes of the fragments and of the workspace merging them needs. - /// - /// The sample payload is shared with the fragments, so it is not counted twice here. + /// The workspace merging the fragments needs; see [`merge_workspace_bytes`]. fn workspace_bytes(&self) -> usize { let rows: usize = self .fragments @@ -539,31 +439,18 @@ impl MergeInput { } } -/// What every node holds: its metric handles and the bytes it reserves. -/// -/// The reservation is the pool's, so a node that buffers input competes with every other operator in the -/// query, and it is the figure itself: a node holds nothing beside what it reserved. -// -// Visible to the aggregate node so that its fold can reserve for what it is about to allocate. +/// A node's metric handles and its memory reservation in the query's pool. pub(super) struct NodeBuffer { metrics: Arc, reservation: MemoryReservation, - /// What this node keeps for the grid timestamps it materialized, folded into every - /// re-estimate of its own figure; see [`NodeBuffer::reserve_grid`]. - /// - /// `None` means this node has not reserved a grid yet and `Some(bytes)` that it has: what the - /// record says is that the reservation was made, which is not the same statement as the figure - /// it ended at. A grid always has at least one point today -- `GridSpec` refuses a length of - /// zero -- so the two happen to coincide, but a reservation of no bytes would still be a - /// reservation made, and reading the figure would make it one made per call. + /// The bytes reserved for this node's grid timestamps, kept across every resize; + /// `None` until [`NodeBuffer::reserve_grid`] reserves them. grid: Option, } impl NodeBuffer { - /// Registers a reservation for the node called `name` with `pool`. - /// - /// The name identifies the operator and its tree location, such as `native.window at - /// root.left`, for errors and the pool's report. It labels the reservation, it does not key it. + /// Registers a reservation with `pool`, labelled `name` (e.g. `native.window at root.left`) in + /// errors and pool reports. pub(super) fn new( name: impl Into, metrics: Arc, @@ -577,27 +464,11 @@ impl NodeBuffer { } } - /// Reserves the timestamps of `grid` before this node reads them, once for the execution. - /// - /// An [`EvalGrid`] allocates its timestamps on first access and keeps them for as long as the - /// plan holds the grid, which outlives the chunk a node read them for. The node that triggers - /// that allocation therefore reserves the array and keeps the reservation: giving it back with - /// the workspace would leave the execution holding bytes no reservation covers, which is what a - /// grid of a million deferred points -- the reason the array is deferred at all -- would go - /// unnoticed through. Only the node that materializes it reserves it: a grid that is already - /// materialized, whether the plan built it eagerly or a node below or beside this one needed it - /// first, was charged to whoever materialized it, so this node grows by nothing. - /// - /// The array is reserved once per node, not once per call: a node is handed its input one chunk - /// at a time and reaches the grid on every chunk it is handed, and a collecting window reaches - /// it again when it flushes what it collected -- which is the call that reads the timestamps, - /// because until then nothing on this node looks at them. Reserving again on each of those - /// calls charges the pool one array per chunk for the one array the execution holds, so a series - /// arriving in `n` pieces would need `n + 1` arrays' worth of budget and exhaust a pool sized - /// for the query over a chunk count that says nothing about what the node keeps. What short - /// circuits the later calls is therefore the reservation this node made (`grid`), not the array - /// having been materialized: it cannot stand in for it, being false exactly while a collecting - /// node is charging for it. + /// Reserves `grid`'s timestamps before this node first reads them, once per node. An + /// [`EvalGrid`] materializes them lazily and keeps them for the plan's lifetime, so the node + /// that triggers materialization keeps the reservation; a grid already materialized was charged + /// by whoever did it. The `grid` record also short-circuits: a collecting window reserves on + /// every chunk long before it materializes the grid at flush. pub(super) fn reserve_grid(&mut self, grid: &EvalGrid) -> Result<()> { if self.grid.is_some() || grid.is_materialized() { return Ok(()); @@ -620,10 +491,7 @@ impl NodeBuffer { Ok(()) } - /// Reserves exactly `bytes`, which is what this node holds from now on: a node that consumes its - /// input chunk by chunk is set from the state that is left, not grown per chunk. What a grid's - /// array takes is not part of that figure: the node keeps it for as long as it lives, so it - /// stays reserved on top of what the caller measured. + /// Sets the reservation to `bytes` plus the grid timestamps reserved by [`Self::reserve_grid`]. pub(super) fn resize(&mut self, bytes: usize) -> Result<()> { self.reservation .try_resize(bytes.saturating_add(self.grid.unwrap_or(0)))?; @@ -638,13 +506,9 @@ impl NodeBuffer { Ok(()) } - /// Moves `bytes` of what this node holds into a reservation of its own. - /// - /// The bytes stay charged to the pool; only who holds them changes. + /// Splits `bytes` off into a separate reservation; the pool total is unchanged. fn transfer(&mut self, bytes: usize) -> Result { - // A chunk is queued with the figure this node grew by, so the two agree unless the - // accounting drifted. Refusing is what keeps a drift from either panicking inside the - // memory path or handing out a chunk nobody is charged for. + // Only an accounting drift gets here; `split` would panic. if bytes > self.reservation.size() { return Err(DataFusionError::Internal(format!( "a queued chunk holds {bytes} bytes, more than the {} its node reserves", @@ -683,33 +547,25 @@ fn metric_bytes(metric: &SeriesLabels) -> usize { /// What a map node applies. struct MapRuntime { ops: Arc<[MapOp]>, - /// The schema of what the map produces, which is what its input is checked against. + /// The output schema, which the input is checked against. schema: Arc, } -/// What an instant node holds: the chunks of the one series it is selecting, until that series ends. -/// -/// [`select_instants`] takes a complete source axis, so this node buffers a whole series and hands one -/// chunk over for it. +/// An instant selection. [`select_instants`] takes a complete source axis, so this buffers each +/// series until its last chunk and emits one chunk for it. struct InstantRuntime { - /// The bound selection: how far back it reads, the offset it reads at, and the grid its values - /// are addressed on. selection: BoundInstant, - /// The layout the chunk it hands out is addressed on: its input's fields on that grid. + /// The input's fields on the selection's output grid. schema: Arc, - /// Where the rows the selection picked are gathered, one series at a time. output: GridSeriesBuilder, - /// The chunks of the series being selected, in arrival order; empty while no series is open. + /// The chunks of the open series; empty while none is open. chunks: Vec, - /// What `chunks` hold, added as each chunk arrives and given back when the series is gathered. + /// The bytes `chunks` hold. held: usize, } impl InstantRuntime { - /// The run-time state of the instant selection `op`, reading the samples of `input`. fn try_new(input: &SeriesSchema, op: &BoundInstant) -> Result { - // The chunk this node hands out is addressed on the selection's own grid, so the grid the - // rows are gathered on is the binding's rather than a copy of it. let schema = Arc::new(SeriesSchema { fields: Arc::clone(&input.fields), eval_grid: Some(Arc::clone(&op.output_grid)), @@ -723,34 +579,15 @@ impl InstantRuntime { }) } - /// The bytes the buffered chunks of the open series hold. fn buffered_bytes(&self) -> usize { self.held } - /// The bytes gathering the series `closing` ends is about to allocate beside its chunks. - /// - /// An upper bound derived from what the selection has in hand rather than a measurement: the rows the - /// series holds once `closing` has joined it, the fields it carries, the points the selection can decide - /// for it, and, per field, the largest histogram a row of it can carry. Each term is one thing the gather - /// allocates: - /// - /// - the concatenated axis ([`buffered_time`]) and the descriptors that read it - /// ([`buffered_fields`]), including the three per segment [`Samples::try_from_chunks`] flattens them - /// into; - /// - the two arrays [`select_instants`] returns, one `u64` source row and one `i64` timestamp per point - /// it can reach; - /// - the rows [`GridSeriesBuilder`] keeps, including one validity byte per (row, field); a field of native - /// histograms adds its index column and the payload of the histogram it names, charged per *point*, - /// because one source row can be selected by every point; - /// - the row the selection fills and one [`RowCursor`] per field; - /// - doubling, since every column the builder keeps is a `Vec` that grows by doubling. - /// - /// The buffered chunks' own headers are not counted: the node's reservation already holds them. + /// An upper bound on what gathering the series `closing` ends allocates beside the buffered + /// chunks: the concatenated axis and segment descriptors, the [`select_instants`] output, and + /// the builder's rows doubled for `Vec` growth. A histogram field is charged its largest row + /// per selected point, since every point can select the same row. fn gather_bytes(&self, closing: &RawSeriesChunk) -> usize { - // The points the selection decides, not the points the grid plans: the gather clips its - // scan to the series it holds, so a figure over the whole grid would charge the pool for - // rows this series can never produce. let points = self.selected_points(closing); let chunks = self.chunks.len().saturating_add(1); let rows = self @@ -793,10 +630,8 @@ impl InstantRuntime { .saturating_add(rows_of_points.saturating_mul(2)) } - /// The number of candidate grid points [`select_instants`] reserves for the buffered series. - /// - /// Candidate points can select nothing, but charging the whole planned grid would refuse short - /// series that fit the pool. + /// The candidate grid points [`select_instants`] can decide for the buffered series, clipped to + /// the series' span unless an `@` modifier pins the selection. fn selected_points(&self, closing: &RawSeriesChunk) -> usize { let spec = self.selection.output_grid.spec(); if self.selection.at_ms.is_some() { @@ -828,10 +663,7 @@ impl InstantRuntime { usize::try_from(span.count).unwrap_or(usize::MAX) } - /// The largest histogram a row of each field can carry, `None` for a field of floats. - /// - /// A histogram row is copied into the builder once per grid point that selects it, so the largest - /// row is what such a field costs per point. + /// The largest histogram row of each field, `None` for a float field. fn largest_histograms(&self, closing: &RawSeriesChunk) -> Vec> { let mut largest = vec![None; self.schema.fields.len()]; for chunk in self.chunks.iter().chain(std::iter::once(closing)) { @@ -844,17 +676,13 @@ impl InstantRuntime { largest } - /// Buffers one chunk of the series being selected, and gathers that series when it ends. - /// - /// `None` means the series is still open: the selection reads one whole axis, so nothing is - /// decided for a series until the chunk carrying `is_last` arrives. + /// Buffers one chunk of the open series and gathers it on its last chunk; `None` while the + /// series is open. fn push(&mut self, chunk: RawSeriesChunk) -> Result> { if let Some(open) = self.chunks.first() && (open.primary_key.as_slice() != chunk.primary_key.as_slice() || open.metric != chunk.metric) { - // One axis is gathered before the kernel reads any of it, so a chunk of another series - // has nowhere to go: it would be selected as though its samples were the open series'. return Err(series_changed()); } let closing = chunk.is_last; @@ -866,11 +694,9 @@ impl InstantRuntime { self.gather().map(Some) } - /// Selects the instants of the buffered series, hands it over closed, and drops the buffer. + /// Selects the instants of the buffered series and frees the buffer. fn gather(&mut self) -> Result { let chunk = self.select()?; - // The selection copied what it needed out of the buffered chunks, so a series that has been - // answered must not keep charging the pool for them. self.chunks.clear(); self.chunks.shrink_to_fit(); self.held = 0; @@ -885,13 +711,10 @@ impl InstantRuntime { )); }; let metric = first.metric.clone().ok_or_else(no_labels)?; - // The buffered chunks are one series, so they are read as the one axis the selection takes. let time = buffered_time(&self.chunks)?; let fields = buffered_fields(&self.chunks, self.schema.fields.len())?; let grid = Arc::clone(&self.selection.output_grid); let spec = grid.spec(); - // The grid's own points are what the selection decides, so the range and the step it is - // asked for are the grid's: `start..=start + (len - 1) * step`, step by step. if let Some(at_ms) = self.selection.at_ms { let timestamp_window = if self.selection.value == InstantValue::Timestamp && self.selection.lookback_ms >= 0 @@ -968,18 +791,15 @@ impl InstantRuntime { return self.project(&metric, &time, &fields, &indices, ×tamps); } self.output.begin_series(); - // One cursor per field, so a row is read as the field holds it rather than by walking the - // chunks of a field from its start once per row. let mut cursors: Vec> = fields.iter().map(Samples::cursor).collect(); - // `GridSample` is not `Clone`, so the row is filled slot by slot rather than from one value. + // `GridSample` is not `Clone`, so the row is filled slot by slot rather than from one + // value. let mut row: Vec> = (0..fields.len()).map(|_| None).collect(); let mut read: Option = None; for (index, timestamp) in indices.iter().zip(×tamps) { let index = *index as usize; - // The selection steps the grid's range by its step, so every timestamp it reports is a - // point of the grid and the position is the point's index in it. let position = grid_position(&grid, *timestamp)?; - // Two grid points can select one source row, and the row is read once for both. + // Consecutive grid points can select the same source row. if read != Some(index) { for (slot, cursor) in row.iter_mut().zip(&mut cursors) { let sample = cursor.at(index).ok_or_else(|| missing_row(index))?; @@ -987,12 +807,9 @@ impl InstantRuntime { } read = Some(index); } - // A position no field holds a value at is not a row: the builder drops it, which is - // what keeps a hole in the grid out of the result instead of padding it. + // The builder drops a position where every field is empty. self.output.push_samples(position, &row)?; } - // The rows the selection picked are the rows this series holds, and the whole series is - // decided at once, so this one chunk closes it. match self.output.finish(metric.clone())? { Some(series) => EvaluatedChunk::try_new(series, true), None => no_row_chunk(&self.schema, metric), @@ -1007,7 +824,7 @@ impl InstantRuntime { } } - /// The sample times of a selection, for a selection that reports them rather than the samples. + /// The selected sample times, for `timestamp()` and `info` selections. fn project( &self, metric: &SeriesLabels, @@ -1036,45 +853,26 @@ impl InstantRuntime { } } -/// An input a node reads whole before it computes -- one operand of a binary node, or the input of a vector -/// operation -- chunk by chunk, until it ends. -/// -/// The kernels read whole series, so the chunks are assembled into one series per logical series once the -/// input has ended. +/// An input a node reads whole before it computes (a binary operand, or the input of a vector +/// operation). Chunks are assembled into one series per logical series once the input ends. #[derive(Default)] struct RetainedInput { - /// The series whose last chunk did not close it, with the position after its last row. - /// - /// `None` when no series is open. A label set may be closed more than once, so a chunk that starts a - /// series again is not an error; one that starts it while another series is open, or goes back inside - /// the open one, is. + /// The open series and the position after its last row. A label set may close and start again + /// (as two logical series); starting another series while one is open is an error. open: Option<(SeriesLabels, usize)>, - /// The chunks this operand handed over, in arrival order. + /// In arrival order. series: Vec, - /// The chunk count at which each logical series closed, exclusive, in arrival order. - /// - /// A label set that closes and starts again is two logical series, which a list of ends keeps - /// apart. + /// The exclusive chunk index at which each logical series closed. ends: Vec, - /// The histogram tables the chunks this operand holds index into, by the address of the allocation - /// behind their `Arc`. - /// - /// A table is one allocation however many chunks index into it, so it is billed once, by the first chunk - /// that references it. A chunk's own figure leaves its tables out ([`operand_chunk_bytes`]), so a table - /// neither this operand nor this set bills is a table no reservation covers. + /// Addresses of histogram tables already billed; see [`unbilled_tables`]. tables: HashSet, - /// The bytes `series` and `ends` hold, folded in as chunks arrive. - /// - /// Each chunk is measured once by [`operand_chunk_bytes`], and shared histogram tables are billed once - /// through [`unbilled_tables`]. + /// The bytes `series`, `ends` and the billed tables hold. held: usize, } impl RetainedInput { - /// The bytes `chunk` would add to what this operand holds, read without retaining it. - /// - /// The same figure [`Self::enqueue`] adds, so a caller reserves it before retaining the chunk and the pool - /// admits the chunk before the operand holds it. + /// The bytes `chunk` would add; the same figure [`Self::enqueue`] adds, so it can be reserved + /// first. fn pending(&self, chunk: &EvaluatedChunk) -> usize { let end = if chunk.is_last { std::mem::size_of::() @@ -1087,20 +885,14 @@ impl RetainedInput { .saturating_add(end) } - /// Retains one chunk after checking that it continues what this input handed over. - /// - /// A chunk that starts another series while one is open, or goes back inside the open one, is - /// refused before it is retained. + /// Retains one chunk, refusing one that starts another series while one is open or goes back + /// inside the open one. fn retain(&mut self, chunk: EvaluatedChunk, reader: Reader) -> Result<()> { - // An empty chunk closes a series without holding a row, so it says nothing about where that - // series ended: only a chunk that carries rows can be read as going backwards. let (first, last) = ( chunk.series.time.first_position(), chunk.series.time.last_position(), ); let metric = chunk.series.metric.clone(); - // The position a chunk of the open series may start at: the row after the last one that - // series handed over. Nothing is open after a series closed, so the next one starts over. let end = self.open.as_ref().map_or(0, |(_, end)| *end); if let Some((open, _)) = &self.open && *open != metric @@ -1125,8 +917,7 @@ impl RetainedInput { Ok(()) } - /// Refuses an input that ended inside a series: a chunk that did not say `is_last` left the last - /// series it handed over open, and nothing came after it to close it. + /// Refuses an input that ended with a series still open. fn ensure_closed(&self, reader: Reader) -> Result<()> { match &self.open { Some((metric, _)) => Err(DataFusionError::Execution(format!( @@ -1139,15 +930,10 @@ impl RetainedInput { } } - /// Retains one chunk, folding the estimate it is charged with into what the operand holds. + /// Retains one chunk and adds the [`Self::pending`] figure to `held`. fn enqueue(&mut self, chunk: EvaluatedChunk) { let closing = chunk.is_last; - // The tables this chunk is the first to reference, read before they are recorded: the same - // figure `pending` billed, so what is reserved for the chunk and what it grows the operand - // by are one. let (tables, bytes) = unbilled_tables(&chunk.series, &self.tables); - // The boundary list is storage the operand keeps, and it grows before the chunk is recorded - // in it: an end is charged for before it exists, the same figure `pending` reported. self.held = self .held .saturating_add(if closing { @@ -1157,8 +943,6 @@ impl RetainedInput { }) .saturating_add(operand_chunk_bytes(&chunk.series)) .saturating_add(bytes); - // From here the operand keeps those tables alive itself, so a chunk arriving later that - // references one is charged its own slices and not the table again. self.tables.extend(tables); self.series.push(chunk.series); if closing { @@ -1175,19 +959,10 @@ impl RetainedInput { }) } - /// The bytes assembling this operand's chunks into logical series allocate, before they do. - /// - /// Nothing copies a sample: the descriptors the chunks' fields are made of are collected and shared, so - /// what is counted is metadata -- per series, per chunk and field, per segment and per run the boundary - /// covers: - /// - /// - per series, the assembled entry and the field list ([`SeriesFields`] takes a one-field list out of - /// its vector and boxes a wider one, so neither copies); - /// - per chunk and field, the descriptor collected out of it; - /// - per segment, three descriptors: the one the flatten copies out, the slot the `Arc<[Samples]>` it is - /// copied into holds, and the doubling of the vector it is copied out of; - /// - per run the boundary covers, the span [`Self::assemble`] collects and the span and row-offset arrays - /// [`TimeAxis::from_grid_spans`] copies them into. + /// The metadata assembling this operand's chunks into logical series allocates; samples are + /// shared, not copied. Per series: the entry and field list; per chunk and field: one + /// descriptor; per segment: three descriptors (flatten copy, `Arc<[Samples]>` slot, vector + /// doubling); per run: the collected span plus [`TimeAxis::from_grid_spans`]'s copies. fn assembly_bytes(&self, schema: &SeriesSchema) -> Option { let samples = std::mem::size_of::(); let grids = std::mem::size_of::(); @@ -1195,8 +970,6 @@ impl RetainedInput { let mut bytes = 0usize; for boundary in self.boundaries() { let chunks = &self.series[boundary]; - // The runs the boundary covers, and the segments its fields hold: a chunk's field can - // itself be chunked, and flattening it copies one descriptor per segment. let mut runs = 0usize; let mut segments = 0usize; for chunk in chunks { @@ -1205,15 +978,11 @@ impl RetainedInput { segments = segments.checked_add(field.segments().len())?; } } - // The descriptors of a field's chunks, the flatten's descriptors and the `Arc` they are - // copied into; a field with no segment still builds an empty `Samples`, which is one - // descriptor. + // `+ width`: a field with no segment still builds one empty `Samples`. let descriptors = chunks .len() .checked_mul(width)? .checked_add(segments.checked_mul(3)?.checked_add(width)?)?; - // The axis: the spans collected, and the span and offset arrays a run layout copies - // them into. let axis = runs.checked_mul( grids .checked_mul(2)? @@ -1228,12 +997,9 @@ impl RetainedInput { Some(bytes) } - /// The logical series this operand closed, each as one series on `schema`'s grid. - /// - /// The chunks of a logical series are collected, not concatenated: the fields keep one descriptor - /// per segment of every chunk and the axis keeps the runs the chunks cover, sharing the buffers - /// with the chunks this operand still holds. [`Series::try_new`] checks that the series holds as - /// many rows as its axis places, and [`Self::assembly_bytes`] is what a caller reserves. + /// The logical series this operand closed, each as one series on `schema`'s grid. Fields are + /// chained segment descriptors sharing the retained buffers; reserve [`Self::assembly_bytes`] + /// first. fn assemble(&self, schema: &SeriesSchema, reader: Reader) -> Result> { let grid = schema.eval_grid.clone().ok_or_else(|| { let (owner, input) = (reader.owner(), reader.input()); @@ -1294,33 +1060,25 @@ impl RetainedInput { self.series.shrink_to_fit(); self.ends.clear(); self.ends.shrink_to_fit(); - // The tables the cleared chunks were keeping alive are gone with them, so their addresses - // name nothing this operand holds any more. self.tables.clear(); self.tables.shrink_to_fit(); self.held = 0; } } -/// What a binary or set node holds: both operands until they end. -/// -/// The operation pairs two whole vectors point by point, so the node retains every chunk each operand -/// hands over, assembles each logical series into the one series the kernel matches, and runs the -/// kernel once both operands closed. +/// A binary, set or `info` node: retains both operands until they end, then assembles their logical +/// series and runs the kernel once. struct BinaryRuntime { node_index: usize, /// Evidence shared with the other output partitions of this fused-series execution. evidence: Option>, /// The query's collector for dropped histogram sample pairs, when requested. annotations: Option, - /// The kernel and the modifiers the compiler bound it with. kernel: PairKernel, - /// The layout each operand is bound to, what a chunk of it is checked against: `0` is the left - /// operand and `1` the right one, the order the tree declares them in. + /// Left then right; each chunk is checked against its operand's schema. schemas: [Arc; 2], - /// The retained chunks of each operand, in the same order. operands: [RetainedInput; 2], - /// Whether the kernel has run. It runs at most once: the operands it read are gone afterwards. + /// Whether the kernel has run; it runs once, since it drops the operands. computed: bool, } @@ -1335,7 +1093,7 @@ enum PairKernel { } impl PairKernel { - /// What the node running this kernel is called in an error. + /// The node name used in errors. fn node(&self) -> &'static str { match self { Self::Binary(_) => "the binary node", @@ -1345,7 +1103,6 @@ impl PairKernel { } } -/// What side `index` is called in an error. fn side_name(index: usize) -> &'static str { match index { 0 => "left", @@ -1353,12 +1110,10 @@ fn side_name(index: usize) -> &'static str { } } -/// The node a [`RetainedInput`] belongs to, which its messages name; formatted only when one is. +/// The owner of a [`RetainedInput`], named in its errors. #[derive(Clone, Copy)] enum Reader { - /// The operand at `side` of `node`, a binary or set node. Operand { side: usize, node: &'static str }, - /// The input of a vector operation. Vector, } @@ -1379,12 +1134,11 @@ impl Reader { } impl BinaryRuntime { - /// Identifies this binary node's evidence slot for a field. + /// This node's evidence slot for a field. fn slot(&self, field: usize) -> (usize, usize) { (self.node_index, field) } - /// The run-time state of `kernel` over its two operands. fn new( kernel: PairKernel, schemas: [Arc; 2], @@ -1402,7 +1156,6 @@ impl BinaryRuntime { } } - /// The reader of the operand at `side`, which names this node in its messages. fn reader(&self, side: usize) -> Reader { Reader::Operand { side, @@ -1410,7 +1163,6 @@ impl BinaryRuntime { } } - /// The bytes the retained operands hold. fn retained_bytes(&self) -> usize { self.operands .iter() @@ -1418,7 +1170,6 @@ impl BinaryRuntime { .fold(0usize, usize::saturating_add) } - /// The bytes assembling both operands into logical series allocates, before it does. fn assembly_bytes(&self) -> Option { let [left, right] = &self.operands; let [left_schema, right_schema] = &self.schemas; @@ -1426,7 +1177,6 @@ impl BinaryRuntime { .checked_add(right.assembly_bytes(right_schema)?) } - /// The logical series both operands closed, ready for the kernel to match. fn assemble(&self) -> Result<[Vec; 2]> { let [left, right] = &self.operands; let [left_schema, right_schema] = &self.schemas; @@ -1436,9 +1186,7 @@ impl BinaryRuntime { ]) } - /// The bytes the chunk of `side` would add to that operand's retention. - /// - /// It is read before the chunk is retained, so it is the figure the operand grows by. + /// The bytes the chunk of `side` would add to that operand; see [`RetainedInput::pending`]. fn pending(&self, side: usize, chunk: &EvaluatedChunk) -> Result { self.operands .get(side) @@ -1446,10 +1194,7 @@ impl BinaryRuntime { .ok_or_else(invalid_binary_operand) } - /// Reports an operand that ended inside a series. - /// - /// The kernel is not run over such an operand: it would answer the pairs of a series whose - /// remaining rows were never read. + /// Refuses an operand that ended with a series still open. fn closed(&self) -> Result<()> { for (side, operand) in self.operands.iter().enumerate() { operand.ensure_closed(self.reader(side))?; @@ -1457,12 +1202,10 @@ impl BinaryRuntime { Ok(()) } - /// Retains one chunk of the operand at `side`, checking it against that operand's binding. + /// Retains one chunk of the operand at `side`, after the kernel's own operand check. The bound + /// tree is no proof of what a chunk carries: `Series` fields are public, so a struct-literal + /// chunk can carry another field count or fewer samples than its axis places rows. fn retain(&mut self, side: usize, chunk: EvaluatedChunk) -> Result<()> { - // What a bound tree says an operand produces is not proof of what a chunk carries: a `Series` - // keeps its fields public, so a struct-literal chunk can carry another field count, or fewer - // samples than its axis places rows. The kernel's own check runs here, before the chunk enters - // the buffer. let Some(schema) = self.schemas.get(side) else { return Err(invalid_binary_operand()); }; @@ -1482,27 +1225,18 @@ impl BinaryRuntime { operand.retain(chunk, reader) } - /// Runs the kernel over both operands and returns the series it produced. + /// Runs the kernel over both assembled operands, or returns `None` if it already ran. /// - /// Each operand's chunks are assembled into their logical series first, because the kernel matches - /// whole series by label set: a series in many chunks would otherwise be a candidate per chunk on - /// its own side, which is quadratic in the chunk count of one series. - /// - /// The reservation covers the retained chunks, the assembled series and the kernel's own live - /// workspace, and it keeps covering the returned results until the caller queues them. + /// Chunks are assembled into logical series first; otherwise every chunk would be a separate + /// match candidate. The reservation covers retained chunks, assembly and the kernel's reported + /// workspace, then the output until the caller queues it. fn compute(&mut self, buffer: &mut NodeBuffer) -> Result>> { - // The kernel reads the operands once and drops them, so a second call has nothing to read - // and nothing left to produce: what it produced the first time is in the node's queue, and - // the reservation is already the queue's. if self.computed { return Ok(None); } self.closed()?; let [left_schema, right_schema] = &self.schemas; let retained = self.retained_bytes(); - // The assembled series are live while the kernel reads them and share the buffers the retained - // chunks hold, so what they add is metadata, and it is reserved before it exists: a figure read - // from it afterwards would be a figure the pool never admitted. let node = self.kernel.node(); let assembly = self .assembly_bytes() @@ -1511,21 +1245,13 @@ impl BinaryRuntime { let assembled = match self.assemble() { Ok(assembled) => assembled, Err(error) => { - // Nothing the assembly allocated outlives this call, so the node falls back to what - // it still holds. A failure of that resize is the pool's to report; the driver stops - // the execution either way and releases every node. buffer.resize(retained)?; return Err(error); } }; let [left, right] = &assembled; - // The operands are still held while the kernel runs, so what this node holds is the operands, - // the assembled series and the workspace the kernel reports; the callback resizes the - // reservation to that sum as the live workspace changes. let metrics = Arc::clone(&buffer.metrics); let output = { - // The timer covers this node's own work only: it is dropped before the driver polls - // the input again. let _timer = metrics.timer(); let mut reserve = |workspace: usize| { let bytes = retained @@ -1560,20 +1286,12 @@ impl BinaryRuntime { right, &mut reserve, ), - // The result keeps the base's fields on the base's grid, so the base's layout is - // the one the kernel builds it on. PairKernel::Info(selector) => { info_with_reservation(left_schema, left, right, selector, &mut reserve) } } }; - // The operands and the assembled series have been handed to the kernel and the reservation - // covers the workspace it allocated past them, so a failure is the driver's to release: it - // stops the execution and every node with it. let output = output?; - // The assembled series were the kernel's input and are read by nothing after it, so they go - // before the chunks they share their buffers with: what this node holds from here on is what - // the kernel returned, and the pool is not charged for a vector nothing reads again. drop(assembled); for operand in &mut self.operands { operand.release(); @@ -1583,19 +1301,16 @@ impl BinaryRuntime { } } -/// What a vector node holds: its whole input until it ends. -/// -/// Which samples `topk` or `limitk` keeps at a point depends on every series present there, so the node -/// retains every chunk and runs its kernel once the input ended, like a binary node. +/// A vector operation (`topk`, `limitk`, ...): its answer at a point depends on every series there, +/// so it retains the whole input and runs the kernel once. struct VectorRuntime { op: BoundVectorOp, - /// The layout of the input, which is also what the node produces. + /// Shared by input and output. schema: Arc, input: RetainedInput, - /// Whether the input's pieces of one label set are merged before the kernel reads them, which - /// `limitk` needs when its input can hold them. + /// Whether pieces of one label set are merged before the kernel; `limitk` needs it when its + /// input can split a label set. merge_input: bool, - /// Whether the kernel has run. It runs at most once: the input it read is gone afterwards. computed: bool, annotations: Option, /// The per-point k of a parameterized topk/bottomk, in grid position order. @@ -1605,11 +1320,10 @@ struct VectorRuntime { } impl VectorRuntime { - /// Validates schema-dependent requirements before the native route is selected. + /// Validates the operation's grouping against `schema`. fn try_new(op: BoundVectorOp, schema: Arc) -> Result { - // Every grouping these operations address their series by is checked here: `topk`, - // `bottomk` and `limitk` key groups by series labels only, so a `by` naming a value field - // would fold series the existing plan keeps apart into one group. + // These operations group by labels only; a `by` naming a value field would wrongly merge + // groups. let bound_grouping = match &op { BoundVectorOp::TopK { group, .. } | BoundVectorOp::LimitK { group, .. } @@ -1645,12 +1359,8 @@ impl VectorRuntime { }) } - /// Runs the kernel over the whole input and returns the series it kept, or `None` when it already - /// ran. - /// - /// The reservation covers the retained chunks, the assembled series and a rough estimate of the - /// kernel's workspace and of the series it rebuilds ([`vector_workspace_bytes`]), which the kernels - /// do not report as they allocate. + /// Runs the kernel over the whole input, or returns `None` if it already ran. The kernels do + /// not report allocations, so their workspace is estimated by [`vector_workspace_bytes`]. fn compute(&mut self, buffer: &mut NodeBuffer) -> Result>> { self.compute_with_histogram_parameters(buffer, &[]) } @@ -1664,8 +1374,6 @@ impl VectorRuntime { return Ok(None); } self.input.ensure_closed(Reader::Vector)?; - // What a failed assembly leaves the node holding: the input it retains beside the per-point - // values it read its parameters into, which outlive the assembly. let retained = self.input.held.saturating_add(self.parameter_bytes); let assembly = self .input @@ -1679,9 +1387,8 @@ impl VectorRuntime { return Err(error); } }; - // `limitk` keeps the first series in the order its input hands them over, as Prometheus takes - // the order of the vector it is given. Pieces of one label set are one series there, so they are - // merged before they are ranked. + // `limitk` keeps series in input order, as Prometheus does; pieces of one label set are one + // series there, so they are merged first. let assembled = if self.merge_input { let rows = assembled.iter().map(|series| series.time.len()).sum(); buffer.grow(merge_workspace_bytes( @@ -1821,9 +1528,8 @@ fn vector_series_with_k( )); } select::topk_at( - // A point the parameter series holds no sample at selects nothing, which is - // Prometheus' empty parameter there; a sample that is present and NaN is still - // an error, as [`select::validate_topk_parameters`] rules. + // No sample selects nothing, as Prometheus does for an empty parameter; a NaN + // sample is still an error (`select::validate_topk_parameters`). |point| match values[point] { Some(k) => select::k_param(k, series.len()), None => Ok(None), @@ -1839,12 +1545,9 @@ fn vector_series_with_k( } BoundVectorOp::LimitK { k, group } => select::limitk(*k, &grouping(group), schema, series), BoundVectorOp::LimitRatio { ratio } => select::limit_ratio(*ratio, schema, series), - // A sort hands back the series it was given, rebuilding only those `sort` and `sort_desc` - // drop histogram samples from. BoundVectorOp::Sort(order) => select::sort_instant(order, schema, series.to_vec()), - // The kernel groups bucket series by label set and takes one native histogram series per - // set, so pieces of one label set -- an empty tag and an absent one, or what a map folded - // -- are merged first, and two of them holding one point fail as they do elsewhere. + // The kernel takes one native histogram series per label set, so pieces of one label set + // are merged first. BoundVectorOp::Histogram(function) => evaluate_histograms_with_annotations( *function, schema, @@ -1872,18 +1575,9 @@ fn vector_series_with_k( } /// A rough estimate of what the vector operation `op` allocates over `series`, beside the input it -/// reads. -/// -/// - a ranking: per row the recorded `(point, row)` and its candidate, per series its place in the -/// label order, its group and result descriptors, and the histograms `limitk` and `limit_ratio` -/// copy into their results; -/// - a sort: the value each series is keyed by, and the floats `sort` and `sort_desc` rebuild a series -/// into when it holds histograms; -/// - `absent`: a presence flag and a result value per grid point and field; -/// - `count_values`: per field sample, the group's label set with the value written into it, its count -/// per field and the result series it becomes; -/// - `histogram_quantile` and `histogram_fraction`: the merge of label-set pieces, per series its group -/// entry and a cursor per field, and per row the bucket it contributes. +/// reads: ranking candidates and copied histograms, sort keys and float rebuilds, `absent`'s +/// per-point flags, `count_values`' per-sample groups, and the histogram functions' merge and +/// per-row buckets. fn vector_workspace_bytes(op: &BoundVectorOp, schema: &SeriesSchema, series: &[Series]) -> usize { let fields = schema.fields.len(); match op { @@ -1929,8 +1623,8 @@ fn vector_workspace_bytes(op: &BoundVectorOp, schema: &SeriesSchema, series: &[S } BoundVectorOp::CountValues { .. } => { let label = std::mem::size_of::<(Arc, Arc)>(); - // The value label at the length of a 17-digit value with sign, point and exponent; - // the `'f'` form writes a large magnitude out in full, which this does not follow. + // A 17-digit value with sign, point and exponent. Large magnitudes formatted in full + // can be longer. let value = 24; let group = std::mem::size_of::>() + fields * std::mem::size_of::() @@ -1976,19 +1670,14 @@ fn vector_workspace_bytes(op: &BoundVectorOp, schema: &SeriesSchema, series: &[S /// The operation a scalar broadcast applies, with the side the constant sits on already resolved. #[derive(Clone, Copy, Debug)] enum BroadcastOp { - /// Float arithmetic between the vector and the constant. Arithmetic(ArithmeticOp), - /// A comparison: `Filter` keeps the positions that passed, `Bool` reports `1`/`0` for them. Compare(Comparison), } /// The scalar side of a broadcast. enum BroadcastScalar { - /// A constant, read off the scalar node's binding, at its position in the operation. Literal(ScalarOperand), - /// A scalar that varies per grid point: the one closed chunk its node hands over. - /// - /// It is read whole before any vector chunk is answered. + /// A per-point scalar, read whole before any vector chunk is answered. Dynamic { /// Whether the scalar is the left operand. left: bool, @@ -1996,39 +1685,32 @@ enum BroadcastScalar { }, } -/// What a binary node holds when one operand is a scalar: the operation, its scalar operand and the -/// layout of the side it is broadcast over. -/// -/// A broadcast applies to each chunk as it arrives; unlike [`BinaryRuntime`] it retains nothing for -/// whole-vector matching. +/// A binary node with one scalar operand. Unlike [`BinaryRuntime`] it applies to each vector chunk +/// as it arrives and retains nothing. struct BroadcastRuntime { - /// The scalar and its position in the operation. scalar: BroadcastScalar, - /// Whether the side broadcast over is the left operand. + /// Whether the vector is the left operand. vector_left: bool, - /// The operation applied to every value of the vector. op: BroadcastOp, - /// The layout of the vector side: the fields a chunk of it carries, on the grid it is addressed - /// on. A chunk of the vector side is checked against it by the kernel itself. + /// The vector side's schema; the kernel checks each chunk against it. sample_schema: Arc, - /// The bytes charged for the scalar's value, which [`BroadcastScalar::Dynamic`] keeps. + /// The bytes charged for a [`BroadcastScalar::Dynamic`] value. scalar_bytes: usize, annotations: Option, } -/// What a map with scalar parameters holds: its function and output layout, and each parameter's -/// value once it has arrived. +/// A map with scalar parameters (`round`, `clamp`, `max_of`, ...), holding each parameter once it +/// arrives. struct ParameterizedMapRuntime { op: ParameterizedOp, schema: Arc, - /// A constant input's value, which its node does not hand over as a chunk, and whether the - /// one chunk it stands for has been built. Only a function of two scalars has an input a - /// constant can be: `max_of(0, time())` maps the constant onto the varying scalar. + /// A constant input (as in `max_of(0, time())`), which its node does not hand over as a chunk, + /// and whether its one chunk has been built. input_literal: Option, input_produced: bool, - /// A constant parameter's value, which its node does not hand over as a chunk. + /// Constant parameters, which their nodes do not hand over as chunks. literals: Vec>, - /// Each parameter's one unlabelled series, in argument order. + /// Each parameter's unlabelled series, in argument order. values: Vec>, /// The bytes charged for `values` and for the constant input's chunk. parameter_bytes: usize, @@ -2074,13 +1756,8 @@ impl BroadcastRuntime { matches!(self.scalar, BroadcastScalar::Dynamic { value: None, .. }) } - /// Whether the operation rewrites the label set of what it hands out. - /// - /// Arithmetic and a `bool` comparison drop the metric name, so two input series can become one - /// label set under this node; a filtering comparison keeps the label set it read. The answer is - /// read off [`Self::op`], so an operation and its label policy cannot disagree. Collection is not - /// this node's work: a collision the rewritten set creates is what a canonical - /// [`NativeExpr::Merge`] above it refuses. + /// Whether the operation drops the metric name (arithmetic and `bool` comparisons). Two input + /// series can then share one label set; a [`NativeExpr::Merge`] above handles that. fn drops_labels(&self) -> bool { match self.op { BroadcastOp::Arithmetic(_) | BroadcastOp::Compare(Comparison::Bool(_)) => true, @@ -2088,10 +1765,8 @@ impl BroadcastRuntime { } } - /// Reports the samples a binary operation had to drop because it has no histogram form. - /// - /// Prometheus answers no value for a histogram under an operator it has no meaning for, and failing - /// the query instead would turn one unsupported sample into no answer at all. + /// Reports histogram samples dropped by an operation with no histogram form, as Prometheus + /// does instead of failing. fn record_dropped_histograms(&self, dropped_histogram: bool, op: impl std::fmt::Display) { if dropped_histogram && let Some(collector) = &self.annotations { collector.record_info(format!( @@ -2100,9 +1775,7 @@ impl BroadcastRuntime { } } - /// The label set a chunk of the vector side's `metric` becomes under this operation. - /// - /// It is what a series closes under when the operation emptied every position. + /// The label set `metric` becomes under this operation. fn output_metric(&self, metric: &SeriesLabels) -> Result { if self.drops_labels() { drop_metric_name(metric) @@ -2111,11 +1784,9 @@ impl BroadcastRuntime { } } - /// Applies the operation to one chunk of the vector side. - /// - /// `None` means the operation emptied every position and the chunk does not close its series. A - /// chunk that does close its series is answered even then -- with a series carrying no row -- - /// because a consumer tells "nothing more here" from "no more input" by that chunk alone. + /// Applies the operation to one vector chunk. `None` means every position was emptied and the + /// chunk does not close its series; a closing chunk always yields a series, possibly with no + /// rows, so the close reaches the consumer. fn apply(&self, chunk: &EvaluatedChunk) -> Result> { let output = match &self.scalar { BroadcastScalar::Literal(operand) => match self.op { @@ -2191,9 +1862,7 @@ fn buffered_time(chunks: &[RawSeriesChunk]) -> Result { RawTimestamps::try_new(ScalarBuffer::from(timestamps)).map_err(series_error) } -/// The buffered chunks as one axis: per field, the chunks' samples in arrival order. -/// -/// A field keeps the chunks it arrived in instead of copying them out. +/// The buffered chunks' fields, each chaining its chunks' samples without copying. fn buffered_fields(chunks: &[RawSeriesChunk], fields: usize) -> Result { let mut per_field: Vec> = vec![Vec::with_capacity(chunks.len()); fields]; for chunk in chunks { @@ -2208,8 +1877,8 @@ fn buffered_fields(chunks: &[RawSeriesChunk], fields: usize) -> Result Option { let holds_histograms = field.segments().iter().any(|segment| { matches!( @@ -2264,21 +1933,16 @@ fn histogram_bytes(view: &HistogramView<'_>) -> usize { const HISTOGRAM_ROW_HEADER_BYTES: usize = 7 * std::mem::size_of::() + 7 * std::mem::size_of::(); -/// The last timestamp of `spec`, which is inclusive: its `len` points step from its start. -/// -/// [`GridSpec::try_new`] checked that the point fits `i64`, so widening it here cannot overflow. +/// The last (inclusive) timestamp of `spec`. [`GridSpec::try_new`] guarantees it fits `i64`. fn grid_end_ms(spec: GridSpec) -> i64 { (i128::from(spec.start_ms) + i128::from(spec.step_ms) * (i128::from(spec.len) - 1)) as i64 } -/// The position of the grid point at `timestamp`, which the selection reported as one of its own. -/// -/// A timestamp off that lattice, or one past the end of the grid, is a disagreement between the -/// selection and its binding rather than a sample to skip, so it is reported instead of dropped. +/// The grid position of `timestamp`. A timestamp off the grid is an internal disagreement, so it +/// is an error rather than skipped. fn grid_position(grid: &EvalGrid, timestamp: i64) -> Result { let spec = grid.spec(); - // This runs once per reported point, so the common case stays in `i64`; a grid whose numbers do not - // fit, or a timestamp off the lattice, falls through to the `i128` path below. + // Fast `i64` path per point; overflow or an off-grid timestamp falls through to `i128`. if spec.step_ms > 0 && let Some(offset) = timestamp.checked_sub(spec.start_ms) && offset >= 0 @@ -2337,11 +2001,10 @@ fn grid_chunk_bytes(grid: &EvalGrid) -> Result { .ok_or_else(|| DataFusionError::Execution("scalar allocation size overflow".into())) } -/// An upper bound of what the operations of a map allocate for the series they write over `series`. -/// -/// Each operation reads the series the one before it wrote, which stays alive until the next one is -/// written, so the bound is the largest of the first one's workspace and of two consecutive ones'. -/// Every such operation writes floats only, at no more rows than it read. +/// An upper bound of what a chain of map operations allocates over `series`. Each operation's +/// output lives until the next one is written, so the bound is the largest sum of two consecutive +/// workspaces. Sizing every operation from `series` relies on each one writing floats only, at no +/// more rows than it read. fn map_workspace_bytes(ops: &[MapOp], series: &Series) -> Result { let (mut previous, mut bound) = (0usize, 0usize); let mut first = true; @@ -2362,13 +2025,9 @@ fn map_workspace_bytes(ops: &[MapOp], series: &Series) -> Result { Ok(bound) } -/// An upper bound of what a kernel that maps each dense segment of `series` into a new array of its -/// length allocates: float math over a series of floats, and arithmetic against a constant, which also -/// rebuilds a histogram field sample by sample. -/// -/// A mapped segment holds its values behind the header of the allocation they share, rounded up to -/// Arrow's 64-byte alignment. A histogram row is not one `f64`: the kernel copies the whole payload, -/// buckets included, so the largest row in the field is the one to charge. +/// An upper bound of what a kernel that maps each dense segment of `series` into a new array of +/// equal length allocates. A histogram row is charged at the field's largest payload, plus a buffer +/// header and 64-byte alignment per segment. fn mapped_workspace_bytes(series: &Series) -> Result { let segments = series .fields @@ -2405,11 +2064,9 @@ fn built_series_workspace_bytes(series: &Series) -> Result { .ok_or_else(|| workspace_overflow(series.time.len(), fields)) } -/// The bytes a result of `fields` fields over `segments` segments is assembled from, beside its values: -/// the descriptor lists and the label set rebuilt from `metric`. -/// -/// A list collected or pushed without knowing its length starts at four entries and doubles, so it -/// holds at most `2 * n + 4` descriptors for `n` of them. +/// The bytes a result of `fields` fields over `segments` segments is assembled from, beside its +/// values: the descriptor lists (a growing list holds at most `2 * n + 4` entries) and the label +/// set rebuilt from `metric`. fn assembly_bytes(fields: usize, segments: usize, metric: &SeriesLabels) -> Option { let descriptors = segments .checked_mul(6)? @@ -2424,14 +2081,13 @@ fn assembly_bytes(fields: usize, segments: usize, metric: &SeriesLabels) -> Opti /// An allowance for the shared header an Arrow buffer or a label list is allocated behind. const BUFFER_HEADER_BYTES: usize = 64; -/// An upper bound of the bytes a [`GridSeriesBuilder`] allocates for a result of `fields` float fields -/// whose positions are a subset of `rows` positions making up `runs` runs. +/// An upper bound of the bytes a [`GridSeriesBuilder`] allocates for a result of `fields` float +/// fields whose positions are a subset of `rows` positions in `runs` runs. /// -/// For a result of `kept` rows in `split` runs, the builder's row indices and each field's values grow -/// by doubling, so each holds at most `2 * kept + 4` entries, and finishing turns each run into a span -/// the axis copies once. Dropping one position splits at most one run in two, so -/// `split <= min(kept, runs + rows - kept)`, and the bound is the larger of the two ends of that -/// region. A caller that cannot say the result's positions are the input's passes `runs = rows`. +/// Keeping `kept` rows in `split` runs costs `2 * kept + 4` entries per growing column plus a span +/// per run. Dropping a position splits at most one run, so `split <= min(kept, runs + rows - kept)` +/// and the maximum is at one end of that range. Pass `runs = rows` when the result's positions are +/// not a subset of the input's. fn built_workspace_bytes(rows: usize, runs: usize, fields: usize) -> Result { let cost = |kept: usize, split: usize| { let capacity = kept.checked_mul(2)?.checked_add(4)?; @@ -2460,15 +2116,13 @@ fn workspace_overflow(rows: usize, fields: usize) -> DataFusionError { )) } -/// An upper bound of what `window`'s next push allocates for the rows it hands out, for input whose -/// last sample is at `last_ts`, closing its series when `last`, with `fields`, of the series `metric` -/// names. +/// An upper bound of what `window`'s next push allocates for its output rows, given the input's +/// last sample time `last_ts` and whether it closes the series. /// -/// The rows are bounded by [`RangeEvaluator::output_rows_bound`] and written as -/// [`built_workspace_bytes`] counts them; the points they sit on are the output grid's, so each may be a -/// run of its own. A function that can answer with a native histogram also writes an index per field -/// and row and a table row grown by doubling, bounded by the widest histogram the evaluator retains or -/// `fields` carries. A combination of disjoint layouts can exceed that row; it is not bounded here. +/// Rows come from [`RangeEvaluator::output_rows_bound`], each possibly its own run. A +/// histogram-valued function adds an index and a doubled table row per field and row, sized by the +/// widest histogram retained or incoming; a result combining disjoint layouts can exceed that and +/// is not bounded. fn window_workspace_bytes( window: &RangeEvaluator, last_ts: Option, @@ -2548,10 +2202,7 @@ fn scalar_chunk_on( EvaluatedChunk::try_new(series, true) } -/// A closing chunk carrying `metric` and no row at all. -/// -/// A series whose selection picked no source row still closes exactly once, on a chunk that holds -/// nothing. +/// A closing chunk carrying `metric` and no rows. fn no_row_chunk(schema: &SeriesSchema, metric: SeriesLabels) -> Result { let grid = schema.eval_grid.clone().ok_or_else(|| { DataFusionError::Execution( @@ -2614,7 +2265,7 @@ enum RuntimeOp { }, Window { input: Box, - // `finish` consumes the evaluator; it is taken only during the terminal finish pass. + // `None` once `finish_windows` has consumed the evaluator. window: Option, merge: Option, state: NodeState, @@ -2683,20 +2334,15 @@ enum RuntimeOp { }, } -/// State shared by the stateful operators. -/// -/// The queue must precede the buffer so it drops before its reservation. +/// State shared by the stateful operators. The queue precedes the buffer so it drops before its +/// reservation. struct NodeState { queued: VecDeque<(NativeChunk, usize)>, queued_tables: usize, buffer: NodeBuffer, } -/// The kind of chunk an input leaf is bound to. -/// -/// The binding, not a property read off a schema, decides what may be queued at the leaf: raw and -/// evaluated inputs carry a series schema, a state input carries the aggregate-state binding, and -/// neither may be fed the other's chunks. +/// The kind of chunk an input leaf is bound to, and so the only kind it accepts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum LeafKind { Raw, @@ -2705,7 +2351,6 @@ enum LeafKind { } impl LeafKind { - /// What a leaf bound to `output` accepts. fn of(output: &NativeType) -> Result { match output { NativeType::Samples(schema) if schema.eval_grid.is_some() => Ok(Self::Evaluated), @@ -2717,7 +2362,6 @@ impl LeafKind { } } - /// What this kind is called in a rejection. fn describe(self) -> &'static str { match self { Self::Raw => "raw samples", @@ -2726,7 +2370,6 @@ impl LeafKind { } } - /// Whether a chunk of `chunk` may be queued at a leaf of this kind. fn accepts(self, chunk: &NativeChunk) -> bool { matches!( (self, chunk), @@ -2743,13 +2386,9 @@ struct InputSlot { kind: LeafKind, /// Whether the series whose chunk this leaf most recently handed over is still open. open_source_series: bool, - /// Whether the series whose chunk the caller most recently queued here is still open. - /// - /// Finality is a property of what the caller sent and not of what the tree has pulled: a node - /// that decides nothing before its whole input is there, such as an aggregate waiting for its - /// parameter, can end a run with a chunk still queued, and that chunk is what says whether the - /// input was closed. Following the handovers alone would read the queued chunk as never having - /// arrived, and the truncated input it holds as a closed one. + /// Whether the series whose chunk the caller most recently queued here is still open. Tracked + /// separately from handovers because a node waiting on a parameter can leave a chunk queued at + /// the end of a run. open_queued_series: bool, state: NodeState, } @@ -2775,10 +2414,8 @@ struct LiveExecution { } impl NodeState { - /// Names the node whose evaluation failed. - /// - /// A failure that carries its own message keeps it: `DataFusionError::Context` displays only the - /// context, so wrapping one would answer a client with the node's name instead of what went wrong. + /// Adds the node name to `error`: an `Execution` message gets it as a prefix and stays + /// `Execution`; any other variant is wrapped in `Context`. fn context(&self, error: DataFusionError) -> DataFusionError { let name = self.buffer.reservation.consumer().name(); match error { @@ -2803,15 +2440,12 @@ impl NodeState { } } -/// Stack one [`RuntimeNode::build`] or [`RuntimeNode::pull`] level needs below it before the recursion -/// grows its stack. -/// -/// Both walks recurse once per tree level and a debug build's frame is large (about 140 KiB for a -/// `build` level and 80 KiB for a `pull` level, measured on a 100-term chain), which can abort an 8 MiB -/// runtime worker. There is no depth limit, so the recursion grows its stack instead. +/// Remaining stack below which [`RuntimeNode::build`] and [`RuntimeNode::pull`] grow it. Both +/// recurse once per tree level with large debug-build frames (about 140 KiB and 80 KiB, measured on +/// a 100-term chain), and the tree has no depth limit, so an 8 MiB worker stack can overflow. const NATIVE_STACK_RED_ZONE: usize = 512 * 1024; -/// Stack a growth adds when the reserve above is spent. It holds several levels of the same walk. +/// Stack added per growth; holds several levels. const NATIVE_STACK_GROWTH: usize = 4 * 1024 * 1024; impl RuntimeNode { @@ -3019,9 +2653,8 @@ impl RuntimeNode { let input_schema = input.output.samples().cloned().ok_or_else(|| { DataFusionError::Execution("window consumes non-sample input".to_string()) })?; - // The child reports fragments only when it cannot prove the labels it drops tell its - // series apart, which is the same question the canonical pass asked before it - // decided this window needs no merge above it. + // Collect and merge fragments only when the input cannot prove its series keep + // distinct label sets: the same check the canonical pass uses to place merges. let unification = unifies_its_own_contributions(input, &sources.tags, &sources.metrics); let merge = matches!(unification, Some(false)) @@ -3033,8 +2666,6 @@ impl RuntimeNode { ); RuntimeOp::Window { input: Box::new(child), - // The collector arrives through `set_annotations` before the first pull; - // a fresh evaluator records nothing until then. window: Some(RangeEvaluator::try_new( &input_schema, Arc::clone(&op.output_grid), @@ -3086,9 +2717,6 @@ impl RuntimeNode { duplicate_evidence.clone(), sources, )?; - // A function of two scalars answers a scalar, which has one unlabelled field on - // the grid it is evaluated on; every other function here answers its input's own - // fields. let schema = match &node.output { NativeType::Samples(schema) => Arc::clone(schema), NativeType::Scalar(grid) => Arc::new(scalar_schema(Arc::clone(grid))), @@ -3106,8 +2734,6 @@ impl RuntimeNode { _ => None, }) .collect(); - // A constant input hands over no chunk of its own, as a constant parameter does: - // the map materializes the one chunk it stands for. let input_literal = match &input.expr { NativeExpr::Scalar(BoundScalar { value }) => Some(*value), _ => None, @@ -3400,8 +3026,7 @@ impl RuntimeNode { duplicate_evidence.clone(), sources, )?; - // The input is built before the parameter, the order the selector walk binds the - // two sources in. + // Input before parameter: the order the selector walk binds the two sources in. let parameter = Self::build( parameter, pool, @@ -3641,8 +3266,6 @@ impl RuntimeNode { match &self.op { RuntimeOp::Input(_) | RuntimeOp::Scalar => 0, RuntimeOp::EvalTime { state, .. } => state.buffer.reservation.size(), - // The retention path resizes this reservation to what the node retains, so the figure is - // read off the one reservation rather than charging the retained bytes a second time. RuntimeOp::ScalarOf { input, state, .. } => state .buffer .reservation @@ -3718,10 +3341,6 @@ impl RuntimeNode { } } -/// What the driver asks of one node. -/// -/// A node reads its own children: a pull descends the part of the tree it needs and returns, and the -/// exclusive borrow the state takes of its root makes the whole descent exclusive. impl RuntimeNode { fn set_annotations(&mut self, collector: PromqlAnnotationCollector) { match &mut self.op { @@ -3731,9 +3350,6 @@ impl RuntimeNode { } input.set_annotations(collector); } - // A map's kernels record nothing: float math and the native-histogram readers answer - // a value per sample with no message of their own, so only its child needs the - // collector. RuntimeOp::Map { input, .. } => input.set_annotations(collector), RuntimeOp::ParameterizedMap { input, parameters, .. @@ -3769,8 +3385,6 @@ impl RuntimeNode { RuntimeOp::Aggregate { input, aggregate, .. } => { - // An aggregate that skips histogram samples reports that it did, so it needs the - // collector as well as its child. aggregate.set_annotations(collector.clone()); input.set_annotations(collector); } @@ -3780,8 +3394,6 @@ impl RuntimeNode { aggregate, .. } => { - // The fold reports skipped samples exactly as the bound one does, so it needs the - // collector too; a parameter is a scalar expression and reads none of them. aggregate.set_annotations(collector.clone()); input.set_annotations(collector.clone()); if let Some(parameter) = parameter { @@ -3793,10 +3405,7 @@ impl RuntimeNode { vector.annotations = Some(collector.clone()); input.set_annotations(collector); } - // `scalar()` answers a value of its own and records nothing, so only its input needs the - // collector. RuntimeOp::ScalarOf { input, .. } => input.set_annotations(collector), - // Ranking records nothing of its own: the parameter and the input are what read it. RuntimeOp::ParameterizedTopK { input, parameter, @@ -3809,8 +3418,6 @@ impl RuntimeNode { parameter.set_annotations(collector); } } - // The histogram kernel reports a native histogram and classic buckets of one label set - // through the collector, so the runtime it runs on needs it as well as its children. RuntimeOp::ParameterizedHistogram { input, parameters, @@ -3827,14 +3434,9 @@ impl RuntimeNode { } } - /// Pulls the next chunk this node hands over, taking what its children owe it. - /// - /// `inputs_finished` is the caller's word that no more source chunks will arrive: a node that - /// decides nothing until its whole input is there reads it to tell "nothing more" from "nothing - /// yet". - /// - /// The pull recurses once per tree level, so it grows its stack as it descends - /// ([`NATIVE_STACK_RED_ZONE`]). + /// Pulls this node's next chunk, pulling its children as needed. `inputs_finished` says no + /// more source chunks will arrive, so a node that needs its whole input can tell "nothing more" + /// from "nothing yet". Grows the stack as it recurses ([`NATIVE_STACK_RED_ZONE`]). fn pull( &mut self, inputs: &mut [InputSlot], @@ -3851,9 +3453,6 @@ impl RuntimeNode { inputs_finished: bool, ) -> Result> { match &mut self.op { - // A source hands over what the caller queued at it. The id was assigned when the tree - // was built, so an id past the leaves means this call and the tree disagree rather than - // that the chunk belongs somewhere else. RuntimeOp::Input(id) => { let input = *id; let count = inputs.len(); @@ -3862,9 +3461,7 @@ impl RuntimeNode { .ok_or_else(|| no_input(count, input))?; slot.pop_source() } - // A scalar owes its consumer no chunk: it produces one value and no series, and the - // value is the constant on the tree, which the consumer reads off its own binding. A - // pull of it is therefore empty by construction and says nothing has stalled. + // A constant has no chunk: consumers read the value off their own binding. RuntimeOp::Scalar => Ok(None), RuntimeOp::ScalarOf { input, @@ -3902,8 +3499,7 @@ impl RuntimeNode { if !*produced { let len = grid.spec().len as usize; let bytes = grid_chunk_bytes(grid).map_err(|e| state.context(e))?; - // The counts the kernel decides its answer by are read while it walks the - // assembled input, so they are reserved on top of the chunk it hands over. + // The kernel's per-point sample counts. let counts_bytes = len.saturating_mul(std::mem::size_of::()); let assembly = retained .assembly_bytes(input_schema) @@ -3916,18 +3512,12 @@ impl RuntimeNode { .assemble(input_schema, Reader::Vector) .map_err(|e| state.context(e))?; retained.release(); - // `scalar()` reads a whole vector, which is what the assembled input is, so - // the kernel Prometheus' `funcScalar` is answers here too: one value per grid - // point, NaN where the point does not hold exactly one float sample, and the - // histogram samples of the input ignored. + // As Prometheus' `funcScalar`: NaN where a point does not hold exactly one + // float sample; histogram samples are ignored. let answer = select::scalar(input_schema, &assembled).map_err(|e| state.context(e))?; - // The assembled input is consumed, so what this node holds from here on is the - // one chunk the answer becomes. drop(assembled); state.buffer.resize(bytes).map_err(|e| state.context(e))?; - // Only the layout the answer is named by changes: a scalar sits on this node's - // grid, in the one field a scalar's carrier has. let schema = scalar_schema(Arc::clone(grid)); let series = Series::try_new(&schema, answer.metric, answer.time, answer.fields) @@ -3947,8 +3537,7 @@ impl RuntimeNode { state, } => { if !std::mem::replace(produced, true) { - // `time()` and the date functions read every point of the grid, so this node is - // what materializes a deferred grid's timestamps. + // `time()` and the date functions materialize the grid's timestamps. state .buffer .reserve_grid(grid) @@ -3985,7 +3574,7 @@ impl RuntimeNode { } return state.pop_queued(evaluated_values); } - // A scalar is already one unlabelled series; only the layout it is named by changes. + // A scalar is already one unlabelled series; only the schema changes. let Some(chunk) = input.pull(inputs, inputs_finished)? else { return Ok(None); }; @@ -4007,8 +3596,7 @@ impl RuntimeNode { state, } => { let selection = instant; - // A selection decides a whole series at once, so every chunk before the one that - // closes it yields nothing and the selection asks its input again. + // Only a series' closing chunk yields output, so keep pulling until one does. loop { let Some(chunk) = input.pull(inputs, inputs_finished)? else { return Ok(None); @@ -4050,17 +3638,14 @@ impl RuntimeNode { merge, state, } => { - // A chunk this window computed while flushing its collected input leaves first: it - // was produced before the window was drained, and the pull that hands it up is the - // one that empties the queue. + // Chunks queued by a flush of collected input go first. if let Some(chunk) = state.take_output().map_err(|error| state.context(error))? { return Ok(Some(chunk)); } let Some(evaluator) = window.as_mut() else { return Err(no_window()); }; - // A window reports on the chunk that closes a series, so a chunk that decides - // nothing yields nothing and the window asks its input again. + // A chunk that decides no point yields nothing; keep pulling. loop { let Some(chunk) = input.pull(inputs, inputs_finished)? else { return Ok(None); @@ -4075,8 +3660,7 @@ impl RuntimeNode { } RuntimeOp::Map { input, map, state } => { let operation = map; - // An operation that empties every position yields no chunk, and the map asks its - // input again rather than reporting a decision it did not make. + // A chunk the operation empties entirely yields nothing; keep pulling. loop { let Some(chunk) = input.pull(inputs, inputs_finished)? else { return Ok(None); @@ -4101,8 +3685,7 @@ impl RuntimeNode { state, } => { let operation = map; - // Every parameter is read whole first, as a broadcast reads its scalar; a constant - // one is materialized from its binding. + // Read every parameter whole first; a constant one is built from its binding. for (index, parameter) in parameters.iter_mut().enumerate() { let slot = &mut operation.values[index]; if slot.is_some() { @@ -4125,11 +3708,8 @@ impl RuntimeNode { .map_err(|error| state.context(error))?; } } - // A parameter reads no data, so it hands its value over on its first pull and is - // always ready by now. if !operation.ready() { - // A parameter that folds its own input answers only once that input ends, so - // its absence is a reason to be pulled again rather than a failure. + // A parameter like `scalar(selector)` answers only after its input ends. if !inputs_finished || !parameters.iter().all(|parameter| parameter.settled(inputs)) { @@ -4139,8 +3719,7 @@ impl RuntimeNode { "a map parameter did not hand over its value".to_string(), )); } - // A constant input hands over no chunk of its own, as a constant parameter does: - // the one chunk it stands for is built here, on the grid the map answers on. + // A constant input has no chunk of its own; build it on the map's grid. if let Some(value) = operation.input_literal && !std::mem::replace(&mut operation.input_produced, true) { @@ -4213,9 +3792,8 @@ impl RuntimeNode { state, } => { let operation = binary; - // Both operands are read to the end of what they hand over: before the input ends a - // binary node only retains the chunks, because a pair is not decided until both - // sides are whole, and after it ends this is the drain that empties the two. + // Retain everything both operands hand over; nothing is decided until both are + // whole. while let Some(chunk) = left.pull(inputs, inputs_finished)? { state .retain_binary(operation, 0, chunk) @@ -4226,17 +3804,13 @@ impl RuntimeNode { .retain_binary(operation, 1, chunk) .map_err(|error| state.context(error))?; } - // Nothing has settled for a point that has an operand still arriving, and an - // operand below a collecting window has not arrived until that window is flushed: - // a node that reports itself settled reports it for everything below it too. + // An empty pull is not the end: a collecting window below may not have flushed. if !inputs_finished || !left.settled(inputs) || !right.settled(inputs) { return Ok(None); } state .compute_binary(operation) .map_err(|error| state.context(error))?; - // A result holds one value per field, and a field may hold none where another - // does, so its values are counted rather than read as its positions. state.pop_queued(evaluated_values) } RuntimeOp::Broadcast { @@ -4246,8 +3820,8 @@ impl RuntimeNode { state, } => { let operation = broadcast; - // A constant is on the node's binding, so only the vector side is pulled. A varying - // scalar is read first, whole; then each vector chunk is transformed as it arrives. + // A dynamic scalar is read whole first; then each vector chunk is mapped as it + // arrives. let (vector, scalar) = if operation.vector_left { (&mut **left, &mut **right) } else { @@ -4263,8 +3837,6 @@ impl RuntimeNode { } } if operation.awaits_scalar() { - // A scalar that folds its own input answers only once that input ends, so - // its absence is a reason to be pulled again rather than a failure. if !inputs_finished || !scalar.settled(inputs) { return Ok(None); } @@ -4272,8 +3844,7 @@ impl RuntimeNode { "a broadcast scalar did not hand over its value".to_string(), )); } - // An operation that empties every position yields no chunk, and the node asks its - // vector side again rather than reporting a decision it did not make. + // A chunk the operation empties entirely yields nothing; keep pulling. loop { let Some(chunk) = vector.pull(inputs, inputs_finished)? else { return Ok(None); @@ -4292,8 +3863,7 @@ impl RuntimeNode { state, } => { let fold = aggregate; - // What the fold reads is not retained, so reading the child dry costs the fold's states - // and not the input's bytes. Nothing is answered before the input ends. + // Nothing is answered before the input ends. while let Some(chunk) = input.pull(inputs, inputs_finished)? { state .retain_aggregate(fold, chunk) @@ -4305,8 +3875,6 @@ impl RuntimeNode { state .compute_aggregate(fold) .map_err(|error| state.context(error))?; - // A group's series holds one value per field and point it decided, so its values - // are counted rather than read as its positions, as a binary result's are. state.pop_queued(evaluated_values) } RuntimeOp::ParameterizedAggregate { @@ -4316,12 +3884,7 @@ impl RuntimeNode { state, } => { let fold = aggregate; - // The φ is read at every point the fold answers, so it is drained whole before the - // fold computes an answer: a point's answer is decided from the group's samples and - // the φ the statement evaluated there, and the fold keeps the group's samples rather - // than a per-point state, so it cannot be handed the φ later. What has arrived of - // the input is still read while the φ is pending, which is what keeps it out of the - // source queue (see the pull below). + // φ is read whole before the fold can answer. if let Some(parameter_node) = parameter.as_mut() { let mut slot = None; let mut held = 0usize; @@ -4331,16 +3894,9 @@ impl RuntimeNode { .map_err(|error| state.context(error))?; } let series = { - // A parameter that folds its own input (a `scalar()` over a selector) has - // nothing to hand over until that input ends, so its absence is a reason to - // be pulled again rather than a failure. Being pulled again is not idling: - // this fold keeps its whole input, so the chunks that have arrived are - // retained now, exactly as they would be once the φ is in hand. Leaving them - // where they are would bill them twice over for the same buffer -- the queue - // charges every queued chunk for the whole allocation it is a slice of - // (`NativeChunk::bytes`, where the retainer below bills that allocation - // once), so an input of a thousand slices of one buffer would be refused by - // a pool that holds the buffer a thousand times rather than once. + // While φ is pending, drain the input into the fold anyway: the source + // queue bills each queued slice for its whole allocation, while the fold + // bills a shared allocation once. if !parameter_node.settled(inputs) { while let Some(chunk) = input.pull(inputs, inputs_finished)? { state @@ -4357,8 +3913,8 @@ impl RuntimeNode { }; fold.hold_parameter(series, &mut state.buffer) .map_err(|error| state.context(error))?; - // Finish windows before dropping the consumed subtree; its children may still - // hold charged emitted history or scalar series even after the scalar was read. + // Run the evaluators' truncation check now: `unclosed` cannot reach this + // subtree once it is dropped. parameter_node.finish_windows()?; *parameter = None; } @@ -4393,9 +3949,6 @@ impl RuntimeNode { .map_err(|error| state.context(error))?; } let series = { - // A parameter that folds its own input (a `scalar()` over a selector) has - // nothing to hand over until that input ends, so its absence is a reason to - // be pulled again rather than a failure. if !parameter_node.settled(inputs) { return Ok(None); } @@ -4414,8 +3967,6 @@ impl RuntimeNode { "topk parameter does not cover its grid".into(), )); } - // The values the parameter is read into are held beside the input for as long - // as the node lives, so the pool admits them before they are allocated. let bytes = len.saturating_mul(std::mem::size_of::>()); state .buffer @@ -4434,15 +3985,13 @@ impl RuntimeNode { select::validate_topk_parameters(&values) .map_err(|error| state.context(error))?; operation.parameter = Some(values); - // The series was the parameter until its values were read off it; what the node - // holds from here on is the values themselves. drop(series); operation.parameter_bytes = bytes; state .settle_vector(operation) .map_err(|error| state.context(error))?; - // Finish windows before dropping the consumed subtree; its children may still - // hold charged buffers or scalar series even after the scalar was read. + // Run the evaluators' truncation check now: `unclosed` cannot reach this + // subtree once it is dropped. parameter_node.finish_windows()?; *parameter = None; } @@ -4514,8 +4063,6 @@ impl RuntimeNode { "histogram parameter does not cover its grid".into(), )); } - // The values each parameter is read into are held beside the input for as - // long as the node lives, so the pool admits them before they are allocated. let bytes = len.saturating_mul(std::mem::size_of::>()); state.buffer.grow(bytes)?; let collected = { @@ -4528,8 +4075,6 @@ impl RuntimeNode { .collect::>>() }; values[index] = Some(collected); - // What the node holds for this parameter is its values, not the series they were - // read from, so the one replaces the other as soon as the series is gone. parameter_bytes[index] = bytes; drop(series); operation.parameter_bytes = parameter_bytes @@ -4543,9 +4088,6 @@ impl RuntimeNode { parameters[index] = None; } } - // Nothing is settled here: what this node holds changes as a parameter is converted above - // and as a chunk is retained below, and each of those settles the reservation. A settle - // over the state as it stands would drop the charge for queued results. while let Some(chunk) = input.pull(inputs, inputs_finished)? { state.retain_vector(operation, chunk)?; } @@ -4569,8 +4111,6 @@ impl RuntimeNode { state, } => { let operation = vector; - // Which samples are kept at a point is not decided until the whole input has - // arrived, so the input is read to the end before anything is handed over. while let Some(chunk) = input.pull(inputs, inputs_finished)? { state .retain_vector(operation, chunk) @@ -4587,20 +4127,14 @@ impl RuntimeNode { } } - /// Whether this node has produced everything it ever will. - /// - /// A pull that finds nothing does not answer it: a collecting window reports nothing until it is - /// flushed, and a binary node nothing until both nodes it reads from are finished. Each node - /// therefore answers from its own state and from its children's. + /// Whether this node has produced everything it ever will. An empty pull does not imply it: a + /// collecting window yields nothing until flushed, and a binary node nothing until both + /// operands are done. fn settled(&self, inputs: &[InputSlot]) -> bool { match &self.op { - // A source has handed over everything it ever will once nothing is queued at it: what - // it hands over is what the caller queued. RuntimeOp::Input(id) => inputs .get(id.index()) .is_some_and(|slot| slot.state.queued.is_empty()), - // A scalar produces its value without reading anything, so it is settled from the - // start: there is no chunk it owes its consumer. RuntimeOp::Scalar => true, RuntimeOp::EvalTime { produced, state, .. @@ -4630,8 +4164,7 @@ impl RuntimeNode { state, .. } => { - // Parameter nodes are released after their values are installed; `computed` - // already implies those values were consumed. + // `computed` implies the released parameters were consumed. state.queued.is_empty() && vector.computed && input.settled(inputs) } RuntimeOp::ParameterizedTopK { @@ -4640,8 +4173,7 @@ impl RuntimeNode { state, .. } => { - // Parameter nodes are released after their values are installed; `computed` - // already implies the parameter was consumed. + // `computed` implies the released parameter was consumed. state.queued.is_empty() && vector.computed && input.settled(inputs) } RuntimeOp::VectorOf { @@ -4653,15 +4185,12 @@ impl RuntimeNode { } => { state.queued.is_empty() && (*produced || literal.is_none()) && input.settled(inputs) } - // These report as they are handed chunks, so a child with nothing left is all it takes - // for them to have nothing left either. RuntimeOp::Instant { input, state, .. } | RuntimeOp::Map { input, state, .. } | RuntimeOp::Timestamp { input, state, .. } => { state.queued.is_empty() && input.settled(inputs) } - // A window that collects its input has not answered until it has flushed it, so a merge - // still held is an answer still owed. + // A collecting window still holding its merge input owes output. RuntimeOp::Window { input, merge, @@ -4673,16 +4202,13 @@ impl RuntimeNode { merge, state, } => state.queued.is_empty() && merge.is_none() && input.settled(inputs), - // An aggregate answers one series per group and only once its input ended, so its own - // fold has to have run as well: a child that has handed everything up is not enough, - // because every one of those chunks was folded and none of them answered yet. + // A settled child is not enough: the fold must also have run. RuntimeOp::Aggregate { input, aggregate, state, } => state.queued.is_empty() && aggregate.computed && input.settled(inputs), - // The same fold, with its parameter released after the fold holds it: `computed` already - // implies the parameter was consumed. + // `computed` implies the released parameter was consumed. RuntimeOp::ParameterizedAggregate { input, aggregate, @@ -4707,19 +4233,14 @@ impl RuntimeNode { && left.settled(inputs) && right.settled(inputs) } - // A broadcast owes what its sides have not handed over yet. A constant side is settled - // from the start. RuntimeOp::Broadcast { left, right, state, .. } => state.queued.is_empty() && left.settled(inputs) && right.settled(inputs), } } - /// Merges the collected input of every window that collects it, deepest first. - /// - /// A window above another collects the chunks the one below hands up, so flushing the shallow one - /// first would merge an input it has not received yet. A window whose input has not settled is left - /// for a later call. + /// Flushes every collecting window and merge whose input has settled, deepest first, so an + /// outer one never merges input still held below it. Returns whether anything was flushed. fn flush_ready_merges(&mut self, inputs: &[InputSlot]) -> Result { match &mut self.op { RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => Ok(false), @@ -4784,8 +4305,6 @@ impl RuntimeNode { state, } => { let mut flushed = input.flush_ready_merges(inputs)?; - // A window collects its input only when it can hold two series under one canonical label - // set, and that input has to be finished before it is merged. if merge.is_some() && input.settled(inputs) { let Some(evaluator) = window.as_mut() else { return Err(no_window()); @@ -4835,16 +4354,13 @@ impl RuntimeNode { RuntimeOp::Binary { left, right, .. } | RuntimeOp::Broadcast { left, right, .. } => { left.any_merge_pending() || right.any_merge_pending() } - // Only a window that collects its input keeps collected input to merge. RuntimeOp::Window { input, merge, .. } => merge.is_some() || input.any_merge_pending(), RuntimeOp::Merge { input, merge, .. } => merge.is_some() || input.any_merge_pending(), } } - /// Refuses a node that ended inside a series, in every node that would read the remainder. - /// - /// The assembly above would read half a vector as a whole one, and a window that collected its input - /// would merge the pieces it has into a series that looks finished. + /// Refuses input that ended with a series still open, in every node that retains whole series; + /// otherwise half a series would be read as a complete one. fn unclosed(&self) -> Result<()> { match &self.op { RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => Ok(()), @@ -4888,8 +4404,7 @@ impl RuntimeNode { } Ok(()) } - // The fold keeps its input rather than folding it away, so a series that ended inside - // the fold's input is exactly what this checks for; the parameter is one scalar series. + // Only the children are checked: the fold's retained input does not track open series. RuntimeOp::ParameterizedAggregate { input, parameter, .. } => { @@ -4944,10 +4459,8 @@ impl RuntimeNode { } } - /// Finishes every window's evaluator that is still here, and reports the first failure. - /// - /// Every evaluator is finished even after one fails -- the first error is the one reported -- so that - /// a failure leaves nothing to be read on the way out. + /// Finishes every window evaluator still present in this subtree. All are finished even after + /// one fails, so none keeps its bytes; the first error is returned. fn finish_windows(&mut self) -> Result<()> { match &mut self.op { RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => Ok(()), @@ -4955,7 +4468,6 @@ impl RuntimeNode { RuntimeOp::ParameterizedMap { input, parameters, .. } => { - // Every evaluator is finished even after one fails, as for a binary node. let first = input.finish_windows(); parameters .iter_mut() @@ -4990,8 +4502,6 @@ impl RuntimeNode { .fold(first, Result::and) } RuntimeOp::Binary { left, right, .. } | RuntimeOp::Broadcast { left, right, .. } => { - // Both sides are finished even when the first one fails: the failure is reported - // from here, and an evaluator left holding a series would keep its bytes. let first = left.finish_windows(); let second = right.finish_windows(); first.and(second) @@ -5003,7 +4513,6 @@ impl RuntimeNode { .. } => { let child = input.finish_windows(); - // Finishing evaluates the points still owed, which reads the grid's timestamps. let own = window .take() .map_or(Ok(()), |evaluator| { @@ -5017,33 +4526,24 @@ impl RuntimeNode { } } -/// What a fused execution knows about the labels its inputs hand over. -/// -/// The planner binds the tree's inputs and knows two things about each: the complete label set it -/// reports, and - when the statement reads one table - the one metric every series it hands over is -/// named. [`unifies_its_own_contributions`] reads exactly those facts, so the collection a consumer -/// performs at run time is decided by the same proof the canonical pass placed its merges with. A -/// caller that knows nothing sets no facts, and every consumer then collects conservatively. +/// Input label sets and metric names used to decide when series must be merged. #[derive(Clone, Debug, Default)] pub struct SourceFacts { - /// The complete runtime label set of each input, indexed by the `source_index` of its leaf. + /// The complete label set of each input, indexed by leaf `source_index`. tags: Vec>, - /// The one metric each input is bound to, indexed the same way; `None` when the input may hand - /// over several, which is what a statement reading several tables binds. + /// The one metric each input is bound to, indexed the same way; `None` when it may have + /// several. metrics: Vec>>, } impl SourceFacts { - /// Says nothing about any input, so every decision stays conservative. + /// No facts; every decision stays conservative. pub fn none() -> Self { Self::default() } - /// One statement-level fact, repeated for each of `sources` inputs. - /// - /// A binding names one metric and one tag set for the node as a whole, and every scan below it - /// reads that one table, so the fact holds for each of them. A binding that names no metric - - /// the node reads one raw source per input - proves nothing, and the proof fails with it. + /// The same tags and metric for each of `sources` inputs, for a statement reading one table. + /// With `metric = None` nothing can be proven. pub fn uniform(tags: Vec, metric: Option>, sources: usize) -> Self { Self { tags: vec![tags; sources], @@ -5061,10 +4561,8 @@ impl NativeExecutionState { Self::try_new_with_sources(tree, pool, duplicate_evidence, &SourceFacts::none()) } - /// Builds the execution over `tree`, judging a dropped label set by `sources`. - /// - /// The canonical pass placed its merges with the same facts, so a consumer that collects here - /// collects exactly where the pass decided a consumer has to - and nowhere else. + /// Builds the execution over `tree`. `sources` must not prove more than the canonical pass + /// assumed when it placed its merges; [`SourceFacts::none`] is always safe. pub fn try_new_with_sources( tree: &NativeTree, pool: Arc, @@ -5082,7 +4580,6 @@ impl NativeExecutionState { duplicate_evidence.clone(), sources, )?; - // A constant root has no node that produces its value, so the state produces it. let scalar_root = match (&tree.root().expr, &tree.root().output) { (NativeExpr::Scalar(BoundScalar { value }), NativeType::Scalar(grid)) => Some(( Arc::clone(grid), @@ -5103,9 +4600,7 @@ impl NativeExecutionState { "native runtime root produces raw samples".to_string(), )); } - // A tree rooted at a `Partial` aggregate answers state, which the caller pulls as - // state. It is still an answer, so nothing is refused here; what the root produces is - // read by `NativeExecutor::next_state` rather than `next_chunk`. + // A `Partial` aggregate root; read through `NativeExecutor::next_state`. NativeType::AggregateState(_) => {} } Ok(Self { @@ -5123,10 +4618,7 @@ impl NativeExecutionState { } } - /// Registers the metric handles of every node of this execution's tree with `set`. - /// - /// A caller invokes this once, before the execution starts; what `set` holds afterwards keeps no - /// topology of this execution alive. + /// Registers every node's metric handles with `set`. Call once, before the execution starts. pub(crate) fn register_metrics(&self, set: &ExecutionPlanMetricsSet, partition: usize) { if let Some(live) = &self.live { live.root.register_metrics("root", set, partition); @@ -5159,10 +4651,8 @@ impl NativeExecutionState { } } -/// Pulls and checks the one live tree the execution owns. impl LiveExecution { - /// Pulls the next chunk the root of this state's tree hands over, passing `inputs_finished` down - /// unchanged. + /// Pulls the root's next chunk; a constant root is produced here on its first pull. fn pull(&mut self, inputs_finished: bool) -> Result> { if let Some((grid, value, mut state)) = self.scalar_root.take() { let bytes = grid_chunk_bytes(&grid).map_err(|error| state.context(error))?; @@ -5180,11 +4670,8 @@ impl LiveExecution { self.root.pull(&mut self.inputs, inputs_finished) } - /// Refuses an input the caller never closed, and every node that ended inside a series. - /// - /// The slots are read first -- an open series there is the input the caller can still close -- and - /// only then the nodes, because a node that retains its whole input reports the same truncation in - /// its own terms. + /// Refuses an input left with an open series. Input slots are checked first, so the error names + /// the input rather than a node that retained it. fn unclosed(&self) -> Result<()> { if let Some(index) = self.inputs.iter().position(InputSlot::ends_open) { let slot = &self.inputs[index]; @@ -5193,12 +4680,10 @@ impl LiveExecution { self.root.unclosed() } - /// Merges what every window that collects its input has been handed, deepest first. fn flush_ready_merges(&mut self) -> Result { self.root.flush_ready_merges(&self.inputs) } - /// Whether any window still holds collected input that has not been merged. fn any_merge_pending(&self) -> bool { self.root.any_merge_pending() } @@ -5210,31 +4695,26 @@ impl LiveExecution { } impl NodeState { - /// Queues a source chunk, holding what it is worth until it leaves. - /// - /// What this node holds is its queue, so the reservation is the sum of the estimates in it. + /// Queues a source chunk, reserving its [`NativeChunk::bytes`] first so a refused chunk leaves + /// nothing behind. fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> { let positions = chunk.positions(); let bytes = chunk.bytes(); - // The chunk is held from here on, so the pool admits it before the queue keeps it: a - // rejected chunk leaves nothing behind. self.buffer.grow(bytes)?; self.queued.push_back((chunk, bytes)); self.buffer.metrics.record_input(1, positions); Ok(()) } - /// Hands over the next queued chunk, if there is one, giving back what it was queued with. - /// - /// It is the one way a chunk leaves this node's queue, for both the caller's chunks and a kernel's - /// results. `values` is how that node counts what it hands over, and the two do not count the same - /// thing: an input's figure is its positions, a kernel's result holds one value per field. + /// Hands over the next queued chunk and releases its charge, recording output metrics; `values` + /// counts the chunk's values (positions for a source, valid values for a result). A state + /// chunk takes its charge with it. [`Self::take_output`] is the metric-free variant used for + /// flushed window and merge output. fn pop_queued(&mut self, values: fn(&NativeChunk) -> usize) -> Result> { let Some((mut chunk, bytes)) = self.queued.pop_front() else { return Ok(None); }; - // A producer hands its state to a consumer that packs rows from the batch across polls, so - // that chunk's charge travels with it instead of being returned here. + // The consumer keeps a state chunk across polls, so its charge moves with it. let moved = match &mut chunk { NativeChunk::AggregateState(StateChunk::Series { reservation, .. }) => { debug_assert!( @@ -5250,36 +4730,27 @@ impl NodeState { }; let metrics = Arc::clone(&self.buffer.metrics); { - // An input node's own work is handing the chunk over, so its self time covers that and - // nothing its producer did. Whatever the chunk did not take with it, the pool no longer - // has to hold. let _timer = metrics.timer(); self.buffer.shrink(bytes - moved)?; self.release_queued_tables()?; } metrics.record_output(1, values(&chunk)); - // An evaluated chunk is addressed on its grid, so its decided positions are grid points; a - // raw source carries timestamps, which are not positions on any grid. + // Raw timestamps are not grid points. if let NativeChunk::Evaluated(chunk) = &chunk { metrics.record_grid_points(chunk.series.time.len()); } Ok(Some(chunk)) } - /// Maps one evaluated chunk, keeping its axis and its closing. - /// - /// `None` means the operation emptied every position and the chunk does not close its series. + /// Maps one evaluated chunk, keeping its closing. `None` means every position was emptied and + /// the chunk does not close its series. fn map(&mut self, map: &MapRuntime, chunk: EvaluatedChunk) -> Result> { let (positions, closing) = (chunk.series.time.len(), chunk.is_last); - // The chunk is held for as long as this node works on it, beside the series its - // operations write. let workspace = map_workspace_bytes(&map.ops, &chunk.series)?; self.buffer.grow(evaluated_bytes(&chunk))?; self.buffer.grow(workspace)?; let metrics = Arc::clone(&self.buffer.metrics); let outcome = { - // The timer covers this node's own work only: it is dropped before the driver polls - // the input again. let _timer = metrics.timer(); map_chunk(&map.schema, &chunk, &map.ops, &mut |bytes| { self.buffer.grow(bytes) @@ -5289,8 +4760,7 @@ impl NodeState { if closing { metrics.record_completed_series(1); } - // The chunk and the workspace are this call's, not the node's, so a failed map gives them - // back here rather than holding the pool's budget until the stopped executor is dropped. + // On failure give back the chunk and workspace now, not when the stopped executor drops. let output = match outcome { Ok(output) => output, Err(error) => { @@ -5302,17 +4772,12 @@ impl NodeState { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); } - // The chunk is gone and this node holds none of it: a rewritten label set is not this - // node's to remember, and what two series sharing one would mean is a canonical merge's - // question. self.buffer.resize(0)?; Ok(output) } - /// Maps one evaluated chunk with its parameters read at each point, keeping its axis and its - /// closing. - /// - /// `None` means no point kept a value and the chunk does not close its series. + /// Maps one evaluated chunk with its parameters read per point. `None` means no point kept a + /// value and the chunk does not close its series. fn parameterized_map( &mut self, map: &ParameterizedMapRuntime, @@ -5331,7 +4796,6 @@ impl NodeState { if closing { metrics.record_completed_series(1); } - // As in `Self::map`, a failed kernel gives back the chunk and the workspace here. let outcome = match outcome { Ok(outcome) => outcome, Err(error) => { @@ -5341,8 +4805,7 @@ impl NodeState { }; let output = match outcome { Some(series) => Some(EvaluatedChunk::try_new(series, closing)?), - // A closing chunk is handed over even when no point kept a value, because a consumer - // tells "nothing more here" from "no more input" by that chunk alone. + // A closing chunk is always handed over so the close reaches the consumer. None if closing => { let metric = drop_metric_name(&chunk.series.metric)?; let empty = no_row_series(&map.schema, &chunk.series, metric)?; @@ -5354,7 +4817,6 @@ impl NodeState { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); } - // What this node still holds is what it read for its parameters and nothing else. self.buffer.resize(map.parameter_bytes)?; Ok(output) } @@ -5367,10 +4829,7 @@ impl NodeState { ) -> Result> { let positions = chunk.series.time.len(); let closing = chunk.is_last; - // The kernel reads the grid's timestamps, which materializes them when the grid is - // deferred. They stay materialized for the rest of the execution, so this node reserves - // them beside what it holds and keeps them there rather than treating them as a workspace - // it gives back. + // The kernel materializes the grid's timestamps. if let Some(grid) = schema.eval_grid.as_deref() { self.buffer.reserve_grid(grid)?; } @@ -5387,7 +4846,6 @@ impl NodeState { if closing { metrics.record_completed_series(1); } - // As in `Self::map`, a failed kernel gives back the chunk and the workspace here. let result = match result { Ok(result) => result, Err(error) => { @@ -5408,10 +4866,8 @@ impl NodeState { Ok(output) } - /// Broadcasts one chunk of the vector side with the constant this node was bound to. - /// - /// `None` means the operation emptied every position and the chunk does not close its series. - /// Nothing of the chunk is retained. + /// Applies the broadcast to one vector chunk without retaining it; see + /// [`BroadcastRuntime::apply`]. fn broadcast( &mut self, broadcast: &BroadcastRuntime, @@ -5423,9 +4879,7 @@ impl NodeState { )); }; let (positions, closing) = (chunk.series.time.len(), chunk.is_last); - // The chunk is held for as long as this node works on it, beside the series the kernel - // writes: arithmetic against a constant maps the vector's segments, and every other - // operation builds a subset of its rows. + // Literal arithmetic maps segments; everything else builds a subset of rows. let workspace = match (&broadcast.scalar, broadcast.op) { (BroadcastScalar::Literal(_), BroadcastOp::Arithmetic(_)) => { mapped_workspace_bytes(&chunk.series)? @@ -5436,18 +4890,13 @@ impl NodeState { self.buffer.grow(workspace)?; let metrics = Arc::clone(&self.buffer.metrics); let outcome = { - // The timer covers this node's own work only: it is dropped before the driver polls - // the vector side again. let _timer = metrics.timer(); broadcast.apply(&chunk) }; metrics.record_input(1, positions); if closing { - // A series closes exactly once, on the chunk carrying `is_last`: the broadcast kept it - // on every chunk it handed up, so the series it read is closed here. metrics.record_completed_series(1); } - // As in `Self::map`, a failed kernel gives back the chunk and the workspace here. let output = match outcome { Ok(output) => output, Err(error) => { @@ -5463,12 +4912,11 @@ impl NodeState { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); } - // The chunk is gone and the scalar's value is what is left. self.buffer.resize(broadcast.scalar_bytes)?; Ok(output) } - /// Keeps the chunk a varying scalar operand hands over, the one closed series it is, in `slot`. + /// Keeps a dynamic scalar operand's single closed chunk in `slot`, adding its bytes to `held`. fn hold_scalar( &mut self, held: &mut usize, @@ -5492,7 +4940,7 @@ impl NodeState { Ok(()) } - /// Keeps a constant parameter's values on `grid` in `slot`, reserved before they are built. + /// Builds a constant's series on `grid` into `slot`, reserving it first. fn hold_constant( &mut self, held: &mut usize, @@ -5507,8 +4955,7 @@ impl NodeState { Ok(()) } - /// Builds the one closed chunk a node that reads no input produces, reserved before it is - /// built, and queues it for the pull that hands it over. + /// Builds and queues the single closed chunk of a node with no input, reserving it first. fn produce(&mut self, grid: &EvalGrid, series: impl FnOnce() -> Result) -> Result<()> { let bytes = grid_chunk_bytes(grid)?; self.buffer.grow(bytes)?; @@ -5519,19 +4966,14 @@ impl NodeState { Ok(()) } - /// Feeds one chunk to this node's window. - /// - /// A window that collects its input keeps the whole series of every chunk it is handed and evaluates - /// nothing yet: the label sets of those fragments are only canonical once the input has ended. Every - /// other window evaluates what it is handed as it arrives. + /// Feeds one chunk to this node's window. A collecting window only retains it until its input + /// ends; any other window evaluates it now. fn window( &mut self, window: &mut RangeEvaluator, merge: &mut Option, chunk: NativeChunk, ) -> Result> { - // A window reads the grid's timestamps to place every point it decides, which materializes - // a deferred grid; the array stays materialized, so the reservation for it is kept. self.buffer.reserve_grid(window.grid())?; if let Some(merge) = merge.as_mut() { let NativeChunk::Evaluated(chunk) = chunk else { @@ -5543,9 +4985,6 @@ impl NodeState { return self.collect(merge, window, chunk); } let (positions, closing) = (chunk.positions(), chunk.is_last()); - // The chunk is held for as long as the evaluator consumes it, beside the rows the push - // hands out, which are counted on the output grid: a sparse input can decide far more - // points than it carries, and a dense one far fewer. let (fields, metric) = match &chunk { NativeChunk::Raw(chunk) => (&chunk.fields, chunk.metric.as_ref()), NativeChunk::Evaluated(chunk) => (&chunk.series.fields, Some(&chunk.series.metric)), @@ -5569,11 +5008,7 @@ impl NodeState { let outcome = { let _timer = metrics.timer(); match &chunk { - // Raw samples are read window by window by the evaluator itself. NativeChunk::Raw(chunk) => window.push(chunk), - // An evaluated input is read as computed samples: the evaluator carries the window state of - // one series across its chunks and closes it on the chunk that says so, so a decision can - // be reported before the series ends. NativeChunk::Evaluated(chunk) => window.push_series(&chunk.series, chunk.is_last), NativeChunk::AggregateState(_) => { return Err(DataFusionError::Execution( @@ -5585,11 +5020,9 @@ impl NodeState { }; metrics.record_input(1, positions); if closing { - // A series closes exactly once, on the chunk carrying `is_last`. A window that decided - // nothing for it still closed it, so it is counted here rather than on its output. + // Counted on input: a window that decided nothing still closed the series. metrics.record_completed_series(1); } - // As in `Self::map`, a failed push gives back the chunk and the workspace here. let output = match outcome { Ok(output) => output, Err(error) => { @@ -5601,18 +5034,13 @@ impl NodeState { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); } - // The chunk has been consumed: what this node still holds is what the evaluator kept of it, - // charged whether or not this chunk produced an answer: a chunk that yields nothing leaves - // the evaluator's samples where they were, and the figure is not charged per chunk consumed, - // which would make a fixed window over a long series read as an allocation failure. + // Settle on what the evaluator retains, not on a per-chunk sum. self.buffer.resize(window.retained_bytes())?; Ok(output) } - /// Retains one operand chunk of this node's binary operation. - /// - /// Nothing is decided for a point yet: the kernel needs both operands whole. The chunk is reserved for - /// before it is retained, so a refused chunk leaves the operand where it was. + /// Retains one operand chunk, reserving it first so a refused chunk leaves the operand + /// unchanged. fn retain_binary( &mut self, binary: &mut BinaryRuntime, @@ -5625,8 +5053,6 @@ impl NodeState { binary.kernel.node() ))); }; - // The figure is read before the chunk is retained, because reserving after the fact would be - // reserving for memory the node already holds. let pending = binary.pending(side, &chunk)?; let positions = chunk.series.time.len(); self.buffer.grow(pending)?; @@ -5652,24 +5078,19 @@ impl NodeState { self.queue_results(output, false, 0) } - /// Settles a vector node's reservation on what it holds: the input it retains and, for a - /// parameterized operator, the per-point values it read its parameters into, which are released with - /// the node. + /// Settles a vector node's reservation on its retained input plus its parameter values. fn settle_vector(&mut self, vector: &VectorRuntime) -> Result<()> { let held = vector.input.held.saturating_add(vector.parameter_bytes); self.buffer.resize(held) } - /// Retains one chunk of a vector node's input, reserved for before it is retained, as - /// [`Self::retain_binary`] retains an operand's. + /// Retains one chunk of a vector node's input, reserving it first. fn retain_vector(&mut self, vector: &mut VectorRuntime, chunk: NativeChunk) -> Result<()> { let NativeChunk::Evaluated(chunk) = chunk else { return Err(DataFusionError::Execution( "the vector operation consumes evaluated chunks, not raw samples".to_string(), )); }; - // What a bound tree says the input produces is not proof of what a chunk carries, so the - // chunk is checked against the layout before it is retained. validate_binary_operand(vector.schema.as_ref(), std::slice::from_ref(&chunk.series)) .map_err(|error| { DataFusionError::Execution(format!( @@ -5683,15 +5104,13 @@ impl NodeState { { let _timer = metrics.timer(); vector.input.retain(chunk, Reader::Vector)?; - // The input this node retains is held beside the parameter values it read whole first, - // which this chunk does not replace. self.settle_vector(vector)?; } metrics.record_input(1, positions); Ok(()) } - /// Runs this node's vector kernel and queues the series it kept. + /// Runs the histogram kernel with its per-point parameters and queues its output. fn compute_histogram( &mut self, vector: &mut VectorRuntime, @@ -5713,14 +5132,10 @@ impl NodeState { self.queue_results(output, shares_input, vector.parameter_bytes) } - /// Queues the series a kernel that reads its whole input produced, and settles the reservation on the - /// queue. - /// - /// `shares_input` says the series are the assembled input itself, as a sort hands it back: each is then - /// measured the way the input was ([`operand_chunk_bytes`]) and its tables billed once to the queue. - /// - /// `beside` is what the node keeps past the queue, such as a parameterized operator's per-point - /// parameter values. + /// Queues a whole-input kernel's output, one closed chunk per series, and settles the + /// reservation on the queue plus `beside` (e.g. parameter values). With `shares_input` (a sort + /// returns its input) each series is measured by [`operand_chunk_bytes`] and its tables billed + /// once. fn queue_results( &mut self, output: Vec, @@ -5728,12 +5143,8 @@ impl NodeState { beside: usize, ) -> Result<()> { let mut tables = HashSet::new(); - // The results are queued the way a node that produces a chunk per input queues what it - // hands on: the queue is the one source of chunk order and of the bytes queued chunks hold. let mut closed = 0usize; for series in output { - // The kernel decided every point of a result series at once, so the one chunk it is handed - // over as closes it. The result is already admitted within the kernel's workspace. let bytes = if shares_input { let (fresh, table_bytes) = unbilled_tables(&series, &tables); tables.extend(fresh); @@ -5746,13 +5157,7 @@ impl NodeState { self.queued.push_back((chunk, bytes)); closed += 1; } - // This node's own accounting of closed series is the results it closed, one per result - // series: an input chunk that closed its series is a closure of the node below, and - // counting it here as well would report the same work twice. self.buffer.metrics.record_completed_series(closed); - // The input the reservation covered is gone and the queue holds what the kernel returned, - // so the reservation settles on the queue: what a queued result is given back with as it - // leaves is exactly the figure it is held for here. let queued = self .queued .iter() @@ -5762,18 +5167,12 @@ impl NodeState { self.buffer.resize(queued.saturating_add(beside)) } - /// Folds one chunk into this node's aggregate. - /// - /// The chunk is reserved for before it is folded, and the reservation settles afterwards on the fold - /// that is left: the fold keeps its states, so a chunk that closes its series leaves nothing behind. + /// Folds one value or state chunk into this node's aggregate, reserving it first. fn retain_aggregate( &mut self, aggregate: &mut AggregateRuntime, chunk: NativeChunk, ) -> Result<()> { - // A `Final` aggregate merges state; the others fold values. Which one a chunk is has - // already been checked against the leaf that queued it, so an unexpected kind here is a - // tree the compiler should have refused. if let NativeChunk::AggregateState(chunk) = chunk { let pending = aggregate.pending_state(&chunk); let positions = match &chunk { @@ -5796,8 +5195,6 @@ impl NodeState { "the aggregate consumes evaluated chunks, not raw samples".to_string(), )); }; - // The figure is read before the chunk is folded, because reserving after the fact would be - // reserving for memory the fold already read. let pending = aggregate.pending(&chunk); let positions = chunk.series.time.len(); self.buffer.grow(pending)?; @@ -5807,16 +5204,11 @@ impl NodeState { aggregate.accumulate(chunk, &mut self.buffer, pending)?; } metrics.record_input(1, positions); - // A chunk that closed its series closed it for the node below: a group is not a series, so - // the fold completing nothing on it is why nothing is counted here. The series this node - // closes are the ones it hands out, counted when it queues them. Ok(()) } - /// Finishes this node's fold and queues one chunk per group it produced. - /// - /// Each group is one series, decided in full by the fold, so the one chunk it is handed over as closes - /// it. + /// Finishes this node's fold and queues one closed chunk per group, or one state chunk for a + /// `Partial`. The queue's capacity is reserved before it grows. fn compute_aggregate(&mut self, aggregate: &mut AggregateRuntime) -> Result<()> { let metrics = Arc::clone(&self.buffer.metrics); let _timer = metrics.timer(); @@ -5838,7 +5230,6 @@ impl NodeState { .max(queue_capacity) .saturating_mul(std::mem::size_of::<(NativeChunk, usize)>()); let output = aggregate.compute(&mut self.buffer, queue_bytes)?; - // The fold has returned its series; reserve their handover before appending them to the queue. let Some(output) = output else { return Ok(()); }; @@ -5852,9 +5243,6 @@ impl NodeState { closed += 1; } } - // A partial aggregate hands its whole partition over as one state chunk: the groups in - // it are the groups this execution folded, and the consumer closes each when its own - // input ends rather than when a chunk arrives. AggregateOutput::State(chunk) => { let StateChunk::Series { series, .. } = &chunk else { return Err(DataFusionError::Internal( @@ -5867,10 +5255,7 @@ impl NodeState { .push_back((NativeChunk::AggregateState(chunk), bytes)); } } - // A group is one series and this node closes each of them exactly once, on the one chunk it - // hands it over as. self.buffer.metrics.record_completed_series(closed); - // The output Vec has been consumed; the node now holds only queue backing and chunks. let queued_bytes = self .queued .iter() @@ -5895,18 +5280,12 @@ impl NodeState { )); }; let (positions, closing) = (chunk.time.len(), chunk.is_last); - // A selection that answers with timestamps reads every point of the grid, which materializes - // a deferred grid's array; the reservation is kept because the array is. + // A timestamp selection materializes the grid's timestamps. if instant.selection.value != InstantValue::Sample { self.buffer.reserve_grid(&instant.selection.output_grid)?; } - // The chunk is held from here on: a selection keeps every chunk of a series until the one - // that closes it, so what this node reserves for is the series it has buffered. self.buffer.grow(raw_bytes(&chunk))?; - // The chunk that closes the series gathers it in one go, and the gather allocates a workspace of - // its own beside the buffered chunks: the axis it concatenates, the descriptors that read it, the - // two arrays the selection returns and the rows the builder keeps. It is reserved here, before it - // exists, so a pool too small for it refuses the gather instead of learning about it afterwards. + // The closing chunk triggers the gather; reserve its workspace up front. let scratch = if closing { instant.gather_bytes(&chunk) } else { @@ -5915,19 +5294,13 @@ impl NodeState { self.buffer.grow(scratch)?; let metrics = Arc::clone(&self.buffer.metrics); let outcome = { - // The timer covers this node's own work only: it is dropped before the driver polls - // the input again. let _timer = metrics.timer(); instant.push(chunk) }; metrics.record_input(1, positions); if closing { - // A series closes exactly once, on the chunk carrying `is_last`: the selection gathers - // the whole series on it, so it is counted here rather than on the chunk handed out. metrics.record_completed_series(1); } - // A failed gather gives its workspace back here rather than leaving it to the driver: the workspace - // is this call's, not something the node keeps. let output = match outcome { Ok(output) => output, Err(error) => { @@ -5939,9 +5312,6 @@ impl NodeState { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); } - // What this node still holds is the chunks of the series it is selecting: a whole series is held - // until it ends. The chunk just consumed and the gather's workspace are both gone, so this gives - // them back. self.settle_buffered(instant)?; Ok(output) } @@ -5951,7 +5321,7 @@ impl NodeState { self.buffer.resize(instant.buffered_bytes()) } - /// Retains and validates a fragment for canonicalization. + /// Validates and retains one fragment for a later merge. fn collect_merge(&mut self, merge: &mut MergeInput, chunk: EvaluatedChunk) -> Result<()> { let EvaluatedChunk { series, is_last } = chunk; merge.check(&series, is_last)?; @@ -5968,7 +5338,7 @@ impl NodeState { Ok(()) } - /// Canonicalizes all fragments before exposing any output. + /// Merges all collected fragments by label set and queues the result. fn flush_canonical_merge(&mut self, merge: &mut Option) -> Result<()> { let Some(merge) = merge.take() else { return Ok(()); @@ -5994,10 +5364,7 @@ impl NodeState { self.buffer.shrink(held) } - /// Keeps one fragment of this node's collected input, charged for as it arrives. - /// - /// The fragment is measured once, here, and its estimate stands until the flush that merges it is over. - /// The merge itself copies no values, and its workspace is charged separately before it runs. + /// Collects one fragment of a collecting window's input; nothing is evaluated until the flush. fn collect( &mut self, merge: &mut MergeInput, @@ -6005,17 +5372,13 @@ impl NodeState { chunk: EvaluatedChunk, ) -> Result> { self.collect_merge(merge, chunk)?; - // What this node holds is the fragments; its evaluator has read none of them yet. let retained = window.retained_bytes(); self.buffer.resize(retained.saturating_add(merge.bytes))?; Ok(None) } - /// Merges this window's collected input and evaluates it, one merged series at a time. - /// - /// Each merged series is handed to the evaluator as one closing series, so the window reports on it - /// once. `merge` is taken here, so a window whose collected input failed to merge does not merge it - /// again. + /// Merges this window's collected input and evaluates each merged series as one closed series. + /// `merge` is taken first, so a failed merge is not retried. fn flush_merge( &mut self, window: &mut RangeEvaluator, @@ -6025,29 +5388,21 @@ impl NodeState { return Ok(()); }; if merge.fragments.is_empty() { - // Nothing arrived, so there is nothing to merge and nothing to answer: the window's - // evaluator never read a series and the charge goes back. return self.buffer.shrink(merge.bytes); } - // The merged series is evaluated by the window, which reads the grid's timestamps. self.buffer.reserve_grid(window.grid())?; - // The workspace the merge allocates is charged before it runs, from the rows, segments and - // fields of the fragments as they were collected. let workspace = merge.workspace_bytes(); let held = merge.bytes.saturating_add(workspace); let schema = Arc::clone(&merge.schema); self.buffer.grow(workspace)?; - // What the queue holds before this flush adds to it: a queued answer is charged until the pull that - // hands it up returns its estimate, so every resize below has to leave it charged. + // Already-queued output stays charged through every resize below. let mut queued_bytes = self .queued .iter() .fold(self.queued_tables, |total, (_, bytes)| { total.saturating_add(*bytes) }); - // The fragments' charge stands for the merged series too -- a merged run is a slice of a - // fragment's own segment, so no value is copied -- and the workspace stays charged until - // the flush is over. + // Merged series slice the fragments' segments, so the fragments' charge covers them. let merged = merge_same_labelset(&schema, merge.fragments)?; for series in merged { let workspace = window_workspace_bytes( @@ -6078,13 +5433,11 @@ impl NodeState { self.enqueue_output(output)?; queued_bytes = queued_bytes.saturating_add(bytes); } - // The fragments and the merge's workspace go back, and whatever the flush produced stays - // charged in the node's queue until the caller pulls it. self.buffer.shrink(held) } - /// Queues one output this node computed while flushing its collected input, charged as it is queued and - /// given back as it leaves. + /// Queues one output computed while flushing, charged until [`Self::take_output`] hands it + /// over. fn enqueue_output(&mut self, chunk: EvaluatedChunk) -> Result<()> { let bytes = evaluated_bytes(&chunk); self.buffer.grow(bytes)?; @@ -6093,7 +5446,7 @@ impl NodeState { Ok(()) } - /// Hands over the next output this node computed while flushing, if there is one. + /// Hands over the next queued chunk without recording metrics (the flush already did). fn take_output(&mut self) -> Result> { let Some((chunk, bytes)) = self.queued.pop_front() else { return Ok(None); @@ -6114,10 +5467,7 @@ impl NodeState { } impl InputSlot { - /// Queues one source chunk at this input, checking it against the binding the leaf was built with. - /// - /// A chunk of the other kind has no address here, so it is refused rather than queued and read as - /// though it were the kind this leaf promised. + /// Queues one source chunk at this input, refusing a chunk of another [`LeafKind`]. fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> { if !self.kind.accepts(&chunk) { return Err(self.state.context(DataFusionError::Execution(format!( @@ -6126,10 +5476,7 @@ impl InputSlot { chunk.describe(), )))); } - // Finality is recorded on receipt as well as on handover: a chunk the tree has not pulled - // yet is still a chunk the caller sent, and whether it closes its series says so whether or - // not anything above this leaf ever reads it. A chunk the pool refuses never arrived, so - // the flag follows the queue. + // Updated only after the pool admits the chunk. let closing = chunk.is_last(); self.state .enqueue(chunk) @@ -6138,17 +5485,11 @@ impl InputSlot { Ok(()) } - /// Hands over the next queued source chunk, if there is one. - /// - /// The handover is what [`Self::open_source_series`] follows: after this call the flag says whether - /// the series the consumer just received a chunk of is still open, which is what closing the execution - /// reads to tell a truncated input from one that ended cleanly. + /// Hands over the next queued source chunk and updates [`Self::open_source_series`]. fn pop_source(&mut self) -> Result> { let Some(chunk) = self.state.pop_queued(NativeChunk::positions)? else { return Ok(None); }; - // Assigned rather than only set: a chunk that closes its series is what says no series is - // open any more, so the flag follows the handover and not the history of handovers. self.open_source_series = !chunk.is_last(); if chunk.is_last() { self.state.buffer.metrics.record_completed_series(1); @@ -6157,44 +5498,32 @@ impl InputSlot { } } -/// Drives one execution of a bound tree. -/// -/// The driver owns the state and nothing else: every decision a node makes was bound before the tree -/// existed, so a pull only reads the position and runs the bound operation. -/// -/// A window directly over a source, a map at the root and a binary node over a constant all stream. A -/// window whose input can hold two series under one canonical label set collects that input instead and -/// reports at [`Self::finish`]. +/// Drives one execution of a bound tree: the caller pushes source chunks, pulls output, and ends +/// the input with [`Self::end_of_input`] or [`Self::finish`]. Streaming nodes (windows, maps, +/// broadcasts) answer as input arrives; collecting windows and whole-input nodes answer only after +/// the input ends. pub struct NativeExecutor { state: NativeExecutionState, phase: Phase, - /// Whether the caller ended the input. - /// - /// Until then a pull that finds nothing means nothing has settled yet, and a binary node retains what - /// its operands hand over without computing. [`NativeExecutor::finish`] drains once, checks that every - /// stream closed, and only then sets this flag and drains again. + /// Passed down every pull; set by `next_output` once the input has ended, the tree has gone + /// quiet, and no series is left open. Until then whole-input nodes only retain. inputs_finished: bool, - /// Whether the caller ended the input. - /// - /// Until then a pull that finds nothing means nothing has settled yet. After it, the same pull runs the - /// next stage of the ending, and only a pull that finds every stage done closes the nodes and returns - /// their reservations. + /// Whether the caller ended the input. After it, an empty pull advances the ending stages in + /// `next_output` instead of returning `None`. ended: bool, } /// Whether the execution can still produce chunks. #[derive(Clone, Debug, PartialEq, Eq)] enum Phase { - /// Chunks may still be queued and pulled. Running, /// The input ended and every node closed. Finished, - /// A chunk failed, so the tree stopped: the evaluators must not be reused after an error. + /// Stopped after an error; evaluators must not be reused. Failed(String), } impl NativeExecutor { - /// Drives `state`, which was built from one execution's tree. pub fn new(state: NativeExecutionState) -> Self { Self { state, @@ -6204,7 +5533,6 @@ impl NativeExecutor { } } - /// The state this driver runs. pub fn state(&self) -> &NativeExecutionState { &self.state } @@ -6217,10 +5545,8 @@ impl NativeExecutor { self.state.live.as_mut().ok_or_else(no_live_execution) } - /// Queues one raw source chunk at the input `input` names. - /// - /// A chunk queued at an id the tree has no input for is refused rather than assigned to whichever - /// input was found first. + /// Queues one raw source chunk at `input`. An unknown id or a chunk kind the leaf is not bound + /// to is an error and stops the execution. pub fn push_raw(&mut self, input: InputId, chunk: RawSeriesChunk) -> Result<()> { self.push_source(input, NativeChunk::Raw(chunk)) } @@ -6230,23 +5556,14 @@ impl NativeExecutor { self.push_source(input, NativeChunk::Evaluated(chunk)) } - /// Queues one aggregate-state chunk at the input `input` names. - /// - /// Only a leaf bound to state accepts one, so a state chunk is never read as a value. + /// Queues one aggregate-state chunk at the input `input` names; only a state leaf accepts it. pub(crate) fn push_state(&mut self, input: InputId, chunk: StateChunk) -> Result<()> { self.push_source(input, NativeChunk::AggregateState(chunk)) } - /// The next chunk the root produces, or `None` when nothing has settled yet. - /// - /// A window and a map take whole chunks from their input, so nothing beyond the chunk in hand is - /// materialised on their edge -- except below a window that collects its input. A binary node that - /// matches two vectors retains every chunk and reports `None` until [`Self::finish`] ends the input; - /// one that broadcasts a constant streams, and so does a vector node's single input read whole. - /// - /// A chunk's `is_last` says the series whose data it carries ended, not that its label set is - /// finished: two source series whose labels were rewritten into one set are two pieces of one logical - /// series, and every window that collects its input performs that merge itself. + /// The next chunk the root produces, or `None` when nothing is ready yet (or, after the input + /// ended, when the execution has finished). A chunk's `is_last` closes one input series, not + /// its label set; see [`crate::native::batch`]. pub fn next_chunk(&mut self) -> Result> { match self.next_output()? { Some(NativeChunk::Evaluated(chunk)) => Ok(Some(chunk)), @@ -6272,10 +5589,7 @@ impl NativeExecutor { } } - /// The next aggregate state chunk the root produces, or `None` when nothing has settled yet. - /// - /// A caller that runs a tree whose root is a `Partial` aggregate pulls here instead of - /// [`Self::next_chunk`]: a state chunk is not a query value. + /// Like [`Self::next_chunk`], for a tree whose root is a `Partial` aggregate. pub(crate) fn next_state(&mut self) -> Result> { match self.next_output()? { Some(NativeChunk::AggregateState(chunk)) => Ok(Some(chunk)), @@ -6291,36 +5605,25 @@ impl NativeExecutor { } } - /// The next chunk the root produces, whatever kind it is: the tree's root output decides whether this - /// is a value, a raw chunk or state. + /// The next chunk the root produces, of any kind. After the input ended, an empty pull runs the + /// next ending stage: the open-series check, then merge flushes, then closing the tree. fn next_output(&mut self) -> Result> { self.check_running()?; - // The end of the input is walked here rather than in one call, so a chunk is handed over as - // soon as the tree settles it: the caller pulls the answer instead of receiving it as one - // collected value, and what it has not pulled yet stays charged to the node holding it. loop { - // The state's tree is the one this execution was built from, and a pull is asked of its - // root; the nodes below it read their own children from there. let inputs_finished = self.inputs_finished; match self.live_mut()?.pull(inputs_finished) { Ok(Some(chunk)) => return Ok(Some(chunk)), - // Nothing has settled: the stages below decide whether that is a stall or an end. Ok(None) => {} Err(error) => { self.stop(&error); return Err(error); } } - // Nothing has settled. While the caller is still pushing, that is a stall and the - // answer is simply not ready; once it has ended the input, each stage below runs on the - // first pull that finds the tree quiet, and the loop looks for what it produced. if !self.ended { return Ok(None); } if !self.inputs_finished { - // The source queues are empty and every node has consumed what it was given, so a series the - // caller never closed is still open here and nowhere else. Half a vector is not a vector, so - // it is refused before a binary node computes. + // Refuse a series the caller never closed before any whole-input node computes. if let Err(error) = self.live()?.unclosed() { self.stop(&error); return Err(error); @@ -6328,11 +5631,7 @@ impl NativeExecutor { self.inputs_finished = true; continue; } - // A window that collects its input answers only once its own input is finished, and what a - // binary node above it reads is that answer, so the deepest ready window is flushed first. match self.live_mut()?.flush_ready_merges() { - // A window answered: what it queued is pulled on the next turn, and that pull is - // also what carries its answer to a node above it. Ok(true) => continue, Ok(false) => {} Err(error) => { @@ -6341,13 +5640,9 @@ impl NativeExecutor { } } if self.live()?.any_merge_pending() { - // A window still holds collected input, so something below it has not finished: - // pulling again is what gives that node its turn. continue; } - // Every node has answered everything it can. Closing them is what hands back the - // reservations they were charged, so pulling to exhaustion leaves the pool as it found - // it. + // Closing the tree frees every reservation. let live = self.state.live.take().ok_or_else(no_live_execution)?; return match live.close() { Ok(()) => { @@ -6362,10 +5657,7 @@ impl NativeExecutor { } } - /// Ends the input, which is what tells the tree that nothing more will be pushed. - /// - /// It hands nothing over: [`Self::next_chunk`] runs the ending stage by stage as the caller pulls. A - /// caller that wants the whole answer at once calls [`Self::finish`] instead. + /// Ends the input; later pulls run the ending stages. Errors if called twice. pub fn end_of_input(&mut self) -> Result<()> { if self.ended { return Err(DataFusionError::Execution( @@ -6376,14 +5668,12 @@ impl NativeExecutor { Ok(()) } - /// Ends the input and collects everything the tree answers: [`Self::end_of_input`] followed by a drain, - /// for callers that want the whole answer in one value. + /// [`Self::end_of_input`] followed by pulling every remaining chunk. pub fn finish(&mut self) -> Result> { self.end_of_input()?; self.drain() } - /// Pulls what has settled until nothing is left. fn drain(&mut self) -> Result> { let mut drained = Vec::new(); loop { @@ -6398,8 +5688,6 @@ impl NativeExecutor { /// Queues a source chunk at the input leaf `input` names. fn push_source(&mut self, input: InputId, chunk: NativeChunk) -> Result<()> { self.check_running()?; - // An execution whose input ended reads no more of it: the ending stages run as the caller pulls, and - // a chunk queued behind them would arrive at a node that has already decided what to answer. if self.ended { return Err(DataFusionError::Execution( "the native execution already ended its input, so no chunk can be queued at it" @@ -6413,11 +5701,7 @@ impl NativeExecutor { result } - /// Queues a source chunk at one input leaf, checking it against that input's binding. fn queue_source(&mut self, input: InputId, chunk: NativeChunk) -> Result<()> { - // The id counts the leaves left to right, so an id past the last one names no leaf at all: - // a caller that miscounted its tree is refused rather than answered from whichever leaf the - // count happened to reach. let live = self.live_mut()?; let count = live.inputs.len(); let slot = live @@ -6440,25 +5724,16 @@ impl NativeExecutor { } } - /// Stops the execution, returning every byte it reserved to the pool. - /// - /// A stopped execution is not resumed: an evaluator that failed must not be reused. + /// Stops the execution for good, dropping the live tree and every reservation. fn stop(&mut self, error: &DataFusionError) { self.state.live = None; self.phase = Phase::Failed(error.to_string()); } } -/// Maps one chunk with `ops`, keeping its axis and its closing. -/// -/// Mapping is point-wise over valued positions: a float chunk keeps the rows it came with under math, a -/// chunk holding native histograms loses the rows only histograms filled, and a histogram function keeps -/// only the rows histograms filled. `None` means the operation emptied every position, which yields no -/// chunk at all unless this chunk closed its series: a closing chunk is still handed over, holding no -/// position. -/// -/// `admit` is handed the bytes a label change can write before the change builds them; an error from it -/// stops the map. +/// Maps one chunk with `ops`, keeping its closing. `None` means every position was emptied and +/// the chunk does not close its series; a closing chunk is always returned, possibly with no rows. +/// `admit` reserves the bytes a label rewrite writes before it runs. fn map_chunk( schema: &Arc, chunk: &EvaluatedChunk, @@ -6480,13 +5755,10 @@ fn map_chunk( series = mapped; continue; } - // `clamp` with `max < min` is the empty vector, math skips native histograms and a histogram function - // skips floats, so a series left without a value of the kind it reads has no row to hand over. if !chunk.is_last { return Ok(None); } - // The closing chunk names the series the map would have produced, so the operations not - // run still decide its labels. + // The empty closing chunk still carries the labels the remaining ops would produce. let mut metric = series.metric.clone(); for op in &ops[index..] { match op { @@ -6505,10 +5777,7 @@ fn map_chunk( EvaluatedChunk::try_new(series, chunk.is_last).map(Some) } -/// A series carrying `metric` and no row at all. -/// -/// It is what a closing chunk holds when the operation emptied its input: `metric` is the identity the -/// operation produces -- a map drops the name, a filtering comparison keeps it -- so the caller says which. +/// A series carrying `metric` and no rows, placed after `series`' last position. fn no_row_series(schema: &SeriesSchema, series: &Series, metric: SeriesLabels) -> Result { let grid = series.time.grid().ok_or_else(|| { DataFusionError::Execution("a mapped chunk must be addressed on a grid".to_string()) @@ -6537,7 +5806,7 @@ fn valid_values(chunk: &EvaluatedChunk) -> usize { .sum() } -/// The values an evaluated chunk hands over, or the timestamps a raw source hands over. +/// The output-values metric for a chunk: valid values, or positions for raw and state chunks. fn evaluated_values(chunk: &NativeChunk) -> usize { match chunk { NativeChunk::Evaluated(chunk) => valid_values(chunk), @@ -6550,8 +5819,6 @@ fn evaluated_values(chunk: &NativeChunk) -> usize { } /// The error for a chunk of another series arriving while one is being selected. -/// -/// [`select_instants`] reads one whole axis, so the buffered chunks have to be one series. fn series_changed() -> DataFusionError { DataFusionError::Execution( "the instant selection combines one series into one axis, and a chunk of another series \ @@ -6575,11 +5842,7 @@ fn missing_row(index: usize) -> DataFusionError { )) } -/// The rejection of an input that ended without the chunk closing its series. -/// -/// A tree with no window has no evaluator to hold the series, so the input node is the one node left that -/// can tell a series that ended from one that was cut off. The input is named by the routing slot its -/// chunks are handed to. +/// The error for an input that ended without the chunk closing its series. fn truncated_input(input: InputId) -> DataFusionError { DataFusionError::Execution(format!( "the input at routing slot {} ended before the last chunk of a series: the last chunk it \ @@ -6588,8 +5851,7 @@ fn truncated_input(input: InputId) -> DataFusionError { )) } -/// The rejection of a chunk routed to an input the execution does not have: an id past the last leaf names -/// no leaf at all. +/// The error for a chunk routed to an input the execution does not have. fn no_input(inputs: usize, input: InputId) -> DataFusionError { DataFusionError::Execution(format!( "the native execution has {inputs} inputs, and no input {} was queued at", @@ -6602,7 +5864,6 @@ fn invalid_binary_operand() -> DataFusionError { DataFusionError::Internal("invalid binary operand index".to_string()) } -/// A running executor must own its live state. fn no_live_execution() -> DataFusionError { DataFusionError::Internal("the running native execution has no state".to_string()) } @@ -6612,10 +5873,7 @@ fn no_window() -> DataFusionError { DataFusionError::Execution("the node holds no window evaluator".to_string()) } -/// The rejection of a scalar broadcast whose matching is not the one a constant can take. -/// -/// A constant has no labels, so there is nothing to match it against: Prometheus does not consult the -/// matching modifiers of a vector–scalar operation at all. +/// The error for a vector-scalar operation carrying vector-matching modifiers. fn matched_scalar() -> DataFusionError { DataFusionError::NotImplemented( "the native runtime does not execute a scalar broadcast whose constant carries matching \ @@ -6625,10 +5883,8 @@ fn matched_scalar() -> DataFusionError { ) } -/// The rejection of a binary node whose operands are neither two evaluated vectors nor one evaluated vector -/// and one constant. -/// -/// `operands` says which shape arrived and why that shape has no place here. +/// The error for a binary node whose operands are neither two evaluated vectors nor a vector and a +/// scalar; `operands` describes what arrived. fn unsupported_binary(operands: &str) -> DataFusionError { DataFusionError::NotImplemented(format!( "the native runtime does not execute this Binary node: it reads {operands}, and this \ @@ -6636,14 +5892,9 @@ fn unsupported_binary(operands: &str) -> DataFusionError { )) } -/// The broadcast a binary node with one scalar operand is, read off its binding. -/// -/// One evaluated vector and one scalar is a broadcast over the vector, and two scalars of which one varies -/// is a broadcast over the varying one. A constant comes from the scalar node's own binding and -/// [`ScalarOperand`] preserves its side; a varying scalar is read from the chunk its node hands over. -/// -/// [`NativeNode::validate`] refuses a binary operand that produces neither evaluated values nor a scalar -/// before any of this runs, so the last arm below is an exhaustiveness backstop. +/// The broadcast runtime of a binary node with a scalar operand: over the vector, or for two +/// scalars over the varying one. A constant is read from its node's binding; a dynamic scalar +/// from its node's chunk. fn broadcast_runtime( left: &NativeNode, right: &NativeNode, @@ -6661,9 +5912,7 @@ fn broadcast_runtime( (false, Arc::clone(vector)) } (NativeType::Scalar(grid), NativeType::Scalar(_)) => { - // Two constants are folded by the compiler; one that was not has no series to carry - // the result. The executor test `an_unimplemented_node_is_reported_not_panicked` - // builds this pair directly. + // The compiler folds two constants; an unfolded pair has no series to carry the result. if literal(left).is_some() && literal(right).is_some() { return Err(unsupported_binary( "two constants, which broadcast over no vector", @@ -6690,8 +5939,7 @@ fn broadcast_runtime( value: None, }, }; - // A scalar has no labels, so the modifiers a vector–vector operation would use have no - // meaning here: a tree that carries them describes another operation than the one it computes. + // A scalar has no labels; matching modifiers here would describe a different operation. if matching.labels != MatchingLabels::Ignoring(Vec::new()) || matching.cardinality != Cardinality::OneToOne || matching.fill != FillValues::default() @@ -6708,11 +5956,7 @@ fn broadcast_runtime( }) } -/// The operation a binary node's `matching` describes. -/// -/// A comparison is a filter unless it was bound as `bool`, and a filter keeps the label set it read while -/// every other operation drops the metric name. Arithmetic has no `bool` form, so one bound that way is -/// refused. +/// The operation a binary node's `matching` describes; `bool` on arithmetic is refused. fn broadcast_op(matching: &BinaryMatching) -> Result { let arithmetic = |op: ArithmeticOp| { if matching.return_bool { @@ -6737,8 +5981,7 @@ fn broadcast_op(matching: &BinaryMatching) -> Result { } } -/// The error for a reservation the platform cannot express: the sum of the retained operands and the -/// kernel's live workspace does not fit an address space. +/// The error for a reservation that overflows `usize`. fn reservation_overflow(node: &str) -> DataFusionError { DataFusionError::Execution(format!( "the operands and the kernel's workspace of {node} do not fit one address space: the bytes \ diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index c8ad8c127e4..f65cc8aa617 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -123,15 +123,8 @@ impl MemoryPool for DropOrderPool { } } -/// A pool that records every reservation it is asked to admit, so a test can count the calls that -/// made one rather than infer them from the figure a reservation ends at. -/// -/// The figure cannot tell two reservations of no bytes apart from one, and it cannot tell a -/// reservation made twice from one made once and then left alone at the same size; the calls can. -/// Each entry is the consumer's name and the bytes it asked for, in the order they were asked for, -/// and the largest total the pool was asked to hold at once is kept beside them: that figure is -/// what a limit has to admit for a run to fit, and it is a maximum inside a call, which the -/// reservation's size between calls does not show. +/// A pool that records every reservation call, so a test can count calls rather than infer them +/// from the final figure, and the peak total held at once. #[derive(Debug)] struct GrowCallPool { inner: GreedyMemoryPool, @@ -278,7 +271,7 @@ fn raw_input_with_source_index_and_ordering( } } -/// The same source over `count` float fields, which one input chunk has to carry all of. +/// The raw source over `count` float fields. fn raw_input_of(count: usize) -> NativeNode { let output = NativeType::Samples(raw_schema_of(field_count(count))); NativeNode { @@ -357,9 +350,7 @@ fn window_with( } } -/// A 1 ms `last_over_time` window over `count` float fields, whose output carries them all. -/// -/// Every other window here is over `fields`; this one is what a test of per-field retention needs. +/// A 1 ms `last_over_time` window over `count` float fields. fn window_over_fields(count: usize, output_grid: Arc) -> NativeNode { let fields = field_count(count); NativeNode { @@ -384,11 +375,8 @@ fn window_over_fields(count: usize, output_grid: Arc) -> NativeNode { } } -/// A bare selector over `inner`: the last sample at or before each grid point, read within -/// `lookback_ms` and at `offset_ms`. -/// -/// The selection reports one value per input field, so its layout is the input's, just as the -/// compiler builds it. +/// A bare selector over `inner`, read within `lookback_ms` at `offset_ms`, keeping the input's +/// field layout. fn instant( inner: NativeNode, lookback_ms: i64, @@ -554,11 +542,9 @@ fn window_and_limitk_collect_only_unified_contributions() { "limitk must not re-merge a window that already unifies its contributions" ); - // A window that drops the metadata labels collects its child only when something it drops tells - // the child's series apart. The child here is `abs(x)`, which already dropped the name: a caller - // that cannot say which metric the scan reads collects, and one that says the scan reads a - // single metric whose tags carry neither `__type__` nor `__unit__` does not - the same proof the - // canonical pass used when it decided this window needs no merge above it. + // A window that drops the metadata labels collects its child only when the drop can fold two of + // its series. The child `abs(x)` already dropped the name: an unknown metric collects, a single + // known metric without `__type__` or `__unit__` tags does not. let dropped_name_window = || { window_with( window_with( @@ -718,10 +704,8 @@ fn raw_chunk_repeated( .unwrap() } -/// One raw chunk of `series-a` whose fields carry `columns`, one column per field. -/// -/// A `None` is a position that field holds no sample at, which is what a partially filled field -/// looks like at the source. +/// One raw chunk of `series-a` whose fields carry `columns`, one column per field; `None` is a +/// missing sample. fn raw_chunk_columns( schema: &SeriesSchema, timestamps: &[i64], @@ -854,10 +838,8 @@ fn raw_histogram_chunk_with_start( .unwrap() } -/// One raw chunk of `series-a` whose one field holds the histogram at `index` of `table`. -/// -/// Two chunks built this way share one `Arc`, which is what makes the allocation -/// one table for accounting even though each chunk carries its own indices into it. +/// One raw chunk of `series-a` whose one field holds the histogram at `index` of `table`. Chunks +/// built from one `table` share its allocation. fn raw_shared_histogram_chunk( schema: &SeriesSchema, table: &Arc, @@ -879,10 +861,7 @@ fn raw_shared_histogram_chunk( .unwrap() } -/// A source leaf: the schema its chunks are checked against and the queue it is held for. -/// -/// The leaf owns the only state a source has, which is why the figure below is read off the slot -/// rather than off a node: a source reserves for what the caller queued at it and for nothing else. +/// A source leaf: the schema its chunks are checked against and the queue it reserves for. fn source_runtime(pool: &Arc) -> InputSlot { InputSlot { source_index: 0, @@ -897,11 +876,7 @@ fn source_runtime(pool: &Arc) -> InputSlot { } } -/// A binary node's state and the operation it runs: both operands bound to `schema`, and the -/// reservation the node is held for. -/// -/// The two are returned side by side because that is how a node keeps them: its state is shared by -/// every node kind, and the operation is the payload that belongs to this one. +/// A binary node's state and operation, with both operands bound to `schema`. fn binary_runtime( pool: &Arc, schema: &Arc, @@ -921,12 +896,8 @@ fn binary_runtime( ) } -/// What a binary node holds once it retains `left` and `right`, and what assembling the retained -/// chunks into the series the kernel matches adds on top. -/// -/// Both are read from a runtime of its own, so a pool can be sized from them: the first is what the -/// node reserves for the operands it retains and the second its own bound, and neither is a figure -/// the pool reports. +/// What a binary node reserves for retaining `left` and `right`, and what assembling them into +/// series adds on top, measured on a runtime of its own so a test can size a pool from them. fn binary_charge( schema: &Arc, left: &EvaluatedChunk, @@ -962,10 +933,8 @@ fn evaluated_chunk( ) } -/// One evaluated chunk of the series `metric`, `values` at `start` and onwards on `schema`'s grid. -/// -/// A `None` value is a position the series decided to hold no sample, which is what an inner -/// evaluated result carries where it had nothing to report. +/// One evaluated chunk of `metric`, `values` at `start` onwards on `schema`'s grid; `None` is a +/// missing sample. fn evaluated_chunk_of( schema: &SeriesSchema, metric: SeriesLabels, @@ -976,10 +945,8 @@ fn evaluated_chunk_of( evaluated_array_chunk_of(schema, metric, start, Float64Array::from(values), is_last) } -/// One evaluated chunk of the series `metric` whose one field holds `values`, addressed at `start`. -/// -/// The array is passed in rather than built here so that two chunks can hold sibling slices of one -/// Arrow allocation, which is what a source handing over the chunks of one batch does. +/// One evaluated chunk of `metric` whose one field holds `values`, addressed at `start`. The array +/// is passed in so two chunks can hold slices of one allocation. fn evaluated_array_chunk_of( schema: &SeriesSchema, metric: SeriesLabels, @@ -998,11 +965,8 @@ fn evaluated_array_chunk_of( EvaluatedChunk::try_new(series, is_last).unwrap() } -/// One evaluated chunk of the series `metric` whose one field holds `indices` into `table`, -/// addressed at `start` on `schema`'s grid. -/// -/// Two chunks built with one `table` are two slices of one allocation; two built with tables of the -/// same shape hold two allocations of the same size. +/// One evaluated chunk of `metric` whose one field holds `indices` into `table`, addressed at +/// `start`. Chunks built with one `table` share its allocation. fn evaluated_histogram_chunk_of( schema: &SeriesSchema, metric: SeriesLabels, @@ -1032,10 +996,8 @@ fn histogram_table(histograms: usize, buckets: i32) -> Arc { builder.finish().unwrap() } -/// What `table` holds: the batch struct and the arrays its columns view. -/// -/// Written out here rather than read from the runtime, so a test can size its expectations from the -/// table it built instead of from the figure it is checking. +/// What `table` holds: the batch struct and its column arrays, computed here rather than by the +/// estimator under test. fn histogram_table_bytes(table: &Arc) -> usize { std::mem::size_of::() + table.as_arrow().get_array_memory_size() } @@ -1052,10 +1014,8 @@ fn named_metric(name: &str, job: &str) -> SeriesLabels { .unwrap() } -/// `requests{host="web-1"}` with `zone` either present and empty or absent. -/// -/// The two are distinct series to a scan — an empty tag value is a present label, an absent one is -/// not — and the same label set to everything that drops empty-valued labels, as Prometheus does. +/// `requests{host="web-1"}` with `zone` either empty or absent: two series to a scan, one label set +/// once empty-valued labels are dropped. fn host_metric(zone: Option<&str>) -> SeriesLabels { let mut tags = vec![Label { name: "host".into(), @@ -1093,7 +1053,6 @@ fn run(executor: &mut NativeExecutor) -> Vec { out } -/// A deep native tree executes after the real FusedSeries envelope is decoded. #[test] fn deep_native_tree_executes_after_fused_series_round_trip() { // A representative deep codec/runtime test owns its worker stack; this is not an @@ -1185,12 +1144,6 @@ fn deep_native_tree_executes_after_fused_series_round_trip() { .unwrap(); } -/// A scalar root answers its own value, once, on the grid it was bound to. -/// -/// It reads nothing, so what it reports is not a series it was handed: one unlabelled chunk holding -/// one value per grid point and closing on that same chunk. Nothing above it exists, so the value's -/// field is the only field, and the chunk is addressed on the statement's grid rather than on one of -/// its own. #[test] fn scalar_root_emits_one_unlabelled_grid_chunk() { let grid = grid(10, 5, 3); @@ -1221,11 +1174,8 @@ fn scalar_root_emits_one_unlabelled_grid_chunk() { assert_eq!(pool.reserved(), 0); } -/// The scalar's chunk is reserved before it is allocated, and its own node reports it. -/// -/// The pool is asked first, so a low budget refuses the chunk instead of allocating it: the failure -/// leaves nothing held, and an execution stopped by it gives back everything it took. What the node -/// reports is the one batch and the values it produced, and no input at all, because it reads none. +/// A pool too small for the scalar's chunk refuses it and leaves nothing reserved. The node's +/// metrics count one output batch and no input. #[test] fn scalar_root_reserves_before_allocating_and_counts_its_output() { let grid = grid(0, 1, 4); @@ -1237,7 +1187,7 @@ fn scalar_root_reserves_before_allocating_and_counts_its_output() { assert!(error.to_string().contains("memory"), "{error}"); assert_eq!(rejected.state().reserved_bytes(), 0); assert_eq!(zero_pool.reserved(), 0); - // A stopped execution holds nothing either, and says so rather than answering again. + // A stopped execution is not resumed. assert!(rejected.next_chunk().is_err()); let pool = pool(); @@ -1263,10 +1213,7 @@ fn scalar_root_reserves_before_allocating_and_counts_its_output() { assert_eq!(count(&metrics, "root", NodeMetric::INPUT_SAMPLES), 0); } -/// A scalar can produce its value before the input ends. -/// -/// Nothing arrives for it, so waiting would be waiting for a chunk no producer will send. Ending the -/// input afterwards changes nothing: the chunk was handed over once and the tree owes no second one. +/// A scalar reads no input, so it answers before the input ends, and only once. #[test] fn scalar_root_settles_before_the_input_ends() { let tree = NativeTree::try_new(scalar(3.0, grid(0, 1, 3))).unwrap(); @@ -1405,13 +1352,8 @@ fn deferred_grid(start: i64, step: i64, len: u64) -> Arc { Arc::new(grid) } -/// The node that materializes a deferred grid reserves its array and keeps that reservation. -/// -/// A deferred grid is what keeps compilation proportional to the plan rather than to the timestamp -/// count, so the array it eventually needs is allocated at execution: the node that triggers the -/// allocation reserves it, and a pool that cannot hold it refuses the query instead of letting it -/// take the array unasked. What it reserved stays reserved for as long as the node lives, because -/// the array outlives the chunk the node read it for. +/// The node that materializes a deferred grid reserves the array and keeps the reservation for its +/// lifetime, because the array outlives the chunk it was read for. #[test] fn a_node_that_materializes_a_deferred_grid_reserves_it_for_its_lifetime() { let points = 1_000u64; @@ -1453,12 +1395,8 @@ fn a_node_that_materializes_a_deferred_grid_reserves_it_for_its_lifetime() { ); } -/// A grid that is already materialized is charged to nobody: the execution reads the array that is -/// there, and only the node that allocates it reserves it. -/// -/// This is also what keeps two nodes reading one grid from charging it twice, and what makes a grid -/// the plan built eagerly -- [`EvalGrid::try_new`] rather than [`EvalGrid::try_deferred`] -- cost -/// the execution nothing. +/// A grid the plan already materialized is charged to nobody; only the node that allocates the +/// array reserves it. #[test] fn a_materialized_grid_is_not_reserved_again() { let points = 1_000u64; @@ -1521,15 +1459,9 @@ fn a_window_reserves_the_grid_it_materializes() { assert_eq!(pool.reserved(), 0); } -/// A node that reads one grid reserves its timestamps once, however many chunks it is handed on -/// that grid. -/// -/// A collecting window reaches its output grid for every chunk it collects and again when it -/// flushes what it collected, and none of those calls finds the array materialized: the timestamps -/// are read by the flush, so what the calls before it reserve is an array that is still deferred. -/// What keeps the execution from charging one array per chunk is the node's record of the -/// reservation it made, which is what this pool counts, rather than the figure the reservation ends -/// at: a reservation the pool is asked for once is one call, whatever it is worth. +/// A collecting window reaches its deferred output grid for every chunk and again at the flush. The +/// node's record of its reservation keeps that to one call, so the pool counts calls rather than +/// reading the final figure. #[test] fn reserve_grid_reserves_the_array_once_however_often_it_is_called() { let grid = deferred_grid(0, 60_000, 1_000); @@ -1569,11 +1501,7 @@ fn reserve_grid_reserves_the_array_once_however_often_it_is_called() { ); } -/// A grid the plan already materialized is charged to nobody, however often a node reaches it. -/// -/// This is the other path a node takes through [`NodeBuffer::reserve_grid`](super::NodeBuffer): the -/// timestamps are there already, so the node that reads them allocates nothing and reserves -/// nothing, and what its own re-estimates add is its input alone. +/// A grid the plan already materialized is never reserved, however often a node reaches it. #[test] fn reserve_grid_charges_nothing_for_a_materialized_grid() { let grid = grid(0, 60_000, 1_000); @@ -1600,7 +1528,6 @@ fn reserve_grid_charges_nothing_for_a_materialized_grid() { assert_eq!(pool.reserved(), 0); } -/// `vector(c)` hands the constant on as one unlabelled series over the whole grid. #[test] fn vector_of_a_constant_is_one_unlabelled_series() { let tree = NativeTree::try_new(vector_of(scalar(4.0, grid(0, 10, 3)))).unwrap(); @@ -1612,7 +1539,6 @@ fn vector_of_a_constant_is_one_unlabelled_series() { assert_eq!(sample_values(&chunks[0]), vec![Some(4.0); 3]); } -/// A varying scalar is broadcast point by point, on the side it was written. #[test] fn a_varying_scalar_is_broadcast_on_its_side() { let grid = grid(1_000, 1_000, 3); @@ -1663,8 +1589,6 @@ fn a_varying_scalar_is_broadcast_on_its_side() { } } -/// An operation between scalars where one varies is a scalar, computed point by point with each -/// side where it was written. #[test] fn scalars_combine_point_by_point_when_one_varies() { let grid = grid(10_000, 10_000, 2); @@ -1721,9 +1645,8 @@ fn run_parameterized(root: NativeNode, vector: Vec>) -> EvaluatedChu chunks.remove(0) } -/// A constant parameter beside a varying one, as in `clamp(vector(1), 0, time())`, is reserved -/// before its values are built: on a grid whose values could never be allocated, the pool refuses -/// it instead of the allocation failing. +/// `clamp(vector(1), 0, time())`: the constant parameter is reserved before its values are built, +/// so on a 2^60-point grid the pool refuses it instead of the allocation failing. #[test] fn a_constant_parameter_is_reserved_before_it_is_built() { let grid = Arc::new(EvalGrid::try_deferred(GridSpec::try_new(0, 1, 1 << 60).unwrap()).unwrap()); @@ -1802,11 +1725,8 @@ fn a_closing_chunk_that_keeps_no_value_is_handed_over_empty() { } /// `max_of(a, b)` and `min_of(a, b)` against Go's `math.Max` / `math.Min`, whose signed-zero, NaN -/// and infinity rules differ from `f64::max` / `f64::min`; `max_min_cases.txt` holds Go's answers -/// for each pair. -/// -/// The cases run through the executor, as a compiled `max_of(a, b)` call does: the call's first -/// operand is the map's scalar input and its second is the map's constant parameter. +/// and infinity rules differ from `f64::max` / `f64::min`. `max_min_cases.txt` holds Go's answers; +/// the first operand is the map's input and the second its constant parameter. #[test] fn max_of_and_min_of_follow_go() { let bits = |text: &str| f64::from_bits(u64::from_str_radix(text, 16).unwrap()); @@ -1931,9 +1851,6 @@ fn field_values(chunk: &EvaluatedChunk, index: usize) -> Vec> { } /// The start timestamp of the histogram at every position of a chunk, in grid order. -/// -/// It is read off the output's own histogram views rather than off a converted value, because the -/// figure under test is the one a later reader sees. fn histogram_starts(chunk: &EvaluatedChunk) -> Vec> { let mut cursor = chunk.series.fields.as_slice()[0].cursor(); chunk @@ -1968,14 +1885,8 @@ fn addressed(chunks: &[EvaluatedChunk]) -> Vec<(usize, Vec>)> { .collect() } -/// Every decided position of a chunk stream with its value, in absolute grid order. -/// -/// Two streams that decided the same positions hold the same result however they were split into -/// chunks, which is what "the same series, delivered differently" means. -/// -/// The positions come from the axis, not from the chunk's start plus a row number: a chunk whose -/// rows form several runs carries them at absolute positions that are not adjacent, so adding the -/// row to the start would name positions the chunk does not hold. +/// Every decided position of a chunk stream with its value, in absolute grid order. Positions come +/// from the axis: a chunk's rows may form non-adjacent runs, so `start + row` is not a position. fn decided(chunks: &[EvaluatedChunk]) -> Vec<(usize, Option)> { chunks .iter() @@ -1996,21 +1907,14 @@ fn decided(chunks: &[EvaluatedChunk]) -> Vec<(usize, Option)> { .collect() } -/// The handles the nodes of `execution`'s tree record into, registered before it does any work. -/// -/// A caller registers once per execution, so what the returned set holds follows what the nodes -/// record from here on, and it keeps none of the execution's topology. +/// Registers the execution's node metrics into a fresh set before it does any work. fn metrics_of(execution: &NativeExecutor) -> ExecutionPlanMetricsSet { let metrics = ExecutionPlanMetricsSet::new(); execution.state().register_metrics(&metrics, 0); metrics } -/// Every node of `execution`'s tree as a weak handle to the metrics it records into, root first. -/// -/// What a node records into is its own, so a weak handle says whether the node still exists: the -/// registered set holds the counters, not the nodes, and dropping the execution must drop both the -/// topology and the handles it held. +/// Weak handles to every node's metrics, root first; a dead handle means the node was dropped. fn node_metrics(execution: &NativeExecutor) -> Vec> { fn walk(node: &RuntimeNode, out: &mut Vec>) { out.push(Arc::downgrade(&node.metrics)); @@ -2063,10 +1967,7 @@ fn node_metrics(execution: &NativeExecutor) -> Vec> { out } -/// The count `metric` of the node called `name`, read from the handles `set` holds. -/// -/// The set was registered from the execution's own tree, so a read here sees what the nodes -/// recorded even after the execution stopped or was dropped. +/// The count `metric` of the node called `name`. fn count(set: &ExecutionPlanMetricsSet, name: &str, metric: &str) -> usize { let full = format!("native.{name}.{metric}"); match set.clone_inner().sum_by_name(&full) { @@ -2083,12 +1984,8 @@ fn gauge(set: &ExecutionPlanMetricsSet, name: &str) -> usize { } } -/// Whether the root node of `execution` still holds the payload its kind keeps. -/// -/// A window's evaluator, an instant node's buffered series and a binary node's retained operands all -/// belong to the node that owns them, so what is read here is the root operator and nothing below -/// it: the trees these tests build have one node of that kind, and it is the root. The state owns -/// that tree, so the read is a borrow of it and the execution can be polled again afterwards. +/// Whether the root node still holds the payload its kind keeps. The trees these tests build have +/// one node of that kind, at the root. fn root_holds(execution: &NativeExecutor, holds: fn(&RuntimeOp) -> bool) -> bool { execution .state() @@ -2209,10 +2106,8 @@ fn finishing_a_window_propagates_its_error_and_drops_the_live_tree() { .unwrap(); drop(execution.next_chunk().unwrap()); assert!(pool.reserved() > 0); - // The source-level check normally catches truncation first; leave the evaluator open so the - // actual terminal finish pass exercises its own error and context propagation. Both halves of - // that check are cleared: the chunk was handed over and it was also the last one received, so - // the leaf reports `is_last` was sent only to the evaluator that never saw it. + // The input node normally reports the truncation first. Clear both of its flags so the window's + // own finish reports it, under the window's context. let slot = &mut execution.state.live.as_mut().unwrap().inputs[0]; slot.open_source_series = false; slot.open_queued_series = false; @@ -2276,11 +2171,8 @@ fn scalar_operations_drop_their_grid_and_topology_on_finish_or_failure() { } } -/// A window over raw input evaluates onto its own output grid, and its values are the evaluator's. -/// -/// The grid is compared by allocation identity, so a window that evaluated on a copy of its -/// output grid — the same timestamps, a different grid — fails here even though every value and -/// every timestamp would still look right. +/// The grid is compared by identity: a window evaluating on a copy of its output grid would produce +/// the same timestamps and values. #[test] fn a_window_over_raw_input_evaluates_onto_its_own_grid() { let out_grid = grid(0, 60_000, 4); @@ -2337,7 +2229,7 @@ fn a_window_over_raw_input_evaluates_onto_its_own_grid() { assert_eq!(addressed(&out), expected); } -/// Timestamp projection reserves its grid-sized workspace before allocating and releases it on failure. +/// Timestamp projection charges its grid-sized workspace to the pool and releases it on failure. #[test] fn timestamp_projection_workspace_failure_releases_runtime() { let schema = evaluated_schema(grid(0, 1, 10_000)); @@ -2373,11 +2265,8 @@ fn timestamp_projection_workspace_failure_releases_runtime() { assert_eq!(execution.state().reserved_bytes(), 0); } -/// `Window -> Map -> Window` keeps the inner grid inside and the outer grid outside. -/// -/// The inner window runs on a 60 s grid and the outer one on a 90 s grid offset by 30 s, so a -/// layer that resampled onto its consumer's grid would change the addressing of every chunk and -/// the values of the last one. +/// The outer grid is 90 s offset by 30 s, so a layer that resampled onto its consumer's grid would +/// change the addressing of every chunk. #[test] fn a_window_map_window_chain_keeps_each_layer_on_its_own_grid() { let inner_grid = grid(0, 60_000, 5); @@ -2506,13 +2395,6 @@ fn a_window_map_window_chain_keeps_each_layer_on_its_own_grid() { ); } -/// A window over an evaluated input reports a decision before its input series has ended. -/// -/// The inner series arrives in two pieces and the window is pulled after the first one, so the -/// outer grid point whose window that piece settled has to come out then. A layer that collected -/// the pieces into a whole series first could not produce anything here: its first answer would -/// only exist once the piece carrying `is_last` had arrived, and the bytes of the whole series -/// would be held until then. #[test] fn a_downstream_window_emits_before_its_input_series_ends() { // 60 s inner grid, 120 s outer grid, so the inner series settles outer points as it arrives. @@ -2609,12 +2491,7 @@ fn a_downstream_window_emits_before_its_input_series_ends() { } } -/// Every binary shape the runtime does not execute is rejected, naming the kind and its position. -/// -/// A scalar is not one of them any more: it is a value node, and a binary node over a constant is -/// executed as a broadcast. The binary shapes that stay refused are the ones no kernel here takes; -/// the aggregate kinds and stages this runtime does not execute are refused by -/// `an_aggregate_kind_or_stage_the_runtime_does_not_compute_is_named`. +/// Binary shapes the runtime does not execute are refused with `NotImplemented`, naming the kind. #[test] fn an_unimplemented_node_is_reported_not_panicked() { // One grid shared by the nodes that validate by allocation identity. @@ -2671,13 +2548,8 @@ fn an_unimplemented_node_is_reported_not_panicked() { } } -/// Each node reports its own chunks, grid points and closed series, at its own position. -/// -/// The two windows decide different traffic — the inner one four grid points of its own grid, the -/// outer one two of its own — so a single total for the tree cannot produce both numbers. The inner -/// window reads the source as it arrives and hands over one chunk per chunk it took in; the outer -/// one collects those chunks, because the inner one keeps the metric name and its output can hold -/// two source series under one label set, and reports the one merged series its input ended with. +/// The inner window decides four points of its grid and the outer one two, so a tree-wide total +/// cannot produce both numbers. #[test] fn each_node_records_its_own_metrics() { let inner_grid = grid(0, 60_000, 4); @@ -2737,8 +2609,7 @@ fn each_node_records_its_own_metrics() { assert_eq!(count(&metrics, "root", NodeMetric::INPUT_BATCHES), 3); assert_eq!(count(&metrics, "root.input", NodeMetric::OUTPUT_BATCHES), 3); assert_eq!(count(&metrics, "root", NodeMetric::OUTPUT_BATCHES), 1); - // The grid points each window decided, which is its own output range: four on the inner grid - // and two on the outer one, which is the figure that tells the two nodes apart. + // Each window's own output range: four inner points, two outer. assert_eq!( count(&metrics, "root.input", NodeMetric::EVALUATED_GRID_POINTS), 4 @@ -2764,12 +2635,7 @@ fn each_node_records_its_own_metrics() { ); } -/// A tree whose left operand is a broadcast registers every node it runs, the constant included. -/// -/// The tree is `(2 + in0) + in1`: the root is a binary, its left operand a broadcast over the first -/// input, its right operand the second. Each of the five nodes keeps its own handles, so one -/// registration names one entry per node and per metric a node reports, and the branches carry what -/// each node did with the input it was handed. +/// `(2 + in0) + in1` registers one entry per node and metric, the constant included. #[test] fn a_binary_over_a_broadcast_registers_every_node_it_runs() { let out_grid = grid(0, 60_000, 2); @@ -2789,8 +2655,7 @@ fn a_binary_over_a_broadcast_registers_every_node_it_runs() { let mut execution = executor(&tree, Arc::clone(&pool)); let metrics = metrics_of(&execution); - // One direct pattern per level, on the nodes the constructor made; the borrow ends before the - // first push. + // The borrow ends before the first push. { let RuntimeOp::Binary { left, right, .. } = &execution.state().live.as_ref().unwrap().root.op @@ -2890,9 +2755,6 @@ fn a_binary_over_a_broadcast_registers_every_node_it_runs() { names }; assert_eq!(exported(&metrics), expected); - // Reading the registered handles again repeats no name, which a doubled entry in the sorted - // list would show: a read registers nothing. - assert_eq!(exported(&metrics), expected); // The execution closed itself, so every node gave its bytes back. assert_eq!(pool.reserved(), 0); @@ -2957,13 +2819,10 @@ fn an_error_releases_the_reservation() { error.to_string().contains("native.window at root"), "{error}" ); - // Everything went back to the pool while the execution is alive: waiting for the drop would - // keep the query's bytes in use for as long as the caller holds the executor. + // Released while the execution is still alive, not on drop. assert_eq!(pool.reserved(), 0); assert_eq!(execution.state().reserved_bytes(), 0); - // The numbers above only say the reservation was returned. The state the bytes were taken for - // has to be gone too, or the executor keeps the evaluator's sample buffers alive while the pool - // reports them as free: the window is dropped, not only its accounting. + // The window itself is dropped, not only its accounting. assert!( !root_holds(&execution, holds_window), "the stopped execution still holds a window's samples while its reservation reads zero" @@ -3119,67 +2978,11 @@ fn a_fanout_enqueue_failure_releases_every_recipient() { ); } -/// A chunk the pool cannot admit fails the execution and gives back everything it already held. +/// The collector refuses the malformed streams a streaming window refuses. /// -/// The window holds the first chunk's samples, so the second one is refused against a reservation -/// that is already standing: the failure has to hand that reservation back too, rather than leaving -/// the pool full for as long as the caller keeps the stopped executor alive. -#[test] -fn a_pool_that_cannot_admit_a_chunk_releases_what_it_held() { - let tree = NativeTree::try_new(window(input(), grid(0, 60_000, 4))).unwrap(); - let schema = raw_schema(); - // Room for the first chunk and what the window keeps of it, not for the second one. - let pool = bounded_pool(16 << 10); - let mut execution = executor(&tree, Arc::clone(&pool)); - let metrics = metrics_of(&execution); - - execution - .push_raw(InputId::new(0), raw_chunk(&schema, &[0], &[1.0], false)) - .unwrap(); - drop(execution.next_chunk().unwrap()); - let held = pool.reserved(); - assert!(held > 0, "the open series has to be reserved for"); - - // A hundred thousand samples are hundreds of kilobytes whatever the pool already holds. - let timestamps: Vec = (0..100_000).collect(); - let values = vec![1.0; 100_000]; - let error = execution - .push_raw( - InputId::new(0), - raw_chunk(&schema, ×tamps, &values, true), - ) - .expect_err("a chunk larger than the pool was admitted"); - assert!(is_resources_exhausted(&error), "{error}"); - - // The chunk never entered the queue, and everything the execution held went back to the pool - // while the executor is still alive. - assert_eq!(execution.state().reserved_bytes(), 0); - assert_eq!(pool.reserved(), 0); - let current = format!("native.root.{}", NodeMetric::CURRENT_RESERVED_BYTES); - assert_eq!(gauge(&metrics, ¤t), 0); - let peak = format!("native.p0.root.{}", NodeMetric::PEAK_RESERVED_BYTES); - assert!(gauge(&metrics, &peak) >= held); - // A stopped execution is not resumed. - let again = execution.next_chunk().unwrap_err(); - assert!( - again.to_string().contains("stopped after an earlier error"), - "{again}" - ); -} - -/// The malformed streams a streaming window refuses are refused by the collector too. -/// -/// The window below the map collects the whole fragment stream and hands it to -/// [`crate::grid_series::merge_same_labelset`], which sorts the rows by position and groups them by -/// label set. That is what makes two closed series that share a label set one series, and it is also -/// what would hide a stream that never was one series: runs that went backwards inside a series, and -/// an identity that changed inside a series, both come out as a plausible merged series with a -/// peaceful answer. A window that read the same stream as it arrived refuses it on the chunk that -/// breaks it, and so does the collector, before the chunk is kept. -/// -/// The stream below is a single series per case and the answer it would have produced is the one -/// nothing asked for: `3` for the first (the merge would sort 1 and 2 onto positions 0 and 1), and -/// two answers for the second. +/// [`crate::grid_series::merge_same_labelset`] sorts rows by position and groups them by label set, +/// so a run that goes backwards or an identity that changes inside one series would come out as a +/// plausible merged series. The collector has to refuse them as they arrive. #[test] fn a_collector_refuses_the_malformed_streams_a_streaming_window_refuses() { let inner_grid = grid(0, 60_000, 2); @@ -3247,13 +3050,8 @@ fn a_collector_refuses_the_malformed_streams_a_streaming_window_refuses() { } } -/// The streams a streaming window accepts are accepted by the collector too. -/// -/// One series arriving in chunks that move forward is what a scan hands over, and the chunk that -/// closes a series may carry no row at all. Both are legal to a streaming window, so both are legal -/// to the collector, which merges them into the one series they are and answers over it. The values -/// are the ones the audit's counterexamples would have produced had they been legal: the two forward -/// chunks hold 1 and 3 and sum to 4, and the close that carries no row leaves the 1 it follows. +/// Forward runs and a closing chunk with no row are accepted by the collector, as by a streaming +/// window. #[test] fn a_collector_accepts_forward_runs_and_a_close_without_a_row() { let inner_grid = grid(0, 60_000, 2); @@ -3309,18 +3107,10 @@ fn a_collector_accepts_forward_runs_and_a_close_without_a_row() { } } -/// An input that ends inside a series is reported by a window that collects its input too. +/// An input that ends inside a series is reported under a collecting window too. /// -/// The collector holds the fragments until the input ends and closes every series it merges with a -/// synthetic `is_last`, so a series the caller never closed would look exactly like one that closed -/// afterwards: the merge would answer it and the barrier would hide the truncation. Nothing is -/// merged here, because the executor refuses the truncation before the flush runs. The check is the -/// input node's own, which follows what it handed over, and it is the only one needed: every closing -/// chunk the caller sent has already reached the collector, which wrote down the series it left open. -/// -/// A root map reports the same truncation, and -/// [`an_input_that_ends_mid_series_is_reported_without_a_window`] is that case on its own; this one -/// is the barrier's, where the flush would have run before the report if the check came later. +/// The collector closes every merged series with a synthetic `is_last`, so the input node has to +/// report the truncation before the flush runs, or the merge would hide it. #[test] fn an_input_that_ends_inside_a_collected_series_is_reported() { let inner_grid = grid(0, 60_000, 2); @@ -3372,8 +3162,7 @@ fn an_input_that_ends_inside_a_collected_series_is_reported() { .contains("native.input at root.input.input (source_index=0)"), "{error}" ); - // Nothing was merged and nothing was answered, and everything went back while the executor is - // alive. + // Nothing was merged or answered, and everything was released. assert_eq!(execution.state().reserved_bytes(), 0); assert_eq!(pool.reserved(), 0); assert!( @@ -3391,19 +3180,8 @@ fn an_input_that_ends_inside_a_collected_series_is_reported() { ); } -/// Two series that a map turns into one label set are merged before the window above reads them. -/// -/// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own source -/// series, and `abs` drops the name, so both become `{job="x"}`. The two hold their values at -/// different positions, so they are one series with a hole each and the answer is the window over -/// the merged series: `sum_over_time` sees 1 and 3 and answers 4, `count_over_time` answers 2. A -/// window that read the two as two series would answer twice, once per source series, and close -/// twice. -/// -/// The window above the map is the node that merges: its input can hold two series under one label -/// set, so it collects the whole input, merges each label set once with -/// [`crate::grid_series::merge_same_labelset`], and only then evaluates. Nothing comes out of it -/// while the pieces arrive, which is the price of merging; what comes out is one series. +/// `abs` maps `a{job="x"}` and `b{job="x"}` onto one label set, with values at different positions. +/// The window above collects and merges them, so it answers once over the merged series. #[test] fn two_series_onto_one_label_set_after_a_map_are_merged_into_one_series() { let inner_grid = grid(0, 60_000, 2); @@ -3495,16 +3273,8 @@ fn two_series_onto_one_label_set_after_a_map_are_merged_into_one_series() { } } -/// A dynamic `topk` hands on the label sets its input holds, so the window above it merges them as -/// it does under a literal `topk`. -/// -/// `topk` keeps whole input series and canonicalises nothing about their labels, so a `topk` over a -/// map hands on what the map handed it: `a{job="x"}` and `b{job="x"}` become two pieces of one -/// label set, and the two hold their values at different positions. The window above is the node -/// that merges them, which it only does when the child says its output can hold two series of one -/// label set. A window that streamed them instead answers once per piece, and the two answers -/// overlap on the same label set at the same position, which is neither Prometheus' answer nor a -/// result the node can hand out: merging first makes `sum_over_time` answer 4, once. +/// A dynamic `topk` passes its input's label sets through, so the window above merges them as under +/// a literal `topk`. #[test] fn two_series_onto_one_label_set_under_a_parameterized_topk_are_merged() { let inner_grid = grid(0, 60_000, 2); @@ -3586,12 +3356,8 @@ fn two_series_onto_one_label_set_under_a_parameterized_topk_are_merged() { ); } -/// Two closed series that hold a value at the same position are still refused under one label set. -/// -/// The pair below maps into one label set and both hold a value at position 0 of the field, which -/// no merge resolves and Prometheus rejects for two series whose label sets became equal. The -/// refusal is the merge's, which the window above runs on the input it collected before it evaluates -/// anything: nothing reaches the evaluator until the pieces of one label set are one series. +/// Two series a map puts under one label set, both with a value at position 0, are refused by the +/// window's merge before anything reaches the evaluator. #[test] fn two_series_onto_one_label_set_after_a_map_are_rejected() { let inner_grid = grid(0, 60_000, 2); @@ -3659,16 +3425,9 @@ fn two_series_onto_one_label_set_after_a_map_are_rejected() { ); } -/// An empty tag and an absent one are two source series and one canonical label set. -/// -/// `requests{host="web-1", zone=""}` and `requests{host="web-1"}` are distinct series to a scan: an -/// empty tag value is a present label, an absent one is not. `last_over_time` keeps the metric name -/// and every tag, so the inner window hands both on as two pieces, each closing its own source -/// series, and the two pieces carry different metrics. The outer window is the node that merges -/// them: a consumer compares label sets without the empty value, so the two are one series there. -/// Merging first is what makes the outer `sum_over_time` answer 4 at the second point -- the two -/// pieces hold 1 at the first point and 3 at the second -- where evaluating each piece on its own -/// would answer 3. +/// `last_over_time` keeps the name and every tag, so `zone=""` and an absent `zone` leave the inner +/// window as two pieces. The outer window merges them and answers 4 at the second point, where +/// evaluating each piece alone would answer 3. #[test] fn an_empty_tag_and_an_absent_one_are_one_label_set_to_the_window_above() { let inner_grid = grid(0, 60_000, 2); @@ -3756,11 +3515,6 @@ fn an_empty_tag_and_an_absent_one_are_one_label_set_to_the_window_above() { ); } -/// A window that collects its whole input gives every byte back when the execution closes. -/// -/// The fragments it holds, the workspace it merges them with and the chunks it queued while -/// flushing are all charged while they live, so the pool never admits memory the node still owns. -/// The close releases all of them, and the figures read zero while the executor is still alive. #[test] fn a_window_that_merges_its_input_releases_what_it_collected() { let inner_grid = grid(0, 60_000, 2); @@ -3791,8 +3545,7 @@ fn a_window_that_merges_its_input_releases_what_it_collected() { "the collecting window reported a piece" ); let held = execution.state().reserved_bytes(); - // The root is the window that collected the fragments, so its own reservation is what the peak - // below has to cover. The borrow ends before the close below. + // The window's own reservation is what the peak below has to cover. let window_held = { let RuntimeOp::Window { state, .. } = &execution.state().live.as_ref().unwrap().root.op else { @@ -3822,13 +3575,8 @@ fn a_window_that_merges_its_input_releases_what_it_collected() { ); } -/// Every answer a merge flush queues stays charged until its own pull hands it over. -/// -/// The flush evaluates one series per label set at once, and only the pull of the first of them -/// returns the fragments it collected: what is left in the queue after that pull is what the node -/// still keeps, so the reservation is what those answers hold, the label sets the node handed out -/// under and what the evaluator retains. Pulling the second one gives its share back in turn, and -/// the pool is empty once the tree has answered everything it had. +/// A merge flush queues one answer per label set, and each stays charged until its own pull hands +/// it over. #[test] fn a_merge_flush_reserves_every_queued_output() { let inner_grid = grid(0, 60_000, 2); @@ -3907,13 +3655,7 @@ fn a_merge_flush_reserves_every_queued_output() { assert_eq!(pool.reserved(), 0); } -/// Dropping the execution releases everything it held and every node it built, and the counters -/// the caller registered still read what those nodes did. -/// -/// The state owns its tree, so the drop takes the evaluator, the collected input, the queued answers, -/// the reservation and the topology with it. What outlives the execution is what the caller -/// registered before it started: the nodes' own counters and gauges, not the nodes, so a weak -/// handle to any of them is dead while the peak the tree reached still stands. +/// The counters registered before the run outlive the dropped execution; the nodes do not. #[test] fn dropping_the_execution_releases_its_tree_and_keeps_the_registered_metrics() { let inner_grid = grid(0, 60_000, 2); @@ -4023,11 +3765,8 @@ fn dropping_the_execution_releases_its_tree_and_keeps_the_registered_metrics() { ); } -/// A `sum_over_time` window over a map over a source: the map can rewrite label sets, so the window -/// collects its whole input before it evaluates any of it. -/// -/// The range covers every point of the `points` the output grid has, so the series the window -/// eventually folds is the whole series it collected. +/// `sum_over_time` over a map over a source: the map can rewrite label sets, so the window collects +/// its whole input before evaluating. The range covers the whole output grid. fn collecting_window_tree(grid: &Arc, points: u64) -> NativeTree { let step = grid.spec().step_ms; NativeTree::try_new(window_with( @@ -4040,12 +3779,8 @@ fn collecting_window_tree(grid: &Arc, points: u64) -> NativeTree { .unwrap() } -/// Delivers one series as `chunks` one-point chunks of `1.0` to a collecting window's source, -/// pulling after each of them. -/// -/// The chunks do not close the series except on the last one, so the window is still collecting -/// when the call returns and nothing has been answered: what changed is only what it keeps of the -/// chunks it was handed. +/// Pushes one series as `chunks` one-point chunks of `1.0`, closing only on the last, and pulls +/// after each. fn push_one_point_chunks(execution: &mut NativeExecutor, schema: &SeriesSchema, chunks: usize) { for position in 0..chunks { execution @@ -4061,15 +3796,9 @@ fn push_one_point_chunks(execution: &mut NativeExecutor, schema: &SeriesSchema, } } -/// A collecting window is handed its input one chunk at a time and reaches its output grid on every -/// one of them, so what it reserves for the timestamps must not grow with the chunk count. -/// -/// The window reads the grid's timestamps only when it flushes, so the array is still deferred when -/// the chunks arrive: a reservation made per call would charge the pool one array for every chunk -/// -- `chunks + 1` of them, the last one on the flush -- for the one array the execution holds. The -/// same chain over an eager grid charges nothing at all for the timestamps, because the plan -/// already allocated them, so what the two figures differ by is exactly what the deferred run -/// reserved: one array. +/// A collecting window reaches its deferred output grid on every chunk, so its grid reservation +/// must not grow with the chunk count: a deferred run holds exactly one array more than an eager +/// one. #[test] fn a_collecting_window_reserves_its_grid_once_for_all_its_chunks() { let points = 1_000u64; @@ -4117,15 +3846,8 @@ fn a_collecting_window_reserves_its_grid_once_for_all_its_chunks() { ); } -/// A pool sized for what a collecting window holds is not exhausted by the number of chunks it was -/// handed. -/// -/// The chain collects `chunks` one-point chunks of one series over a deferred grid, and the bytes it -/// needs are those fragments, the merge's workspace, the answer and one array of timestamps. The -/// same chain over an eager grid needs all of that and nothing for the timestamps, so its peak -/// plus a few arrays is a budget that holds the deferred run -- and a reservation made per call, -/// one array for each of `chunks + 1` calls, would run out of it after a handful of chunks. A -/// chunk count is then something the query carries rather than something it is sized by. +/// A pool of the eager run's peak plus a few arrays holds the deferred run however many chunks it +/// collects; one array per chunk would exhaust it after a handful. #[test] fn many_chunks_do_not_exhaust_a_pool_that_holds_one_grid() { let points = 1_000u64; @@ -4190,13 +3912,8 @@ fn many_chunks_do_not_exhaust_a_pool_that_holds_one_grid() { assert_eq!(pool.reserved(), 0, "the release left bytes reserved"); } -/// A pool that cannot admit what a collecting chain holds fails the execution and gives everything -/// back. -/// -/// The window collects its whole input, so the fragment it keeps costs more than the chunk it was -/// made from: the pool below holds room for the chunk and no more, so one of the charges the chain -/// makes fails. Whichever it is, the failure hands every reservation back while the executor is -/// still alive, and the evaluators and the collected fragments go with it. +/// A pool that holds the queued chunk but not what the collecting chain makes of it fails the +/// execution and releases everything. #[test] fn a_pool_that_cannot_admit_a_collected_fragment_releases_what_it_held() { let inner_grid = grid(0, 60_000, 2); @@ -4217,9 +3934,8 @@ fn a_pool_that_cannot_admit_a_collected_fragment_releases_what_it_held() { vec![Some(1.0), None], true, ); - // Room for the chunk the source queue holds -- read where the pool admits anything, so the limit - // is what the queue charges and not a figure derived from the estimator -- and nothing for the - // label sets the map records or the fragment the window collects. + // Room for the queued chunk, measured on an unbounded pool, and nothing for the map's label + // sets or the collected fragment. let queued = { let mut probe = executor(&tree, pool()); probe @@ -4246,15 +3962,8 @@ fn a_pool_that_cannot_admit_a_collected_fragment_releases_what_it_held() { ); } -/// A merge whose workspace the pool cannot admit stops the execution and gives everything back. -/// -/// The fragments are admitted one by one as they arrive, so their charge is not what fails here: -/// what fails is the workspace the merge needs, taken in `finish` before the helper runs. The first -/// run measures what the collected input holds where the pool admits it; the second is given that -/// much, the map's transient charge for one chunk and a little over -- enough for every fragment, -/// not for the workspace, which charges at least one `(position, member, row)` triple and one -/// position per row. The failure releases the fragments, the evaluators and the queues while the -/// executor is still alive. +/// A pool that admits every collected fragment but not the merge workspace taken in `finish` fails +/// the execution and releases everything. #[test] fn a_pool_that_cannot_admit_the_merge_workspace_releases_what_it_held() { let inner_grid = grid(0, 60_000, 2); @@ -4324,8 +4033,7 @@ fn a_pool_that_cannot_admit_the_merge_workspace_releases_what_it_held() { .finish() .expect_err("the merge ran without its workspace admitted"); assert!(is_resources_exhausted(&error), "{error}"); - // Everything the chain held went back while the executor is alive: the fragments, the - // evaluator and both queues. + // Fragments, evaluator and both queues are released. assert_eq!(execution.state().reserved_bytes(), 0); assert_eq!(pool.reserved(), 0); assert!( @@ -4340,10 +4048,8 @@ fn a_pool_that_cannot_admit_the_merge_workspace_releases_what_it_held() { ); } -/// `rate(x[5m])` alone, with `metrics` as the fact the planner states about what its source reads. -/// -/// The tree is the window and nothing else: what the pass is asked is where a consumer of a whole -/// label set reads one, not what the fixture's source holds. +/// `rate(x[5m])` alone, canonicalized with `metrics` as the planner's fact about what its source +/// reads. fn window_over_rate(metrics: &[Option>]) -> NativeTree { let out_grid = grid(0, 60_000, 5); let tree = NativeTree::try_new(window_with( @@ -4366,14 +4072,9 @@ fn window_over_rate(metrics: &[Option>]) -> NativeTree { .unwrap() } -/// The error a merge over the window answers when two of its series are one label set to `rate`. -/// -/// `{host="web-1", zone=""}` and `{host="web-1"}` are two series to the scan: an empty tag value is -/// a present label, an absent one is not. `rate` drops the metric name, and to the comparison a merge -/// groups by - the one that treats an empty label value as no label - both are `{host="web-1"}`, each -/// covering the same positions of the same field. The merge above the window is where the second -/// value of one label set at one position is refused: what must not happen is both leaving, and -/// neither is the answer a merge owes this pair. +/// Runs `{host="web-1", zone=""}` and `{host="web-1"}` through `tree` and returns the error the +/// merge refuses them with: `rate` drops the name and a merge ignores empty label values, so both +/// are one label set holding the same positions. fn rate_onto_one_label_set_error(tree: &NativeTree) -> String { let schema = raw_schema(); let counter = [0, 60_000, 120_000, 180_000, 240_000]; @@ -4418,8 +4119,7 @@ fn rate_onto_one_label_set_error(tree: &NativeTree) -> String { .to_string() } -/// Two series carrying different hosts stay distinct, which is what a rate over a label that -/// survives the rewrite looks like. +/// Two series with different hosts stay two series. fn rate_over_two_hosts_stays_two(tree: &NativeTree) { let schema = raw_schema(); let counter = [0, 60_000, 120_000, 180_000, 240_000]; @@ -4505,13 +4205,8 @@ fn two_series_onto_one_label_set_after_a_window_are_rejected() { rate_over_two_hosts_stays_two(&tree); } -/// A window that drops empty-valued labels is collected when its labels cannot prove the drop, and -/// the merge above it rejects the two series as one label set. -/// -/// The same pair as above, over a selector that discovered several metrics: the name the window -/// drops is not one every series it reads shares, so dropping the name can fold two metrics that -/// agree on every other label. The window's output is collected for that fact, and the merge refuses -/// the pair the same way. +/// Over a selector that discovered several metrics, the name drop can fold two metrics, so the pass +/// collects the window and the merge refuses the pair. #[test] fn two_series_onto_one_label_set_after_a_window_of_a_discovery_are_rejected() { let tree = window_over_rate(&[None]); @@ -4527,16 +4222,9 @@ fn two_series_onto_one_label_set_after_a_window_of_a_discovery_are_rejected() { rate_over_two_hosts_stays_two(&tree); } -/// Two hosts survive a name drop the labels prove, each with the values its own statement answers. -/// -/// `timestamp(x)`, `rate(x[5m])` and `timestamp(rate(x[5m]))` all drop the metadata labels, and over -/// a scan bound to one metric whose tags carry no metadata label nothing collects them: the labels -/// prove the drop, so the pass leaves the selection and the window where they are. What these three -/// then say about two hosts is what the kernels say. -/// -/// The values are the statement's own. `timestamp` reports each point's own time in seconds, and -/// `rate` answers the slope of the counter it reads - both fixtures rise one step a minute, so both -/// hosts answer the same slope and neither's values depend on the other being there. +/// Over a scan bound to one metric whose tags carry no metadata label, the labels prove the name +/// drop: nothing is collected, and each host answers its own values under `timestamp(x)`, +/// `rate(x[5m])` and `timestamp(rate(x[5m]))`. #[test] fn two_hosts_survive_a_proved_name_drop_with_their_own_values() { let out_grid = grid(0, 60_000, 5); @@ -4733,12 +4421,8 @@ fn two_hosts_survive_a_proved_name_drop_with_their_own_values() { ); } -/// Two series a `timestamp` hands out under one label set are refused by the merge above it. -/// -/// `timestamp` reports a sample's own time under the metric name dropped, so `a{job="x"}` and -/// `b{job="x"}` are one label set the moment they leave it, whatever their input held. The merge -/// collecting its output is where the second value of one position is reported, as Prometheus -/// refuses two series of one label set; a single series passes through it unchanged. +/// `timestamp` drops the name, so `a{job="x"}` and `b{job="x"}` collide in the merge above it; a +/// single series passes through unchanged. #[test] fn two_series_onto_one_label_set_after_a_timestamp_are_rejected() { let grid = grid(0, 60_000, 2); @@ -4805,60 +4489,8 @@ fn two_series_onto_one_label_set_after_a_timestamp_are_rejected() { ); } -/// A chunk that holds a value where the same field already holds one is rejected. -/// -/// Each piece is a whole source series that closes itself, and the refusal is about the positions -/// the two hold, not about the close: they are one label set to the merge, and both hold a value of -/// field 0 at position 0. `v0` would carry two values at position 0 under one label set, which no merge can -/// resolve, so the merge collecting the map's output refuses rather than picking one. -#[test] -fn two_series_holding_a_value_at_one_position_are_rejected() { - let map_grid = grid(0, 60_000, 2); - let tree = NativeTree::try_new(merge(map( - evaluated_input(Arc::clone(&map_grid)), - vec![MathOp::Abs], - ))) - .unwrap(); - let schema = evaluated_schema(Arc::clone(&map_grid)); - - let mut execution = executor(&tree, pool()); - for (name, values) in [ - ("a", vec![Some(-1.0), Some(-2.0)]), - ("b", vec![Some(-3.0), Some(-4.0)]), - ] { - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of(&schema, named_metric(name, "x"), 0, values, true), - ) - .unwrap(); - } - // The merge holds both pieces until its input ends, and then reports the shared position. - execution.end_of_input().unwrap(); - let error = match execution.next_chunk() { - Ok(None) => panic!("the map produced no chunk at all"), - Ok(Some(chunk)) => panic!( - "a second series holding a value at the same position was handed on: {:?}", - decided(&[chunk]) - ), - Err(error) => error, - }; - let message = error.to_string(); - assert!( - message.contains("vector cannot contain metrics with the same labelset"), - "{message}" - ); - assert!(message.contains("job"), "{message}"); -} - -/// Two closed series under one label set are two pieces of one logical series. -/// -/// `a{job="x"}` and `b{job="x"}` are two series to the input and one label set to `abs`, which drops -/// the name. Each holds a value where the other holds none, and each says it is the last chunk of -/// its own source series — which is what `is_last` means here: the source series ended, not the -/// label set. The map hands both pieces on, and merging the two pieces with -/// [`crate::grid_series::merge_same_labelset`] gives the one series the data has, which is what a -/// caller holding the root's pieces does. +/// A map hands on both closed pieces of one label set: `is_last` closes a source series, not the +/// label set. Merging them with [`crate::grid_series::merge_same_labelset`] gives the one series. #[test] fn a_merge_across_two_closed_series_is_the_root_piece_stream() { let map_grid = grid(0, 60_000, 2); @@ -4979,9 +4611,6 @@ fn merge_canonicalizes_complementary_series_and_flushes_only_at_eof() { } /// A table of `wide`- and `wider`-bucket histograms, so two samples of one field differ in payload. -/// -/// The payload is what a merge can lose and still answer the right positions, so every test below -/// names the histogram it expects rather than only counting rows. fn two_sized_histograms() -> (Arc, u32, u32) { let mut builder = HistogramBatchBuilder::new(); let wide = push_histogram(&mut builder, 2); @@ -5014,13 +4643,8 @@ fn histogram_rows(chunk: &EvaluatedChunk) -> Vec<(usize, f64, usize)> { .collect() } -/// Native histogram frames merge by position across the canonical merge, payload and all. -/// -/// This is the merge a metadata drop over a nullable key pays for: one label set arrives as two -/// pieces from the same partition, each holding some of its positions, and what comes out is one -/// series with one histogram per position, each still carrying the payload it was pushed with. A -/// position neither piece holds stays a hole, and the merge owes nothing until its input ends - the -/// closing chunk it answers with is the merged series. +/// Histogram pieces of one label set merge by position with their payloads; a position neither +/// holds stays a hole, and nothing is answered before the input ends. #[test] fn merge_canonicalizes_complementary_histogram_pieces_and_flushes_only_at_eof() { let grid = grid(0, 1, 4); @@ -5065,57 +4689,8 @@ fn merge_canonicalizes_complementary_histogram_pieces_and_flushes_only_at_eof() assert!(execution.next_chunk().unwrap().is_none()); } -/// Two pieces 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, and the histogram -/// payload changes nothing about it: the check reads whether a sample is there, not what it holds. -#[test] -fn a_histogram_merge_rejects_a_position_two_pieces_hold() { - let grid = grid(0, 1, 4); - let tree = NativeTree::try_new(merge(evaluated_input(Arc::clone(&grid)))).unwrap(); - let schema = evaluated_schema(Arc::clone(&grid)); - let label = named_metric("same", "x"); - let (table, wide, wider) = two_sized_histograms(); - let mut execution = executor(&tree, pool()); - for (start, index) in [(0, wide), (0, wider)] { - execution - .push_evaluated( - InputId::new(0), - evaluated_histogram_chunk_of( - &schema, - label.clone(), - start, - vec![None, Some(index)], - &table, - true, - ), - ) - .unwrap(); - } - execution.end_of_input().unwrap(); - let error = match execution.next_chunk() { - Ok(None) => panic!("the merge settled nothing at all"), - Ok(Some(chunk)) => panic!( - "a histogram position two pieces held was handed on: {:?}", - histogram_rows(&chunk) - ), - Err(error) => error, - }; - let message = error.to_string(); - assert!( - message.contains("vector cannot contain metrics with the same labelset"), - "the rejection does not name the shared label set: {message}" - ); -} - -/// A float-producing histogram function above the canonical merge reduces what the merge collected. -/// -/// `histogram_count(rate(h[5m]))` is this shape: the window below it answers histograms, the drop it -/// makes over a nullable key is collected into a merge carrying those frames, and the map above the -/// merge answers one float per histogram it reads. The merge is what proves the frames crossed the -/// boundary intact - a count of a lost payload would not be the count the piece was pushed with - and -/// the map above it drops the positions holding nothing. +/// `histogram_count` over a merge of histogram pieces counts the payloads the pieces were pushed +/// with. #[test] fn a_float_producing_histogram_map_reduces_the_histograms_a_merge_collected() { let grid = grid(0, 1, 4); @@ -5176,11 +4751,6 @@ fn a_float_producing_histogram_map_reduces_the_histograms_a_merge_collected() { } /// A parent reads a merge's answer only once the merge has flushed. -/// -/// `Merge` is the only node that answers nothing until its input ends, so a parent that treats it -/// as settled would compute over an empty vector. The tree here is the shape that exposes it: two -/// merges over complementary pieces of one label set, combined by a binary operation. Each side -/// answers 3 once merged, and the parent answers only at EOF. #[test] fn a_parent_of_a_merge_waits_for_the_flush() { let grid = grid(0, 1, 4); @@ -5455,9 +5025,8 @@ fn standalone_merge_collection_budget_failure_releases_input_and_stops() { vec![Some(1.0), None], true, ); - // The input queue is drained before collection grows the merge buffer. The budget is what the - // queue charges -- read where the pool admits anything -- so it admits that entry and leaves - // nothing for the fragment the collector retains. + // A budget of exactly what the queue charges, measured on an unbounded pool, leaves nothing for + // the fragment the collector retains. let queued = { let mut probe = executor(&tree, pool()); probe @@ -5501,9 +5070,8 @@ fn standalone_merge_flush_budget_failure_releases_fragments_and_stops() { vec![Some(1.0), None], true, ); - // What the collector holds once it has absorbed the queued fragment, read where the pool admits - // anything: a budget of exactly that admits the collection and leaves nothing for the flush's - // workspace. + // A budget of exactly what the collector holds, measured on an unbounded pool, leaves nothing + // for the flush workspace. let collected = { let mut probe = executor(&tree, pool()); probe @@ -5569,116 +5137,8 @@ fn standalone_merge_partial_drain_and_drop_release_queued_output() { assert_eq!(pool.reserved(), 0); } -#[test] -fn merge_rejects_overlapping_occupancy() { - let grid = grid(0, 1, 2); - let tree = NativeTree::try_new(merge(evaluated_input(Arc::clone(&grid)))).unwrap(); - let schema = evaluated_schema(Arc::clone(&grid)); - let mut execution = executor(&tree, pool()); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of( - &schema, - named_metric("same", "x"), - 0, - vec![Some(f64::NAN), None], - true, - ), - ) - .unwrap(); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of( - &schema, - named_metric("same", "x"), - 0, - vec![Some(1.0), None], - true, - ), - ) - .unwrap(); - execution.end_of_input().unwrap(); - assert!( - execution.next_chunk().is_err(), - "NaN occupancy overlap was accepted" - ); -} - -/// Two open chunks that share a label set are handed on as they arrive. -/// -/// `a{job="x"}` and `b{job="x"}` are two series to the input and one label set to `abs`, which -/// drops the name. Neither piece says it is the last chunk of its series, so the second one arrives -/// while the first is still open. The two occupy disjoint positions of field 0 — a value at 0 and a -/// value at 3 — so nothing about their labels is decided here: a map passes each chunk through as it -/// arrives, and combining two pieces of one label set is -/// [`crate::grid_series::merge_same_labelset`]'s job, which the merge a consumer reads them through -/// performs. A pair holding a value at the same position is what that merge refuses, not this -/// layer. -#[test] -fn two_open_series_that_share_a_label_set_are_accepted_when_no_position_collides() { - let map_grid = grid(0, 60_000, 4); - let tree = NativeTree::try_new(map( - evaluated_input_with_ordering(Arc::clone(&map_grid), SeriesOrdering::Contiguous), - vec![MathOp::Abs], - )) - .expect("a map-only tree is legal over a contiguous input"); - let schema = evaluated_schema(Arc::clone(&map_grid)); - - let mut execution = executor(&tree, pool()); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of( - &schema, - named_metric("a", "x"), - 0, - vec![Some(-1.0), None], - false, - ), - ) - .unwrap(); - let first = execution - .next_chunk() - .unwrap() - .expect("the first open chunk is handed on as it arrives"); - assert_eq!(sample_values(&first), vec![Some(1.0), None]); - assert_eq!(series_start(&first), 0); - - // Positions 2 and 3 of field 0, holding a value at 3 only: no position of the field is - // occupied twice, so nothing the check looks at is claimed by both series. - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of( - &schema, - named_metric("b", "x"), - 2, - vec![None, Some(-3.0)], - false, - ), - ) - .unwrap(); - let second = execution - .next_chunk() - .unwrap_or_else(|error| panic!("the second open chunk was refused: {error}")) - .expect("the second open chunk is handed on too"); - assert_eq!(sample_values(&second), vec![None, Some(3.0)]); - assert_eq!(series_start(&second), 2); - assert!( - execution.next_chunk().unwrap().is_none(), - "the map handed on more than the two chunks it was given" - ); -} - -/// A `NaN` is a value and a missing sample is not, so only the `NaN` occupies its position. -/// -/// `abs` drops the metric name, so the two series below are one label set to the map, and the merge -/// above it is where the two are read against each other. A position holding no sample is a -/// position the series never claimed, and another series may fill it; a position holding a `NaN` is -/// decided and holds a value, like any other, so a second value there is the collision no merge -/// resolves. +/// A missing sample leaves its position free for another piece of the label set; a `NaN` occupies +/// it. #[test] fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { let map_grid = grid(0, 60_000, 1); @@ -5700,9 +5160,8 @@ fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { (vec![Some(1.0)], vec![None], true), (vec![None], vec![Some(f64::NAN)], true), ]; - // Each chunk is a whole source series that closes itself, so the merge reads the two as two - // pieces of one label set rather than as one series' runs. It holds both until the input ends - // and only then answers or refuses the pair. + // Each chunk closes its own source series, so the merge reads them as two pieces of one label + // set. for (first, second, accepted) in cases { let mut execution = executor(&tree(), pool()); execution @@ -5728,13 +5187,8 @@ fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { } } -/// One series arriving in pieces is not two series: the pieces are merged into the one series they -/// are, and the window above reports it once. -/// -/// The map is passed twice for one label set, so the window above collects both pieces and merges -/// them with [`crate::grid_series::merge_same_labelset`] before it evaluates: the two pieces hold -/// one position each, the window across them needs both, and answering per piece would close the -/// first series in the evaluator before the second arrived. +/// Two pieces of one series, one position each, are merged before the window above evaluates, so +/// the window across both answers once. #[test] fn a_series_that_continues_where_it_ended_is_not_a_second_series() { let inner_grid = grid(0, 60_000, 4); @@ -5791,14 +5245,8 @@ fn a_series_that_continues_where_it_ended_is_not_a_second_series() { assert!(out.last().unwrap().is_last); } -/// A window reserves what it retains, not what it has consumed. -/// -/// A long series is fed one sample per chunk to a pool with a fixed budget, pulling and dropping the -/// result of every chunk and closing only on the last one. The same one-sample-per-chunk input -/// leaves the evaluator's storage at the same size however many chunks it arrives in, so the peak -/// reservation is the same whether the data is split into 64 chunks or into 1024, and it stays a -/// small constant rather than the running total of what arrived. A figure charged per chunk -/// consumed would grow with the chunk count and exhaust the budget the first chunks fit in. +/// A window reserves what it retains, not what it consumed: the peak is the same for 64 one-sample +/// chunks as for 1024. #[test] fn a_window_reserves_what_it_retains_not_what_it_consumed() { // A 1 ms window on a 1 ms grid, so every chunk's sample is out of the window of the next one. @@ -5859,12 +5307,8 @@ fn a_window_reserves_what_it_retains_not_what_it_consumed() { ); } -/// A window's retention is per field, as the evaluator's storage is. -/// -/// The same one-sample-per-chunk input goes to a window over one float field, over two and over -/// three. Every field costs its own timestamps, values and row slot, so the reservation a window -/// reaches grows with the width of the series; a figure counting one timestamp and one float per -/// row, or one field per series, would not. +/// Every field costs its own timestamps, values and row slot, so a window's peak grows with the +/// series width. #[test] fn a_window_retains_the_samples_of_every_field() { // The most the window ever retained, over the same input and the same short window. @@ -5903,13 +5347,8 @@ fn a_window_retains_the_samples_of_every_field() { ); } -/// A window cannot run over an interleaved input, and the runtime says so before reading a chunk. -/// -/// The binding refuses a window whose own input declares the ordering, and the runtime refuses the -/// ordering itself -- which is what catches a window over a map over the source, where the binding -/// only sees the map. A tree with no window above the source is refused by the same check, since -/// every node here reads one series at a time; [`an_interleaved_input_is_refused_without_a_window`] -/// is that case on its own. +/// The binding refuses a window directly over an interleaved input. A map in between hides the +/// ordering from the binding, so the runtime refuses it before reading a chunk. #[test] fn a_window_over_an_interleaved_input_is_rejected() { let inner_grid = grid(0, 60_000, 2); @@ -5921,19 +5360,15 @@ fn a_window_over_an_interleaved_input_is_rejected() { Some(Arc::clone(&inner_grid)), Arc::clone(&outer_grid), )); - // A window directly over an interleaved source is rejected when the tree is bound: the - // binding is where the ordering is known, and refusing there fails before a chunk is read. + // Bound directly, the window is refused by the binding. let error = tree.expect_err("a window over an interleaved input must not bind"); - // A rejected tree is a compiler defect rather than a query error, so the binding reports it as - // `Internal`; what this pins is that the refusal names the ordering it came from rather than - // the node kind, since the same check refuses every input that declares it. + // The binding reports a rejected tree as `Internal`: it is a compiler defect, not a query + // error. assert!(matches!(error, DataFusionError::Internal(_)), "{error}"); let message = error.to_string(); assert!(message.contains("interleaved"), "{message}"); - // A map between them is not caught by the binding, which only looks at a window's own input: - // the map passes chunks through in the order they arrive, so the window still reads an - // interleaved stream. That is what this runtime checks for itself. + // A map in between hides the ordering from the binding. let tree = NativeTree::try_new(window_with( map( evaluated_input_with_ordering(Arc::clone(&inner_grid), SeriesOrdering::Interleaved), @@ -5957,14 +5392,8 @@ fn a_window_over_an_interleaved_input_is_rejected() { assert!(message.contains("Interleaved"), "{message}"); } -/// An interleaved input is refused with no window above it to notice it. -/// -/// A map over an input has no evaluator, so nothing in the tree reads one series to its `is_last`. -/// The sequence the input node cannot tell from a whole one is `a{job="x"}` open, `b{job="y"}` -/// closed, and the end of the input: the flag that reports a series left open would say the last -/// chunk closed its series and `finish` would accept an input whose first series never closed. The -/// runtime therefore refuses the ordering when the state is built, before a chunk is read, instead -/// of reporting a truncation it cannot see. +/// A map over an interleaved input has no evaluator to notice a series left open, so the runtime +/// refuses the ordering when the state is built. #[test] fn an_interleaved_input_is_refused_without_a_window() { let map_grid = grid(0, 60_000, 2); @@ -5985,187 +5414,8 @@ fn an_interleaved_input_is_refused_without_a_window() { assert!(message.contains("Interleaved"), "{message}"); } -/// A selection over an interleaved input is refused when the tree is bound, before it can run. -/// -/// The binding is where the ordering is known, and the plan's `Instant` arm refuses an input that -/// declares `Interleaved` for the reason the window arm does: a selection's consumer collects one -/// series' chunks into one buffer, so it reads a series to its last chunk before the next. Nothing -/// about an interleaved input is therefore left to the runtime along a selection, and the tree -/// never reaches [`NativeExecutionState::try_new`]. The ordering check there stays for the shape -/// the binding cannot see through: it only looks at a window's own input, so a window over a map -/// over the source still reads an interleaved stream, which is -/// [`a_window_over_an_interleaved_input_is_rejected`]. The shape with a map above the selection is -/// [`an_interleaved_input_is_refused_under_a_map_over_a_selection`]. -#[test] -fn an_interleaved_input_is_refused_under_a_selection() { - let out_grid = grid(0, 60_000, 2); - let error = NativeTree::try_new(instant( - raw_input_with_ordering(SeriesOrdering::Interleaved), - 60_000, - 0, - Arc::clone(&out_grid), - )) - .expect_err("a selection over an interleaved input must not bind"); - // A rejected tree is a compiler defect rather than a query error, so the binding reports it as - // `Internal`; what this pins is that the refusal names the ordering it came from, since the - // same check refuses a window over the same input. - assert!(matches!(error, DataFusionError::Internal(_)), "{error}"); - let message = error.to_string(); - assert!( - message.contains("interleaved chunks cannot be fed to it"), - "{message}" - ); -} - -/// The same refusal with a map above the selection. -/// -/// The tree here is `Input -> Instant -> Map`: the map sits above the selection, and the selection -/// reads the interleaved input directly. A map between the input and the selection is not a tree -/// this compiler can build at all -- a `Map` produces an evaluated vector while an instant -/// selection requires raw samples, and the plan's `Instant` arm rejects evaluated values -- so what -/// this test pins is the recursion: `validate` descends through the outer map to the selection -/// below it, whose own arm then refuses the input it reads, and the tree is refused at the same -/// point as [`an_interleaved_input_is_refused_under_a_selection`]. -#[test] -fn an_interleaved_input_is_refused_under_a_map_over_a_selection() { - let out_grid = grid(0, 60_000, 2); - let error = NativeTree::try_new(map( - instant( - raw_input_with_ordering(SeriesOrdering::Interleaved), - 60_000, - 0, - Arc::clone(&out_grid), - ), - vec![MathOp::Abs], - )) - .expect_err("a map over a selection over an interleaved input must not bind"); - assert!(matches!(error, DataFusionError::Internal(_)), "{error}"); - let message = error.to_string(); - assert!( - message.contains("interleaved chunks cannot be fed to it"), - "{message}" - ); -} - -/// A series that produced values under a label set, followed by one that produced none under the -/// same label set, is not a collision: the second contributes no sample, so the answer is just the -/// first one's values. -/// -/// This is the other order of [`two_series_with_no_result_do_not_collide`]: a series that produced -/// values under a label set, followed by one that produced none. The empty one occupies no -/// position, so it records nothing and changes nothing, and the answer is the first one's values. -/// -/// The first series closed, which closes the source series and not the label set: the empty series -/// is a later one that also answers empty, and -/// [`an_empty_closing_chunk_of_another_series_does_not_close_a_label_set`] is its mirror image. -#[test] -fn a_series_with_no_result_after_a_closed_one_is_passed_over() { - let map_grid = grid(0, 60_000, 1); - let tree = NativeTree::try_new(map( - evaluated_input(Arc::clone(&map_grid)), - vec![MathOp::Abs], - )) - .unwrap(); - let schema = evaluated_schema(Arc::clone(&map_grid)); - let mut execution = executor(&tree, pool()); - - // `abs` drops the name, so both series arrive under the same label set. The first holds a - // value; the second holds none at all and has to be passed over rather than refused. - for (name, values) in [("a", vec![Some(-7.0)]), ("b", vec![None])] { - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of(&schema, named_metric(name, "x"), 0, values, true), - ) - .unwrap(); - } - - let mut handed = Vec::new(); - loop { - match execution.next_chunk() { - Ok(Some(chunk)) => handed.push(decided(&[chunk])), - Ok(None) => break, - Err(error) => panic!("an empty series after a closed one was refused: {error}"), - } - } - assert!( - handed - .iter() - .flatten() - .any(|(_, value)| *value == Some(7.0)), - "the first series' value is missing: {handed:?}" - ); -} - -/// An empty closing chunk of one series does not close a label set another series is still filling. -/// -/// `abs` drops the metric name, so `a{job="x"}` and `b{job="x"}` are one label set to the map. `b` -/// holds no row at all: its closing chunk closes a series that contributed nothing, so it must not -/// close the set `a` opened, or `a`'s continuation would be refused for a label set that `a` itself -/// never closed. Two series back to back are what contiguous input hands over, so this is a stream -/// the runtime executes rather than an ordering it refuses. -#[test] -fn an_empty_closing_chunk_of_another_series_does_not_close_a_label_set() { - let map_grid = grid(0, 60_000, 2); - let tree = NativeTree::try_new(map( - evaluated_input(Arc::clone(&map_grid)), - vec![MathOp::Abs], - )) - .unwrap(); - let schema = evaluated_schema(Arc::clone(&map_grid)); - let mut execution = executor(&tree, pool()); - - // `a` opens the label set and has not closed it when `b` closes an empty series onto it, and the - // chunk that closes `a` itself comes last. - let chunks = [ - evaluated_chunk_of(&schema, named_metric("a", "x"), 0, vec![Some(-1.0)], false), - evaluated_chunk_of(&schema, named_metric("b", "x"), 0, vec![], true), - evaluated_chunk_of(&schema, named_metric("a", "x"), 1, vec![Some(-2.0)], true), - ]; - let steps = chunks.len(); - let mut handed = Vec::new(); - for (step, chunk) in chunks.into_iter().enumerate() { - execution.push_evaluated(InputId::new(0), chunk).unwrap(); - while let Some(chunk) = execution - .next_chunk() - .unwrap_or_else(|error| panic!("step {step} was refused: {error}")) - { - handed.push(chunk); - } - } - assert_eq!( - handed.len(), - steps, - "the map did not consume all {steps} chunks it was given: {:?}", - decided(&handed) - ); - let last = handed.last().expect("the map handed nothing on"); - assert!(last.is_last, "the final output does not close its series"); - // `abs` drops the metric name, so the label set the output closes is `{job="x"}`. - let mut mapped = named_metric("a", "x"); - mapped.remove("__name__"); - assert_eq!( - last.series.metric, mapped, - "the final output closes a label set other than the one `abs` leaves of `a{{job=\"x\"}}`" - ); - assert_eq!( - (series_start(last), sample_values(last)), - (1, vec![Some(2.0)]), - "the value `a` held at position 1 did not survive" - ); - assert!( - execution.finish().unwrap().is_empty(), - "the map still held a chunk when the input ended" - ); -} - -/// Two series that each produce no value at all are not a collision: both answer empty, and the -/// node hands nothing on rather than refusing the second one. -/// -/// `rate` over a five-minute window with one sample in it has no result, in the single-point and -/// the batch kernel alike. Both series then arrive as a closing chunk of missing values under the -/// same label set -- `rate` drops the name -- but neither holds a sample, so there is nothing to -/// report twice and nothing to merge. +/// `rate` over a single sample has no result, so two series that share a label set once the name is +/// dropped answer nothing and do not collide. #[test] fn two_series_with_no_result_do_not_collide() { let out = grid(0, 60_000, 1); @@ -6210,11 +5460,8 @@ fn two_series_with_no_result_do_not_collide() { ); } -/// A chunk of `metric` whose rows are the `spans` of `schema`'s grid, with `values` row by row. -/// -/// This is what a producer that decided only some positions hands over: the rows are absolute grid -/// positions and need not be adjacent, so a consumer that reads them as `start + row` names -/// positions the chunk does not hold. +/// A chunk of `metric` whose rows are the `spans` of `schema`'s grid, with `values` row by row. The +/// spans need not be adjacent, so `start + row` is not a position. fn sparse_chunk( schema: &SeriesSchema, metric: SeriesLabels, @@ -6293,56 +5540,9 @@ fn a_sparse_chunk_is_read_at_the_positions_it_holds_through_window_map_window() assert_eq!(out.iter().filter(|chunk| chunk.is_last).count(), 1); } -#[test] -fn a_sparse_chunk_occupies_only_the_positions_it_holds() { - let map_grid = grid(0, 60_000, 8); - let tree = NativeTree::try_new(map( - evaluated_input(Arc::clone(&map_grid)), - vec![MathOp::Abs], - )) - .unwrap(); - let schema = evaluated_schema(Arc::clone(&map_grid)); - - let mut execution = executor(&tree, pool()); - // Series a holds positions 0, 1 and 5, 6: two runs with a hole in the middle, not one run - // covering the hole. - execution - .push_evaluated( - InputId::new(0), - sparse_chunk( - &schema, - named_metric("a", "x"), - &[(0, 2), (5, 2)], - vec![-1.0, -2.0, -3.0, -4.0], - false, - ), - ) - .unwrap(); - execution - .next_chunk() - .unwrap() - .expect("the first open chunk is handed on as it arrives"); - - // Position 2 sits in the hole, so series b occupies it and collides with nothing a holds. - execution - .push_evaluated( - InputId::new(0), - sparse_chunk(&schema, named_metric("b", "x"), &[(2, 1)], vec![-5.0], true), - ) - .unwrap(); - execution - .next_chunk() - .unwrap_or_else(|error| panic!("the series in the hole was refused: {error}")) - .expect("the second series is handed on"); -} - -/// What an operation that empties every position hands on: nothing while the series is open, and -/// one empty chunk when it closes. -/// -/// The two are not interchangeable. A non-closing empty chunk is rejected by a downstream evaluator -/// (an empty delivery inside a series decides nothing), and dropping the closing one would leave -/// the consumer unable to tell "nothing more here" from "no more input", so the series would never -/// close and `finish` would report an input that ended mid-series. +/// An emptying operation hands on nothing while the series is open and one empty chunk when it +/// closes: a downstream evaluator refuses an empty non-closing delivery, and without the closing +/// one the series would never close. #[test] fn an_emptying_operation_hands_on_nothing_until_it_closes_the_series() { let inner_grid = grid(0, 60_000, 4); @@ -6403,14 +5603,8 @@ fn an_emptying_operation_hands_on_nothing_until_it_closes_the_series() { assert!(out.last().unwrap().is_last); } -/// A tree with no window reports an input that ended mid-series as a truncated input. -/// -/// A window's evaluator is what knows a series has not closed: it holds the series until the chunk -/// carrying `is_last`, so closing the execution over what is left reports the input that never -/// delivered it. A tree of an input alone, or of a map over one, has no evaluator at all, so -/// without the input node saying so the series would reach the consumer open and never close. The -/// input node is the only place that sees every chunk the caller queued, so the truncation is -/// reported against it, for a tree of one node and for one with a map above it alike. +/// Without a window, the input node is the only one that sees a series left open, so it reports the +/// truncation, for an input alone and under a map. #[test] fn an_input_that_ends_mid_series_is_reported_without_a_window() { let map_grid = grid(0, 60_000, 2); @@ -6453,12 +5647,8 @@ fn an_input_that_ends_mid_series_is_reported_without_a_window() { } } -/// A window over native histograms reserves what it retains, payload included. -/// -/// A chunk is estimated from the samples it holds rather than from one float per field and row, so a -/// histogram field -- which holds no float at all -- reaches the figure as the table its indices point -/// into. A window over such a series therefore reserves for the payload it keeps, and a one-sample -/// histogram chunk is worth more than a one-sample float chunk of the same shape. +/// A histogram field is estimated by the table its indices point into, so a window over histograms +/// reserves the payload it keeps. #[test] fn a_window_over_histograms_reserves_what_it_retains() { let out = grid(0, 10_000, 2); @@ -6506,12 +5696,8 @@ fn a_window_over_histograms_reserves_what_it_retains() { ); } -/// A source reserves the estimate of every queued chunk, and gives each one back as it leaves. -/// -/// The figure is symmetric: what a chunk added when it entered is what comes out when it leaves, so a -/// queue that empties returns its reservation to the pool exactly. Two chunks of one series may share -/// one immutable histogram table, and each of them is charged for it: the estimate is per chunk, which -/// costs a bounded over-count of a shared table rather than a pass over the queue per operation. +/// A source charges each queued chunk's estimate and gives exactly that back as the chunk leaves. +/// Two chunks sharing a histogram table are each charged for it. #[test] fn a_source_charges_its_queue_and_gives_it_back() { let pool = pool(); @@ -6563,11 +5749,7 @@ fn a_source_charges_its_queue_and_gives_it_back() { assert!(source.pop_source().unwrap().is_none()); } -/// Dropping a node drops its queue and returns the reservation once. -/// -/// A node stopped with chunks still queued holds nothing afterwards: the queue goes, and the bytes it -/// was reserved for go back to the pool rather than staying held for as long as the caller keeps the -/// stopped executor alive. +/// Dropping a node with chunks still queued releases its queue's reservation once. #[test] fn dropping_a_node_drops_its_queue() { let pool = pool(); @@ -6593,12 +5775,8 @@ fn dropping_a_node_drops_its_queue() { assert!(gauge(&metrics, "native.p0.source.peak_reserved_bytes") > 0); } -/// A bare selector stamps the last sample at or before each grid point onto its own grid. -/// -/// The chunk is addressed on the node's output grid, not on the source's timestamps; a grid point -/// may select a row an earlier point already did (the point after the last sample repeats it); and -/// the same samples delivered as one chunk and as three answer the same, because the selection reads -/// a whole axis rather than a chunk. +/// The selection is addressed on the node's output grid, a later point may repeat an earlier +/// point's row, and one chunk or three answer the same. #[test] fn a_bare_selector_selects_instants_onto_its_own_grid() { let out_grid = grid(0, 60_000, 4); @@ -6665,79 +5843,6 @@ fn a_bare_selector_selects_instants_onto_its_own_grid() { ); } -/// The lookback edge is exclusive: a sample exactly `lookback_ms` before a grid point is not -/// selected, one millisecond later is. -/// -/// This pins what the selection kernel does rather than what Prometheus' documentation suggests: a -/// sample at the point itself is always selected, and the window is `(point - lookback, point]`. -#[test] -fn a_sample_at_the_lookback_edge_is_not_selected() { - // The statement's grid is the single point 1000ms, and the lookback is 200ms. - let out_grid = grid(1000, 100, 1); - let schema = raw_schema(); - let selected = |timestamp: i64| { - let tree = NativeTree::try_new(instant(input(), 200, 0, Arc::clone(&out_grid))).unwrap(); - let mut execution = executor(&tree, pool()); - execution - .push_raw( - InputId::new(0), - raw_chunk(&schema, &[timestamp], &[1.0], true), - ) - .unwrap(); - run(&mut execution) - }; - - // 800 is exactly `1000 - 200`, so the edge itself selects nothing. - let edge = selected(800); - assert_eq!(edge.len(), 1, "the series still closes on one chunk"); - assert!(edge[0].is_last); - assert!( - decided(&edge).is_empty(), - "a sample exactly at the lookback edge was selected: {:?}", - decided(&edge) - ); - // One millisecond inside the window is selected; a sample after the grid point never is. - assert_eq!(decided(&selected(801)), vec![(0, Some(1.0))]); - assert!(decided(&selected(1001)).is_empty()); -} - -/// A positive offset reads earlier samples, and a negative one later samples. -#[test] -fn an_offset_reads_a_different_sample_at_each_grid_point() { - let out_grid = grid(0, 60_000, 2); - let schema = raw_schema(); - let values = |offset_ms: i64| { - let tree = NativeTree::try_new(instant(input(), 600_000, offset_ms, Arc::clone(&out_grid))) - .unwrap(); - let mut execution = executor(&tree, pool()); - execution - .push_raw( - InputId::new(0), - raw_chunk(&schema, &[-60_000, 0, 60_000], &[1.0, 2.0, 3.0], true), - ) - .unwrap(); - decided(&run(&mut execution)) - }; - - assert_eq!( - values(0), - vec![(0, Some(2.0)), (1, Some(3.0))], - "without an offset a point reads the sample at or before it" - ); - assert_eq!( - values(60_000), - vec![(0, Some(1.0)), (1, Some(2.0))], - "a minute of offset did not read the samples a minute earlier" - ); - // A negative offset reads samples the statement's own range does not reach: both points read - // the sample one minute after them. - assert_eq!( - values(-60_000), - vec![(0, Some(3.0)), (1, Some(3.0))], - "a negative offset did not read the samples a minute later" - ); -} - /// A series that selects nothing still closes, exactly once, on a chunk that holds no row. #[test] fn a_series_with_no_selectable_sample_closes_once() { @@ -6822,11 +5927,8 @@ fn a_selected_row_keeps_the_fields_that_miss_it_null() { ); } -/// A grid position nobody fills is not a row, and a hole does not close the series early. -/// -/// The samples lie at the first and the last point of the grid with nothing in between, and the -/// lookback is too short to carry either one across: two rows, two runs, and no row per position -/// between them. +/// The samples sit at the grid's first and last points with a lookback too short to bridge them: +/// two rows, and the hole between them does not close the series. #[test] fn a_position_no_field_fills_is_not_a_row() { let out_grid = grid(0, 60_000, 5); @@ -6873,17 +5975,8 @@ fn a_position_no_field_fills_is_not_a_row() { ); } -/// An instant selection selects: the histogram it picks keeps its start timestamp. -/// -/// The sample is read, converted into the histogram type the builder writes back, and written out -/// again, and that type used to have no start timestamp to write: a sample carrying -/// `start_timestamp = Some(1500)` at 2000ms came out `None`. It matters downstream -- a reader -/// detects a counter reset from a start timestamp that falls inside the range it reads -- and it is -/// the difference between selecting a sample and computing a value. -/// -/// One source sample is selected by three grid points here, which is the case a per-row conversion -/// can get wrong twice: applied once and forgotten on the second use, or applied to a value that no -/// longer carries the timestamp. +/// A selected histogram keeps its start timestamp, which a reader uses to detect counter resets. +/// One sample selected by three grid points checks that every repeated row keeps it. #[test] fn a_selected_histogram_keeps_its_start_timestamp() { let out_grid = grid(2000, 1, 3); @@ -6906,11 +5999,8 @@ fn a_selected_histogram_keeps_its_start_timestamp() { ); } -/// Two series that differ only in an empty-valued label are two series, and both are answered. -/// -/// The label set a merge groups by drops empty values, so the two would be one set to a merge. A -/// selection keeps the labels it read, empty values included, so it hands the two on apart and -/// collects nothing. +/// A selection keeps empty-valued labels, so two series differing only in one are answered apart +/// and nothing is collected. #[test] fn two_series_differing_only_in_an_empty_label_are_both_answered() { let out_grid = grid(0, 60_000, 1); @@ -6939,17 +6029,8 @@ fn two_series_differing_only_in_an_empty_label_are_both_answered() { assert_eq!(decided(&out[1..]), vec![(0, Some(2.0))]); } -/// What a selection reserves is the series it has buffered, measured chunk by chunk. -/// -/// The node holds a whole series, so its reservation grows with the chunks that series arrived in -/// and goes back when the series is answered. Each chunk is measured once, with the same estimate a -/// queued chunk is charged with: an allocation two chunks share is counted once per chunk, which is -/// the over-count a figure that keeps no state across chunks accepts. -/// -/// What this checks is the buffer alone. The workspace the gather of that buffer allocates -- the -/// axis, the selection's two arrays and the rows the builder keeps -- is reserved for while it is -/// live and is not part of this figure, so this test cannot see it, however many bytes it is: -/// [`an_instant_selection_reserves_the_workspace_it_gathers`] is the one that does. +/// A selection reserves the series it buffers, chunk by chunk, with the queued-chunk estimate, and +/// releases it once the series is answered. The gather workspace is not part of this figure. #[test] fn an_instant_selection_reserves_the_series_it_buffers() { let out_grid = grid(0, 60_000, 4); @@ -6990,22 +6071,9 @@ fn an_instant_selection_reserves_the_series_it_buffers() { ); } -/// The workspace the gather allocates is reserved for before it exists. -/// -/// A selection decides the points of the grid it can be selected at, so its workspace is -/// proportional to those points rather than to the samples of the series: the axis it concatenates, -/// the source row and evaluation timestamp it reports per point, and the rows the builder keeps. -/// The lookback here reaches from the sample to the last point, so this series is decididable at -/// every one of the million points -- the clipped count equals the grid's -- and the two selection -/// arrays alone are 16 MB while the built rows are more, against a series the node holds of one -/// sample of a few hundred bytes. [`a_selection_reserves_the_points_it_decides`] is the other side -/// of the same figure: a series whose samples cover only the start of a long grid reserves for the -/// few points it can decide and is admitted by a pool this one is refused by. -/// -/// The pool here holds 8 KiB, which is enough for the buffered chunk and nothing near the -/// workspace, so the gather is refused instead of being performed. Nothing else refuses a million -/// points, so this is the reservation and not a point limit answering: without it the gather simply -/// runs. +/// The gather workspace scales with the points a series can be selected at, not with its samples: +/// one sample with a lookback covering a million points needs megabytes, and an 8 KiB pool refuses +/// the gather. No point limit applies, so the refusal is the reservation's. #[test] fn an_instant_selection_reserves_the_workspace_it_gathers() { let out_grid = grid(0, 1, 1_000_000); @@ -7300,18 +6368,8 @@ fn instant_candidate_span_covers_native_selection_at_boundaries() { /// A selection reserves the points it can decide, not the points the grid plans. /// -/// The review's shape: a seven-day grid at a one-minute step is 10,081 points, and one sample at -/// the start of the series read with a five-minute lookback is decided at five of them. The -/// grid-scaled terms of `InstantRuntime::gather_bytes` at the planned grid -- the selection's two -/// arrays and the doubled builder columns -- are about 504 KB, which the 64 KiB pool here is far -/// below; the handful of points really decided need a few hundred bytes, so this gather has to be -/// admitted. What it hands out is the rows `select_instants` reports for the same series, bounded -/// by the candidate count the reservation agrees with. -/// -/// The second half is the other direction: the same grid, the same pool, and a series that spans -/// the grid with a lookback long enough to cover it, so all 10,081 points can be decided. The -/// figure then exceeds the pool and the gather is refused, which is what keeps this from being a -/// reservation of nothing. +/// One sample on a 10,081-point grid with a five-minute lookback is decided at five points, so a +/// 64 KiB pool admits it; the same pool refuses a series whose lookback covers the whole grid. #[test] fn a_selection_reserves_the_points_it_decides() { let out_grid = grid(0, 60_000, 10_081); @@ -7384,54 +6442,7 @@ fn a_selection_reserves_the_points_it_decides() { assert_eq!(execution.state().reserved_bytes(), 0); } -/// A grid longer than any point limit is charged for, and the pool is what refuses it. -/// -/// `gather_bytes` used to return zero for a grid this long, so that a point limit inside the -/// kernel stayed the error reported and the workspace of a long gather was never reserved. The -/// estimate now applies to every gather, so the pool is asked before the kernel is and its refusal -/// is the one the caller sees — a bound in bytes, on the path that decides the points, rather than -/// a count that says nothing about what they cost. -#[test] -fn an_oversized_selection_is_refused_by_the_pool() { - // One million and two points over two samples: longer than the short circuit used to allow, - // so the estimate has to cover it rather than return zero. - let out_grid = grid(0, 1, 1_000_002); - let tree = NativeTree::try_new(instant(input(), 1_000_000, 0, out_grid)).unwrap(); - let pool = bounded_pool(8 * 1024); - let mut execution = executor(&tree, Arc::clone(&pool)); - let schema = raw_schema(); - execution - .push_raw( - InputId::new(0), - raw_chunk(&schema, &[0, 1_000_001], &[1.0, 2.0], true), - ) - .unwrap(); - - let error = execution.next_chunk().unwrap_err(); - assert!( - is_resources_exhausted(&error), - "the gather's workspace was taken without asking the pool: {error}" - ); - assert!( - !error.to_string().contains("exceed limit"), - "a point limit answered in the pool's place: {error}" - ); - // Nothing is dropped silently: the execution stops and gives its reservation back. - assert_eq!(pool.reserved(), 0); - assert_eq!(execution.state().reserved_bytes(), 0); - assert!(!root_holds(&execution, holds_instant)); - let again = execution.next_chunk().unwrap_err(); - assert!( - again.to_string().contains("stopped after an earlier error"), - "{again}" - ); -} - -/// An input that ends inside a series is an error, not an empty answer. -/// -/// The selection holds the series and gathers it only on the chunk that closes it, so nothing is -/// answered for it. The node that notices is the input: the chunk it handed over did not say -/// `is_last`, and the tree's close reports that before any collected input is merged. +/// An input that ends inside a series is an error reported by the input node, not an empty answer. #[test] fn an_input_that_ends_inside_a_series_is_reported() { let tree = NativeTree::try_new(instant(input(), 300_000, 0, grid(0, 60_000, 2))).unwrap(); @@ -7456,10 +6467,7 @@ fn an_input_that_ends_inside_a_series_is_reported() { ); } -/// A selection combines one series into one axis, so a chunk of another series is refused. -/// -/// The buffered chunks are read as one axis, so a chunk of a second series has nowhere to go: it -/// would be selected as though its samples were the open series'. +/// A selection reads its buffered chunks as one axis, so a chunk of another series is refused. #[test] fn a_chunk_of_another_series_is_refused() { let tree = NativeTree::try_new(instant(input(), 300_000, 0, grid(0, 60_000, 2))).unwrap(); @@ -7694,10 +6702,7 @@ fn evaluated_columns( } /// One evaluated chunk of `metric` addressed on `rows` positions from `start`, carrying `columns`. -/// -/// The axis and the columns are given independently so that a chunk whose two disagree can be built: -/// [`Series`] keeps its fields public, so nothing between a caller and a kernel refuses such a chunk -/// on its way in. +/// The two are independent so a chunk whose axis and fields disagree can be built. fn evaluated_on( schema: &SeriesSchema, metric: SeriesLabels, @@ -7768,7 +6773,7 @@ fn histogram_counts(chunk: &EvaluatedChunk) -> Vec { .collect() } -/// A source bound in label mode: `name{job="api",pod="a"}` and the other series here. +/// `name{job=..., pod=...}`. fn pod_metric(name: &str, job: &str, pod: &str) -> SeriesLabels { SeriesLabels::try_new( Some(name.into()), @@ -7786,24 +6791,6 @@ fn pod_metric(name: &str, job: &str, pod: &str) -> SeriesLabels { .unwrap() } -/// The one side of a `group_left` match: `one{job=...,instance=...}`. -fn one_metric(job: &str, instance: &str) -> SeriesLabels { - SeriesLabels::try_new( - Some("one".into()), - vec![ - Label { - name: "job".into(), - value: job.into(), - }, - Label { - name: "instance".into(), - value: instance.into(), - }, - ], - ) - .unwrap() -} - /// A tree of two evaluated sources over `points` points under a binary node, with the two paths a /// caller queues at. fn binary_tree(op: BinaryOp, points: u64) -> (NativeTree, Arc, InputId, InputId) { @@ -7865,35 +6852,8 @@ fn runtime_input_ids_route_repeated_and_distinct_source_indexes() { ); } -/// Two evaluated sources under a binary node add the series they match, point by point. -#[test] -fn a_binary_of_two_inputs_adds_the_matched_series() { - let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); - let schema = evaluated_schema(grid); - let mut execution = executor(&tree, pool()); - execution - .push_evaluated( - left, - evaluated_chunk(&schema, 0, vec![1.0, 2.0, 3.0, 4.0], true), - ) - .unwrap(); - execution - .push_evaluated( - right, - evaluated_chunk(&schema, 0, vec![10.0, 20.0, 30.0, 40.0], true), - ) - .unwrap(); - assert_eq!( - addressed(&run(&mut execution)), - vec![(0, vec![Some(11.0), Some(22.0), Some(33.0), Some(44.0)])] - ); -} - -/// Neither the order the sides arrive in nor the chunk boundaries of one side change the result. -/// -/// A binary node matches whole series, so the two deliveries below are the same vector: one splits -/// the right side over two chunks, the other queues the right side first. `is_last` is the only -/// thing that ends a series, so a chunk boundary carries no meaning of its own. +/// A binary node matches whole series, so neither arrival order nor one side's chunk boundaries +/// change the result. #[test] fn a_binary_result_does_not_depend_on_arrival_order_or_chunk_boundaries() { let (tree, grid, left, right) = binary_tree(BinaryOp::Sub, 4); @@ -7938,12 +6898,8 @@ fn a_binary_result_does_not_depend_on_arrival_order_or_chunk_boundaries() { assert_eq!(reversed, expected); } -/// Two series that arrive in separate chunks and hold a value at the same point are refused. -/// -/// Each chunk is a series of its own, closed by its own `is_last`, and the two claim one label set: -/// Prometheus reports the duplicate at the first point both are present at, which no chunk boundary -/// can resolve. Two such series whose positions do not meet are accepted instead, as -/// `a_sparse_binary_keeps_the_shared_positions` shows. +/// Two series of one label set, closed in separate chunks, that hold a value at the same point are +/// refused as a duplicate. #[test] fn a_cross_chunk_duplicate_on_one_side_is_refused() { let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); @@ -8014,7 +6970,6 @@ fn an_empty_closing_chunk_does_not_rewind_a_series() { assert_eq!(decided(&run(&mut execution)), vec![(0, Some(11.0))]); } -/// Two sparse operands meet at the positions both carry. #[test] fn a_sparse_binary_keeps_the_shared_positions() { let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); @@ -8084,8 +7039,7 @@ fn a_binary_pairs_the_fields_of_each_operand() { // Position 1 holds no left value of field 0, so that field keeps it null while field 1 has one. assert_eq!(field_values(&out[0], 0), vec![Some(11.0), None]); assert_eq!(field_values(&out[0], 1), vec![Some(12.0), Some(14.0)]); - // The result decided two positions and holds three values: the two positions are what the node - // evaluated, and a value is what a field sample holds, which is one fewer for the null. + // Two positions decided, three values: the null is not a value. assert_eq!( count(&metrics, "root", NodeMetric::EVALUATED_GRID_POINTS), 2 @@ -8093,155 +7047,6 @@ fn a_binary_pairs_the_fields_of_each_operand() { assert_eq!(count(&metrics, "root", NodeMetric::OUTPUT_VALUES), 3); } -/// A comparison without `bool` filters the points it does not hold at; with `bool` it reports both. -#[test] -fn a_comparison_filters_and_a_bool_comparison_reports_both_outcomes() { - let grid = grid(0, 60_000, 4); - let schema = evaluated_schema(Arc::clone(&grid)); - for (return_bool, expected) in [ - (false, vec![(2, Some(3.0)), (3, Some(4.0))]), - ( - true, - vec![ - (0, Some(0.0)), - (1, Some(0.0)), - (2, Some(1.0)), - (3, Some(1.0)), - ], - ), - ] { - let matching = BinaryMatching { - op: BinaryOp::Gt, - return_bool, - labels: MatchingLabels::Ignoring(Vec::new()), - cardinality: Cardinality::OneToOne, - fill: FillValues::default(), - }; - let root = binary_of( - evaluated_input_of(1, Arc::clone(&grid)), - evaluated_input_of(1, Arc::clone(&grid)), - matching, - ); - let tree = NativeTree::try_new(root).unwrap(); - let mut execution = executor(&tree, pool()); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk(&schema, 0, vec![1.0, 2.0, 3.0, 4.0], true), - ) - .unwrap(); - execution - .push_evaluated( - InputId::new(1), - evaluated_chunk(&schema, 0, vec![2.0, 2.0, 2.0, 2.0], true), - ) - .unwrap(); - assert_eq!( - decided(&run(&mut execution)), - expected, - "bool={return_bool}" - ); - } -} - -/// `group_left(instance)` keeps every many-side series and copies the label from its match. -#[test] -fn a_group_modifier_copies_the_one_side_label() { - let grid = grid(0, 60_000, 2); - let matching = BinaryMatching { - op: BinaryOp::Add, - return_bool: false, - labels: MatchingLabels::On(vec![Arc::from("job")]), - cardinality: Cardinality::ManyToOne(vec![Arc::from("instance")]), - fill: FillValues::default(), - }; - let root = binary_of( - evaluated_input_of(1, Arc::clone(&grid)), - evaluated_input_of(1, Arc::clone(&grid)), - matching, - ); - let tree = NativeTree::try_new(root).unwrap(); - let schema = evaluated_schema(Arc::clone(&grid)); - let (left, right) = (InputId::new(0), InputId::new(1)); - let mut execution = executor(&tree, pool()); - for (metric, values) in [ - (pod_metric("a", "api", "p1"), vec![Some(1.0), Some(2.0)]), - (pod_metric("b", "db", "p2"), vec![Some(3.0), Some(4.0)]), - ] { - execution - .push_evaluated(left, evaluated_chunk_of(&schema, metric, 0, values, true)) - .unwrap(); - } - for (metric, values) in [ - (one_metric("api", "i1"), vec![Some(10.0), Some(20.0)]), - (one_metric("db", "i2"), vec![Some(100.0), Some(200.0)]), - ] { - execution - .push_evaluated(right, evaluated_chunk_of(&schema, metric, 0, values, true)) - .unwrap(); - } - - // The result is compared as label sets, so the two series are sorted by the labels they carry: - // the value lists of `f64` have no total order, and none is needed here. - let mut results: Vec<_> = run(&mut execution) - .iter() - .map(|chunk| { - let mut tags: Vec<(String, String)> = chunk - .series - .metric - .tags() - .iter() - .map(|tag| (tag.name.to_string(), tag.value.to_string())) - .collect(); - tags.sort(); - (tags, sample_values(chunk)) - }) - .collect(); - results.sort_by(|left, right| left.0.cmp(&right.0)); - assert_eq!( - results, - vec![ - ( - vec![ - ("instance".to_string(), "i1".to_string()), - ("job".to_string(), "api".to_string()), - ("pod".to_string(), "p1".to_string()), - ], - vec![Some(11.0), Some(22.0)], - ), - ( - vec![ - ("instance".to_string(), "i2".to_string()), - ("job".to_string(), "db".to_string()), - ("pod".to_string(), "p2".to_string()), - ], - vec![Some(103.0), Some(204.0)], - ), - ] - ); -} - -/// Two native histograms are added bucket by bucket. -#[test] -fn a_binary_adds_the_native_histograms_of_both_sides() { - let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); - let schema = evaluated_schema(grid); - let mut execution = executor(&tree, pool()); - execution - .push_evaluated(left, evaluated_histograms(&schema, metric(), 0, 4, 2, true)) - .unwrap(); - execution - .push_evaluated( - right, - evaluated_histograms(&schema, metric(), 0, 4, 2, true), - ) - .unwrap(); - let out = run(&mut execution); - assert_eq!(out.len(), 1); - // Each side holds four buckets of one count at each point, so the sum counts eight. - assert_eq!(histogram_counts(&out[0]), vec![8.0, 8.0]); -} - /// The native vector matcher annotates only unsupported, present histogram pairs. #[test] fn binary_histogram_drop_info_respects_presence_and_duplicates() { @@ -8371,137 +7176,6 @@ fn binary_histogram_drop_info_respects_presence_and_duplicates() { assert_eq!(pool.reserved(), 0); } -/// A filled pair is a pair the operation is run on, so the native executor annotates the -/// unsupported histogram pairing a fill value made. -/// -/// `hist{job="a"}` has no `job="b"` counterpart, so `hist + on(job) fill_right(0) float` answers -/// every point of it with `histogram + 0`, the pairing Prometheus runs `doBinOp` on after it fills -/// a step. The Info it records is the wording the legacy planner states the same rule with, and a -/// pair the fill never forms at all carries nothing. -#[test] -fn binary_histogram_fill_reports_the_dropped_info() { - use common_query::promql_annotations::PromqlAnnotationCollector; - - let dropped = |symbol: &str| { - vec![format!( - "{symbol}: dropped native histogram samples because this binary operation is not supported for native histograms" - )] - }; - // `fill_right` answers a missing right-hand sample, so the histogram is the left operand and - // every point of it is the pair `histogram + 0`; `fill_left` answers a missing left-hand one, - // so the histogram is the right operand and the pair is `0 + histogram`. - for (fill, histogram_left) in [ - ( - FillValues { - lhs: None, - rhs: Some(0.0), - }, - true, - ), - ( - FillValues { - lhs: Some(0.0), - rhs: None, - }, - false, - ), - ] { - let grid = grid(0, 60_000, 2); - let mut matching = binary_matching(BinaryOp::Add); - matching.labels = MatchingLabels::On(vec![Arc::from("job")]); - matching.fill = fill; - let tree = NativeTree::try_new(binary_of( - evaluated_input_with_source_index(Arc::clone(&grid), 0), - evaluated_input_with_source_index(Arc::clone(&grid), 1), - matching, - )) - .unwrap(); - let schema = evaluated_schema(grid); - // The two sides carry different `job` labels, so nothing matches and the fill value is what - // every point of the histogram series pairs with. - let histogram = || evaluated_histograms(&schema, named_metric("hist", "a"), 0, 4, 2, true); - let float = || { - evaluated_chunk_of( - &schema, - named_metric("float", "b"), - 0, - vec![Some(2.0), Some(2.0)], - true, - ) - }; - let (left, right) = if histogram_left { - (histogram(), float()) - } else { - (float(), histogram()) - }; - let collector = PromqlAnnotationCollector::default(); - let pool = pool(); - let mut state = NativeExecutionState::try_new(&tree, Arc::clone(&pool), None).unwrap(); - state.set_annotations(Some(collector.clone())); - let mut execution = NativeExecutor::new(state); - execution.push_evaluated(InputId::new(0), left).unwrap(); - execution.push_evaluated(InputId::new(1), right).unwrap(); - let chunks = run(&mut execution); - assert!( - chunks.is_empty(), - "a dropped fill pair filed a row: {:?}", - chunks - .iter() - .map(|chunk| chunk.series.metric.clone()) - .collect::>() - ); - let mut warnings = Vec::new(); - let mut infos = Vec::new(); - collector.append_to(&mut warnings, &mut infos); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(infos, dropped("+"), "{fill:?}"); - assert_eq!(pool.reserved(), 0); - } - - // Without a fill modifier the two sides never pair, and a pair that was never formed produces - // no sample to drop. - let grid = grid(0, 60_000, 2); - let mut matching = binary_matching(BinaryOp::Add); - matching.labels = MatchingLabels::On(vec![Arc::from("job")]); - let tree = NativeTree::try_new(binary_of( - evaluated_input_with_source_index(Arc::clone(&grid), 0), - evaluated_input_with_source_index(Arc::clone(&grid), 1), - matching, - )) - .unwrap(); - let schema = evaluated_schema(grid); - let collector = PromqlAnnotationCollector::default(); - let pool = pool(); - let mut state = NativeExecutionState::try_new(&tree, Arc::clone(&pool), None).unwrap(); - state.set_annotations(Some(collector.clone())); - let mut execution = NativeExecutor::new(state); - execution - .push_evaluated( - InputId::new(0), - evaluated_histograms(&schema, named_metric("hist", "a"), 0, 4, 2, true), - ) - .unwrap(); - execution - .push_evaluated( - InputId::new(1), - evaluated_chunk_of( - &schema, - named_metric("float", "b"), - 0, - vec![Some(2.0), Some(2.0)], - true, - ), - ) - .unwrap(); - assert!(run(&mut execution).is_empty()); - let mut warnings = Vec::new(); - let mut infos = Vec::new(); - collector.append_to(&mut warnings, &mut infos); - assert!(warnings.is_empty(), "{warnings:?}"); - assert!(infos.is_empty(), "{infos:?}"); - assert_eq!(pool.reserved(), 0); -} - /// Matched histogram arithmetic: the payload it answers with, and the pairs its diagnostics drop. #[test] fn binary_histogram_add_sub_payload_and_diagnostics() { @@ -8834,82 +7508,8 @@ fn binary_histogram_add_sub_payload_and_diagnostics() { } } -/// Supported histogram scaling keeps the values, labels and grid in both operand orders. -#[test] -fn binary_histogram_scaling_preserves_payload_and_labels() { - for (op, histogram_left, expected) in [ - (BinaryOp::Mul, true, 8.0), - (BinaryOp::Mul, false, 8.0), - (BinaryOp::Div, true, 2.0), - ] { - let (tree, grid, left, right) = binary_tree(op, 2); - let schema = evaluated_schema(Arc::clone(&grid)); - let pool = pool(); - let mut execution = executor(&tree, Arc::clone(&pool)); - let histogram = evaluated_histograms(&schema, named_metric("hist", "a"), 0, 4, 2, true); - let float = evaluated_chunk_of( - &schema, - named_metric("float", "a"), - 0, - vec![Some(2.0); 2], - true, - ); - let (lhs, rhs) = if histogram_left { - (histogram, float) - } else { - (float, histogram) - }; - execution.push_evaluated(left, lhs).unwrap(); - execution.push_evaluated(right, rhs).unwrap(); - let chunks = run(&mut execution); - assert_eq!(chunks.len(), 1); - assert_eq!(histogram_counts(&chunks[0]), vec![expected; 2]); - let mut cursor = chunks[0].series.fields.as_slice()[0].cursor(); - for row in 0..2 { - let SampleRef::Histogram(histogram) = cursor.at(row).unwrap() else { - panic!("scaled sample is not a histogram"); - }; - assert_eq!(histogram.sum, expected); - let bucket = if op == BinaryOp::Mul { 2.0 } else { 0.5 }; - assert_eq!(histogram.positive.buckets, &[bucket; 4]); - } - assert_eq!( - chunks[0].series.time.timestamps().unwrap().as_ref(), - &grid.timestamps().unwrap()[..] - ); - assert_eq!(chunks[0].series.metric.get("job"), Some("a")); - assert_eq!(chunks[0].series.metric.name(), None); - assert_eq!(chunks[0].series.time.grid().unwrap().spec(), grid.spec()); - assert_eq!(pool.reserved(), 0); - } -} - -/// Nothing is decided before the input ends; `finish` is what hands the result over. -#[test] -fn a_binary_yields_nothing_until_the_input_finishes() { - let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); - let schema = evaluated_schema(grid); - let mut execution = executor(&tree, pool()); - execution - .push_evaluated(left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) - .unwrap(); - execution - .push_evaluated(right, evaluated_chunk(&schema, 0, vec![10.0, 20.0], true)) - .unwrap(); - assert!( - execution.next_chunk().unwrap().is_none(), - "a binary node answered before its input ended" - ); - assert_eq!( - addressed(&execution.finish().unwrap()), - vec![(0, vec![Some(11.0), Some(22.0)])] - ); -} - -/// A truncated operand is refused before the kernel is handed anything. -/// -/// The right side also carries a duplicate series, which the kernel would report: the truncation is -/// what comes back, so the kernel never ran over half a vector. +/// A truncated operand is refused before the kernel runs, so the duplicate the kernel would report +/// is never reached. #[test] fn a_truncated_operand_is_refused_before_the_kernel_runs() { let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); @@ -8962,11 +7562,8 @@ fn an_oversized_binary_workspace_is_refused_by_the_pool() { assert!(!root_holds(&execution, holds_binary)); } -/// A pool that cannot hold both operands refuses the second one, and the first is given back. -/// -/// Both chunks sit in their input's queue until the input ends, so the reservation covers them at -/// once: the second one is what the pool refuses, and stopping the execution returns what the first -/// one held. +/// Both chunks sit in their queues until the input ends, so a pool that cannot hold both refuses +/// the second and releases the first. #[test] fn an_oversized_binary_operand_is_refused_by_the_pool() { let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 100_000); @@ -8988,14 +7585,9 @@ fn an_oversized_binary_operand_is_refused_by_the_pool() { assert_eq!(execution.state().reserved_bytes(), 0); } -/// A binary operand reserves each chunk it retains before it retains it, and holds what those -/// chunks hold between them. -/// -/// The figure of a retained chunk is what its rows occupy rather than the allocation they are slices -/// of, so a series delivered in sibling slices of one batch is charged the batch's data once instead -/// of once per chunk: the two halves of a 40 000-row batch cost the 320 000 bytes of its samples and -/// not twice that. A chunk is also reserved for exactly what retaining it charges, so a reservation -/// made before the fact does not leave the operand holding more, or less, than the pool gave it. +/// A retained chunk is charged for the rows it occupies, not the allocation it slices: two halves +/// of one 40 000-row batch cost the batch's 320 000 bytes once. Retaining a chunk grows the operand +/// by exactly the figure reserved for it. #[test] fn a_binary_operand_reserves_what_it_retains() { let grid = grid(0, 60_000, 40_000); @@ -9005,9 +7597,7 @@ fn a_binary_operand_reserves_what_it_retains() { let second = evaluated_array_chunk_of(&schema, metric(), 20_000, batch.slice(20_000, 20_000), true); - // The two chunks are the halves of one 40 000-row float batch, so what the operand holds - // between them is that batch's data: 320 000 bytes of samples, however the rows are cut up. A - // figure that charged the whole allocation per chunk would hold 640 000 for the same rows. + // Two halves of one 40 000-row batch: 320 000 bytes of samples, not 640 000. let rows = 40_000 * std::mem::size_of::(); let descriptors = 4 * 1024; let pool = bounded_pool(rows + descriptors); @@ -9076,13 +7666,8 @@ fn a_binary_operand_reserves_what_it_retains() { } } -/// Two chunks that are first to reference a histogram table each are billed a table each. -/// -/// A histogram field's samples are a column of indices into a table, and the table is the bulk of -/// what such a chunk costs: the indices are four bytes a row where the table is thousands of bytes -/// of buckets. Two chunks of the same shape hold two tables, so each costs the other, and each -/// costs at least the table it holds -- a figure that charged the column of indices alone would -/// leave both tables outside everything the node reserves. +/// Two chunks that are each the first to reference a histogram table are each billed their table, +/// not just their column of indices. #[test] fn a_binary_operand_bills_each_histogram_table_it_retains() { const BUCKETS: i32 = 4_000; @@ -9142,11 +7727,6 @@ fn a_binary_operand_bills_each_histogram_table_it_retains() { } /// Two chunks that index one histogram table are billed that table once. -/// -/// A table is one allocation however many chunks of a series index into it, so the second chunk is -/// charged the descriptor, the index and the end it records, and not the table again. The two -/// chunks here are the same shape, so what separates their figures is the table: the pair costs one -/// table plus both chunks' own descriptors, not one table per chunk and not no table at all. #[test] fn a_binary_operand_bills_a_shared_histogram_table_once() { const BUCKETS: i32 = 4_000; @@ -9210,14 +7790,8 @@ fn a_binary_operand_bills_a_shared_histogram_table_once() { assert_eq!(pool.reserved(), state.buffer.reservation.size()); } -/// A pool with room for one histogram table admits one chunk of a table, refuses a second chunk -/// holding another table, and admits a second slice of the table it already holds. -/// -/// This is the figure the reservation is made for: a chunk that is the first to reference a table -/// costs that table, so two of them do not fit in room for one, while a chunk that indexes a table -/// the operand already holds costs its own slice and does. The room beside the first chunk is half a -/// table -- far more than the descriptors of a second chunk and far less than a second table -- and -/// the refused chunk leaves the operand where it was. +/// With room for one table and half another, a chunk of a second table is refused, while a second +/// slice of the held table is admitted. #[test] fn a_pool_that_holds_one_histogram_table_refuses_a_second() { const BUCKETS: i32 = 4_000; @@ -9287,13 +7861,9 @@ fn a_pool_that_holds_one_histogram_table_refuses_a_second() { ); } -/// The executor's binary node holds no more than the operands it retains: the peak of its own -/// reservation is the data the retained chunks hold between them -- the thirty-two thousand bytes of -/// one 4 000-row float batch, whichever way the batch is sliced -- and not a second copy of it. -/// -/// The source queue holds one chunk while the node retains the other, so what is read here is the -/// binary node's own figure rather than the pool's: the overlap of the two nodes is a charge of the -/// input and says nothing about what the operand costs. +/// The executor's binary node reserves one copy of what it retains: two halves of one 4 000-row +/// batch peak at 32 000 bytes. The node's own gauge is read, since the source queue holds the other +/// half. #[test] fn a_binary_beneath_the_executor_reserves_what_it_retains() { let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4_000); @@ -9302,9 +7872,7 @@ fn a_binary_beneath_the_executor_reserves_what_it_retains() { let first = evaluated_array_chunk_of(&schema, metric(), 0, batch.slice(0, 2_000), false); let second = evaluated_array_chunk_of(&schema, metric(), 2_000, batch.slice(2_000, 2_000), true); - // Both chunks are halves of one 4 000-row float batch, so what the node holds once it retains - // them is that batch's data: 32 000 bytes of samples. A figure that charged the allocation per - // chunk would hold the same rows twice. + // Two halves of one 4 000-row batch: 32 000 bytes of samples, not twice that. let retained = 4_000 * std::mem::size_of::(); let descriptors = 4 * 1024; @@ -9338,14 +7906,8 @@ fn a_binary_beneath_the_executor_reserves_what_it_retains() { ); } -/// A query rooted at a binary node streams its answer after the input ends, one chunk per pull. -/// -/// The kernel needs both whole vectors before it answers anything, so nothing is settled until the -/// caller ends the input. From there the answer is not handed over as one collected value: each pull -/// takes the next chunk out of the node that holds it and gives back what that chunk was charged, -/// and the pull that finds nothing left is where the execution closes. A caller that stops pulling -/// early therefore still holds nothing it did not ask for, and the pool is empty when the last -/// `None` arrives. +/// After the input ends, a binary root hands its answer over one chunk per pull, each pull +/// releasing that chunk's charge, and the pool is empty once the last `None` arrives. #[test] fn an_ended_input_streams_the_binary_answer_one_chunk_at_a_time() { let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); @@ -9364,8 +7926,7 @@ fn an_ended_input_streams_the_binary_answer_one_chunk_at_a_time() { execution .end_of_input() .expect("a closed input with two whole operands ends cleanly"); - // Ending the input runs the kernel and leaves its answer in the node that computed it, charged - // there until it is pulled; it does not collect the answer into a value of its own. + // Ending the input runs the kernel; the answer stays charged in the node until it is pulled. let mut chunks = Vec::new(); while let Some(chunk) = execution.next_chunk().unwrap() { chunks.push(chunk); @@ -9379,35 +7940,8 @@ fn an_ended_input_streams_the_binary_answer_one_chunk_at_a_time() { assert!(again.to_string().contains("already finished"), "{again}"); } -/// `finish` still answers the whole result in one value for a caller that wants it that way. -#[test] -fn finish_collects_what_the_streaming_contract_would_have_pulled() { - let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); - let schema = evaluated_schema(Arc::clone(&grid)); - let pool = bounded_pool(1 << 22); - let mut execution = executor(&tree, Arc::clone(&pool)); - execution - .push_evaluated(left, evaluated_chunk(&schema, 0, vec![1.0; 4], true)) - .unwrap(); - execution - .push_evaluated(right, evaluated_chunk(&schema, 0, vec![2.0; 4], true)) - .unwrap(); - let chunks = execution.finish().expect("the whole answer is collected"); - assert_eq!(addressed(&chunks), vec![(0, vec![Some(3.0); 4])]); - assert_eq!(execution.state().reserved_bytes(), 0); - assert_eq!(pool.reserved(), 0); -} - -/// A binary node reads an operand a collecting window below it produces only after that window -/// flushes. -/// -/// `Add(LastOverTime(Abs(a)), b)` puts a collecting window under a binary node: the window is above -/// a map, so it collects its whole input and answers at the end of it, while the binary node needs -/// both operands whole before it decides a point. Ending the input therefore has to finish the -/// subtree below each operand before the binary node computes -- flushing the window first and -/// letting the pull that follows carry its answer up. A binary node that computed on the empty -/// left operand would mark itself computed and answer nothing, and the value the window produced -/// afterwards would never be read. +/// Ending the input flushes a collecting window below a binary node before the binary computes; +/// computing over the still-empty operand would answer nothing. #[test] fn a_binary_reads_an_operand_a_collecting_window_flushes() { let grid = grid(0, 60_000, 1); @@ -9449,14 +7983,8 @@ fn a_binary_reads_an_operand_a_collecting_window_flushes() { ); } -/// A series that arrives in ten thousand one-point chunks is one candidate for the kernel, not ten -/// thousand. -/// -/// The kernel matches whole series, so the chunks of a logical series are assembled into the series -/// it reads before it runs: the pairing is over candidates, and a chunk that was a candidate of its -/// own would pair every chunk of one side with every chunk of the other. The same series delivered -/// whole must answer the same result, so the count of pairs the kernel actually visited is what -/// separates the two deliveries rather than their outcome. +/// The chunks of one series are assembled into one kernel candidate: ten thousand one-point chunks +/// visit as many pairs as the whole series does. #[test] fn a_series_of_many_chunks_is_one_candidate_for_the_kernel() { let points = 10_000usize; @@ -9520,136 +8048,8 @@ fn a_series_of_many_chunks_is_one_candidate_for_the_kernel() { assert_eq!(decided(&split), expected); } -/// The assembly of the operands into the series the kernel matches is reserved before it allocates. -/// -/// Assembling one series per closed series is metadata on top of the chunks the node retains -- the -/// descriptors the chunks' fields are collected into and the runs the axis is built from -- and the -/// pool is asked for that figure before it exists. A pool a byte short of it refuses the assembly, -/// and nothing of it is left charged: the node holds what it retained while the runtime is still -/// alive. -#[test] -fn an_assembly_the_pool_cannot_hold_is_refused_before_it_allocates() { - let grid = grid(0, 60_000, 2); - let schema = evaluated_schema(Arc::clone(&grid)); - let left = evaluated_chunk(&schema, 0, vec![1.0, 2.0], true); - let right = evaluated_chunk(&schema, 0, vec![10.0, 20.0], true); - let (retained, assembly) = binary_charge(&schema, &left, &right); - assert!( - assembly > 0, - "assembling the operands into series is not charged for" - ); - - // One byte short of the assembly: the assembly is refused rather than run over the budget. - let pool = bounded_pool(retained + assembly - 1); - let (mut state, mut binary) = binary_runtime(&pool, &schema); - state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(left.clone())) - .unwrap(); - state - .retain_binary(&mut binary, 1, NativeChunk::Evaluated(right.clone())) - .unwrap(); - assert_eq!(state.buffer.reservation.size(), retained); - let error = state.compute_binary(&mut binary).unwrap_err(); - assert!( - is_resources_exhausted(&error), - "the assembly was not reserved before it allocated: {error}" - ); - // The assembly never ran, so its charge is gone: what the node holds is what it retained, and - // the pool holds no more than that while the runtime is still alive. - assert_eq!(state.buffer.reservation.size(), retained); - assert_eq!(pool.reserved(), retained); - assert_eq!( - binary.retained_bytes(), - retained, - "the refused assembly changed what the operand retains" - ); - - // The figure covers the assembly itself: with exactly that much more, the series are built and - // hold the rows the chunks carried. - let pool = bounded_pool(retained + assembly); - let (mut state, mut binary) = binary_runtime(&pool, &schema); - state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(left)) - .unwrap(); - state - .retain_binary(&mut binary, 1, NativeChunk::Evaluated(right)) - .unwrap(); - let assembled = binary.assemble().unwrap(); - assert_eq!(assembled[0].len(), 1, "one closed series is one series"); - assert_eq!(assembled[1].len(), 1, "one closed series is one series"); - let built = EvaluatedChunk::try_new(assembled[0][0].clone(), true).unwrap(); - assert_eq!(sample_values(&built), vec![Some(1.0), Some(2.0)]); -} - -/// An assembly the executor's pool cannot hold stops it and leaves it holding nothing. -/// -/// The pool is one byte short of what the node retains plus what assembling the retained chunks -/// allocates, so both operands are retained and the assembly is what the pool refuses. What a caller -/// sees afterwards is a stopped execution that holds nothing: the operand chunks are dropped and the -/// reservation is back at zero while the executor is still alive. -#[test] -fn an_assembly_the_executors_pool_cannot_hold_stops_it() { - let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); - let schema = evaluated_schema(grid); - let (left_chunk, right_chunk) = ( - evaluated_chunk(&schema, 0, vec![1.0, 2.0], true), - evaluated_chunk(&schema, 0, vec![10.0, 20.0], true), - ); - let (retained, assembly) = binary_charge(&schema, &left_chunk, &right_chunk); - let pool = bounded_pool(retained + assembly - 1); - let mut execution = executor(&tree, Arc::clone(&pool)); - let metrics = metrics_of(&execution); - execution.push_evaluated(left, left_chunk).unwrap(); - execution.push_evaluated(right, right_chunk).unwrap(); - // Both operands are retained before anything is assembled, and nothing is answered: the refusal - // below is the assembly's and not a chunk's. - assert!(execution.next_chunk().unwrap().is_none()); - assert_eq!( - pool.reserved(), - retained, - "the operands are not what the pool holds" - ); - assert_eq!( - gauge( - &metrics, - &format!("native.p0.root.{}", NodeMetric::PEAK_RESERVED_BYTES) - ), - retained, - "the binary node reserved past what it retains" - ); - - let error = execution.finish().unwrap_err(); - assert!( - is_resources_exhausted(&error), - "the assembly was not reserved before it allocated: {error}" - ); - assert_eq!( - pool.reserved(), - 0, - "the stopped execution kept a reservation" - ); - assert_eq!(execution.state().reserved_bytes(), 0); - assert!( - !root_holds(&execution, holds_binary), - "the stopped execution kept the operands it retained" - ); - let stopped = execution.next_chunk().unwrap_err(); - assert!( - stopped - .to_string() - .contains("stopped after an earlier error"), - "a stopped execution answered again: {stopped}" - ); -} - -/// The assembly bound covers the vector a field's descriptors are flattened into, on the shape that -/// grows it the most. -/// -/// One chunk's field can itself hold 1024 segments. Beside a second chunk's one, [`Samples::try_from_chunks`] -/// copies all 1025 descriptors into a vector that doubled to 2048 slots, and then into the -/// `Arc<[Samples]>` it returns, so 3073 slots are live at once: two slots per segment -- 2052 here -- -/// would reserve less than the assembly allocates. The segments are dense slices of one histogram -/// table, which the assembled field keeps sharing rather than copying. +/// A pool one byte short of the operand assembly refuses it, and the node keeps only what it +/// retained. #[test] fn an_assembly_bound_covers_the_capacity_its_flatten_grows_to() { let (segments, chunks) = (1025usize, 2usize); @@ -9756,14 +8156,62 @@ fn an_assembly_bound_covers_the_capacity_its_flatten_grows_to() { assert_eq!(histogram_counts(&built), vec![4.0; segments]); } -/// A mixed operand delivered in two chunks over a sparse axis assembles into one series that keeps -/// its holes, both its fields and the allocations they are slices of. -/// -/// Field 0 holds native histograms and field 1 floats, both chunks index one table, and the -/// positions they decide are 0, 2 and 3 of a four-point grid. The assembly keeps one descriptor per -/// segment instead of copying a sample, so the assembled series reads the same table and the same -/// float buffers the chunks read, and the position neither chunk decided stays a hole. The kernel -/// then answers that series as one candidate, which is what the result below is computed from. +#[test] +fn an_assembly_the_pool_cannot_hold_is_refused_before_it_allocates() { + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let left = evaluated_chunk(&schema, 0, vec![1.0, 2.0], true); + let right = evaluated_chunk(&schema, 0, vec![10.0, 20.0], true); + let (retained, assembly) = binary_charge(&schema, &left, &right); + assert!( + assembly > 0, + "assembling the operands into series is not charged for" + ); + + // One byte short of the assembly: the assembly is refused rather than run over the budget. + let pool = bounded_pool(retained + assembly - 1); + let (mut state, mut binary) = binary_runtime(&pool, &schema); + state + .retain_binary(&mut binary, 0, NativeChunk::Evaluated(left.clone())) + .unwrap(); + state + .retain_binary(&mut binary, 1, NativeChunk::Evaluated(right.clone())) + .unwrap(); + assert_eq!(state.buffer.reservation.size(), retained); + let error = state.compute_binary(&mut binary).unwrap_err(); + assert!( + is_resources_exhausted(&error), + "the assembly was not reserved before it allocated: {error}" + ); + // The assembly never ran, so its charge is gone: what the node holds is what it retained, and + // the pool holds no more than that while the runtime is still alive. + assert_eq!(state.buffer.reservation.size(), retained); + assert_eq!(pool.reserved(), retained); + assert_eq!( + binary.retained_bytes(), + retained, + "the refused assembly changed what the operand retains" + ); + + // The figure covers the assembly itself: with exactly that much more, the series are built and + // hold the rows the chunks carried. + let pool = bounded_pool(retained + assembly); + let (mut state, mut binary) = binary_runtime(&pool, &schema); + state + .retain_binary(&mut binary, 0, NativeChunk::Evaluated(left)) + .unwrap(); + state + .retain_binary(&mut binary, 1, NativeChunk::Evaluated(right)) + .unwrap(); + let assembled = binary.assemble().unwrap(); + assert_eq!(assembled[0].len(), 1, "one closed series is one series"); + assert_eq!(assembled[1].len(), 1, "one closed series is one series"); + let built = EvaluatedChunk::try_new(assembled[0][0].clone(), true).unwrap(); + assert_eq!(sample_values(&built), vec![Some(1.0), Some(2.0)]); +} + +/// A mixed histogram/float operand in two sparse chunks assembles into one series that keeps its +/// hole and shares the chunks' table and float buffers. #[test] fn a_mixed_nested_operand_assembles_into_one_series_with_its_holes() { let grid = grid(0, 60_000, 4); @@ -9910,38 +8358,6 @@ fn a_mixed_nested_operand_assembles_into_one_series_with_its_holes() { ); } -/// A kernel error and dropping the execution both give back everything the node reserved. -#[test] -fn a_kernel_error_and_a_drop_release_the_binary_reservation() { - let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 2); - let schema = evaluated_schema(grid); - let pool = pool(); - let mut execution = executor(&tree, Arc::clone(&pool)); - execution - .push_evaluated(left, evaluated_chunk(&schema, 0, vec![1.0, 2.0], true)) - .unwrap(); - // The same label set twice on the right, both holding a value at position 0. - execution - .push_evaluated(right, evaluated_chunk(&schema, 0, vec![1.0], true)) - .unwrap(); - execution - .push_evaluated(right, evaluated_chunk(&schema, 0, vec![2.0], true)) - .unwrap(); - let error = execution.finish().unwrap_err(); - assert!(error.to_string().contains("duplicate series"), "{error}"); - assert_eq!(pool.reserved(), 0, "the kernel error kept its reservation"); - assert_eq!(execution.state().reserved_bytes(), 0); - - // A dropped execution returns its reservation without being told to. - let mut dropped = executor(&tree, Arc::clone(&pool)); - dropped - .push_evaluated(left, evaluated_chunk(&schema, 0, vec![1.0], true)) - .unwrap(); - assert!(pool.reserved() > 0, "the operand reserved nothing"); - drop(dropped); - assert_eq!(pool.reserved(), 0); -} - /// A queued chunk has to name an input the tree has. #[test] fn a_queued_chunk_names_an_input_the_tree_has() { @@ -9949,8 +8365,7 @@ fn a_queued_chunk_names_an_input_the_tree_has() { let schema = evaluated_schema(grid); let chunk = evaluated_chunk(&schema, 0, vec![1.0, 2.0], true); - // Two leaves are indexed zero and one, so an id past the last one names nothing: the count is - // what says so, rather than an assignment to whichever leaf the count happened to reach. + // Two leaves are indexed 0 and 1, so id 2 names nothing. let mut missing = executor(&tree, pool()); let error = missing.push_evaluated(InputId::new(2), chunk).unwrap_err(); assert!( @@ -10095,12 +8510,8 @@ fn a_binary_over_two_windows_and_selections_is_executed() { ); } -/// The chain Prometheus evaluates as `abs(instant - last_over_time)`, with the raw samples of each -/// side and the literal rows it decides. -/// -/// The left side is a selection reading back 1001 ms and the right side a 1000 ms window, on a grid -/// of 1000 ms steps: the two report different samples of the two raw series, which is what the -/// subtraction then pairs. +/// `abs(instant - last_over_time)` against Prometheus' answer: a 1001 ms lookback and a 1000 ms +/// window on a 1000 ms grid read different samples of the two series. #[test] fn a_binary_of_a_selection_and_a_window_matches_prometheus() { let out = grid(0, 1_000, 4); @@ -10156,11 +8567,8 @@ fn a_binary_of_a_selection_and_a_window_matches_prometheus() { ); } -/// An operand chunk whose series changes before it ends is refused, naming the side and the node. -/// -/// A binary node matches whole series, so the pairs of a series that is still open cannot be -/// computed from a chunk of another one: the two are reported instead of being paired as though the -/// second were a continuation of the first. +/// An operand chunk of another series arriving while one is open is refused, naming the side and +/// the node. #[test] fn a_chunk_of_another_series_on_one_operand_is_refused() { let (tree, grid, left, right) = binary_tree(BinaryOp::Add, 4); @@ -10206,11 +8614,8 @@ fn a_chunk_of_another_series_on_one_operand_is_refused() { assert!(execution.finish().is_err()); } -/// An operand chunk that starts behind the end of the open series is refused, values or not. -/// -/// The overlap is read off the axes, not off the samples they carry: a chunk whose every sample is -/// missing still occupies the positions its axis places, so a second chunk that reaches back into -/// them is a rewind rather than a continuation. +/// An operand chunk that starts inside the positions the open series already placed is refused, +/// even when every sample there is missing. #[test] fn an_operand_chunk_that_rewinds_is_refused_with_or_without_values() { let (tree, grid, left, _right) = binary_tree(BinaryOp::Add, 4); @@ -10243,10 +8648,7 @@ fn an_operand_chunk_that_rewinds_is_refused_with_or_without_values() { assert!(!root_holds(&execution, holds_binary)); } -/// A chunk that does not match the layout its operand is bound to is refused before the kernel. -/// -/// Each case is a chunk a caller can build: [`Series`] keeps its fields public, so an axis and the -/// fields beside it can disagree, and a chunk can be addressed on a grid no operand was bound to. +/// A chunk that does not match its operand's bound layout is refused before the kernel. #[test] fn a_chunk_that_does_not_match_its_operand_is_refused_before_the_kernel() { let (tree, out_grid, left, _right) = binary_tree(BinaryOp::Add, 4); @@ -10308,11 +8710,8 @@ fn a_chunk_that_does_not_match_its_operand_is_refused_before_the_kernel() { } } -/// A series cannot be built with no field at all, which is what keeps a zero-field check honest. -/// -/// The validator's field-count check is not skipped by an empty field list because an empty one -/// cannot exist: [`SeriesFields`] refuses it, so every chunk any caller can build carries at least -/// one field. The boundary is the constructor's, and it is recorded here rather than loosened there. +/// [`SeriesFields`] refuses an empty field list, so no chunk reaches the validator with zero +/// fields. #[test] fn a_series_cannot_carry_no_fields() { let error = @@ -10324,10 +8723,7 @@ fn a_series_cannot_carry_no_fields() { assert_eq!(one.len(), 1); } -/// A binary node with no chunk at all on either side answers nothing, and holds nothing. -/// -/// The input ending without a chunk is a stream that held no series, not a tree that never ran: the -/// kernel is asked about two empty vectors and reports none, so the answer is the empty one. +/// A binary node whose inputs end without a chunk on either side answers nothing and holds nothing. #[test] fn an_absent_operand_yields_no_series() { let (tree, grid, _left, right) = binary_tree(BinaryOp::Add, 2); @@ -11010,10 +9406,7 @@ fn name_of(chunk: &EvaluatedChunk) -> Option<&str> { chunk.series.metric.name() } -/// A constant on the right multiplies every value of the vector and drops the metric name. -/// -/// The chunk arrives as it is pushed, before the input ends: a broadcast answers a chunk from that -/// chunk alone, so nothing waits for the vector to be complete. +/// A broadcast answers each chunk as it arrives, multiplying every value and dropping the name. #[test] fn a_constant_on_the_right_multiplies_every_value() { let grid = grid(0, 60_000, 4); @@ -11054,10 +9447,7 @@ fn a_constant_on_the_right_multiplies_every_value() { assert_eq!(execution.state().reserved_bytes(), 0); } -/// A `Complete` aggregate over `inner`, carrying `inner`'s fields and evaluated on its grid. -/// -/// A `Complete` aggregate neither adds nor drops a field and lands on its input's grid, so the node's -/// own output is the layout its input produces. +/// A `Complete` aggregate over `inner`, with `inner`'s fields and grid. fn aggregate(inner: NativeNode, op: BoundAggregate) -> NativeNode { let fields = inner .output @@ -11093,10 +9483,7 @@ fn sum_grouping(group: Grouping) -> BoundAggregate { } } -/// A `Partial` `sum` over `inner`, ungrouped, exporting state for a later merge. -/// -/// A partial aggregate folds only this execution's contributions and keeps what it folded until its -/// input ends, so a duplicate it read would end up in one group rather than being answered as two. +/// A `Partial` ungrouped `sum` over `inner`, exporting state for a later merge. fn partial_sum(inner: NativeNode) -> NativeNode { let samples = inner .output @@ -11157,9 +9544,6 @@ type GroupResult = ( ); /// The groups a run produced, each with the absolute positions it decided, sorted by identity. -/// -/// Sorting is the test's, not the runtime's: a group's place in the answer is the order its first -/// input appeared, which the tests that check it assert on the stream rather than here. fn groups_of(chunks: &[EvaluatedChunk]) -> Vec { let mut results: Vec = chunks .iter() @@ -11245,10 +9629,8 @@ fn an_aggregate_drops_every_label_and_adds_its_group_per_point() { assert_eq!(execution.state().reserved_bytes(), 0); } -/// The side a constant is on decides which operand the vector's value is. -/// -/// Division is not commutative, so `x / 100` and `100 / x` answering different values is what says -/// the operand direction survived the broadcast. +/// Division is not commutative, so `x / 100` and `100 / x` differing shows the operand direction +/// survived the broadcast. #[test] fn a_broadcast_keeps_the_operand_direction() { let grid = grid(0, 60_000, 3); @@ -11396,10 +9778,8 @@ fn a_constant_of_minus_one_on_the_left_negates_the_vector() { ); } -/// A position the vector held no value at stays missing, and a position it skipped stays skipped. -/// -/// The chunk that is not last is answered as it arrives: a broadcast transforms a chunk and hands -/// it up, so `is_last` is the only thing that says where a series ends. +/// A missing value stays missing and a skipped position stays skipped; a non-last chunk is answered +/// as it arrives. #[test] fn a_broadcast_preserves_missing_values_and_skipped_positions() { let grid = grid(0, 60_000, 6); @@ -11594,10 +9974,8 @@ fn a_histogram_function_names_an_emptied_closing_chunk_like_its_kernel() { assert_eq!(closing.series.metric.get("__type__"), Some("histogram")); } -/// A filter that passes nothing on the chunk that closes a series still closes it. -/// The chunk it hands over holds no row and carries the label set the operation produces, which is -/// the only way the consumer downstream learns that the series ended rather than that no input has -/// arrived yet. +/// A filter that passes nothing on a series' closing chunk still hands over an empty closing chunk +/// under the operation's label set. #[test] fn a_filter_that_passes_nothing_still_closes_the_series() { let grid = grid(0, 60_000, 3); @@ -11681,11 +10059,8 @@ fn a_filter_that_passes_nothing_still_closes_the_series() { assert_eq!(execution.state().reserved_bytes(), 0); } -/// A broadcast holds the chunk it is working on and nothing more, however long the vector is. -/// -/// The same series arrives in one chunk and in many: what the node reserves has to be the chunk in -/// hand and the label sets it handed out, not the vector it read, or a broadcast over a long series -/// would cost the whole series. +/// A broadcast reserves the chunk in hand, not the vector: its peak is the same for one chunk and +/// many. #[test] fn a_broadcast_does_not_retain_the_vector_it_reads() { // The most the node ever reserved, over the same series delivered in `count` chunks. @@ -11742,14 +10117,8 @@ fn a_broadcast_does_not_retain_the_vector_it_reads() { ); } -/// A window above a broadcast that drops the metric name merges what that broadcast collapses. -/// -/// The multiplication rewrites the label set, so two input series with different names and one set -/// of tags become one label set under it. A window above therefore has to collect its input and -/// merge the pieces before it evaluates: reporting each piece on its own answers two series where -/// Prometheus answers one, and the second piece's positions are exactly the ones the first left -/// empty. `holds_shared` is what tells the window to collect, so a window that streams here is the -/// regression this test exists for. +/// A broadcast that drops the name can collapse two series into one label set, so the window above +/// collects and merges them before evaluating. #[test] fn a_window_above_a_broadcast_merges_the_series_it_collapses() { let grid = grid(0, 60_000, 4); @@ -11957,11 +10326,8 @@ fn an_aggregate_folds_a_series_split_across_chunks_like_a_whole_one() { ); } -/// A point no member of a group has a value at is not a point of the group's result. -/// -/// Sparse input is what says the fold indexes its states by absolute position: a chunk holding -/// positions 0 and 1 and another holding 1 and 2 leave position 3 to nothing, and the hole between -/// the rows is never filled with a value. +/// The fold indexes its states by absolute position: a point no member holds a value at is not in +/// the group's result. #[test] fn an_aggregate_reports_only_the_points_a_group_holds_a_value_at() { let grid = grid(0, 60_000, 4); @@ -12028,10 +10394,7 @@ fn an_aggregate_over_no_series_produces_nothing() { assert_eq!(execution.state().reserved_bytes(), 0); } -/// A broadcast hands one chunk over for every chunk it reads, and closes the series once. -/// -/// The metrics are what says the chunk-per-chunk behaviour held: one input batch per chunk read, one -/// output batch per chunk handed over, and one closed series for the series that ended. +/// A broadcast hands over one chunk per chunk read and closes the series once. #[test] fn a_broadcast_reports_one_chunk_in_for_each_chunk_out() { let grid = grid(0, 60_000, 4); @@ -12182,73 +10545,9 @@ fn a_broadcast_above_a_collecting_window_waits_for_its_flush() { assert_eq!(pool.reserved(), 0); } -/// A broadcast rejects distinct input names that become one output label set at occupied points. -/// -/// The multiplication drops the metric name, so `requests` and `requests_total` hold one label set -/// above it and both hold a value at the same positions. The merge above the broadcast is what -/// refuses the pair: the node itself is point-wise and hands every chunk over as it arrives. -#[test] -fn a_broadcast_refuses_two_series_that_share_a_label_set_and_releases_the_reservation() { - let grid = grid(0, 60_000, 2); - let schema = evaluated_schema(Arc::clone(&grid)); - let tree = NativeTree::try_new(merge(broadcast_right( - evaluated_input(Arc::clone(&grid)), - 100.0, - BinaryOp::Mul, - false, - ))) - .unwrap(); - let pool = pool(); - let mut execution = executor(&tree, Arc::clone(&pool)); - let first_metric = - SeriesLabels::try_new(Some("requests".to_string().into()), Vec::new()).unwrap(); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of(&schema, first_metric, 0, vec![Some(1.0), Some(2.0)], true), - ) - .unwrap(); - let second_metric = - SeriesLabels::try_new(Some("requests_total".to_string().into()), Vec::new()).unwrap(); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of(&schema, second_metric, 0, vec![Some(3.0), Some(4.0)], true), - ) - .unwrap(); - // The merge collects both mapped series and reports the collision when its input ends. - execution.end_of_input().unwrap(); - let error = execution - .next_chunk() - .expect_err("the output label set and occupied positions conflict"); - let message = error.to_string(); - // The refusal names the defect the way Prometheus does: one label set holding two series. The - // scalar broadcast produced no label set of its own, so the rendering is empty and the two - // series are told apart only by what they produced. - assert!( - message.contains("vector cannot contain metrics with the same labelset"), - "expected the collision the node produces, got: {message:?}" - ); - assert_eq!( - pool.reserved(), - 0, - "error retained a pool reservation: {message}" - ); - assert_eq!( - execution.state().reserved_bytes(), - 0, - "error retained execution bytes: {message}" - ); -} - -/// What a literal arithmetic broadcast hands on under a name-dropping window keeps its positions: -/// series that differ only by name hold different ones, so nothing collides, each hands over its own -/// close, and the constant reaches every value that is there. -/// -/// `sum_over_time` over a 1 ms window answers each position its input holds a sample at, so the two -/// series occupy disjoint positions and the missing samples in between stay missing. The window -/// drops the name, so both answer under one label set: what lets them through is occupancy, which -/// the broadcast neither widens nor narrows. +/// `sum_over_time` over a 1 ms window drops the name and answers only the positions its input +/// holds, so two series differing only by name occupy disjoint positions and pass the broadcast +/// above without colliding. #[test] fn a_literal_arithmetic_over_a_name_dropping_window_keeps_the_positions_it_reads() { let grid = grid(0, 60_000, 4); @@ -12317,13 +10616,8 @@ fn a_literal_arithmetic_over_a_name_dropping_window_keeps_the_positions_it_reads } } -/// A collecting window that drops the metric name hands its flush to the literal arithmetic above -/// it, which keeps no table of its own and so passes every position of that flush on. -/// -/// The window collects because its input reports fragments, merges the two series that share a tag -/// set once their name is gone, and answers only when the input ends: what reaches the broadcast is -/// that flush, its closes included. The second tag set the flush answers holds no value, so the -/// chunk that closes it carries no row -- the one a consumer tells "nothing more here" by. +/// Literal arithmetic above a collecting, name-dropping window passes on every position of the +/// window's flush, including the empty closing chunk of a tag set that holds no value. #[test] fn a_literal_arithmetic_over_a_collecting_window_hands_on_its_flush() { let grid = grid(0, 60_000, 4); @@ -12408,13 +10702,8 @@ fn a_literal_arithmetic_over_a_collecting_window_hands_on_its_flush() { assert_eq!(pool.reserved(), 0); } -/// The merge over a name-dropping window refuses two series that collapse onto one label set, and -/// it does so before the aggregate above can fold them into one group. -/// -/// `rate` drops the metric name, so the two series below leave the window under one label set: the -/// merge collecting the window's output is where the pair is refused. That placement is what keeps -/// the refusal upstream -- a duplicate the partial aggregate read would land in one group and answer -/// a wrong value instead of refusing, and the reservations would be held until the fold answered. +/// The merge over a name-dropping window refuses two series that collapse onto one label set before +/// the aggregate above could fold them into one group. #[test] fn a_merge_over_a_name_dropping_window_refuses_before_the_aggregate() { let out_grid = grid(0, 60_000, 5); @@ -12453,8 +10742,7 @@ fn a_merge_over_a_name_dropping_window_refuses_before_the_aggregate() { execution.next_state().unwrap().is_none(), "the partial aggregate answered before its input ended" ); - // The second series is a different one to the scan and the same one to `rate`: the merge over - // the window is where the two meet, and the broadcast above it collects nothing of its own. + // A different series to the scan, the same one once `rate` drops the name. execution .push_raw( InputId::new(0), @@ -12482,8 +10770,6 @@ fn a_merge_over_a_name_dropping_window_refuses_before_the_aggregate() { && message.contains("host=\"web-1\""), "expected the merge's refusal, got: {message:?}" ); - // The refusal is upstream of the fold: a duplicate it read would land in one group and answer a - // wrong value instead of refusing. assert_eq!( count(&metrics, "root", NodeMetric::OUTPUT_BATCHES), 0, @@ -12501,11 +10787,8 @@ fn a_merge_over_a_name_dropping_window_refuses_before_the_aggregate() { ); } -/// A window that keeps the metric name leaves the collision to the merge above the broadcast. -/// -/// `last_over_time` reports the name it read, so the two series stay distinct under it; the -/// multiplication drops the name, and the two then hold one label set at the same positions. Nothing -/// below the merge has collected that identity, so the merge above this node is where it is refused. +/// `last_over_time` keeps the name, so the two series stay apart under it; the multiplication drops +/// the name, and the merge above the broadcast refuses the collision. #[test] fn a_name_preserving_window_leaves_the_collision_to_the_merge_above_the_broadcast() { let grid = grid(0, 60_000, 2); @@ -12689,11 +10972,8 @@ fn a_histogram_window_under_literal_arithmetic_never_expands_occupancy() { } } -/// A series that ended is one member of a group, not the group: nothing is answered until the input -/// ends. -/// -/// The observable state between the two is what this pins: the fold has read the closing chunk of -/// the first series and answered nothing, and `computed` still says so. +/// A series that ended is one member of a group, not the group: nothing is answered, and the fold +/// is not computed, until the input ends. #[test] fn an_aggregate_answers_nothing_until_its_whole_input_ends() { let grid = grid(0, 60_000, 4); @@ -12704,8 +10984,7 @@ fn an_aggregate_answers_nothing_until_its_whole_input_ends() { )) .unwrap(); let mut execution = executor(&tree, pool()); - // The root is the aggregate the tree built, and the fold is its own payload: what is read - // below is a copy of the flag, not a borrow held across the pulls. + // Copies the flag rather than holding a borrow across pulls. let computed = |execution: &NativeExecutor| { let RuntimeOp::Aggregate { aggregate, .. } = &execution.state().live.as_ref().unwrap().root.op @@ -12776,12 +11055,8 @@ fn an_aggregate_answers_nothing_until_its_whole_input_ends() { ); } -/// A chunk of another layout is refused, naming the aggregate and its position, and the execution -/// stops with nothing reserved. -/// -/// The fold indexes its states by absolute position and by field, so a chunk of another field count -/// would be folded into states that mean something else. It is refused rather than folded, and what -/// the refusal leaves behind is a stopped execution whose reservation went back to the pool. +/// A chunk with another field count is refused rather than folded into states indexed by field, and +/// the stopped execution holds nothing. #[test] fn an_aggregate_refuses_a_chunk_of_another_layout_and_returns_its_reservation() { let grid = grid(0, 60_000, 4); @@ -12825,8 +11100,7 @@ fn an_aggregate_refuses_a_chunk_of_another_layout_and_returns_its_reservation() let error = execution .next_chunk() .expect_err("a chunk of another field count was folded"); - // The refusal names the node it came from and keeps the sentence that says what disagreed, so a - // client reads the cause and not just the node. + // The refusal names the node and keeps the sentence saying what disagreed. let message = error.to_string(); assert!( message.contains("native.aggregate at root: "), @@ -12841,7 +11115,7 @@ fn an_aggregate_refuses_a_chunk_of_another_layout_and_returns_its_reservation() "the refusal does not say what disagreed: {message}" ); assert_eq!(execution.state().reserved_bytes(), 0); - // A stopped execution is not resumed: the fold must not be asked to continue after this. + // A stopped execution is not resumed. assert!(execution.next_chunk().is_err()); } @@ -12899,9 +11173,8 @@ fn aggregate_runtime_queue_keeps_only_backing_after_pops_until_release() { let first = execution.next_chunk().unwrap().expect("first group output"); assert_eq!(first.series.time.positions().count(), 1); let entry = std::mem::size_of::<(NativeChunk, usize)>(); - // What the root's queue holds, what the first chunk in it was queued with, the node's - // reservation and the backing the queue grew to. The borrow ends inside the call, so the pull - // below is taken with nothing held. + // (queued chunks, first chunk's charge, node reservation, queue capacity); the borrow ends + // inside the call. let queue = |execution: &NativeExecutor| -> (usize, usize, usize, usize) { let RuntimeOp::Aggregate { state, .. } = &execution.state().live.as_ref().unwrap().root.op else { @@ -12963,14 +11236,8 @@ fn aggregate_sparse_output_budget_uses_rows_not_grid_length() { assert_eq!(pool.reserved(), 0); } -/// `quantile` answers what the kernel answers, because the node keeps the input the kernel reads. -/// -/// The node is not a second implementation of the quantile: it retains its members and hands them to -/// [`crate::aggregate::aggregate_quantile`] with a constant parameter over the rows they hold, so the -/// assertion is against that kernel over the same series. Positions, values and the group each row -/// belongs to must agree row for row. The input is uneven on purpose - a group's members hold -/// different points, and one point's values come only from one member - which is what a per-point -/// fold would answer and this must not. +/// `quantile` answers what [`crate::aggregate::aggregate_quantile`] answers over the same members, +/// row for row. The input is uneven so that a per-point fold would answer differently. #[test] fn quantile_answers_what_the_kernel_answers() { let grid = grid(0, 60_000, 6); @@ -13059,13 +11326,8 @@ fn quantile_answers_what_the_kernel_answers() { } } -/// A `quantile`'s parameter is as wide as the points the input holds, not the span they sit in. -/// -/// The two points are 99_999 positions apart on a 100_000-point grid, so a parameter over the window -/// between them carries a value for every position in it -- 800 KB at this width -- and no admission -/// ever sized it. That pool is 64 KiB, which the dense span could not be admitted into and which this -/// fold answers in: the parameter is built over the input's own positions, so the gaps cost a span -/// and not a row. What the fold took is released again when it answers. +/// A `quantile`'s parameter covers the points the input holds, not the span between them: two +/// points 99 999 positions apart fit a 64 KiB pool that a dense 800 KB parameter would not. #[test] fn quantile_parameter_costs_the_points_held_not_the_span_between_them() { let grid = grid(0, 1, 100_000); @@ -13102,18 +11364,8 @@ fn quantile_parameter_costs_the_points_held_not_the_span_between_them() { assert_eq!(pool.reserved(), 0); } -/// A `quantile` whose input holds no sample at all answers nothing, rather than failing on the -/// parameter it has no point to write the φ at. -/// -/// The node hands the empty input to [`crate::aggregate::aggregate_quantile`] with the φ as an -/// unlabelled single-field scalar, and that scalar is built over exactly the points the retained -/// members sit at. An input with no member sits at none of them, so the builder it is written -/// through finishes with no series at all -- and there is no point the kernel could ask for a φ it -/// has no value at. The statement is still a legal one whose answer is the empty vector: -/// `quantile(0.5, m)` over a range `m` holds no sample in is exactly this case, and Prometheus -/// answers it with no series rather than with an error. The parameter is therefore an empty scalar -/// over the grid instead -- the same thing said in the form the kernel reads -- which is what keeps -/// "no sample in range" an answer of no samples rather than a failure to build a parameter. +/// A `quantile` over no input answers nothing, as Prometheus does for `quantile(0.5, m)` over an +/// empty range: its φ parameter is an empty scalar over the grid rather than an error. #[test] fn a_quantile_over_no_input_answers_nothing() { let grid = grid(0, 60_000, 4); @@ -13129,8 +11381,7 @@ fn a_quantile_over_no_input_answers_nothing() { .unwrap(); let pool = bounded_pool(1 << 20); let mut execution = executor(&tree, Arc::clone(&pool)); - // Nothing is pushed: the selection under this aggregate held no sample in the range it was - // asked for, so its leaf hands over no chunk at all and the fold keeps no member. + // Nothing is pushed: the fold keeps no member. let output = run(&mut execution); assert!( output.is_empty(), @@ -13140,10 +11391,7 @@ fn a_quantile_over_no_input_answers_nothing() { assert_eq!(pool.reserved(), 0); } -/// A `Complete` aggregate whose one argument is read per point, over `inner` and `parameter`. -/// -/// The fold answers one value per field on its input's grid, exactly as its bound counterpart does: -/// only where its `φ` comes from differs. +/// A `Complete` aggregate over `inner` whose one argument is read per point from `parameter`. fn parameterized_aggregate( inner: NativeNode, op: BoundAggregate, @@ -13177,9 +11425,8 @@ fn parameterized_aggregate( /// A `Complete` `quantile` grouped as `group` whose `φ` is read at every grid point. fn per_point_quantile(group: Grouping) -> BoundAggregate { BoundAggregate { - // Unused by this fold: the `φ` it reads is its parameter's, one value per point. The - // constant is here because it is what a `Quantile` carries, as a parameterized `topk` - // carries an unused `k`. + // Unused: the fold reads `φ` from its parameter, as a parameterized `topk` carries an + // unused `k`. kind: AggregateKind::Quantile { quantile: 0.0 }, group, stage: AggregateStage::Complete, @@ -13197,15 +11444,8 @@ fn value_at(answer: &[GroupResult], index: usize, point: usize) -> Option { .unwrap_or_else(|| panic!("group {index} answered no value at point {point}")) } -/// A `quantile` reads its argument at every step, and answers there what the same fold bound to -/// that step's `φ` answers. -/// -/// The argument is `time() / 120`, which is `0`, `0.5` and `1` on this grid, so each of the three steps -/// is compared against `quantile(, m)` computed on its own: the bound fold is the -/// constant path, and comparing against it is comparing against the value the query means. The -/// grouping is checked in both shapes, because a fold that reads its `φ` per point groups exactly as -/// the one that binds it: `by (job)` folds one group per job, and the `φ` is read beside the fold -/// rather than once per group. +/// A `quantile` reads `φ = time() / 120` (0, 0.5, 1) at every step and answers there what the fold +/// bound to that step's `φ` answers, grouped `by (job)` and ungrouped. #[test] fn a_quantile_reads_its_parameter_at_every_grid_point() { let grid = grid(0, 60_000, 3); @@ -13297,13 +11537,8 @@ fn a_quantile_reads_its_parameter_at_every_grid_point() { ); } -/// A step whose `φ` the statement has no sample for answers NaN there, not no point. -/// -/// `scalar(foo)` answers one value per grid point -- NaN where `foo` holds no float sample -- so the -/// series this fold holds covers every step, and a step it covers with NaN is a step with a -/// `quantile` answer: Prometheus' `quantile` of a NaN `φ` is NaN. A step the parameter had no sample -/// at at all would be unanswered instead, which is the rule the kernel applies to a parameter series -/// with a gap; this node is handed one that never has one. +/// A NaN `φ` answers NaN at that step, as Prometheus' `quantile` does: `scalar(foo)` is NaN where +/// `foo` holds no float, so the parameter covers every step. #[test] fn a_quantile_answers_nan_where_its_parameter_is_nan() { let grid = grid(0, 60_000, 3); @@ -13350,14 +11585,8 @@ fn a_quantile_answers_nan_where_its_parameter_is_nan() { assert_eq!(pool.reserved(), 0); } -/// An input that ends with a chunk still queued is refused as truncated, not folded. -/// -/// The fold reads its parameter before it reads any input, and a parameter that answers only once -/// its own input ended leaves the fold with nothing to do but wait. A caller that ends the input -/// while the vector's last chunk still waits in the leaf's queue therefore ends a run in which the -/// fold has never looked at that chunk: it says `is_last` was not sent, and the fold would fold half -/// a vector into a quantile if it were read as closed. Finality is what the caller sent, so the -/// queued chunk is what reports the truncation. +/// An input that ends with its last chunk still queued is refused as truncated rather than folded: +/// the fold waits for its parameter and has not read the chunk when the input ends. #[test] fn a_quantile_refuses_a_queued_chunk_that_never_closed() { let grid = grid(0, 60_000, 3); @@ -13407,17 +11636,9 @@ fn a_quantile_refuses_a_queued_chunk_that_never_closed() { assert_eq!(pool.reserved(), 0); } -/// A `quantile` bills the parameter it holds across the handoff and while it computes. -/// -/// The parameter here is `time()` over a grid far wider than the fold's input: one row of `m`, so -/// the input says nothing about the parameter's width at all. Its own series costs eight bytes a -/// point, and the kernel reads the whole of it into one `(position, φ)` pair per point before it -/// folds anything, so the fold answers only over a pool that holds the series and that copy. -/// -/// A pool of the values alone is refused by the source that produces the parameter (`POINTS`), one -/// that holds the parameter but not the copy the kernel reads is refused after the handoff -/// (`24 * POINTS`: over the series and under the copy), and one that holds both answers the query -/// and is left empty (`64 * POINTS`). +/// A `quantile` bills its `time()` parameter across the handoff and while the kernel copies it into +/// `(position, φ)` pairs: a pool of `POINTS` bytes is refused by the parameter's source, `24 * +/// POINTS` after the handoff, and `64 * POINTS` answers and ends empty. #[test] fn a_parameterized_quantile_bills_the_parameter_it_holds() { // Eight bytes a point for the values alone, and the axis, the validity slots and the descriptor @@ -13458,26 +11679,10 @@ fn a_parameterized_quantile_bills_the_parameter_it_holds() { } } -/// A `quantile` bills the buffer its chunks are slices of once, not once per chunk. -/// -/// One 2000-sample Arrow allocation is handed over as 2000 one-row chunks, which is what a source -/// handing over the rows of one batch does: every chunk is a slice of the same 16 KB buffer, so the -/// series holds 16 KB of values and one descriptor per chunk. Charging each chunk for the allocation -/// its slice points into -- `series_bytes`, which reads the capacity of the buffer a slice keeps -/// alive -- bills 2000 x ~16.3 KB ≈ 32 MB, and the 4 MiB pool below refuses this input at about the -/// 260th chunk (4 MiB / 16.3 KB), while `min` over the same chunks answers, because a point-wise fold -/// holds one chunk at a time and never the input. Retained the way this node bills its input -- -/// `chunk_bytes_beside_samples` per chunk, plus the allocations the chunks' samples are slices of, -/// each billed once by the first chunk that references one (`unbilled_sample_buffers`) -- the input -/// costs its rows, its descriptors and one charge for the buffer they slice: under a megabyte, so -/// the fold answers and leaves the pool empty. -/// -/// The φ is read at every grid point in the second fold below, as `scalar()`, which has nothing to hand over until that source has ended. The chunks that arrive -/// while it waits are retained as they come, so this fold pays the same figure: a fold that waited -/// without reading its input would leave those chunks in the source queue, which bills every queued -/// chunk for the whole buffer it points into -- 2000 x 16 392 bytes ≈ 32 MB, refused by this 4 MiB -/// pool at the 255th slice -- and the pool would answer the queue's figure rather than the input's. +/// A `quantile` bills the buffer its chunks slice once, not once per chunk: 2000 one-row slices of +/// one 16 KB buffer cost about 32 MB billed per chunk, past the 4 MiB pool, and under a megabyte +/// billed once. The same holds when `φ` is `scalar()` of another source and the fold retains its +/// input while it waits; chunks left in the source queue would each be billed the whole buffer. #[test] fn a_quantile_bills_a_shared_buffer_once() { const ROWS: usize = 2_000; @@ -13490,9 +11695,7 @@ fn a_quantile_bills_a_shared_buffer_once() { evaluated_array_chunk_of(&schema, metric(), row, batch.slice(row, 1), row + 1 == ROWS) }) .collect(); - // What a one-row chunk is charged by the figure this test is about: the buffer it is a slice of, - // not the eight bytes of the row it holds. The whole input is that buffer twice over -- once - // spent on the values and once billed per chunk -- which is what the pool would refuse. + // A one-row chunk billed for the buffer it slices, not the eight bytes it holds. let per_chunk = series_bytes(&chunks[0].series); assert!( per_chunk >= ROWS * std::mem::size_of::(), @@ -13515,10 +11718,7 @@ fn a_quantile_bills_a_shared_buffer_once() { evaluated_chunk_of(&schema, metric(), 0, vec![Some(0.5); ROWS], true), ) }; - // One source hands the chunks over and one pulls after each: a source queue holds the chunk the - // caller just pushed, so a pull per push keeps what the pool holds to what the nodes retain - // rather than to the whole input stream. An aggregate answers once its input ended, so nothing - // has settled here yet. + // A pull after each push keeps the pool to what the nodes retain, not the whole input stream. let run = |tree: &NativeTree, parameter: Option<(InputId, EvaluatedChunk)>, pool: Arc| { @@ -13577,15 +11777,8 @@ fn a_quantile_bills_a_shared_buffer_once() { assert_eq!(groups_of(&per_point), groups_of(&minimum)); } -/// A `quantile` bills the allocation its chunks' slices point into, once, and not the rows it holds of -/// it. -/// -/// A one-row chunk of a 100 000-row batch keeps that batch's whole 800 KB buffer resident, so that is -/// what retaining it costs: its row is eight bytes, and a figure that stopped at the rows would leave -/// the buffer the chunk pins to nothing -- a chunk holding a small slice of a large batch under-billed -/// by everything the batch holds. One allocation is also one however many chunks slice it, so a second -/// one-row chunk of the same batch is charged its descriptors and not the buffer again: billing every -/// chunk for the buffer it slices would refuse an input whose buffer fits the pool. +/// A `quantile` bills the buffer a one-row slice keeps resident, not just its row, and bills it +/// once: a second slice of the same batch costs only its descriptors. #[test] fn a_quantile_bills_the_allocation_its_slices_point_into_once() { const ROWS: usize = 100_000; @@ -13641,10 +11834,8 @@ fn a_quantile_bills_the_allocation_its_slices_point_into_once() { "two chunks slicing one {residency}-byte buffer are charged {both} bytes, so the buffer is \ counted once per chunk rather than once" ); - // What the second chunk cost is its own descriptors and the slot it takes in the vector: the - // allocation it slices is already billed, and its `Series` is that slot rather than a second - // figure beside it. The delta is exact, because the settle reads back the capacity the vector - // really holds, so a chunk billed twice -- or a buffer billed again -- shows up here. + // The second chunk costs exactly its descriptors and its slot in the vector: the buffer it + // slices is already billed. let second_cost = both.saturating_sub(one); let expected = super::chunk_bytes_beside_samples(&second.series) .saturating_add(std::mem::size_of::()); @@ -13663,13 +11854,7 @@ fn a_quantile_bills_the_allocation_its_slices_point_into_once() { assert_eq!(pool.reserved(), 0); } -/// A `quantile` skips a histogram sample and says so, exactly as `min` does. -/// -/// The φ-quantile orders the values of its group and a native histogram is not one it can order, so -/// Prometheus answers the quantile of the float samples and skips the histogram ones -- which for a -/// group of nothing but histograms is no answer at all. `min` reads a histogram the same way and -/// records the same info while doing it; the two are one branch in the legacy planner, and this pins -/// that the native fold agrees with them rather than answering from samples it dropped. +/// A `quantile` skips histogram samples and records the same info as `min`, as Prometheus does. #[test] fn a_quantile_skips_histogram_samples_and_reports_it_like_min() { let grid = grid(0, 60_000, 2); @@ -13722,55 +11907,13 @@ fn a_quantile_skips_histogram_samples_and_reports_it_like_min() { } } -/// An aggregate retains its fold before finish and release returns its reservation. -#[test] -fn aggregate_fold_state_is_released_after_input() { - let grid = grid(0, 1, 4); - let schema = evaluated_schema(Arc::clone(&grid)); - let tree = NativeTree::try_new(aggregate( - evaluated_input(Arc::clone(&grid)), - sum_grouping(Grouping::By(Arc::new([]))), - )) - .unwrap(); - let pool = bounded_pool(1 << 20); - let mut execution = executor(&tree, Arc::clone(&pool)); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of(&schema, metric(), 0, vec![Some(2.0)], true), - ) - .unwrap(); - assert!(execution.next_chunk().unwrap().is_none()); - // The root is the aggregate the tree built: its fold holds one group and has not run. The - // borrow ends before the close below takes the state again. - { - let RuntimeOp::Aggregate { aggregate, .. } = - &execution.state().live.as_ref().unwrap().root.op - else { - panic!("the root is not the aggregate the tree built"); - }; - assert_eq!(aggregate.groups(), 1); - assert!(!aggregate.computed); - } - assert!(pool.reserved() > 0); - execution.finish().unwrap(); - assert_eq!(pool.reserved(), 0); -} - -/// A `quantile` carries no state, so a tree cannot even bind it as anything but `Complete`. -/// -/// `quantile` is answered from its group's whole sample set, so a stage that saw part of a group -/// would answer the quantile of a subset of it, and the quantile of two partial groups is not a -/// function of their quantiles. There is no state layout to export or merge, which is what the tree's -/// own validation refuses while it is built: a `Partial` or `Final` node has nowhere to put its -/// state. That refusal is the only one there is -- the runtime starts from a validated tree and so -/// starts the `Complete` stage alone, without a second check of its own. +/// `quantile` has no mergeable state, so validation refuses a `Partial` or `Final` stage and the +/// runtime only ever starts `Complete`. #[test] fn a_quantile_stage_the_runtime_does_not_compute_is_named() { let grid = || grid(0, 60_000, 4); let schema = || evaluated_schema(grid()); - // The state layout a `Sum` exports is enough to build the stage's tree: what this test asks is - // which stages the runtime starts, and a `quantile` state is refused before it is read. + // A `Sum` state layout is enough to build the stage's tree. let (state_kind, components) = crate::native::plan::aggregate_state_binding(AggregateKind::Sum, FieldKind::Float).unwrap(); let state_schema = || { @@ -13865,13 +12008,8 @@ fn a_quantile_stage_the_runtime_does_not_compute_is_named() { ); } -/// An aggregate above a window that collects and merges its input waits for that merge. -/// -/// The multiplication drops the metric name, so the two input series land on one label set and the -/// `last_over_time` above them has to collect and merge before it evaluates. The aggregate above the -/// window must wait for that merge: its guard is `inputs_finished && settled(child)`, and with only -/// the first half it finalizes on the pull that follows the caller's last chunk, before the window -/// has answered. +/// An aggregate above a collecting window waits for the window's merge, not just for the input to +/// end. #[test] fn an_aggregate_above_a_collecting_window_waits_for_the_merge() { let grid = grid(0, 60_000, 4); @@ -14118,7 +12256,7 @@ fn topk_ranks_whole_series_at_each_point() { } #[test] -fn parameterized_topk_varies_by_grid_point_and_handles_invalid_k() { +fn parameterized_topk_varies_by_grid_point_including_zero_k() { let grid = grid(1_000, 2_000, 3); let schema = evaluated_schema(Arc::clone(&grid)); let input = evaluated_input(Arc::clone(&grid)); @@ -14193,12 +12331,8 @@ fn parameterized_topk_varies_by_grid_point_and_handles_invalid_k() { assert_eq!(counts, [1, 3, 0]); } -/// A point the parameter series holds no sample at selects nothing there, as Prometheus' empty -/// parameter does at that step, and does not abort the points that do hold one; a parameter that is -/// present and NaN is still an error. -/// -/// `values` is what the topk arm reads a parameter series into: `None` is a position the series -/// decided nothing at, `Some(k)` a value it decided. +/// A point the parameter holds no sample at selects nothing there, as Prometheus' empty parameter +/// does, without aborting the other points; a present NaN is still an error. #[test] fn a_topk_parameter_with_a_gap_selects_nothing_at_that_point() { let grid = grid(0, 1_000, 3); @@ -14247,10 +12381,8 @@ fn a_topk_parameter_with_a_gap_selects_nothing_at_that_point() { assert!(error.to_string().contains("NaN"), "{error}"); } -/// A parameterized `topk` reads its per-point parameter whole before it reads any input, so the -/// values it reads it into are held beside the input for as long as the node lives: a pool that -/// admits the parameter series but not the values refuses the query rather than running it over the -/// budget. +/// A parameterized `topk` holds the values it reads its parameter into for its whole life, so a +/// pool that admits the parameter series but not those values refuses the query. #[test] fn parameterized_topk_reserves_the_values_of_its_parameter() { // `eval_time` hands over one value per grid point: eight bytes a point in the series the node is @@ -14473,12 +12605,8 @@ fn dynamic_parameters_finish_windows_before_dropping_the_subtree() { } } -/// A parameterized `topk` released before it computes gives back everything it holds: the input it -/// retained, and with it the samples and the label allocations those chunks keep alive. -/// -/// The node's payload is the whole vector runtime, not the parameter values alone: a release that -/// cleared only those would hand the pool its bytes back while the retained chunks -- and the -/// executor a caller keeps alive -- still hold what it released. +/// A parameterized `topk` released before it computes drops the input it retained, including the +/// label allocations its chunks keep alive. #[test] fn a_parameterized_topk_released_before_it_computes_drops_its_retained_input() { let grid = grid(0, 1_000, 2); @@ -14537,13 +12665,11 @@ fn a_parameterized_topk_released_before_it_computes_drops_its_retained_input() { ); } -/// A parameterized histogram function reads each parameter whole before it reads its input, so the -/// values it reads them into are held beside the input for as long as the node lives: a pool that -/// admits the parameter series but not the values refuses the query rather than running it over the -/// budget. +/// A parameterized histogram function holds the values it reads its parameters into for its whole +/// life, so a pool that admits the parameter series but not those values refuses the query. #[test] fn parameterized_histogram_reserves_the_values_of_its_parameters() { - // As above: eight bytes a point in the series, sixteen in the values read off it. + // Eight bytes a point in the series, sixteen in the values read off it. const POINTS: usize = 1 << 18; let grid = grid(0, 1_000, POINTS as u64); let root = NativeNode { @@ -14576,13 +12702,9 @@ fn parameterized_histogram_reserves_the_values_of_its_parameters() { } } -/// A parameterized histogram decides every result on the pull that finds its input ended, and hands -/// them over from its own queue one result a pull: each pull after the first settles on what the -/// node still holds, the results still queued beside the values it reads its parameters into. -/// -/// Settling over the state as the kernel left it would drop the queued results' bytes: the handover -/// that follows would take them from a reservation that no longer holds them, and the query would -/// fail on results it had already computed. +/// A parameterized histogram queues every result on the pull that finds its input ended and hands +/// them over one per pull; each pull keeps the parameter values and the still-queued results +/// charged. #[test] fn parameterized_histogram_hands_over_its_results_from_its_own_queue() { let grid = grid(0, 1_000, 2); @@ -14596,10 +12718,8 @@ fn parameterized_histogram_hands_over_its_results_from_its_own_queue() { output: evaluated(Arc::clone(&grid)), }; let tree = NativeTree::try_new(root).unwrap(); - // Two label sets of buckets over two points, so the kernel decides two series and the queue - // holds a result the pull after the first has to hand over. The pool is sized for the run as it - // is accounted for: 16 KiB, which covers the chunks, their assembly and the kernel's workspace, - // is not enough -- what the node holds at its peak is a little over 20 KB. + // Two label sets over two points, so a result stays queued after the first pull. The node peaks + // a little over 20 KB. let pool = bounded_pool(64 << 10); let mut execution = executor(&tree, Arc::clone(&pool)); for host in ["a", "b"] { @@ -14743,13 +12863,9 @@ fn parameterized_histogram_quantile_uses_each_grid_point_parameter() { assert_eq!(decided(&chunks), vec![(0, Some(1.5)), (1, Some(2.0))]); } -/// A literal argument of a parameterized histogram call is materialized from its bound value: a -/// constant node produces no chunk, so a consumer that pulls it finds nothing to read. -/// -/// `histogram_fraction(0, , m)` is the statement that reported `histogram parameter -/// produced no scalar` before the constant was read off its binding. The same statement with the -/// literal `0` written as an expression that evaluates to zero answers the same rows, so this -/// compares the two rather than a hand-computed fraction: the literal is honoured, not skipped. +/// A literal argument of a parameterized histogram call is read from its binding, since a constant +/// node hands over no chunk: `histogram_fraction(0, , m)` answers what the same call with +/// `0` computed from `time()` answers. #[test] fn parameterized_histogram_reads_its_literal_parameter_without_a_chunk() { let grid = grid(0, 1_000, 2); @@ -14812,103 +12928,8 @@ fn parameterized_histogram_reads_its_literal_parameter_without_a_chunk() { ); } -/// The same buckets with a constant `phi` answer the same value at every point, so the two values -/// the parameterized run above reports are the parameter read per point rather than once. -#[test] -fn constant_histogram_quantile_answers_every_point_with_its_one_phi() { - let grid = grid(0, 1_000, 2); - let schema = evaluated_schema(Arc::clone(&grid)); - let tree = NativeTree::try_new(vector_op( - evaluated_input(Arc::clone(&grid)), - BoundVectorOp::Histogram(HistogramFunction::Quantile(0.5)), - )) - .unwrap(); - let mut execution = executor(&tree, pool()); - for (le, counts) in [ - ("1", vec![Some(1.0), Some(1.0)]), - ("2", vec![Some(9.0), Some(9.0)]), - ("+Inf", vec![Some(10.0), Some(10.0)]), - ] { - let metric = SeriesLabels::try_new( - Some("m".into()), - vec![Label { - name: "le".into(), - value: le.into(), - }], - ) - .unwrap(); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of(&schema, metric, 0, counts, true), - ) - .unwrap(); - } - let chunks = run(&mut execution); - assert_eq!(decided(&chunks), vec![(0, Some(1.5)), (1, Some(1.5))]); -} - -#[test] -fn parameterized_topk_rejects_nan_and_overflow_parameters() { - for (grid, parameter) in [ - { - let grid = grid(0, 1_000, 1); - let time = eval_time(None, Arc::clone(&grid)); - let zero = scalar_binary(time.clone(), time, binary_matching(BinaryOp::Sub)); - let nan = scalar_binary(zero.clone(), zero, binary_matching(BinaryOp::Div)); - (grid, nan) - }, - { - let grid = grid(1_000, 1_000, 1); - let huge = scalar_binary( - eval_time(None, Arc::clone(&grid)), - scalar(1e30, Arc::clone(&grid)), - binary_matching(BinaryOp::Mul), - ); - (grid, huge) - }, - ] { - let schema = evaluated_schema(Arc::clone(&grid)); - let input = evaluated_input(Arc::clone(&grid)); - let root = NativeNode { - expr: NativeExpr::ParameterizedTopK { - input: Box::new(input.clone()), - op: BoundVectorOp::TopK { - k: 0.0, - top: true, - group: Grouping::By(Arc::from([])), - }, - parameter: Box::new(parameter), - }, - output: input.output, - }; - let tree = NativeTree::try_new(root).unwrap(); - let mut execution = executor(&tree, pool()); - for index in 0..5 { - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of( - &schema, - named_metric("m", &index.to_string()), - 0, - vec![Some(index as f64)], - true, - ), - ) - .unwrap(); - } - execution.end_of_input().unwrap(); - let error = execution.next_chunk().unwrap_err(); - assert!( - error.to_string().contains("NaN") || error.to_string().contains("overflows int64"), - "{error}" - ); - } -} - -/// The full parameter grid is validated before selecting any point, including a negative k whose -/// underflow would otherwise be hidden by a later valid value. +/// The whole parameter grid is validated before any point is selected, even with no input: NaN and +/// int64 overflow are refused, zero is not. #[test] fn parameterized_topk_validates_parameters_even_when_input_is_empty() { for (grid, parameter, error) in [ @@ -15010,104 +13031,6 @@ fn parameterized_topk_rejects_underflow_across_grid() { assert!(error.to_string().contains("underflows int64"), "{error}"); } -#[test] -fn scalar_of_reads_one_series_value_at_each_point() { - let grid = grid(0, 1_000, 3); - let schema = evaluated_schema(Arc::clone(&grid)); - let tree = NativeTree::try_new(scalar_of(evaluated_input(Arc::clone(&grid)))).unwrap(); - let mut execution = executor(&tree, pool()); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of( - &schema, - named_metric("a", "a"), - 0, - vec![Some(1.0), Some(2.0), Some(3.0)], - true, - ), - ) - .unwrap(); - assert_eq!( - decided(&run(&mut execution)), - vec![(0, Some(1.0)), (1, Some(2.0)), (2, Some(3.0))] - ); -} - -#[test] -fn scalar_of_ignores_histogram_when_one_float_is_present() { - let grid = grid(0, 1_000, 1); - let schema = evaluated_schema(Arc::clone(&grid)); - let tree = NativeTree::try_new(scalar_of(evaluated_input(Arc::clone(&grid)))).unwrap(); - let mut execution = executor(&tree, pool()); - execution - .push_evaluated( - InputId::new(0), - evaluated_chunk_of( - &schema, - named_metric("float", "float"), - 0, - vec![Some(7.0)], - true, - ), - ) - .unwrap(); - let mut builder = HistogramBatchBuilder::new(); - let index = push_histogram(&mut builder, 2); - let table = Arc::new(builder.finish().unwrap()); - execution - .push_evaluated( - InputId::new(0), - evaluated_histogram_chunk_of( - &schema, - named_metric("histogram", "histogram"), - 0, - vec![Some(index)], - &table, - true, - ), - ) - .unwrap(); - assert_eq!(decided(&run(&mut execution)), vec![(0, Some(7.0))]); -} - -#[test] -fn scalar_of_answers_nan_for_a_histogram_alone() { - let grid = grid(0, 1_000, 1); - let schema = evaluated_schema(Arc::clone(&grid)); - let tree = NativeTree::try_new(scalar_of(evaluated_input(Arc::clone(&grid)))).unwrap(); - let mut execution = executor(&tree, pool()); - let mut builder = HistogramBatchBuilder::new(); - let index = push_histogram(&mut builder, 2); - let table = Arc::new(builder.finish().unwrap()); - execution - .push_evaluated( - InputId::new(0), - evaluated_histogram_chunk_of( - &schema, - named_metric("histogram", "histogram"), - 0, - vec![Some(index)], - &table, - true, - ), - ) - .unwrap(); - // A histogram sample holds no float value, so the point answers NaN rather than an error: the - // kernel ignores it, as Prometheus' `funcScalar` does. - let values = decided(&run(&mut execution)); - assert_eq!( - values.len(), - 1, - "one answer for the one grid point: {values:?}" - ); - assert_eq!(values[0].0, 0); - assert!( - values[0].1.is_some_and(f64::is_nan), - "a histogram alone is no element of the vector: {values:?}" - ); -} - #[test] fn scalar_of_reads_one_value_per_point_from_the_whole_vector() { let grid = grid(0, 1_000, 4); @@ -15275,11 +13198,8 @@ fn scalar_of_reserves_its_counts_while_it_reads_the_assembly() { } } -/// `scalar()` reports what it holds while it retains its input, not that memory twice. -/// -/// The retention path sets the node's reservation to what it retains, so the figure it reports is a -/// reading of that one reservation: adding the retained bytes to it again would report more than the -/// pool granted, and a caller watching the pool would read a node holding more than it holds. +/// `scalar()` reports the one reservation it holds while it retains its input, not that figure +/// twice. #[test] fn scalar_of_reports_what_it_holds_while_its_input_is_retained() { let grid = grid(0, 1_000, 2); @@ -15764,16 +13684,12 @@ fn count_values_reserves_a_group_per_field_sample() { assert!(estimate(4) >= 4 * estimate(1)); } -/// `label_replace` runs in a map: each series is relabelled as it passes, and two series it gives -/// one label set collide where both hold a value, as Prometheus' same-labelset check refuses. -/// -/// The map rewrites a label its input carries, so the canonical pass collects what it hands out: the -/// merge above the rewrite is where the two pieces are read against each other. +/// `label_replace` relabels each series as it passes, and two series it puts under one label set +/// collide in the merge above where both hold a value. #[test] fn a_label_rewrite_relabels_series_and_refuses_a_shared_point() { let grid = grid(0, 60_000, 2); let schema = evaluated_schema(Arc::clone(&grid)); - let rewrite = LabelRewrite::replace("job", "all", "job", ".*").unwrap(); let tree = |merge_above: bool| { let rewritten = map_ops( evaluated_input(Arc::clone(&grid)), @@ -15788,7 +13704,6 @@ fn a_label_rewrite_relabels_series_and_refuses_a_shared_point() { }) .unwrap() }; - assert_eq!(rewrite.destination(), "job"); // The rewrite itself: one series passes and leaves under the label it wrote. let mut relabelled = executor(&tree(false), pool()); @@ -15962,9 +13877,8 @@ fn a_label_change_admits_the_label_it_writes_before_building_it() { assert_eq!(pool.reserved(), 0); } -/// An ended execution drops its tree, input schema and grid, while registered counters survive. -/// Both ways an execution ends are covered: the answer is drained, and a rejected push stops it -/// first. +/// An ended execution keeps neither its input schema nor its grid, whether it drained its answer or +/// a rejected push stopped it; registered counters survive. #[test] fn an_ended_execution_keeps_no_input_schema_or_grid() { for fails in [false, true] { @@ -16022,16 +13936,6 @@ fn an_ended_execution_keeps_no_input_schema_or_grid() { drop(refused); } - // The chunks still queued on the execution must not retain either input allocation. - assert!( - schema_weak.upgrade().is_none(), - "queued chunks retained the schema they were built with" - ); - assert!( - grid_weak.upgrade().is_none(), - "queued chunks retained the grid they are addressed on" - ); - // What the caller registered before the run sees is what the nodes recorded. assert!( schema_weak.upgrade().is_none(), "the ended execution kept the schema its input was bound to" @@ -16064,11 +13968,8 @@ fn an_ended_execution_keeps_no_input_schema_or_grid() { } } -/// A chunk pushed after the input ended is refused, and the answer already queued stays pullable. -/// -/// The ending stages run as the caller pulls, so a chunk arriving behind them would reach a leaf -/// whose consumer has already decided what to answer. It is refused rather than queued, and the -/// refusal is not a stop: what the execution holds is the answer the caller has not pulled yet. +/// A chunk pushed after the input ended is refused without stopping the execution: the answer +/// already queued stays pullable. #[test] fn a_chunk_pushed_after_the_input_ended_is_refused() { let (tree, grid, _, _) = binary_tree(BinaryOp::Add, 4); @@ -16185,13 +14086,9 @@ fn a_chunk_pushed_after_the_input_ended_is_refused() { assert_eq!(pool.reserved(), 0); } -/// A point-wise node reserves the series its kernel builds before the kernel runs. -/// -/// Every case reads one dense series over a grid of `1 << 20` points, or -- for the window -- one -/// raw sample whose window reaches every point, so the kernel writes a row per point. The first -/// budget admits what the node is handed (the vector, the varying scalar, the grid's timestamps) -/// and not the series it writes, which only the reservation taken before the kernel can refuse: -/// nothing after it rejects a dense result of one run. The second admits both. +/// A point-wise node reserves the series its kernel builds before the kernel runs: with a `1 << 20` +/// point dense result, a budget for the node's input but not its output is refused, and one for +/// both is admitted. #[test] fn point_wise_nodes_reserve_the_series_their_kernel_builds() { const MIB: usize = 1 << 20; @@ -16271,13 +14168,8 @@ fn aggregate_with_output(input: NativeNode, op: BoundAggregate, output: NativeTy } } -/// A state chunk the producer hands over stays charged until the consumer drops it. -/// -/// The producer queues a chunk against its own reservation and gives that reservation back when the -/// chunk leaves the queue. A consumer that keeps the batch - the state exporter packs rows from it -/// across polls - must then be the one holding those bytes, or the pool admits memory nobody -/// accounts for. The charge therefore moves with the chunk, and dropping the chunk returns exactly -/// that figure. +/// A state chunk carries its charge out of the producer's queue and returns it when the consumer +/// drops it. #[test] fn a_handed_over_state_chunk_keeps_its_charge_until_it_is_dropped() { let grid = grid(0, 60_000, 2); @@ -16319,23 +14211,9 @@ fn a_handed_over_state_chunk_keeps_its_charge_until_it_is_dropped() { .next_state() .unwrap() .expect("a partial sum exports one state chunk"); - let crate::native::state::StateChunk::Series { - reservation, - state_schema: exported, - .. - } = &chunk - else { + let crate::native::state::StateChunk::Series { reservation, .. } = &chunk else { panic!("a partial producer exports series state, not a decoded row"); }; - assert_eq!( - state_kind, exported.kind, - "the exported state keeps its kind" - ); - assert_eq!( - state_schema.components.as_ref(), - exported.components.as_ref(), - "the exported state keeps its components" - ); let carried = reservation .as_ref() .expect("the handed-over chunk carries the charge the queue released") @@ -16510,21 +14388,6 @@ fn partial_final_matches_complete_over_concatenated_input() { .unwrap(), ) .unwrap(); - assert_eq!(row.fields.field(0).unwrap().len(), value_len); - assert!(values.values().inner().capacity() > value_len * 100); - assert!(compensations.values().inner().capacity() > value_len * 100); - let retained_value = row - .fields - .field(0) - .unwrap() - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!( - retained_value.values().inner().as_ptr(), - values.values().inner().as_ptr() - ); backing_probe = Some(crate::native::state::StateChunk::Row(row)); } partial_states.push(crate::native::state::StateChunk::Row(row)); @@ -16556,9 +14419,7 @@ fn partial_final_matches_complete_over_concatenated_input() { assert!(value.values().inner().capacity() > visible_len * 100); assert!(compensation.values().inner().capacity() > visible_len * 100); - // The charge is the row's own extent, not the 4096-element buffers it borrows: a - // Final row is a one-row slice of the frame's list values, and charging the parent per - // row is what multiplied a chained router's figure. + // The charge is the row's own extent, not the 4096-element buffers it borrows. let own = crate::native::state::state_row_bytes(row); assert!( own < backing_bytes, @@ -16733,9 +14594,8 @@ fn grid_position_reads_the_lattice_and_reports_what_is_off_it() { #[test] fn grid_position_still_answers_a_lattice_whose_offset_does_not_fit_in_an_i64() { - // The points are `i64::MIN`, `-1` and `i64::MAX - 1`: the last one is in range, but it sits - // `2 * i64::MAX` past the start, so only the `i128` path can place it. Answering an error here - // would make the fast path narrower than the code it replaces. + // The points are `i64::MIN`, `-1` and `i64::MAX - 1`: the last sits `2 * i64::MAX` past the + // start, so only the `i128` path can place it. let grid = EvalGrid::try_new(GridSpec::try_new(i64::MIN, i64::MAX, 3).unwrap()).unwrap(); assert_eq!(0, grid_position(&grid, i64::MIN).unwrap()); // The offset is `i64::MAX`, the widest the fast path accepts. diff --git a/src/promql/src/native/metrics.rs b/src/promql/src/native/metrics.rs index 22381001511..a3157b80ce1 100644 --- a/src/promql/src/native/metrics.rs +++ b/src/promql/src/native/metrics.rs @@ -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..` 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`, 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..`, 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..`, 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>, } 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..`, and `native.p..` 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..` or `native.p..` 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(); diff --git a/src/promql/src/native/mod.rs b/src/promql/src/native/mod.rs index 0012c28b03d..bbb9796dfa3 100644 --- a/src/promql/src/native/mod.rs +++ b/src/promql/src/native/mod.rs @@ -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; diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index f0d4d61be14..3deda316147 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -15,17 +15,12 @@ //! The bound tree a native PromQL evaluation compiles to. //! //! A query is compiled into [`NativeTree`]: [`NativeNode`]s whose operations are already bound to -//! kernels, fields and grids. Nothing in this module interprets a function name, resolves a label -//! or picks a column at run time; those decisions are made before the tree exists, so the hot -//! path only feeds batches to kernels it was handed. +//! kernels, fields and grids, so nothing here interprets a function name, resolves a label or picks +//! a column at run time. //! -//! The tree is also the unit of legality. [`NativeNode::validate`] checks the contract every -//! operation states about its input, which is what lets a new combination of supported operations -//! be an ordinary tree instead of another hand-written shape. -//! -//! What the tree cannot express yet is deliberate for this stage: [`NativeExpr::Scalar`] holds a -//! constant, so `time()` and `scalar(v)` have no node. The legality below is therefore about the -//! operations that exist, not about PromQL's whole surface. +//! The tree is also the unit of legality: [`NativeNode::validate`] checks the contract each +//! operation states about its input, so any combination of supported operations that passes it is +//! executable. use std::hash::Hash; use std::sync::Arc; @@ -51,54 +46,31 @@ use crate::vector_match::{ BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp, }; -/// The bucket-bound label a classic histogram's series carry, which the histogram function folds and -/// its result does not report. +/// The bucket-bound label a classic histogram function folds away. const LE_LABEL: &str = "le"; -/// The label a metric name is stored under, which a scan binds beside its tag columns rather than -/// among them. +/// The metric-name label. A scan binds it beside its tag columns, not among them. pub(crate) const METRIC_NAME: &str = "__name__"; -/// Metadata labels the runtime removes from histogram result label sets. +/// The labels `map::drop_metric_name` removes (`grid_series::METADATA_LABELS`). const PROMQL_METADATA_LABELS: [&str; 3] = ["__name__", "__type__", "__unit__"]; -/// A conservative set of reportable label names for `node`. +/// A conservative set of label names `node` may report, following Prometheus' result labels. /// /// `source_tags` is indexed by each leaf's `source_index`. The canonical pass supplies runtime -/// label names, including `__name__` for named scans; the planner supplies declared tag columns -/// to derive output columns. The result need not describe the labels of any individual series: -/// `or` includes a nullable `__name__` column even when both operands drop their names. Math -/// operations remove only `__name__` here, while their runtime also removes `__type__` and -/// `__unit__`. +/// label names, including `__name__` for named scans; the planner supplies declared tag columns. +/// The result is a superset over all output series: `or` includes a nullable `__name__` even when +/// both operands drop their names. A node whose kernel drops the metric name drops it here too, so +/// a name rewrite below it cannot make the name reappear above it. /// -/// They follow Prometheus' result labels: a one-to-one match keeps the left side's labels, narrowed -/// by `on` or `ignoring`; `and` and `unless` keep the left side's series and `or` adds the right -/// side's; `info` adds the data labels of the info table; an operation with a scalar or a function -/// of each value keeps its operand's; a scalar and `vector(s)` have none; `count_values` keeps its -/// grouping and the label it writes; a fill that answers a missing many-side sample files the one -/// side's matching labels, so they join the set, while a grouped `include` label joins them only when -/// the one side carries it or the matching keeps it in the key a fill reads. A label rewrite writes -/// its destination, and a destination that names the metric name writes that name. -/// -/// A node that reports a value of its own drops the name where its kernel does - `timestamp`, a -/// range function whose result is computed (`rate`, `increase`, ...), a math or histogram map, -/// `histogram_quantile`, every non-filtering binary - so a name rewrite below one of them cannot -/// make the name reappear above it. -/// -/// `None` for a node whose labels this walk does not derive - a `count_values` whose destination is -/// empty, or an input whose source has no entry. `None` proves nothing: the canonical pass treats -/// it as "may alias" rather than as "distinct", and the planner keeps the statement off the native -/// route. +/// `None` when the labels are not derived (a `count_values` with an empty destination, or an input +/// without a `source_tags` entry). Callers must treat `None` as "may alias", not as "distinct". pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Option> { match &node.expr { NativeExpr::Input(input) => source_tags.get(input.source_index).cloned(), NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } | NativeExpr::VectorOf { .. } => { Some(Vec::new()) } - // These report a value of their own rather than the sample they read, and the runtime drops - // the name for each of them. `source_tags` is the authority on what an input carries, so a - // discovery input arrives carrying `__name__` and these arms are what decides it does not - // survive. NativeExpr::Instant { input, op } => { let tags = fused_output_tags(input, source_tags)?; Some(match op.value { @@ -118,10 +90,7 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti input, source_tags, )?)), - // A label rewrite changes the label set itself: `label_replace` adds its destination label - // and an empty replacement removes it, so the input's labels are not the output's. A math or - // histogram kernel drops the metric name where it runs, and the ops apply in written order, - // so what follows a rewrite sees the set the rewrite left. + // The ops apply in written order, so a math op after a rewrite of `__name__` still drops it. NativeExpr::Map { input, op } => { let mut tags = fused_output_tags(input, source_tags)?; for operation in op.ops.iter() { @@ -129,14 +98,9 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti MapOp::Label(rewrite) => { let destination = rewrite.destination(); if tags.iter().any(|tag| tag == destination) { - // The input carries the label, so the rewrite changes its value - and an - // empty replacement may remove it, which the column still represents. tags.retain(|tag| tag != destination); tags.push(destination.to_string()); } else if rewrite.writes_value() { - // A fresh destination is a label the output only carries when the - // rewrite can write a value; a delete-only rewrite of a label no input - // carried publishes nothing. tags.push(destination.to_string()); } } @@ -145,48 +109,26 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti } Some(tags) } - // Its parameters are scalars, which carry no labels; the map computes a value of its own - // with the input, and its kernel drops the metric name. NativeExpr::ParameterizedMap { input, .. } => Some(without_metadata_labels( fused_output_tags(input, source_tags)?, )), - // `scalar()` reports one value and no labels, like the scalar it produces. NativeExpr::ScalarOf { .. } => Some(Vec::new()), - // Its parameter is a scalar, which carries no labels, and ranking keeps each selected - // series' own labels. NativeExpr::ParameterizedTopK { input, .. } => fused_output_tags(input, source_tags), - // A parameterized histogram function folds the bucket series that share the other labels - // into one series and drops `le` along with the metadata labels, exactly as its bound - // counterpart does. Its parameters are scalars and carry no labels. NativeExpr::ParameterizedHistogram { input, .. } => { let mut tags = fused_output_tags(input, source_tags)?; tags.retain(|tag| tag != LE_LABEL && !PROMQL_METADATA_LABELS.contains(&tag.as_str())); Some(tags) } - // An aggregate reports the grouping labels its input carries: `by(...)` keeps exactly the - // ones it names, and `without(...)` keeps the rest and drops the metric name, as Prometheus - // does. A grouping by `__name__` keeps the name where the input reports one - which is - // `source_tags`'s answer, not the schema's: a named input declares it when the statement - // reads more than one, so the groups two metrics form stay apart, and a statement reading - // one leaves the column to the rows layout's appended name, which is what `sum by - // (__name__)` over one metric reports. NativeExpr::Aggregate { input, op } => grouped_output_tags(input, op, source_tags), - // Its parameter is a scalar, which carries no labels, so a fold that reads it per point - // reports the same columns as the one that binds its `φ`. NativeExpr::ParameterizedAggregate { input, op, .. } => { grouped_output_tags(input, op, source_tags) } - // Selecting some of the input's series keeps each one's own labels, and `count_values` - // keeps its grouping's; `histogram` folds bucket series into one histogram, so it does not - // report the input's set. NativeExpr::Vector { input, op } => match op { BoundVectorOp::TopK { .. } | BoundVectorOp::LimitK { .. } | BoundVectorOp::LimitRatio { .. } | BoundVectorOp::Sort(_) => fused_output_tags(input, source_tags), - // `absent` reports the labels its own matchers name, not the input's set and not the - // table's columns: it answers one series carrying exactly those, so a label the input - // does not carry is still a label of the result. + // `absent` reports the equality matchers' labels, not the input's. BoundVectorOp::Absent { labels } => Some( labels .tags() @@ -194,17 +136,8 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti .map(|label| label.name.to_string()) .collect(), ), - // `count_values` writes the value it counts into its own label and then keeps its - // grouping: `by(...)` keeps the labels named plus that destination, `without(...)` - // keeps the rest minus the labels named and the metric name. What the node reports is - // therefore the grouping applied to the labels its input carries, with the destination - // among them - not the input's set, and not the scan's, since the grouping narrows both. - // - // The destination is a label the node creates, so a rewrite of it above this node is a - // rewrite of an existing label. A destination naming the metric name writes the name - // the node groups by, which is the one label its result carries. This walk derives the - // labels; it does not decide which groupings the kernel accepts, and those refusals stay - // where they are. + // `count_values` adds its destination label, then applies its grouping; `by` always + // keeps the destination. BoundVectorOp::CountValues { label, group } if !label.is_empty() => { let mut tags = fused_output_tags(input, source_tags)?; if !tags.contains(&label.to_string()) { @@ -216,7 +149,6 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti .into_iter() .filter(|tag| names.iter().any(|name| name.as_ref() == tag)) .collect::>(); - // `by` keeps the label the node writes whether the input carried it or not. if !output.contains(&label.to_string()) { output.push(label.to_string()); } @@ -231,9 +163,6 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti }) } BoundVectorOp::CountValues { .. } => None, - // A classic histogram function folds the bucket series that share the other labels into - // one series and drops `le`, along with the metadata labels the runtime does not put on - // its result. What it keeps is everything else its input carried. BoundVectorOp::Histogram(_) => { let mut tags = fused_output_tags(input, source_tags)?; tags.retain(|tag| { @@ -273,19 +202,15 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti }; let left_tags = fused_output_tags(left, source_tags)?; let right_tags = fused_output_tags(right, source_tags)?; - // One-to-one matching narrows the left side's labels with `on`/`ignoring`. - // A group retains the many side's labels and copies the named labels from the one - // side: `group_left(container)` keeps the left labels and adds `container` from - // the right. + // One-to-one narrows the left side's labels by `on`/`ignoring`; a group keeps + // the many side's labels and copies its include labels from the one side. let mut tags = match &matching.cardinality { Cardinality::OneToOne => kept(left_tags.clone()), Cardinality::ManyToOne(_) => left_tags.clone(), Cardinality::OneToMany(_) => right_tags.clone(), }; - // `result_metric` drops the metadata labels before it matches or copies an - // included label, so an arithmetic result starts without the name. An include can - // still put it back from the one side, which is why the final rule below does not - // run on this branch. + // `result_metric` drops the name before copying include labels, so an include can + // still put it back from the one side. if !keeps_name { tags.retain(|tag| tag != METRIC_NAME); } @@ -302,18 +227,12 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti tags.push(tag.clone()); } } - // A grouped result carries an include label only when a row can give it one. - // `result_metric` removes the label from the many side's labels unless the one side - // has it, so a paired row and a row filed from a one-side series take it from the - // one series, which is what the loop above declares. A row filed from a many-side - // series takes it from that series' match key instead, so it carries the label only - // when the matching keeps the label in the key. Everything else the many side - // carries is the base above, so a label neither of those can provide has to leave - // the set: nothing would ever fill its column. + // `result_metric` removes an include label from the many side unless the one side + // has it. A row filled from a many-side series takes it from its match key, so + // the label survives only if the one side carries it or a fill keys on it. if !includes.is_empty() { let many_rows_filled = match &matching.cardinality { - // `group_right` puts the one side on the left, so the fills trade places: - // `fill_left` is the one that answers a missing one-side sample there. + // `group_right` puts the one side on the left, so the fills swap. Cardinality::OneToMany(_) => matching.fill.lhs, Cardinality::ManyToOne(_) | Cardinality::OneToOne => matching.fill.rhs, } @@ -334,24 +253,16 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti || (many_rows_filled && in_match_key(tag)) }); } - // A fill answers a missing sample from the series of the other side, and the kernel - // files that row at the label set the series it has gives it - // (`vector_match::binary_field`): a many-side series keeps all of its labels, which - // `tags` already holds, while a one-side series keeps only its matching labels plus - // the group labels the modifier names, which the loop above adds. So what a fill can - // add here is the one side's matching labels, and only a fill that can file a - // one-side row has any to add: one where the many side is the missing side. Which - // fill that is follows the kernel, which trades the two for `group_right`, whose one - // side is the left - there it is `fill_right` that leaves the many side missing. + // A row filled from a one-side series keeps only its matching labels plus the + // include labels (`vector_match::binary_field`), so only the fill for a missing + // many side adds labels here. `group_right` swaps the fills. let (one_tags, fills_many_side) = match &matching.cardinality { Cardinality::OneToMany(_) => (&left_tags, matching.fill.rhs), Cardinality::ManyToOne(_) | Cardinality::OneToOne => { (&right_tags, matching.fill.lhs) } }; - // A filled row keeps only the one side's matching labels, so the name can reach - // it only through an `on` key that names the metric name, and only while the - // operation reports its samples' names. + // A filled one-side row carries the name only through an `on(__name__)` key. let fill_carries_name = keeps_name && matches!(&matching.labels, MatchingLabels::On(names) if names.iter().any(|name| name.as_ref() == METRIC_NAME)); @@ -382,17 +293,15 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti tags.push(tag); } } - // `or` reports the series of both sides, and each row keeps the name of the side it - // came from, so the name is a label of the result even when neither source declares - // it as a tag column. A side whose kernel dropped the name leaves the column empty. + // Each `or` row keeps its own side's name, so the result needs the column even + // when neither source declares it. if !tags.iter().any(|tag| tag == METRIC_NAME) { tags.push(METRIC_NAME.to_string()); } } Some(tags) } - // A base series keeps its labels and takes the data labels of its info series: the ones the - // selector names, or all of them when it names none. + // The selector's data labels, or all of the info series' labels when it names none. NativeExpr::Info { base, info, @@ -414,15 +323,8 @@ pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec]) -> Opti } } -/// The labels an aggregate reports: the ones its grouping keeps among those its input carries. -/// -/// `by(...)` keeps exactly the labels it names, and `without(...)` keeps the rest and drops the -/// metric name, as Prometheus does. A grouping by `__name__` keeps the name where the input reports -/// one; a named scan only reports it among the runtime labels, so the aggregate keeps it there and -/// publishes no column for it, which is what `sum by (__name__)` over one metric reports. -/// -/// Both the fold that binds its argument and the one that reads it per point answer this way: what -/// decides the columns is the grouping, not where the aggregate's one argument comes from. +/// `without(...)` also drops the metric name, as Prometheus does. A named scan reports `__name__` +/// only among the runtime labels, so `by (__name__)` keeps it there and publishes no column for it. fn grouped_output_tags( input: &NativeNode, op: &BoundAggregate, @@ -443,23 +345,12 @@ fn grouped_output_tags( }) } -/// Whether a binary operation reports the samples of the side it keeps, name included. -/// -/// A filtering comparison reports those samples, so the name survives it. Every other binary -/// operation computes new values, and `bool` reports the comparison's own outcome rather than -/// either operand's samples, so both drop the name. +/// Whether a binary operation keeps the metric name: only a filtering comparison does. fn keeps_metric_name(matching: &BinaryMatching) -> bool { matching.op.is_comparison() && !matching.return_bool } -/// The labels a node reports after the metadata labels are dropped, which is what a kernel that -/// computes a value of its own does to the samples it reports. -/// -/// The runtime drops all of [`PROMQL_METADATA_LABELS`] here, not the name alone: a name-dropping -/// window and `timestamp` both go through `drop_metric_name`, and both end with -/// `remove_all(&METADATA_LABELS)` - an empty value leaves with them too. Deriving only the name -/// would leave `__type__` and `__unit__` in a label set the runtime no longer reports them in, and -/// a drop above such a node would then be collected for labels that are already gone. +/// Mirrors `map::drop_metric_name`, which removes `__type__` and `__unit__` along with the name. fn without_metadata_labels(tags: Vec) -> Vec { tags.into_iter() .filter(|tag| !PROMQL_METADATA_LABELS.contains(&tag.as_str())) @@ -468,19 +359,13 @@ fn without_metadata_labels(tags: Vec) -> Vec { /// What one node produces. /// -/// A sample type with an evaluation grid is an evaluated series: one value per grid point. Without -/// a grid it is raw samples carrying their own timestamps. A scalar is one value per grid point -/// and no labels. Intermediate aggregate state is a different type altogether, so an operation -/// that cannot consume it is rejected by type rather than by convention. +/// Aggregate state is a type of its own, so an operation that cannot consume it is rejected by type. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)] pub enum NativeType { /// Samples, evaluated when the schema carries a grid and raw otherwise. Samples(Arc), - /// One value per grid point and no labels, which binary operations broadcast. - /// - /// PromQL scalars vary with the evaluation time (`time()`, `scalar(v)`), so this carries the - /// grid it is evaluated on. Its value carrier is a series without labels, but its type is - /// what keeps a broadcast from becoming label matching. + /// One value per grid point and no labels, which binary operations broadcast rather than + /// match. Scalar(Arc), /// Intermediate aggregate state, not a query value. AggregateState(Arc), @@ -495,10 +380,7 @@ impl NativeType { } } - /// The grid this type is evaluated on, or `None` when it holds raw samples or state. - /// - /// A scalar is evaluated on its grid like a vector, which is what lets a binary operation - /// line it up with a vector point by point; only raw samples and state have no positions. + /// The grid this type is evaluated on, or `None` for raw samples and state. pub fn grid(&self) -> Option<&Arc> { match self { Self::Samples(schema) => schema.eval_grid.as_ref(), @@ -507,7 +389,6 @@ impl NativeType { } } - /// What this type is, for a rejection that has to say what a consumer was handed. fn describe(&self) -> &'static str { match self { Self::Samples(schema) if schema.eval_grid.is_some() => "an evaluated vector", @@ -517,10 +398,8 @@ impl NativeType { } } - /// Whether `self` binds the same thing as `other`: the same samples or the same state. - /// - /// Bindings compare their semantic content, not process-local allocation identity. Scalars are - /// produced by a node and never handed to one by a source, so they never match. + /// Whether `self` and `other` bind equal schemas. Scalars never come from a source, so they + /// never match. fn same_binding(&self, other: &NativeType) -> bool { match (self, other) { (Self::Samples(mine), Self::Samples(theirs)) => **mine == **theirs, @@ -530,12 +409,8 @@ impl NativeType { } } -/// The [`FieldKind`] every referenced field of a scan carries, or `None` when they disagree or one -/// is a type this route does not answer. -/// -/// The route declares one output column per field, so a statement whose selectors carry different -/// kinds has no column to declare them in and keeps the existing plan. `Float64` and the canonical -/// native histogram struct are the two kinds this route answers. +/// The [`FieldKind`] every referenced field carries, or `None` when they disagree or one is neither +/// `Float64` nor the native histogram struct. pub fn uniform_field_kind<'a>( kinds: impl IntoIterator>, ) -> Option { @@ -574,8 +449,8 @@ pub fn binary_output_field_kind( | BinaryOp::Mod | BinaryOp::Pow | BinaryOp::Atan2 => { - // An unsupported pair emits no sample, not a float. Fill values are floats, so one - // field can be produced by the real pair and by either enabled synthetic pair. + // An unsupported pair emits no sample. Fill values are floats, so the field must agree + // across the real pair and each enabled fill pair. let payload_kind = |left, right| match (left, op, right) { (FieldKind::Float, _, FieldKind::Float) => Some(FieldKind::Float), (FieldKind::Histogram, BinaryOp::Add | BinaryOp::Sub, FieldKind::Histogram) @@ -600,11 +475,8 @@ pub fn binary_output_field_kind( // With no possible samples, retain the legacy float layout for an empty result. Some(kind.unwrap_or(FieldKind::Float)) } - // A comparison over one kind answers that kind's samples, which is what keeps a histogram - // column a histogram. A comparison over two kinds answers no sample at all: the kernel - // reports every mixed pair - `(Float, Histogram)` and `(Histogram, Float)` included - as - // unsupported and skips it without counting a match (`vector_match::elem_binop`), so the - // column is the same empty float layout arithmetic keeps for a pair that can emit nothing. + // A mixed-kind comparison emits no sample (`vector_match::elem_binop`), so it gets the + // empty float layout. _ if left == right => Some(left), _ => Some(FieldKind::Float), } @@ -613,64 +485,44 @@ pub fn binary_output_field_kind( impl NativeNode { /// The kind this node's output field carries, given the kind its sources carry. /// - /// `None` means this walk cannot name it: either the caller has no kind for the statement's - /// sources and this tree reads one, or the shape's samples are ones the model does not describe. - /// Both keep the existing plan rather than declaring a column the first batch might not fill. + /// `None` when `input` is `None` and the tree reads a source, or when the kind is not derived, + /// e.g. a math function over histograms, a set over two kinds, or a vector binary whose fill + /// pairs disagree. pub fn output_field_kind(&self, input: Option) -> Option { let kind_of = |node: &NativeNode| node.output_field_kind(input); match &self.expr { NativeExpr::Input(_) => input, - // A tree that reads no source answers floats: a constant, the evaluation time, `vector()` - // over one of them, and a date function of the evaluation time. None of them carries a - // sample kind of its own, so none of them needs the source kind either. NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } | NativeExpr::VectorOf { .. } | NativeExpr::Timestamp { .. } => Some(FieldKind::Float), - // The window functions that answer with a histogram are the ones the range kernel says - // yield one; every other range function reduces its window to a float. NativeExpr::Window { input, op } => { let inner = kind_of(input)?; (!op.function.yields_histograms()) .then_some(FieldKind::Float) .or(Some(inner)) } - // An instant selection reads one sample of the field, so it keeps the kind; the two - // timestamp forms replace the sample with a float of its own time. NativeExpr::Instant { input, op } => match op.value { InstantValue::Sample => kind_of(input), InstantValue::Timestamp | InstantValue::InfoTimestamp => Some(FieldKind::Float), }, - // `histogram_count` and the other native-histogram readers answer with one float per - // sample; the map kernels that keep the samples keep their kind as well. NativeExpr::Map { input, op } => { let mut kind = kind_of(input)?; for op in op.ops.iter() { kind = match op { - // The native-histogram readers answer one float per sample. MapOp::Histogram(_) => FieldKind::Float, - // A label rewrite writes labels only, so the samples it passes on are the - // ones it was given, kind included. MapOp::Label(_) => kind, - // No math function keeps a histogram, so a histogram reaching one is a - // shape this walk does not name rather than a silent float. MapOp::Math(_) if kind == FieldKind::Histogram => return None, MapOp::Math(_) => FieldKind::Float, }; } Some(kind) } - // A constant beside a vector is broadcast over it, so the operation answers with the - // vector's own samples: a histogram times a float is still a histogram. Two vectors - // use the arithmetic result's kind, including any samples emitted by fill, and an - // empty float field only when no possible pairing can emit a sample. NativeExpr::Binary { left, right, matching, } => { - // `bool` makes a comparison answer 1 or 0 whatever its operands hold, which is - // what the kernel does before it looks at the kinds. if matching.return_bool { return Some(FieldKind::Float); } @@ -691,43 +543,17 @@ impl NativeNode { } } } - // A canonical merge collects pieces of one label set: it assembles the samples it was - // given and never converts them, so the field keeps the kind it had. NativeExpr::Merge { input } => kind_of(input), - // A set operation keeps the payloads it selects - `and` and `unless` keep the left - // samples, `or` keeps the left's and the right's unmatched ones - so a pair of - // different kinds would answer a field carrying both. This route declares one type per - // field, so it names the answer only when both sides agree. That is this planner's - // condition for a uniformly typed column, not a rule Prometheus states. + // A set passes both sides' samples through, so it is typed only when the sides agree. NativeExpr::Set { left, right, .. } => { let left_kind = kind_of(left)?; (left_kind == kind_of(right)?).then_some(left_kind) } - // `scalar()` answers one float per grid point, whatever its input holds. NativeExpr::ScalarOf { .. } => Some(FieldKind::Float), - // A ranking hands on the series it selected, so the field keeps the kind it read; its - // parameter is a scalar, which carries no samples of its own. NativeExpr::ParameterizedTopK { input, .. } => kind_of(input), - // `histogram_quantile` and `histogram_fraction` reduce a histogram to one float per - // sample whatever their arguments are, constant or per point. NativeExpr::ParameterizedHistogram { .. } => Some(FieldKind::Float), - // An aggregate answers the kind its own state carries: `count`/`group` answer a count - // or a `1` whatever the samples they counted, `min`/`max`/`stddev`/`stdvar`/`quantile` - // fold the float samples and skip the histogram ones, and `sum`/`avg` answer the - // payload they folded - a native histogram when their binding is a histogram state, a - // float otherwise. Naming it here is what lets `sum(count_over_time(h[5m]))` - a float - // built from histograms - declare a float column, and `sum(h)` declare a histogram one. NativeExpr::Aggregate { op, .. } => Some(aggregate_output_kind(op)), - // A per-point parameter decides the `φ` the fold reads, not the layout it answers, so - // the kind is the one the same aggregate's state carries. NativeExpr::ParameterizedAggregate { op, .. } => Some(aggregate_output_kind(op)), - // A whole-vector operation either hands on the series it selected - a ranking keeps the - // ones it ranked, `limit_ratio` the ones its hash kept, and `sort` the same series in - // another order - so the field keeps the kind it read, which is the rule the - // per-point `k` form above already states for the same `TopK`. The other three compute - // the value: `absent` writes `1.0` where the input held nothing, `histogram_quantile` - // and `histogram_fraction` reduce a classic histogram to one float, and `count_values` - // counts samples as floats. NativeExpr::Vector { input, op } => Some(match op { BoundVectorOp::TopK { .. } | BoundVectorOp::LimitK { .. } @@ -737,25 +563,16 @@ impl NativeNode { | BoundVectorOp::Histogram(_) | BoundVectorOp::CountValues { .. } => FieldKind::Float, }), - // `info` answers the base series' own samples with the info series' data labels added, - // so the field is the base's field: natively it never reads the info series' values as - // the answer (`info` is selected as a timestamp, `InstantValue::InfoTimestamp`). NativeExpr::Info { base, .. } => kind_of(base), - // A parameterized map is a math function over its input - `round` and the three - // `clamp`s - and math skips native histogram samples rather than converting them - // (`map::map_math`), so the field shape is unchanged and keeps the input's kind. The - // two scalar functions, `max_of` and `min_of`, take a scalar input, whose kind is a - // float whether or not the source carries histograms. + // `round` and `clamp*` skip histogram samples rather than converting them + // (`map::map_math`); `max_of`/`min_of` take a scalar input, which is float. NativeExpr::ParameterizedMap { input, .. } => kind_of(input), } } } -/// The kind an aggregate's own output column carries. -/// -/// It follows the state the aggregate keeps rather than the samples it read, because the two can -/// differ in both directions: `count` over a histogram answers a float, and so does every aggregate -/// that skips histogram samples, while `sum`/`avg` over a histogram answer the histogram they folded. +/// The kind an aggregate's output column carries, which follows its state binding rather than its +/// input: `count` over histograms answers a float, `sum`/`avg` over histograms a histogram. pub fn aggregate_output_kind(op: &BoundAggregate) -> FieldKind { match aggregate_state_binding(op.kind, op.field_kind) { Some((kind, _)) if kind.is_histogram() => FieldKind::Histogram, @@ -763,13 +580,9 @@ pub fn aggregate_output_kind(op: &BoundAggregate) -> FieldKind { } } -/// The layout of intermediate aggregate state. -/// -/// State is indexed by `(group labels, absolute grid index)`, so it carries the grid it was -/// accumulated on. It is not a query value and does not pretend to be one. +/// The layout of intermediate aggregate state, indexed by `(group labels, absolute grid index)`. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)] pub struct AggregateStateSchema { - /// How the groups its rows are indexed by are identified. pub group: Grouping, /// Aggregate whose partial accumulator this state carries. pub kind: AggregateStateKind, @@ -781,15 +594,8 @@ pub struct AggregateStateSchema { pub grid: Arc, } -/// Returns the state type implied by an aggregate over an input of `field_kind`, if that state can -/// be merged across a partition boundary. -/// -/// Two families share this table. A numeric input keeps the components the accumulator kernel -/// declares, and the component list comes from that kernel rather than a second mapping, so changing -/// a kernel's state fields changes the native binding in lockstep. A native-histogram input binds -/// the histogram state of the same aggregate: it carries the payload and the compensation that -/// belongs to it, plus the evidence a merge of two partitions has to report. A quantile has no -/// partial kernel at all, whatever it reads. +/// The state an aggregate over `field_kind` binds, or `None` when it has no mergeable partial state +/// (a quantile). Numeric components come from the accumulator kernel, so the two stay in lockstep. pub fn aggregate_state_binding( kind: AggregateKind, field_kind: FieldKind, @@ -798,18 +604,14 @@ pub fn aggregate_state_binding( let state_kind = match kind { AggregateKind::Sum => AggregateStateKind::HistogramSum, AggregateKind::Avg => AggregateStateKind::HistogramAvg, - // Every other aggregate folds a float answer out of the samples it reads - a count is a - // count whatever it counted, and the extreme and deviation kinds skip a histogram - // sample - so a histogram input keeps their numeric state. + // The rest answer floats over histograms (count, or skipping histogram samples). _ => return float_state_binding(kind), }; - // The layout is the kind's own canonical list, which is the list its frame accepts. return Some((state_kind, state_kind.components().to_vec())); } float_state_binding(kind) } -/// The numeric state one aggregate keeps, from the components its kernel declares. fn float_state_binding(kind: AggregateKind) -> Option<(AggregateStateKind, Vec)> { use crate::aggregate::{AggregateOp, StateField}; @@ -839,32 +641,24 @@ fn float_state_binding(kind: AggregateKind) -> Option<(AggregateStateKind, Vec, - /// What the selection reports for the sample it selects. pub value: InstantValue, - /// The grid the selection produces values on. pub output_grid: Arc, } @@ -895,19 +687,14 @@ pub enum InstantValue { InfoTimestamp, } -/// A window function over raw samples or over an evaluated input. -/// -/// The input and output grids are bound separately: a subquery evaluates its inner expression on -/// its own grid and consumes the result directly, without resampling it onto the outer grid. +/// A window function over raw samples or over an evaluated input. A subquery's input grid differs +/// from its output grid; the input is consumed without resampling. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)] pub struct BoundWindow { - /// The function this node runs. pub function: RangeFunction, - /// The window length, offset and anchor. pub window: RangeWindow, /// The grid the input is evaluated on, or `None` when the input is raw samples. pub input_grid: Option>, - /// The grid this node produces values on. pub output_grid: Arc, } @@ -918,15 +705,11 @@ pub struct BoundMap { pub ops: Arc<[MapOp]>, } -/// A math function whose scalar parameters are bound as nodes, because at least one of them varies -/// per grid point; Prometheus reads each parameter at every step. With constant parameters the same -/// function is a [`MathOp`] in a [`BoundMap`]. +/// A math function whose scalar parameters are bound as nodes because at least one varies per grid +/// point. With constant parameters the same function is a [`MathOp`] in a [`BoundMap`]. /// -/// Every function here reads one parameter per point except `max_of` and `min_of`, which are -/// functions of two scalars: their input is the one scalar the call wrote first and their one -/// parameter is the other. [`Self::takes_a_scalar_input`] says which shape a function has, so the -/// node's input and output are checked against the function it carries rather than against a -/// convention the functions no longer all share. +/// `max_of` and `min_of` are functions of two scalars: the input is the first argument and the one +/// parameter is the second. #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)] pub enum ParameterizedOp { /// `round(v, to_nearest)`. @@ -944,7 +727,7 @@ pub enum ParameterizedOp { } impl ParameterizedOp { - /// How many parameters the function reads after its input. + /// The number of parameters after the input. pub fn arity(self) -> usize { match self { Self::Clamp => 2, @@ -952,19 +735,13 @@ impl ParameterizedOp { } } - /// Whether the function's input is a scalar, which is what a function of two scalars has. - /// - /// A parameterized map otherwise maps a vector's fields onto the same fields; `max_of` and - /// `min_of` answer one scalar from one, so their input carries a scalar's single unlabelled - /// field and their answer is a scalar on that field's grid. + /// Whether the input and output are scalars rather than vectors. pub fn takes_a_scalar_input(self) -> bool { matches!(self, Self::MaxOf | Self::MinOf) } } -/// One operation of a map, applied to each series on its own: math over its float values, a -/// function of its native histograms, or a change of its labels. Each can give two series one label -/// set, which is why all live in a map. +/// One per-series operation of a map. Each can give two series one label set. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)] pub enum MapOp { Math(MathOp), @@ -972,42 +749,23 @@ pub enum MapOp { Label(Arc), } -/// Which aggregate a node computes. +/// An aggregate that folds each group's values into one value per grid point. Series-selecting +/// aggregates and `count_values` are [`BoundVectorOp`]s. /// -/// Every kind here folds a group's values into one value per grid point. The aggregates that -/// instead select some of the input's series (`topk`, `bottomk`, `limitk`, `limit_ratio`) or write -/// one output label per distinct value (`count_values`) are a different shape and have no variant, -/// so a node cannot claim to compute one of them. -/// -/// A kind may be bound before its kernel exists: whether the tree can run is -/// [`NativeTree::try_new`]'s and the runtime's question, not this enum's. -/// -/// `Eq` is missing because [`AggregateKind::Quantile`] carries an `f64`, as -/// [`RangeFunction::QuantileOverTime`] does. -/// -/// [`RangeFunction::QuantileOverTime`]: crate::range_eval::RangeFunction::QuantileOverTime +/// [`AggregateKind::Quantile`] carries an `f64`, so equality and hashing are implemented by hand +/// over its bits. #[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)] pub enum AggregateKind { - /// `sum`: the total of each group's values at each grid point. Sum, - /// `avg`: the mean of each group's values at each grid point. Avg, - /// `count`: how many values each group has at each grid point. Count, - /// `min`: the smallest of each group's values at each grid point. Min, - /// `max`: the largest of each group's values at each grid point. Max, - /// `group`: `1` where a group has any value at a grid point. Group, - /// `stddev`: the standard deviation of each group's values at each grid point. Stddev, - /// `stdvar`: the variance of each group's values at each grid point. Stdvar, - /// `quantile`: the φ-quantile of each group's values at each grid point, as written. Quantile { - /// The φ the query wrote, which `0` to `1` does not bound: Prometheus reads a negative φ as - /// `-Infinity` and one above `1` as `+Infinity`. + /// φ as written, unbounded: Prometheus answers `-Inf` below `0` and `+Inf` above `1`. quantile: f64, }, } @@ -1023,12 +781,7 @@ pub enum AggregateStage { Final, } -/// How an aggregate's groups are identified, in the binding's own terms. -/// -/// The kernel already takes both shapes ([`aggregate::Grouping`]), and the two are not -/// interchangeable: `by(job)` keeps `job` and drops everything else, while `without(job)` keeps -/// every other label and drops `job` too. A list of group labels can only spell the first, so a -/// `without` written that way would group a query by labels it meant to remove. +/// How an aggregate's groups are identified; mirrors [`aggregate::Grouping`]. /// /// [`aggregate::Grouping`]: crate::aggregate::Grouping #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)] @@ -1042,27 +795,16 @@ pub enum Grouping { /// An aggregate bound to its kind, grouping and stage. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)] pub struct BoundAggregate { - /// Which aggregate to compute. pub kind: AggregateKind, - /// How its groups are identified. pub group: Grouping, - /// Where this aggregate sits in the execution. pub stage: AggregateStage, - /// The kind the aggregate's direct input answers with, decided where this node was bound. - /// - /// It is what its state carries: a `sum` or `avg` over native histograms keeps histogram state, - /// while the same aggregate over floats keeps numeric components. It is decided from the input's - /// own output kind rather than from the source, because an operator between the two can change - /// it -- `sum(count_over_time(h[5m]))` aggregates a float built from histograms. + /// The direct input's field kind, which picks the state binding. It is not the source's kind: + /// `sum(count_over_time(h[5m]))` aggregates floats built from histograms. pub field_kind: FieldKind, } -/// An operator over the whole input vector at each grid point: one that keeps some of the input's -/// samples with their series' labels and values, orders the series, reports where none is present, -/// reads a classic histogram from its bucket series, or counts the samples sharing a value. -/// -/// Its constants are bound here, as a window's are: a `k` or a ratio only known at run time has no -/// field. +/// An operator over the whole input vector at each grid point, with constant parameters. A per-point +/// `k` is [`NativeExpr::ParameterizedTopK`]. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub enum BoundVectorOp { /// `topk` (`top`) or `bottomk`: the `k` largest or smallest values of each group. @@ -1072,18 +814,15 @@ pub enum BoundVectorOp { /// `limit_ratio`: the series whose label hash falls in the ratio; it keeps whole series, so it /// has no grouping. LimitRatio { ratio: f64 }, - /// `sort`, `sort_desc`, `sort_by_label` and `sort_by_label_desc`: the input's series in another - /// order, which only an instant result shows. `sort` and `sort_desc` also drop histogram - /// samples, in a range result too. + /// `sort`, `sort_desc`, `sort_by_label` and `sort_by_label_desc`. The order shows only in an + /// instant result; `sort` and `sort_desc` also drop histogram samples, in a range result too. Sort(SortOrder), - /// `absent`: `1` under `labels` at every point where the input holds no sample. The labels are - /// what the compiler derives from the argument's matchers. + /// `absent`: `1` under `labels` (derived from the argument's matchers) at every point where the + /// input holds no sample. Absent { labels: SeriesLabels }, - /// `histogram_quantile` or `histogram_fraction`: each classic histogram is read from the bucket - /// series that share its labels, so this too reads the whole vector at a point. + /// `histogram_quantile` or `histogram_fraction` over classic bucket series. Histogram(HistogramFunction), - /// `count_values(label, v)`: how many samples of each group share a value, under a label set - /// per value. It writes a label per distinct value, which an aggregate's fixed groups cannot. + /// `count_values(label, v)`. CountValues { label: Arc, group: Grouping }, } @@ -1095,57 +834,47 @@ pub enum BoundVectorOp { pub struct BoundSetOp { /// `and`, `or` or `unless`. pub op: SetOp, - /// The labels a sample's match group is read from on either side. pub labels: MatchingLabels, } -/// What a node computes. Every variant holds a bound operation, never a name to resolve. +/// What a node computes. /// -/// The variants are numbered by their position, and postcard writes that number, so these indices -/// are a wire contract: a version 3 [`crate::extension_plan::FusedSeries`] envelope carries the -/// whole [`NativeTree`] rather than a prefix of it, and a variant inserted anywhere but the end -/// renames every variant after it for a reader of an earlier build. New variants are therefore -/// appended after `Info`, and `native_expr_variant_indices_are_a_wire_contract` in the tests below -/// pins the numbers. +/// Postcard encodes a variant by its position and a [`crate::extension_plan::FusedSeries`] carries +/// the whole [`NativeTree`], so variant indices are a wire contract: append new variants at the end +/// (pinned by `native_expr_variant_indices_are_a_wire_contract`). #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)] pub enum NativeExpr { /// A scan or an exchange boundary. Input(BoundInput), - /// A constant scalar, evaluated on the statement's grid. + /// A constant scalar. Scalar(BoundScalar), - /// The evaluation time of each grid point, as `time()` reads it in seconds, or a date function - /// of it, as a date function called without an argument reads it. + /// `time()` in seconds, or a date function called without an argument. /// - /// A date function is bound here rather than over `time()`: Prometheus reads the calendar from - /// the evaluation timestamp truncated to whole seconds, which the float `time()` does not carry - /// exactly for every timestamp. + /// The date function is bound here rather than over `time()` because Prometheus reads the + /// calendar from the timestamp truncated to whole seconds, which the float `time()` does not + /// carry exactly. EvalTime { date: Option }, /// `vector(s)`: the scalar as one series without labels. VectorOf { input: Box }, - /// An instant selection over its input. + /// An instant selection over raw samples. Instant { input: Box, op: BoundInstant, }, /// Canonicalizes evaluated fragments that share a label set. Merge { input: Box }, - /// A window function over its input. + /// A range function over raw samples or a subquery's evaluated input. Window { input: Box, op: BoundWindow, }, - /// Point-wise operations over its input. + /// Point-wise operations, applied in order. Map { input: Box, op: BoundMap, }, - /// A point-wise math function over its input whose parameters are scalar nodes, in argument - /// order. - /// - /// The input is the evaluated vector the function maps, or -- for `max_of` and `min_of`, which - /// are functions of two scalars -- the scalar the call wrote first, which the node answers as - /// one scalar on the same grid. A constant input has no chunk of its own and is read off its - /// binding, as a constant parameter is. + /// A point-wise math function whose parameters are scalar nodes, in argument order. For + /// `max_of`/`min_of` the input is the first scalar argument and the output is a scalar. ParameterizedMap { input: Box, op: ParameterizedOp, @@ -1153,7 +882,7 @@ pub enum NativeExpr { }, /// The timestamp of an evaluated input, in seconds. Timestamp { input: Box }, - /// An aggregate over its input. + /// An aggregate at the stage its binding names. Aggregate { input: Box, op: BoundAggregate, @@ -1163,23 +892,20 @@ pub enum NativeExpr { input: Box, op: BoundVectorOp, }, - /// A binary operation between two inputs, with its matching rules. - /// - /// Scalar operands are broadcast, so `matching` only applies to vector–vector operations. + /// Scalar operands are broadcast, so `matching` only applies between two vectors. Binary { left: Box, right: Box, matching: BinaryMatching, }, - /// A set operation between two vectors, which keeps samples of either side as they are. + /// `and`, `or` or `unless` between two vectors. Set { left: Box, right: Box, op: BoundSetOp, }, - /// `info(base, {selector})`: the series of `base` with the data labels of the info series that - /// share their identifying labels. `info` is the instant selection of those info series, whose - /// values are the times of the samples it selected ([`InstantValue::InfoTimestamp`]). + /// `info(base, {selector})`. `info` is an instant selection with + /// [`InstantValue::InfoTimestamp`]. Info { base: Box, info: Box, @@ -1188,10 +914,7 @@ pub enum NativeExpr { /// `scalar(v)`: at each grid point, the sole sample value or NaN when the vector has zero or /// more than one sample. ScalarOf { input: Box }, - /// `topk`/`bottomk` whose `k` is evaluated at every grid point instead of bound as a constant. - /// - /// `op` is still the `TopK` the constant path binds; its `k` is unused here, because the value - /// this node selects with is the parameter's, read once per point. + /// `topk`/`bottomk` with a per-point `k`. `op` is a `TopK` whose own `k` is ignored. ParameterizedTopK { input: Box, op: BoundVectorOp, @@ -1203,14 +926,7 @@ pub enum NativeExpr { op: BoundVectorOp, parameters: Vec, }, - /// An aggregate whose argument is read at every grid point instead of bound as a constant: - /// `quantile(<φ per point>, v)`. - /// - /// `op` is still the `Quantile` the constant path binds; its `φ` is unused here, because the - /// value this node folds with is the parameter's, read once per point -- exactly as - /// [`Self::ParameterizedTopK`] ignores the `k` its own binding carries. What the fold keeps is - /// its group's sample set either way, so a parameter read per point changes what is folded, not - /// how. + /// `quantile` with a per-point φ. `op` is a `Quantile` whose own φ is ignored. ParameterizedAggregate { input: Box, op: BoundAggregate, @@ -1221,9 +937,7 @@ pub enum NativeExpr { /// One node of a bound tree. #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)] pub struct NativeNode { - /// What this node computes, including its bound operands. pub expr: NativeExpr, - /// What this node produces. pub output: NativeType, } @@ -1358,8 +1072,7 @@ impl NativeNode { .any(|child| child.any(predicate)) } - /// The input leaves below this node, in the order the tree evaluates them. A source that two - /// leaves read is listed once per leaf. + /// The input leaves below this node in evaluation order, one entry per leaf. pub fn inputs(&self) -> Vec<&BoundInput> { fn collect<'a>(node: &'a NativeNode, inputs: &mut Vec<&'a BoundInput>) { if let NativeExpr::Input(input) = &node.expr { @@ -1374,8 +1087,7 @@ impl NativeNode { inputs } - /// Whether this node reads no data at all: a constant, the evaluation time, or an operation - /// between them. Every execution computes the same value for it. + /// Whether this node reads no data, so every execution computes the same value for it. pub fn is_data_free(&self) -> bool { match &self.expr { NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => true, @@ -1386,65 +1098,23 @@ impl NativeNode { } } -/// Whether this tree can hand over two series that share one canonical label set. +/// Whether this tree can hand over two series that share one canonical label set (the metric name +/// plus the ordinary labels, which is what [`NativeExpr::Merge`] groups by). /// -/// A canonical label set is the identity a [`NativeExpr::Merge`] groups by: the metric name plus the -/// ordinary labels, which is exactly what [`SeriesLabels`] holds. One scan partition holds one -/// series per such set - a stored series is one identity, and the scan splits rows by storage key -/// rather than by label set - so only a computation that *writes* an existing label, or drops one, -/// can turn two of those identities into one. A `label_replace` or a `label_join` writes one, and it -/// may name the very label that told its input's series apart; a range function that drops the -/// metric name, and `timestamp` in either of its forms, drop one. +/// A scan partition holds one series per canonical label set, so only a node that writes an +/// existing label or drops one can create duplicates: /// -/// The rewrite is judged by the labels it writes and the ones its input carries, which is why the -/// caller supplies what it knows about each source's tags, indexed by the `source_index` the leaves -/// were bound to: a destination that names no ordinary label of the input writes a fresh one, and a -/// fresh ordinary label cannot make two series equal. That is the difference between -/// `label_replace(x, "dst", "$1", "host", "(.*)")` - which no merge has to collect - and -/// `label_replace(x, "host", "same", "host", ".*")`, which folds every series of `x` into one label -/// set. +/// - A label rewrite whose destination the input already carries, judged against `source_tags` +/// (indexed by `source_index`). A `__name__` destination always counts, because the scan below +/// may hold several metrics whose ordinary labels are equal. +/// - A node that drops [`PROMQL_METADATA_LABELS`] (a name-dropping window, `timestamp`, a math or +/// histogram map, a parameterized map, an arithmetic or `bool` scalar broadcast), unless +/// [`metadata_labels_keep_series_apart`] proves the drop injective. /// -/// A source's entry is its complete runtime label set, so `__name__` is one of its labels whenever -/// its series carry a name - a scan bound to one metric names every series from its binding. That is -/// what makes `label_replace(x, "__name__", "same", "__name__", ".*")` a rewrite of an existing -/// label: two metrics whose ordinary labels are equal can be told apart by name alone, and rewriting -/// that name folds them into one identity. A name write is collected even when the derived set no -/// longer carries `__name__` - after `abs`, a `timestamp` or a range function dropped it - because -/// the scan below those kernels can still hold several metrics whose ordinary labels are equal, and -/// writing one name puts them under one identity; the walk has no proof that the input reads a -/// single metric, so the conservative answer is the one that collects. -/// -/// Everything else either keeps the set it read or answers a set of its own: -/// -/// - A map of math drops the metadata labels, and so do a histogram map, a parameterized map, an -/// arithmetic or `bool` scalar broadcast, a range function that computes its result and a -/// `timestamp` in either of its forms. Such a node is judged by the labels it and its input -/// report ([`metadata_labels_keep_series_apart`]): a source bound to one metric names every series -/// it hands over, so the name the drop removes told none of them apart, and a source that may hand -/// over several is collected. A key column that holds `NULL` in one series and `''` in another is -/// *not* part of that proof - see the doc comment of the function - so a drop whose labels prove -/// it is never collected for the storage keys alone. -/// - An `Aggregate` answers its groups, a `Vector` that folds series answers its result sets, and a -/// `Binary` that reads whole vectors files its rows by the label set a sample *ends* under and -/// refuses two values of a field at one point. A `Set` does the same, and `info` merges the -/// results that share a label set. Each answers one series per set it names. -/// - A `Window` that drops the metadata labels, and the two timestamps, claim one of their own: the -/// name is part of the identity a merge groups by, so two series that shared every other label are -/// one label set from there on - unless the labels tell them apart by the same rule the kernels -/// above are judged by. -/// - A [`Merge`](NativeExpr::Merge) at or below a drop answers nothing for it -/// ([`canonical_below`](crate::native::plan::canonical_below)): a merge hands over one series per -/// canonical label set, but the labels that tell two of its series apart still have to prove the -/// drop. A chain of drops over one metric is therefore collected once per collision the labels do -/// not prove, and not at all when they do. -/// - A node that hands its input's series over unchanged - a selection, a name-keeping window, -/// `topk` and its ranking siblings - passes the answer on: an alias below it is still an alias -/// above it. -/// -/// This is the fact [`merge_label_rewrites`](crate::native::canonicalize::merge_label_rewrites) -/// inserts a `Merge` for: a consumer that reads a whole label set cannot answer from pieces, and this -/// says where pieces of one set can exist at all. A `Merge` is the collection itself, so it answers -/// `false` - which is what makes the pass idempotent. +/// Nodes that file their rows by result label set (aggregates, vector-vector binaries, sets, `info`, +/// `absent`, `count_values`, histogram functions) answer `false`, and so does `Merge`, which is what +/// makes [`merge_label_rewrites`](crate::native::canonicalize::merge_label_rewrites) idempotent. +/// Nodes that pass their input's series through propagate the input's answer. pub fn duplicates_canonical_labels( node: &NativeNode, source_tags: &[Vec], @@ -1455,35 +1125,21 @@ pub fn duplicates_canonical_labels( | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } | NativeExpr::VectorOf { .. } => false, - // The collection itself: one series per label set comes out of it. NativeExpr::Merge { .. } => false, - // These hand each series over as they read it, so what aliases below them still aliases -- - // except `timestamp`, which reports a sample's own time under the metadata labels dropped - // and is therefore a source of duplicates in its own right unless the labels prove that - // drop injective ([`metadata_labels_keep_series_apart`]). NativeExpr::Instant { input, op } => { (op.value == InstantValue::Timestamp && !metadata_labels_keep_series_apart(input, source_tags, source_metrics)) || duplicates_canonical_labels(input, source_tags, source_metrics) } - // A window that drops the metadata labels can fold two series that agreed on every other - // label into one set, so it is a source of duplicates whether or not its input was one - - // unless the labels below it provably tell those series apart still. NativeExpr::Window { input, op } => { (op.function.drops_metric_name() && !metadata_labels_keep_series_apart(input, source_tags, source_metrics)) || duplicates_canonical_labels(input, source_tags, source_metrics) } - // `timestamp` always drops the metadata labels, so two series it reads can become one set - - // unless the labels below it are all bound to one metric, which is what proves that the name - // it removes told none of those series apart. NativeExpr::Timestamp { input } => { !metadata_labels_keep_series_apart(input, source_tags, source_metrics) || duplicates_canonical_labels(input, source_tags, source_metrics) } - // A parameterized map is a math kernel - `round`, `clamp` - and drops the metadata labels as - // a math map does, so it answers for the same reason. Its parameter is a scalar and carries - // no labels of the input's. NativeExpr::ParameterizedMap { input, .. } => { !metadata_labels_keep_series_apart(input, source_tags, source_metrics) || duplicates_canonical_labels(input, source_tags, source_metrics) @@ -1491,19 +1147,8 @@ pub fn duplicates_canonical_labels( NativeExpr::ParameterizedTopK { input, .. } => { duplicates_canonical_labels(input, source_tags, source_metrics) } - // `scalar()` answers one value, which names no label set at all. NativeExpr::ScalarOf { .. } => false, - // The histogram functions fold the bucket series of one histogram into one series, so two - // pieces of one label set cannot survive them. NativeExpr::ParameterizedHistogram { .. } => false, - // A rewrite writes a caller-chosen destination label, so two series can end under one set - - // but only if that label was one of the input's, because writing a label no series carries - // leaves every series' identity distinct. `map_writes_existing_label` is that question, and - // an input whose labels this walk cannot derive is collected rather than trusted. Even a - // whole-vector consumer can emit distinct series whose labels a later rewrite makes equal. - // A math or histogram kernel in the same map drops the metadata labels, which is a source of - // duplicates of its own unless the labels tell its input's series apart - see the doc - // comment above. NativeExpr::Map { input, op } => { (op.ops .iter() @@ -1512,18 +1157,14 @@ pub fn duplicates_canonical_labels( || map_writes_existing_label(input, op, source_tags).unwrap_or(true) || duplicates_canonical_labels(input, source_tags, source_metrics) } - // A fold answers one series per group, which is one label set per group. NativeExpr::Aggregate { .. } | NativeExpr::ParameterizedAggregate { .. } => false, NativeExpr::Vector { input, op } => match op { - // These keep and order the series they read, so they alias exactly as their input does. BoundVectorOp::TopK { .. } | BoundVectorOp::LimitK { .. } | BoundVectorOp::LimitRatio { .. } | BoundVectorOp::Sort(_) => { duplicates_canonical_labels(input, source_tags, source_metrics) } - // `absent` reports one series, `count_values` one per distinct value, and the histogram - // functions fold the bucket series of one histogram into one series. BoundVectorOp::Absent { .. } | BoundVectorOp::Histogram(_) | BoundVectorOp::CountValues { .. } => false, @@ -1535,13 +1176,9 @@ pub fn duplicates_canonical_labels( } => { let vector = |side: &NativeNode| side.output.samples().is_some(); match (vector(left), vector(right)) { - // Two vectors are matched by label, and the kernel files its rows by the label set a - // sample ends under, refusing two values of one field at one point. (true, true) => false, - // A broadcast reaches each series of its vector side as it is, one series of the - // vector side per output series. An arithmetic one and one that reports a `bool` - // drop the metadata labels, which is a source of duplicates of its own unless the - // labels tell its series apart; a filtering comparison keeps the set it read. + // Arithmetic and `bool` broadcasts drop the metadata labels; a filtering comparison + // keeps them. (true, false) | (false, true) => { let carried = if vector(left) { left } else { right }; let drops_metadata = !matching.op.is_comparison() || matching.return_bool; @@ -1549,32 +1186,19 @@ pub fn duplicates_canonical_labels( && !metadata_labels_keep_series_apart(carried, source_tags, source_metrics)) || duplicates_canonical_labels(carried, source_tags, source_metrics) } - // Two scalars name no label set at all. (false, false) => false, } } - // A set operation keeps each side's samples and files them by result label set, refusing two - // values of one field at one point. NativeExpr::Set { .. } => false, - // `info` indexes the info side by identifying labels and merges the results that share a - // label set. NativeExpr::Info { .. } => false, } } -/// Whether `op`, applied to `input`'s series, writes a label those series already carry. +/// Whether `op`, applied in written order to `input`'s series, writes a label they already carry. /// -/// The walk is over the ops in written order, starting from the labels the input reports. A -/// destination the input already carries can fold two series into one; a fresh destination cannot. -/// A `__name__` destination is always treated as carried, even when the derived set has lost it: a -/// kernel such as `abs`, `timestamp` or a range function drops the name, but the scan below it can -/// still hold several metrics whose ordinary labels are equal, and writing one name puts those -/// identities under one label set. Nothing here proves the input reads a single metric, so the -/// conservative answer is the one that collects. -/// -/// `None` when the input's label set is not derivable, which is treated as "it may carry the -/// destination" by the caller: an unknown set proves nothing, so the conservative answer is the one -/// that collects. +/// A `__name__` destination always counts as carried: even after a kernel dropped the name, the +/// scan below may hold several metrics whose ordinary labels are equal. `None` when the input's +/// labels are not derivable. fn map_writes_existing_label( input: &NativeNode, op: &crate::native::plan::BoundMap, @@ -1588,8 +1212,6 @@ fn map_writes_existing_label( if destination == METRIC_NAME || tags.iter().any(|tag| tag == destination) { existing = true; } - // A label the input did not carry is one the rewrite publishes only when it can write a - // value; a delete-only rewrite adds nothing a later op could read as carried. if rewrite.writes_value() && !tags.iter().any(|tag| tag == destination) { tags.push(destination.to_string()); } @@ -1598,53 +1220,21 @@ fn map_writes_existing_label( Some(existing) } -/// Whether the metadata labels a rewrite drops are the only ones telling `node`'s series apart. +/// Whether dropping [`PROMQL_METADATA_LABELS`] from `node`'s series keeps them distinct. /// -/// A range function that computes its result and `timestamp` in either of its forms drop -/// [`PROMQL_METADATA_LABELS`] - the metric name, `__type__` and `__unit__` - and a consumer above -/// them that reads a whole label set has to establish those series cannot collide once the three are -/// gone. Two series of one input collide only if they differed in one of the three alone, -/// so the drop is injective - and nothing has to be collected - when neither can tell two of them -/// apart: +/// - If `node` reports `__type__` or `__unit__`, nothing is proved. +/// - If `node` still reports `__name__`, it is proved when every series carries the same name +/// ([`single_metric_name`]). +/// - If the name is already gone, it is proved when `node` itself answers one series per label set +/// ([`answers_one_series_per_label_set`]), or when every source below reads the same one metric +/// ([`single_source_metric`]), since a drop on the way may have folded several metrics. /// -/// - The name: a source bound to one metric names every series it hands over, so the name is the -/// same for all of them and removing it merges nothing (see [`single_metric_name`]). A source that -/// may hand over several - one selector that discovered several metrics, or a caller that cannot -/// tell - is not proved, and the conservative answer is the one that collects. -/// - `__type__` and `__unit__`: both are removed along with the name, and neither is a label this -/// walk can prove constant across a source's series. They are ordinary labels when a source -/// carries them as tags or a rewrite writes them, and two series that agree on everything else are -/// one label set once they are gone. Their presence anywhere in `node`'s output is therefore -/// enough to withhold the proof. +/// `false` when `node`'s labels are not derivable. [`duplicates_canonical_labels`] and +/// [`unifies_its_own_contributions`] both use this, so planning and runtime agree on a merge. /// -/// A node whose own kernel answers one series per label set - a fold, a match between two vectors, a -/// set operation, `info`, `count_values` - has already told those series apart, so a drop above it is -/// proved whatever metrics it reads ([`answers_one_series_per_label_set`]). -/// -/// A node whose labels already lost the name - `abs`, a name-dropping window below it - has no name -/// of its own left to remove, and what its surviving labels tell apart is then only as good as the -/// metrics below it: a drop that happened on the way there removed a name without asking this walk, -/// so the proof asks instead that every source it reads is bound to the same one metric -/// ([`single_source_metric`]). Over a selector that discovered several metrics that drop folds them -/// together, and the answer is the one that collects. -/// -/// `false` when the walk cannot derive `node`'s labels at all, because an unknown set proves nothing. -/// -/// This is the whole of the drop's proof: every arm of [`duplicates_canonical_labels`] that decides -/// whether a collection is needed asks it, and so does [`unifies_its_own_contributions`] at run -/// time, so the two cannot disagree about a merge. -/// -/// What it does not answer is a key column that holds `NULL` in one series and `''` in another, both -/// of which decode to no label once the empty value is dropped with the name. That pair is -/// deliberately outside the proof: it is a property of a nullable tag column rather than of the -/// labels, and every tag column of a metric-engine table is nullable, so collecting a drop for it -/// puts a canonical merge - and the fragmenting boundary that merge carries - over every statement -/// whose kernel drops the metadata labels, including the ones whose labels prove the drop injective. -/// The fact is still read from the resolved table -/// ([`keys_survive_metadata_drop`](crate::extension_plan::keys_survive_metadata_drop)) and the -/// statements whose labels prove the drop while that pair does not are still counted -/// ([`leaves_a_drop_to_the_storage_keys`]), so what the pair can hide stays observable even though -/// nothing is collected for it. +/// A key column holding `NULL` in one series and `''` in another is deliberately outside the proof: +/// every metric-engine tag column is nullable, so counting it would put a merge over every +/// name-dropping statement. [`leaves_a_drop_to_the_storage_keys`] reports those statements instead. fn metadata_labels_keep_series_apart( node: &NativeNode, source_tags: &[Vec], @@ -1660,50 +1250,27 @@ fn metadata_labels_keep_series_apart( return false; } if !tags.iter().any(|tag| tag == METRIC_NAME) { - // A node whose own kernel already answers one series per label set told those series apart - // itself, so the drop above it removes a name no two of them were told apart by: `1 - a / b` - // matches the two metrics and refuses two values of one field at one point, and the broadcast - // above that match only drops a name the match no longer carries. Nothing is collected for - // such a consumer, whatever metrics it reads. + // e.g. `1 - a / b`: the vector match already filed its rows by result label set. if answers_one_series_per_label_set(node) { return true; } - // Otherwise no name is left to lose, so what the surviving labels tell apart is decided by - // the sources below: every one of them reading the same single metric is what says a name - // dropped on the way here could not have folded two metrics together either. `abs` and a - // name-dropping window both drop the name without asking, so without that fact nothing - // below is proved. return single_source_metric(node, source_metrics).is_some(); } single_metric_name(node, source_metrics).is_some() } -/// Whether `node` answers one series per label set by construction. +/// Whether `node`'s kernel files or folds its rows by result label set, so its series are distinct +/// whatever its inputs held. /// -/// These are the nodes whose own kernel files or folds its rows by the label set a sample ends -/// under, so two of the series it answers are distinct label sets whatever its inputs held: a fold -/// answers one series per group, a match between two vectors and a set operation file their rows by -/// the result label set and refuse two values of one field at one point, `info` merges the results -/// that share a label set, and the functions that build one series out of many - `absent`, -/// `count_values` and the histogram functions - answer a set of their own. -/// -/// A metadata drop above one of them therefore cannot fold two of its series by removing the name: -/// the identity that told them apart is the label set the kernel filed them under, and that set is -/// what the drop is handed. -/// -/// A [`NativeExpr::Merge`] is deliberately not one of them. It answers one series per *canonical* -/// label set, and that set includes the name: a merge keeps `a{job="x"}` and `b{job="x"}` apart, so a -/// drop above it that removes the name does fold those two, and it is collected -/// (`a_merge_below_a_drop_does_not_answer_the_metadata_labels`). +/// [`NativeExpr::Merge`] is not one: its canonical label set includes the name, so a drop above it +/// can still fold `a{job="x"}` and `b{job="x"}`. fn answers_one_series_per_label_set(node: &NativeNode) -> bool { match &node.expr { NativeExpr::Aggregate { .. } | NativeExpr::Set { .. } | NativeExpr::Info { .. } | NativeExpr::ParameterizedHistogram { .. } => true, - // A match between two vectors is the one `Binary` shape that files its rows by the result - // label set; a node with a scalar on one side reaches each series of its vector side as it - // is, which tells nothing apart on its own. + // Only vector-vector matching; a scalar broadcast passes series through. NativeExpr::Binary { left, right, .. } => { left.output.samples().is_some() && right.output.samples().is_some() } @@ -1717,20 +1284,11 @@ fn answers_one_series_per_label_set(node: &NativeNode) -> bool { } } -/// Whether a [`NativeExpr::Merge`] collects the series `node` hands over, at it or below it. +/// Whether a [`NativeExpr::Merge`] sits at or below `node` on its sample-carrying path. /// -/// A merge holds one series per canonical label set, so the series above one are not stored series -/// any more: a merge with nothing to merge hands its input's pieces through, and one that does -/// merge keeps the first piece's labels and drops the pieces it folded, so what comes out is unique -/// under the label set Prometheus compares (`label_set` in `grid_series`) - the one that treats an -/// empty label value as no label. Two pieces that came out of one merge are therefore distinct under -/// that comparison even though their rows may still spell an empty value, which is what makes a -/// second drop above the merge unable to fold them by removing an empty value. What it does not make -/// impossible is the rest of such a drop: a merge keeps two series that differ in `__name__`, -/// `__type__` or `__unit__`, and removing those is exactly what a metadata drop does. -/// -/// Only the children that carry samples are searched: a parameter is a scalar or a vector of -/// constants, and a merge below one reads series this node's own samples did not come from. +/// A merge's output is unique under Prometheus' `label_set` comparison, which treats an empty value +/// as absent, so the `NULL`/`''` key pair cannot collide above it. Parameter children are skipped: +/// their series are not the ones `node` hands over. fn canonical_below(node: &NativeNode) -> bool { matches!(node.expr, NativeExpr::Merge { .. }) || node @@ -1741,32 +1299,15 @@ fn canonical_below(node: &NativeNode) -> bool { .any(canonical_below) } -/// Whether `node` drops [`PROMQL_METADATA_LABELS`] on its own over series whose labels are proved to -/// tell apart and whose keys are not. -/// -/// This is what the pair the proof leaves outside costs, stated rather than collected: the labels -/// prove the drop ([`metadata_labels_keep_series_apart`]), nothing at or below it has collected -/// already ([`canonical_below`]), and the scan's primary key holds a column that can spell `NULL` in -/// one series and `''` in another. Those two decode to an absent and to an empty label, and the drop -/// normalizes them into one - the case a collection used to be inserted for and that a name-dropping -/// kernel over a metric-engine table, whose tag columns are all nullable, paid a merge for. The -/// collection is gone (see [`metadata_labels_keep_series_apart`]) and this is the count that keeps -/// the statements it would have covered observable. -/// -/// Every node that drops the metadata labels on its own counts: a map of math, a histogram map, a -/// parameterized map and an arithmetic or `bool` scalar broadcast, and the three that rewrite a -/// sample's own value - a name-dropping range function, `timestamp(x)` and a `timestamp` over an -/// evaluated input. +/// Whether `node` or a descendant drops [`PROMQL_METADATA_LABELS`] where the labels prove the drop +/// ([`metadata_labels_keep_series_apart`]) but the storage keys may not: `keys_survive` is `false` +/// and no merge sits below the drop ([`canonical_below`]). fn drops_metadata_labels_over_one_metric( node: &NativeNode, source_tags: &[Vec], source_metrics: &[Option>], keys_survive: bool, ) -> bool { - // The statement is counted exactly when the labels prove the drop and the key columns are the - // only thing left that does not: nothing at or below it has collected already - // ([`canonical_below`]), and the resolved table's keys can spell the `NULL`/`''` pair - which is - // the fact this count exists to surface now that nothing is collected for it. let decided_by_the_keys = |carried: &NativeNode| { !keys_survive && metadata_labels_keep_series_apart(carried, source_tags, source_metrics) @@ -1787,8 +1328,6 @@ fn drops_metadata_labels_over_one_metric( .any(|operation| matches!(operation, MapOp::Math(_) | MapOp::Histogram(_))) && decided_by_the_keys(input) } - // A broadcast reaches each series of its vector side as it is; an arithmetic one and one - // that reports a `bool` drop the metadata labels, a filtering comparison keeps them. NativeExpr::Binary { left, right, @@ -1815,15 +1354,9 @@ fn drops_metadata_labels_over_one_metric( }) } -/// Whether `tree` holds a node that drops the metadata labels over series whose labels are proved to -/// tell apart and whose keys are not (see [`drops_metadata_labels_over_one_metric`]). -/// -/// A statement this answers `true` for is one whose drop the labels prove while the scan below it -/// keys its series by a column that can hold `NULL` in one series and `''` in another -/// (`keys_survive` is `false`, and the caller states that fact from the resolved table). Nothing is -/// collected for that pair - the labels are the whole of the proof - so this is the count that keeps -/// the statements it leaves unproved observable, and the caller reports it as the reason its -/// label-set check does not cover them. +/// Whether `tree` drops the metadata labels where the labels prove the drop but a key column that +/// can hold both `NULL` and `''` may not (`keys_survive` is `false`). Nothing is merged for that +/// case; the caller reports it. pub fn leaves_a_drop_to_the_storage_keys( tree: &NativeTree, source_tags: &[Vec], @@ -1833,11 +1366,7 @@ pub fn leaves_a_drop_to_the_storage_keys( drops_metadata_labels_over_one_metric(tree.root(), source_tags, source_metrics, keys_survive) } -/// The one metric every source `node` reads is bound to, or `None` when they are not all one. -/// -/// This is the facts-free question about the leaves alone: a node can drop the metric name on the -/// way (a math map, a range function) whatever its sources hold, so what the surviving labels tell -/// apart is only as good as the set of metrics below them. +/// The one metric every source below `node` is bound to, or `None` when they are not all one. fn single_source_metric( node: &NativeNode, source_metrics: &[Option>], @@ -1846,7 +1375,6 @@ fn single_source_metric( let mut metric: Option<&Arc> = None; while let Some(node) = pending.pop() { match &node.expr { - // A source that may hand over several metrics proves nothing about their names. NativeExpr::Input(input) => { let bound = source_metrics.get(input.source_index)?.as_ref()?; match metric { @@ -1880,8 +1408,6 @@ fn single_source_metric( pending.push(input); pending.push(parameter); } - // A fold reads its group's values and the series its argument is answered from, so both - // halves are sources this question is asked of. NativeExpr::ParameterizedAggregate { input, parameter, .. } => { @@ -1903,17 +1429,11 @@ fn single_source_metric( metric.cloned() } -/// The one metric every series `node` hands over is named, or `None` when this walk cannot say. -/// -/// Only the nodes that hand their input's label set on unchanged can carry a name: every kernel that -/// reports a value of its own drops it, so a name above one of those is one a rewrite wrote. What is -/// left is the boundary the leaves are bound to - where `source_metrics` answers, indexed by the -/// `source_index` the leaf reads - and the nodes that pass a set through. +/// The one metric name every series `node` hands over carries, followed only through nodes that +/// pass their input's label set on unchanged. `None` when this walk cannot say. fn single_metric_name(node: &NativeNode, source_metrics: &[Option>]) -> Option> { match &node.expr { NativeExpr::Input(input) => source_metrics.get(input.source_index).cloned().flatten(), - // These report the label set they read rather than one of their own, so the name is their - // input's. A map that computes a value or writes a name is not one of them. NativeExpr::Merge { input } | NativeExpr::ParameterizedTopK { input, .. } | NativeExpr::Vector { @@ -1940,34 +1460,16 @@ fn single_metric_name(node: &NativeNode, source_metrics: &[Option>]) -> { single_metric_name(input, source_metrics) } - // A kernel that reports a value of its own drops the name, and a fold, a set operation, an - // `info` lookup and a rewrite writing the name answer a set this walk does not follow. _ => None, } } /// Whether `node` reads the whole input vector at a point rather than one series at a time. /// -/// An `Aggregate` folds every series of its group, whether its argument is bound or read per point, -/// a `Binary` and a `Set` pair two vectors' series by label, an `Info` looks the info series of each -/// series up by its identifying labels, and a `Vector` operation (`sort`, `absent`, `topk`, `limitk`, -/// `histogram_quantile`, ...) reorders or reads the whole vector at a grid point. -/// -/// `Merge` answers one series per label set, and the label sets it answers span every input series: -/// two of them can collapse into the one it emits. It is therefore whole-vector too, which is why it -/// also cannot be moved below a boundary that holds only part of a metric. Everything else - an -/// input, a scalar, a selection, a window, a map, and a binary operation with a constant on one -/// side, whose broadcast reaches each series the other side answers - answers one series from one -/// series' rows. -/// -/// Both a region-side placement and the native route's admission ask this, and they must agree: a -/// tree admitted here but refused there becomes a node the physical layer cannot build, and one -/// refused here but admitted there would be pushed to a region that holds part of the metric. -/// -/// The walk asks the facts-free form of [`unifies_its_own_contributions`]: a placement reads a tree -/// without the binding that says which metric each of its inputs reads, and every reader of this -/// answer - the admission below, the region-side classification and the locality of a built node - -/// asks it of the same tree, so the conservative answer is the one that keeps them agreeing. +/// Aggregates, vector-vector binaries, sets, `info`, vector operations, `scalar()`, per-point +/// `topk`/histogram functions and `Merge` do; so does a window over an input that may hand over +/// fragments of one label set. A region-side placement and the native route's admission both ask +/// this and must agree, so it passes no source facts to [`unifies_its_own_contributions`]. pub fn reads_across_series(node: &NativeNode) -> bool { match &node.expr { NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => false, @@ -1979,27 +1481,19 @@ pub fn reads_across_series(node: &NativeNode) -> bool { | NativeExpr::VectorOf { input } | NativeExpr::Map { input, .. } | NativeExpr::Timestamp { input } => reads_across_series(input), - // A parameterized operation reads its parameters too, and one of them can read across series - // as well: `clamp_min(b, scalar(a))` bounds each series of `b` by a value that only exists - // once the whole of `a` is gathered, so the node reads across series wherever its parameter - // does. + // e.g. `clamp_min(b, scalar(a))` reads across series through its parameter. NativeExpr::ParameterizedMap { input, parameters, .. } => reads_across_series(input) || parameters.iter().any(reads_across_series), - // `scalar()` needs the whole vector: which series carries the one value at a point decides - // the answer, so the node reads across series. NativeExpr::ScalarOf { .. } => true, NativeExpr::Binary { left, right, .. } => { let scalar = |side: &NativeNode| matches!(side.output, NativeType::Scalar(_)); if scalar(left) || scalar(right) { reads_across_series(left) || reads_across_series(right) } else { - // Two vectors are matched by label, which pairs series of the whole vector. true } } - // A parameterized operation reads its parameter too, and a `k` that changes per point - // decides which series survive. NativeExpr::ParameterizedTopK { .. } | NativeExpr::ParameterizedHistogram { .. } => true, NativeExpr::Aggregate { .. } | NativeExpr::ParameterizedAggregate { .. } @@ -2010,48 +1504,26 @@ pub fn reads_across_series(node: &NativeNode) -> bool { } } -/// Whether `node` is a supported child of a [`NativeExpr::Merge`], and the evaluated vector it hands -/// over. -/// -/// A merge receives fragments and groups them by canonical label set, combining the ones a label set -/// shares by grid position; it names neither the tree nor the operator that produced a fragment. What -/// it reads is therefore the whole of its requirement: samples evaluated on one grid in one field -/// layout, which is an evaluated vector and nothing else. This is that type check and no more, so no -/// node kind is refused for what it computes: a scan's samples, a window's rate, an aggregate's fold -/// and a binary operation's match all hand over the same thing, and which one of them did says -/// nothing about whether the fragments merge. -/// -/// The collection does rely on the shape of the stream - a series arrives whole, its chunks -/// contiguous and its last one marked as closing it - and every node that answers an evaluated vector -/// keeps it. A window, a map, an instant selection, a timestamp and a scalar broadcast hand their -/// input's closing on, and an aggregate, a vector operation, a binary or set operation and a merge -/// itself close each series they answer, because each decides a whole series at once. There is hence -/// no operator above a merge that could break the collection, and none has to be listed here; the -/// collector checks the shape chunk by chunk before it keeps a fragment, which is where a stream that -/// broke it is refused. +/// The evaluated vector a [`NativeExpr::Merge`] child hands over, or `None` if it is not one. fn merge_shape_supported(node: &NativeNode) -> Option<(&Arc, &Arc)> { evaluated_vector(&node.output) } -/// A bound evaluation tree. -/// -/// The tree itself carries no run-time state: every execution builds its own, so one compiled plan -/// can serve every partition. +/// A validated bound evaluation tree. It carries no run-time state, so one tree serves every +/// partition. #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)] pub struct NativeTree { root: NativeNode, } impl NativeTree { - /// Creates a tree over `root`, checking that every node's contract holds. - /// - /// A structurally inconsistent tree is a compiler defect. + /// Creates a tree over `root`. Errors when [`NativeNode::validate`] rejects it, which is a + /// compiler defect. pub fn try_new(root: NativeNode) -> Result { root.validate()?; Ok(Self { root }) } - /// The root node. pub fn root(&self) -> &NativeNode { &self.root } @@ -2088,59 +1560,26 @@ impl<'de> serde::Deserialize<'de> for NativeTree { } } -/// Whether the native runtime executes `tree`, answered from the tree itself. +/// Whether the native runtime builds `tree`. /// -/// This is the question the native route asks before it commits a statement: a tree the runtime -/// refuses has to keep the plan it had, because a refusal raised during physical planning cannot -/// fall back. It used to be answered by building a -/// [`NativeExecutionState`](crate::native::execute::NativeExecutionState) over the tree and -/// dropping it, which allocates a runtime node per node per partition only to throw it away. Every -/// term of the answer is bound on the tree, so the answer is read from the tree instead. +/// The native route asks this before committing a statement, because a refusal raised during +/// physical planning cannot fall back. It mirrors what `RuntimeNode::build` and +/// `NativeExecutionState::try_new` refuse beyond [`NativeNode::validate`]: /// -/// # What is refused +/// - a root of raw samples; +/// - an interleaved input leaf; +/// - `scalar()`, `topk`, `bottomk`, `limitk`, `sort` or `sort_desc` over more than one field; +/// - a binary of two literals, a scalar broadcast with vector-matching modifiers, or `bool` on +/// arithmetic; +/// - a `quantile` aggregate at any stage but `Complete`; +/// - an aggregate below `Final`, or a `topk`/`bottomk`/`limitk`/`count_values`, whose grouping names +/// a value field, and a `count_values` with an empty label; +/// - an `anchored` or `smoothed` window over evaluated input, over a function its kernel does not +/// correct, or with a negative lookback; +/// - a window whose `@` fold offset or `predict_linear` instants overflow `i64`. /// -/// This lists what `RuntimeNode::build` (and the root check in -/// `NativeExecutionState::try_new`) refuses, less what [`NativeNode::validate`] has already -/// refused: a `NativeTree` exists only through [`NativeTree::try_new`] or `Deserialize`, and both -/// validate, so a compiled tree's per-node type contracts hold by the time this runs. What is left -/// is the shape of the nodes, and the arithmetic each of them leaves to the runtime: -/// -/// - a root that answers raw samples, which has no positions to answer on; -/// - an input leaf whose series chunks may interleave, which no consumer of a leaf can order; -/// - `scalar()` over a vector carrying more than one field; -/// - a binary node that is neither a vector–vector operation nor a broadcast the runtime performs: -/// two constant operands (no series to carry the result), a scalar broadcast carrying -/// vector-matching modifiers, or `bool` on an arithmetic operator, which has no `bool` form; -/// - a `quantile` aggregate at any stage but `Complete`, which would need a partial state it does -/// not keep (`validate` refuses one for the same reason; this arm keeps the predicate and the -/// runtime agreeing on it); -/// - an aggregate below `Final` whose `by` names a value field, which would fold series the -/// existing plan keeps apart; -/// - `topk`, `bottomk`, `limitk`, `sort` and `sort_desc` over a vector carrying more than one -/// field, whose series have no one value to rank; -/// - a `topk`, `bottomk`, `limitk` or `count_values` grouping that names a value field, and a -/// `count_values` label that is empty; -/// - a window whose `anchored` or `smoothed` modifier reads evaluated input, names a function its -/// kernel does not correct, or carries a negative lookback; -/// - a window whose timestamps do not fit: the fold offset an `@` anchor turns into, or the one -/// `predict_linear` adds to a point of the grid, where the sum leaves `i64`. Not a shape, but it -/// is decided by the grid and the window alone, so this is where it is decided (see -/// `window_instants_fit`). -/// -/// # What `NativeExecutionState::try_new` still decides -/// -/// Not every refusal is decided by the tree, and the ones below stay where the runtime builds: -/// -/// - a reservation the memory pool refuses, which no tree carries. Every site that admits a tree -/// ran the trial build over an -/// [`UnboundedMemoryPool`](datafusion::execution::memory_pool::UnboundedMemoryPool), which -/// refuses nothing, and none of them builds a runtime any more, so this is not a refusal -/// admission can meet at any site; -/// - a tree a test assembled directly, whose nodes disagree about their types, which -/// [`NativeNode::validate`] rejects for every compiled one. +/// A memory reservation refusal is left to the runtime. pub fn native_tree_supported(tree: &NativeTree) -> bool { - // A constant root and a state root are answers the state produces itself; a root of raw - // samples is not one, because raw samples carry their own timestamps instead of positions. let root_supported = match &tree.root().output { NativeType::Scalar(_) | NativeType::AggregateState(_) => true, NativeType::Samples(schema) => schema.eval_grid.is_some(), @@ -2148,17 +1587,12 @@ pub fn native_tree_supported(tree: &NativeTree) -> bool { root_supported && native_node_supported(tree.root()) } -/// Whether `node` and every input below it is a shape the runtime builds. fn native_node_supported(node: &NativeNode) -> bool { stacker::maybe_grow(VALIDATE_STACK_RED_ZONE, VALIDATE_STACK_GROWTH, || { native_node_supported_within_stack(node) }) } -/// [`native_node_supported`] one tree level down. -/// -/// Every arm reads this node's own shape and recurses into exactly the inputs its variant holds, -/// so a new [`NativeExpr`] variant does not compile until it is classified here. fn native_node_supported_within_stack(node: &NativeNode) -> bool { match &node.expr { NativeExpr::Input(bound) => bound.ordering != SeriesOrdering::Interleaved, @@ -2182,9 +1616,6 @@ fn native_node_supported_within_stack(node: &NativeNode) -> bool { NativeExpr::Aggregate { input, op } => { native_node_supported(input) && aggregate_supported(node, input, op) } - // A per-point argument does not change which fold runs, only where its `φ` comes from: the - // same aggregate checks apply, and the parameter is a subtree like any other. That it is a - // scalar on this fold's grid is a type contract `validate` already refuses. NativeExpr::ParameterizedAggregate { input, op, @@ -2192,8 +1623,7 @@ fn native_node_supported_within_stack(node: &NativeNode) -> bool { } => { native_node_supported(input) && native_node_supported(parameter) - // A literal hands over no chunk, so the fold could never read a value from it: - // `validate` refuses one, and a tree this predicate admits must be one it does not. + // A literal hands over no chunk to read φ from; `validate` refuses it too. && !matches!(parameter.expr, NativeExpr::Scalar(_)) && aggregate_supported(node, input, op) } @@ -2211,15 +1641,12 @@ fn native_node_supported_within_stack(node: &NativeNode) -> bool { } => { native_node_supported(input) && native_node_supported(parameter) - // A per-point `k` ranks the same series as the constant one, one value per series. && node.output.samples().is_some_and(|schema| { schema.fields.len() == 1 && vector_op_supported(schema, op) }) } NativeExpr::ScalarOf { input } => { native_node_supported(input) - // `scalar()` answers the sole value of a vector, so a vector of several fields has - // more than one value to answer with. && input .output .samples() @@ -2243,12 +1670,8 @@ fn native_node_supported_within_stack(node: &NativeNode) -> bool { } } -/// Whether a binary node over `left` and `right` is a shape the runtime builds. -/// -/// Two evaluated vectors are matched by `matching`, which the kernel takes as it is bound. Every -/// other pair is a broadcast over one scalar side, and a broadcast has no labels to match and no -/// series to pair: two constants leave no series to carry the result, a modifier a vector match -/// would use has no meaning over a scalar, and arithmetic has no `bool` form. +/// Two evaluated vectors are always supported. A broadcast must have default matching and no `bool` +/// on arithmetic, and two scalars must not both be literals. fn binary_supported(left: &NativeNode, right: &NativeNode, matching: &BinaryMatching) -> bool { let evaluated = |node: &NativeNode| { node.output @@ -2272,11 +1695,8 @@ fn binary_supported(left: &NativeNode, right: &NativeNode, matching: &BinaryMatc && !(!matching.op.is_comparison() && matching.return_bool) } -/// Whether the runtime folds `op` over `input` with the layout `node` declares. -/// -/// A `Complete` or `Partial` node folds values into groups it keys by series labels only, while -/// `Final` merges state that was already grouped, which is why only the folding stages are checked -/// against the schema. +/// Only `Complete` and `Partial` are checked against the schema; `Final` merges state that was +/// already grouped. fn aggregate_supported(node: &NativeNode, input: &NativeNode, op: &BoundAggregate) -> bool { match op.kind { AggregateKind::Sum @@ -2288,9 +1708,7 @@ fn aggregate_supported(node: &NativeNode, input: &NativeNode, op: &BoundAggregat | AggregateKind::Stddev | AggregateKind::Stdvar => {} AggregateKind::Quantile { .. } => { - // A quantile is one `Complete` fold over its group's whole input: it keeps no state, - // so `validate` refuses a `Partial` or `Final` one and there is nothing to merge. The - // runtime answers the `Complete` stage, which is the only shape compiled. + // A quantile keeps no partial state. if op.stage != AggregateStage::Complete { return false; } @@ -2305,10 +1723,7 @@ fn aggregate_supported(node: &NativeNode, input: &NativeNode, op: &BoundAggregat .is_some_and(|schema| grouping_supported(schema, &op.group)) } -/// Whether `op` is an operation the vector kernel runs over a vector of `schema`. fn vector_op_supported(schema: &SeriesSchema, op: &BoundVectorOp) -> bool { - // These five rank or order one value per series, so a vector whose samples carry several - // fields has no one value to rank. let one_field = matches!( op, BoundVectorOp::TopK { .. } @@ -2338,26 +1753,18 @@ fn vector_op_supported(schema: &SeriesSchema, op: &BoundVectorOp) -> bool { } } -/// Whether the kernel folds `schema`'s series the way `group` asks. -/// -/// The kernel validates its grouping by the schema alone: the group is a set of series labels, and -/// a `by` naming one of the schema's fields would group by a value that varies between samples. -/// This is the check `FloatAggregator::try_new_budgeted` and `VectorRuntime::try_new` run, spelled -/// once so a reader of either name finds the same rule. +/// The grouping check `FloatAggregator::try_new_budgeted` and `VectorRuntime::try_new` run. fn grouping_supported(schema: &SeriesSchema, group: &Grouping) -> bool { let names = group_names(group); crate::aggregate::validate_vector_grouping(schema, kernel_grouping(group, &names)).is_ok() } -/// The labels `group` names, which is what the kernel's grouping is built over. fn group_names(group: &Grouping) -> Vec<&str> { match group { Grouping::By(names) | Grouping::Without(names) => names.iter().map(AsRef::as_ref).collect(), } } -/// `group` spelled with the kernel's own [`Grouping`](crate::aggregate::Grouping), over the labels -/// [`group_names`] reports for it: `by` and `without` are not interchangeable to the kernel. fn kernel_grouping<'a>(group: &Grouping, names: &'a [&'a str]) -> crate::aggregate::Grouping<'a> { match group { Grouping::By(_) => crate::aggregate::Grouping::By(names), @@ -2365,15 +1772,9 @@ fn kernel_grouping<'a>(group: &Grouping, names: &'a [&'a str]) -> crate::aggrega } } -/// Whether the runtime evaluates `op` over `input`, with or without a range modifier. -/// -/// An `anchored` or `smoothed` window reads samples around the window to pin its boundary values, -/// which only a raw sample stream can offer and only a kernel that corrects its boundaries reads. -/// That is one rule, not two: [`check_modifier`](crate::range_eval::check_modifier) states it for -/// [`RangeEvaluator::try_new`](crate::range_eval::RangeEvaluator::try_new), and it is asked here -/// over the schema the tree binds, so a modifier a runtime refuses is one admission declines. +/// The [`check_modifier`](crate::range_eval::check_modifier) rule +/// [`RangeEvaluator::try_new`](crate::range_eval::RangeEvaluator::try_new) applies. fn window_modifier_supported(input: &NativeNode, op: &BoundWindow) -> bool { - // Without a modifier there is nothing for the rule to decide. let Some(modifier) = op.window.modifier else { return true; }; @@ -2382,37 +1783,23 @@ fn window_modifier_supported(input: &NativeNode, op: &BoundWindow) -> bool { }) } -/// Whether the runtime can compute the timestamps `op` reads. -/// -/// Unlike the window itself, which a point of the grid opens alone, these timestamps are sums of -/// the window's own parts: an `@` anchor becomes an offset from the grid's first point, and -/// `predict_linear` adds that offset to the first and last point of the grid. Every term of either -/// sum is bound on the node, but a sum of two that fit can still leave `i64`, and the runtime -/// refuses the window when one does. Asking [`fold_offset`] and [`predict_linear_instants`] here -/// rather than repeating their arithmetic keeps the two verdicts the same one: a query whose only -/// refusal is this one keeps the plan it had instead of failing while the runtime is built. +/// Whether the `@` fold offset and `predict_linear` instants fit in `i64`, asked through the same +/// functions the runtime calls. fn window_instants_fit(op: &BoundWindow) -> bool { let grid = op.output_grid.spec(); let Ok(fold_offset) = fold_offset(grid, op.window) else { return false; }; match op.function { - // Only `predict_linear` reads the instant it reports; every other function reads the - // window it opens, which the grid alone decides. RangeFunction::PredictLinear(_) => predict_linear_instants(grid, fold_offset).is_ok(), _ => true, } } -/// Stack one [`NativeNode::validate`] level needs below it before the check grows its stack. -/// -/// The check recurses once per tree level, and a debug build's frame for one level is large: -/// measured on an 80-term chain, the whole check needed about 1.9 MiB, which overflows the 2 MiB -/// stack a test thread has. There is no depth limit on the trees this route compiles, so the check -/// grows its stack on demand rather than relying on the caller's. +/// Stack reserve before a tree walk grows its stack. Trees have no depth limit, and in a debug build +/// an 80-term chain needed about 1.9 MiB, over a test thread's 2 MiB. const VALIDATE_STACK_RED_ZONE: usize = 256 * 1024; -/// Stack a growth adds when the reserve above is spent. It holds several levels of the same check. const VALIDATE_STACK_GROWTH: usize = 4 * 1024 * 1024; impl NativeNode { @@ -2426,8 +1813,6 @@ impl NativeNode { fn validate_within_stack(&self) -> Result<()> { match &self.expr { NativeExpr::Input(input) => { - // An input node's output is exactly the binding it was bound to: a scan hands over - // the samples it was created for, and an exchange boundary the state. if !self.output.same_binding(&input.output) { return Err(invalid( "an input node's output is not the binding it was bound to", @@ -2460,14 +1845,10 @@ impl NativeNode { if !self.output.samples().is_some_and(|s| s.fields.len() == 1) { return Err(invalid("vector() produces one field")); } - // The scalar is materialized on the grid it is evaluated on, so an output on another - // grid would address positions the scalar does not have. ensure_grid(&self.output, input_grid, "vector()")?; } NativeExpr::Instant { input, op } => { input.validate()?; - // An instant selection reads raw samples and stamps them onto its own grid: an - // evaluated vector is already stamped, and a scalar has no timestamps at all. match &input.output { NativeType::Samples(schema) if schema.eval_grid.is_none() => {} NativeType::Samples(_) => { @@ -2482,17 +1863,11 @@ impl NativeNode { } ensure_not_interleaved(input)?; ensure_samples(&self.output, "an instant selection")?; - // A selection is one source row per grid point: `select_instants` picks row - // indices and every field is taken at them, so it carries one value per input - // field. ensure_same_fields(&input.output, &self.output, "an instant selection")?; ensure_grid(&self.output, &op.output_grid, "an instant selection")?; } NativeExpr::Merge { input } => { input.validate()?; - // A merge canonicalizes evaluated fragments, so an evaluated vector is the whole of - // what it needs of its input: [`merge_shape_supported`] is that check, and its - // documentation says why no shape of tree above those fragments matters. let Some((_input_schema, input_grid)) = merge_shape_supported(input) else { return Err(invalid(&format!( "a merge consumes an evaluated vector, not {}", @@ -2505,27 +1880,19 @@ impl NativeNode { } NativeExpr::Window { input, op } => { input.validate()?; - // A window reads a range of samples per grid point, so it consumes samples: state - // is not a sample stream and a scalar has no timestamps. let NativeType::Samples(schema) = &input.output else { return Err(invalid(&format!( "a window consumes samples, not {}", input.output.describe() ))); }; - // A range that is not positive reads nothing at every grid point. if op.window.range_ms <= 0 { return Err(invalid( "a window reads an empty range: its range must be positive", )); } ensure_not_interleaved(input)?; - // What is checked here and just below is that the declared input grid equals the - // input's grid, and that the output grid matches the declared one. That the grid - // covers the window's read range - // `(out.start - offset - range, out.end - offset]` is not checked here: only a - // subquery feeds an evaluated input to a window, and deriving that coverage is the - // compiler's, which builds the subquery's child grid to span it. + // That a subquery's input grid covers the read range is the compiler's to ensure. match (op.input_grid.as_ref(), schema.eval_grid.as_ref()) { (None, None) => {} (Some(bound), Some(actual)) if bound.spec() == actual.spec() => {} @@ -2541,8 +1908,6 @@ impl NativeNode { } NativeExpr::Map { input, op } => { input.validate()?; - // A map is point-wise over an evaluated vector: raw samples have no shared - // positions to be point-wise over, and a scalar is not a vector. let Some((_, input_grid)) = evaluated_vector(&input.output) else { return Err(invalid(&format!( "a map consumes an evaluated vector, not {}", @@ -2562,9 +1927,6 @@ impl NativeNode { parameters, } => { input.validate()?; - // `max_of` and `min_of` are functions of two scalars, so their input is the first - // of the two rather than a vector's fields; every other function here maps an - // evaluated vector and answers one of the same shape. let input_grid = if op.takes_a_scalar_input() { let NativeType::Scalar(input_grid) = &input.output else { return Err(invalid(&format!( @@ -2679,8 +2041,6 @@ impl NativeNode { } NativeExpr::Vector { input, .. } => { input.validate()?; - // A vector operation keeps the input's fields and grid, so it consumes and produces - // the same evaluated vector. let Some((_, input_grid)) = evaluated_vector(&input.output) else { return Err(invalid(&format!( "a vector operation consumes an evaluated vector, not {}", @@ -2702,13 +2062,9 @@ impl NativeNode { } NativeExpr::Aggregate { input, op } => { input.validate()?; - // A stage's contract is a pair of types, not only what it produces: `Partial` - // turns a vector into state and `Final` turns state back into a vector, so state - // never sits where a value is expected and a value never sits where state is. + // `Partial` turns a vector into state and `Final` turns state back into a vector. match op.stage { AggregateStage::Complete => { - // Every contribution lies within this execution: vector in, vector out, - // both on the input's grid, one value per input field. let Some((_, input_grid)) = evaluated_vector(&input.output) else { return Err(invalid(&format!( "a complete aggregate consumes an evaluated vector, not {}", @@ -2720,9 +2076,6 @@ impl NativeNode { ensure_grid(&self.output, input_grid, "a complete aggregate")?; } AggregateStage::Partial => { - // Only this execution's contributions were seen, so the output is state - // for a later merge: on the input's grid, grouped the same way, one - // accumulator per input field. let Some((input_schema, input_grid)) = evaluated_vector(&input.output) else { return Err(invalid(&format!( @@ -2774,8 +2127,6 @@ impl NativeNode { } } AggregateStage::Final => { - // The state was collected from every contributing execution, so the - // output is the complete value on the grid that state is indexed on. let NativeType::AggregateState(state) = &input.output else { return Err(invalid(&format!( "a final aggregate consumes aggregate state, not {}", @@ -2809,7 +2160,6 @@ impl NativeNode { )); } let output = ensure_samples(&self.output, "a final aggregate")?; - // The merged value carries one value per accumulator the state holds. ensure_field_count( output.fields.len(), state.accumulators.len(), @@ -2826,36 +2176,24 @@ impl NativeNode { } => { input.validate()?; parameter.validate()?; - // The parameter is read off the chunk its node hands over, once per grid point, so - // it has to be a scalar the node answers a series for -- `scalar()`, `time()` and - // the like all do. A literal has no chunk of its own: its value is on the binding - // of a node that carries it, and a fold that never receives one would run to the - // end of its input and fail instead of folding. A query that writes a constant gets - // the constant path, which binds the number on the fold itself; a tree that reaches - // here with one was not built by the compiler, so it is refused before it runs. + // φ is read off the parameter's chunks, and a literal hands over none; the compiler + // binds a constant φ on the `Aggregate` instead. if matches!(parameter.expr, NativeExpr::Scalar(_)) { return Err(invalid( "a parameterized aggregate reads a parameter node that hands over a \ scalar series, not a literal", )); } - // Only a `quantile` takes an argument a query reads per point: it is the one - // aggregate whose argument is a value rather than a name, and every other kind - // binds its parameter into its own op (or is not an aggregate at all). if !matches!(op.kind, AggregateKind::Quantile { .. }) { return Err(invalid( "a parameterized aggregate that is not a `quantile`", )); } - // A quantile answers from its group's whole sample set, so it keeps no state: the - // stage that reads a parameter is the one that folds, exactly as for the bound `φ`. if op.stage != AggregateStage::Complete { return Err(invalid( "a parameterized aggregate at a stage other than `Complete`", )); } - // The parameter is read at every point the fold answers, one value per point and no - // labels, so it is a scalar on the grid the answer is stamped on. let Some((_, output_grid)) = evaluated_vector(&self.output) else { return Err(invalid( "a parameterized aggregate does not produce an evaluated vector", @@ -2887,9 +2225,6 @@ impl NativeNode { NativeExpr::Binary { left, right, .. } => { left.validate()?; right.validate()?; - // A binary operation is point-wise, so both sides are evaluated on the statement's - // grid: state has no positions at all, and raw samples carry their own timestamps - // instead of positions on a shared grid. let Some(left_grid) = left.output.grid() else { return Err(invalid(&format!( "a binary operation consumes evaluated values, not {} on its left", @@ -2906,7 +2241,6 @@ impl NativeNode { return Err(invalid("a binary operation aligns two different grids")); } match (&left.output, &right.output) { - // Two scalars make a scalar: there is nothing to match and nothing to keep. (NativeType::Scalar(_), NativeType::Scalar(_)) => { if !matches!(&self.output, NativeType::Scalar(grid) if grid.spec() == left_grid.spec()) { @@ -2915,9 +2249,6 @@ impl NativeNode { )); } } - // A scalar side carries no labels and no fields, so the operation is a - // broadcast on the statement's grid and `matching` is not consulted. A scalar - // has no fields of its own, so the broadcast keeps the vector side's fields. (NativeType::Scalar(_), NativeType::Samples(vector)) | (NativeType::Samples(vector), NativeType::Scalar(_)) => { let Some(output) = self.output.samples() else { @@ -2933,8 +2264,7 @@ impl NativeNode { )); } } - // Two vectors are matched by `matching` on the grid they share, and the match - // pairs fields by position, so it keeps the shorter side's fields. + // The match pairs fields by position, so it keeps the shorter side's count. (NativeType::Samples(left_vector), NativeType::Samples(right_vector)) => { let Some(output) = self.output.samples() else { return Err(invalid(&format!( @@ -2949,10 +2279,7 @@ impl NativeNode { )?; ensure_grid(&self.output, left_grid, "a binary operation")?; } - // State has no grid, so the grid checks above return for either side before - // this match and these two arms cannot be reached at run time. They are - // spelled out because `NativeType` names `AggregateState` and the match has to - // cover the pair; the message says so rather than pretending a value arrived. + // Unreachable: state has no grid, so the checks above already returned. (NativeType::AggregateState(_), _) | (_, NativeType::AggregateState(_)) => { return Err(invalid( "a binary operation reached aggregate state, which has no grid: the \ @@ -2964,8 +2291,6 @@ impl NativeNode { NativeExpr::Set { left, right, .. } => { left.validate()?; right.validate()?; - // A set operation keeps samples of whole vectors on the grid both share: a scalar - // has no labels to match, and PromQL refuses it on either side. let Some((left_schema, left_grid)) = evaluated_vector(&left.output) else { return Err(invalid(&format!( "a set operation consumes evaluated vectors, not {} on its left", @@ -2981,8 +2306,7 @@ impl NativeNode { if left_grid.spec() != right_grid.spec() { return Err(invalid("a set operation aligns two different grids")); } - // `or` hands the right side's samples on under the left side's fields, so the - // kernel pairs every field by position and refuses sides of different counts. + // `or` emits the right side's samples under the left side's fields, by position. if left_schema.fields.len() != right_schema.fields.len() { return Err(invalid(&format!( "a set operation pairs fields by position, and its sides carry {} and {}", @@ -3003,12 +2327,8 @@ impl NativeNode { base.output.describe() ))); }; - // The kernel reads the info side's values as sample times, which only an instant - // selection that reports them produces. A canonical merge above that selection only - // collects the pieces of one label set into one series, so it hands the times on - // unchanged and the check looks through it. Nothing else is looked through: an - // evaluated value vector is not a set of sample times, and reading one as times - // would compare a sample's value against another's. + // The kernel reads the info side's values as sample times, so it must be an + // `InfoTimestamp` selection; a merge above it passes the times through unchanged. let mut source = info.as_ref(); while let NativeExpr::Merge { input } = &source.expr { source = input; @@ -3045,56 +2365,23 @@ impl NativeNode { } } -/// Whether a binary operation drops the metric name when one side is a scalar broadcast. -/// -/// `BroadcastRuntime::drops_labels` in [`execute`](crate::native::execute) is the rule the runtime -/// applies: arithmetic and a `bool` comparison answer a series under the metric name dropped, and a -/// filtering comparison keeps the label set it read. +/// Whether a scalar broadcast drops the metric name; mirrors `BroadcastRuntime::drops_labels` in +/// [`execute`](crate::native::execute). fn broadcast_drops_labels(matching: &BinaryMatching) -> bool { !matching.op.is_comparison() || matching.return_bool } -/// Whether `node` hands over one logical series per canonical label set, or several. +/// Whether `node` hands over one series per canonical label set. /// -/// This is the rule the runtime collectors use to decide whether a consumer above `node` has to -/// collect what `node` emits. `RuntimeNode::build` in [`execute`](crate::native::execute) and the -/// Window and `limitk` collectors share this predicate so their decisions cannot disagree. +/// - `Some(true)`: one series per label set; a consumer collects nothing. +/// - `Some(false)`: several series may share a label set; the `Window` runtime collects them +/// through `MergeInput`, and `limitk` merges its retained input. +/// - `None`: unknown. Only an [`NativeExpr::Input`] answers this, and pass-through nodes propagate +/// it; the runtime collectors treat it like `Some(true)`. /// -/// Three answers, because what a consumer may do about a contribution carries two facts and a -/// boundary answers neither: -/// -/// - `Some(true)`: the output is one series per canonical label set, established here, so a -/// consumer that needs one unified series already has it and collects nothing. -/// - `Some(false)`: the output may hold several series of one label set, and this node *says so*, -/// so a consumer that needs one unified series collects them through `MergeInput`. A -/// [`NativeExpr::Merge`] above such a node would make it stream an already-merged series and -/// turn that collection off. -/// - `None`: the output may hold several, and this node says nothing: it has neither a proof to -/// offer nor a report to make. Only a boundary ([`NativeExpr::Input`]) answers this, and a node -/// that hands its input's series back unchanged passes the answer on. Runtime collectors leave -/// this case alone because they collect only when the answer is `Some(false)`. -/// -/// The collection condition is `matches!(answer, Some(false))`: the Window `MergeInput` collector -/// at runtime and the `limitk` collector both ask this predicate of their input. -/// -/// `source_tags` and `source_metrics` are the same facts -/// [`duplicates_canonical_labels`] judges a whole label set by, indexed the same way: a node that -/// drops the metadata labels reports fragments only when -/// [`metadata_labels_keep_series_apart`] cannot prove the labels tell its series apart. That is the -/// whole of the drop's proof, so this predicate and the canonical pass cannot disagree about a drop: -/// a `NULL`/`''` pair in one key column is outside it for both, and the statements the pair leaves -/// unproved are counted by [`leaves_a_drop_to_the_storage_keys`] rather than collected. -/// -/// This predicate is only ever asked of a node by the consumer directly above it - the `Window` -/// `MergeInput` collector and the `limitk` one, both in [`execute`](crate::native::execute) - and -/// that is exactly where the canonical pass puts its [`NativeExpr::Merge`] when a collection is -/// needed: it collects the input of a `Window`, an `Aggregate`, a `Vector`, a `Map`, a -/// `ParameterizedMap` and each side of a `Binary`/`Set`/`Info` -/// ([`merge_label_rewrites`](crate::native::canonicalize::merge_label_rewrites)). The collector -/// then reads the merge's `Some(true)` - a merge *is* the collection - so the weaker answer this -/// function gives about the node beneath it is never the one acted on. Where the pass left the tree -/// alone, the proof held, and the answer asked here is the same one. A caller without these facts -/// (placement, which reads a tree without a binding) passes empty slices and gets the conservative +/// A metadata-label drop is judged by [`metadata_labels_keep_series_apart`] with the same +/// `source_tags` and `source_metrics` as [`duplicates_canonical_labels`], so this and the canonical +/// pass agree about a drop. [`reads_across_series`] passes empty slices and gets the conservative /// answer. #[allow(clippy::match_same_arms)] // Keep each expression's contribution guarantee explicit. pub fn unifies_its_own_contributions( @@ -3103,26 +2390,13 @@ pub fn unifies_its_own_contributions( source_metrics: &[Option>], ) -> Option { match &node.expr { - // A boundary hands over the pieces some upstream execution produced: what it holds is one - // storage series at a time for a scan and one partition's fragments of a label set for an - // exchange, and nothing in the tree can tell which series those fragments belong to. A - // merge binds samples evaluated on a grid rather than proving the pieces are one series - // per label set, so a proof is not this function's to give: it answers `None`. Runtime - // collectors gather only when this node reports fragments with `Some(false)`. NativeExpr::Input(_) => None, - // A constant holds no label set at all, so it has nothing that could arrive twice. NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } | NativeExpr::VectorOf { .. } => { Some(true) } - // A selection reads raw samples - `validate` refuses an evaluated input - and raw samples - // arrive one whole storage series at a time, so it answers one series per series it read, - // under the label set it read. `timestamp(x)` is the exception: it reports the sample's own - // time under the metric name dropped, which can give two series one label set. + // Raw samples arrive one whole storage series at a time. NativeExpr::Instant { input, op } => { if op.value == InstantValue::Timestamp { - // `timestamp` drops the metadata labels, so what it emits aliases unless the drop - // provably tells its series apart. The labels half is asked here; the keys half is - // what the pass collects with, above this node - see this function's docs. Some(metadata_labels_keep_series_apart( input, source_tags, @@ -3132,34 +2406,15 @@ pub fn unifies_its_own_contributions( Some(true) } } - // The merge is the collection: whatever its input handed over, it groups the fragments by - // canonical label set and emits one series per set, so what it emits shares none. NativeExpr::Merge { .. } => Some(true), - // A window answers three ways, and what the function does to labels decides the first: - // - // - the function drops the metric name, so what it emits can coincide with another series' - // label set whatever its input held: `Some(false)` (this is a real report, and the case - // `Map`, `Timestamp` and a label-dropping broadcast are in); - // - the function keeps the metric name, and the child answers one series per label set - - // `Some(true)` - or reports fragments the window's `MergeInput` collects - `Some(false)`. - // Either way the window emits one series per label set and answers `Some(true)`: an - // already-unified child keeps that property through the labels the window retains, and - // fragments are collected before the window folds them; - // - the function keeps the metric name, but the child is a boundary - `None`. The window - // folds each contribution on its own, so what it emits does alias its input's fragments, - // and `Some(false)` is exact. + // Over a boundary the window folds each fragment on its own, so its output may alias. + // Otherwise its input is unified or collected through `MergeInput`, so only a + // name-dropping function can make two series collide. NativeExpr::Window { input, op } => { let child = unifies_its_own_contributions(input, source_tags, source_metrics); if child.is_none() { - // A boundary hands the pieces of one series over one at a time, and the window folds - // them without ever seeing the whole series: what it emits aliases whatever the - // labels say. Some(false) } else if op.function.drops_metric_name() { - // The function drops the metadata labels, so the window answers `Some(true)` exactly - // when the labels say the drop tells its input's series apart. The keys half is the - // pass's to ask: where it fails, the pass has already put its merge above this - // window and the collector reads that merge's answer - see this function's docs. Some(metadata_labels_keep_series_apart( input, source_tags, @@ -3169,21 +2424,12 @@ pub fn unifies_its_own_contributions( Some(true) } } - // A map can rewrite labels, so two series can end under one label set: what it hands out is - // not one series per set until a canonical merge has collected the set. NativeExpr::Map { .. } | NativeExpr::ParameterizedMap { .. } => Some(false), - // `topk` hands back the series it read with their labels, so the input's answer is its own - - // exactly as for the bound operation. NativeExpr::ParameterizedTopK { input, .. } => { unifies_its_own_contributions(input, source_tags, source_metrics) } - // A histogram function groups its rows by label set itself, so it emits one series per set. NativeExpr::ParameterizedHistogram { .. } => Some(true), - // `scalar()` answers one value per point, which is not several series. NativeExpr::ScalarOf { .. } => Some(true), - // A timestamp reports a position under the metadata labels dropped, and the labels half - // asked here is answered for the same reason the `timestamp` selection's is: the keys half - // is the one the pass turns into a merge above this node - see this function's docs. NativeExpr::Timestamp { input } => Some(metadata_labels_keep_series_apart( input, source_tags, @@ -3196,25 +2442,12 @@ pub fn unifies_its_own_contributions( } => { if evaluated_vector(&left.output).is_some() && evaluated_vector(&right.output).is_some() { - // Two vectors are matched by the kernel, which files its rows by the label set a - // sample ends under and emits one series per set. Some(true) } else if broadcast_drops_labels(matching) { - // A broadcast whose operation drops the metric name can give two series of its - // vector side one label set. Some(false) } else { - // A filtering comparison keeps the label set it read, so the side that carries - // series answers for this node. Which side that is follows the rule the runtime's - // broadcast matches on: an evaluated vector carries them, and with two scalars the - // carrier is the side that is not a bound constant (`broadcast_runtime`'s - // `literal(left).is_none()`), which is what the second test below reads. - // - // The two selection rules agree wherever it is observable: every scalar node kind - // answers `Some(true)` (`Scalar`, `EvalTime`, `VectorOf`), so a scalar-scalar pair - // answers `Some(true)` whichever side is named and a consumer collects nothing - // either way. The constant check is still what keeps the two readers describing - // the same node rather than coinciding by accident. + // A filtering comparison answers for the side that carries series, picked as + // `broadcast_runtime` picks it: the vector, or the non-literal of two scalars. let carries_series = |node: &NativeNode| { if node.output.samples().is_some() { return true; @@ -3225,21 +2458,11 @@ pub fn unifies_its_own_contributions( unifies_its_own_contributions(vector, source_tags, source_metrics) } } - // A set operation keeps each side's samples and files them by label set, one series per - // set. NativeExpr::Set { .. } => Some(true), - // `info` indexes the info side by identifying labels and merges the results that share a - // label set. NativeExpr::Info { .. } => Some(true), - // A finished aggregate emits one series per group, and two groups are two label sets. - // `Partial` state is not a series at all, which is not several either. A per-point parameter - // does not change that: the labels a group is filed under are its grouping's. NativeExpr::Aggregate { .. } | NativeExpr::ParameterizedAggregate { .. } => Some(true), - // `topk`, `limit_ratio` and `sort` hand back the series they read with their labels, so the - // input's answer is theirs. The four that read the whole vector - `limitk`, `absent`, - // `histogram_*` and `count_values` - emit one series per label set: `limitk` counts series - // in input order, so its input carries the merge the runtime performs when that input reports fragments, and the other three group their rows - // by label set themselves. + // `limitk` collects its input's fragments at run time; `absent`, `histogram_*` and + // `count_values` group by label set themselves. NativeExpr::Vector { input, op } => { let whole = matches!( op, @@ -3257,25 +2480,13 @@ pub fn unifies_its_own_contributions( } } -/// The schema and grid of an evaluated vector, or `None` when `ty` is raw samples, a scalar or -/// state. -/// -/// An operation over values needs both halves: that its input is samples at all, which rules out -/// a scalar, and that those samples are stamped onto a grid, which rules out raw samples. The -/// schema comes back with the grid because a consumer that needs the grid also declares a field -/// layout for the fields the schema carries. +/// The schema and grid of an evaluated vector, or `None` for raw samples, a scalar or state. fn evaluated_vector(ty: &NativeType) -> Option<(&Arc, &Arc)> { let schema = ty.samples().filter(|schema| schema.eval_grid.is_some())?; Some((schema, schema.eval_grid.as_ref()?)) } -/// Checks that a node declares the field layout its input produces. -/// -/// A window, a map, an instant selection and a complete aggregate all report one value per input -/// field, so they keep the layout of their input. A node that declares a different number of -/// fields than it consumes describes a computation this model has no meaning for, and letting it -/// through would only surface at run time as a field count mismatch against a schema the tree was -/// supposed to have validated. +/// Checks that a node declares as many fields as its input produces. fn ensure_same_fields(input: &NativeType, output: &NativeType, what: &str) -> Result<()> { let (NativeType::Samples(input), NativeType::Samples(output)) = (input, output) else { return Ok(()); @@ -3283,12 +2494,6 @@ fn ensure_same_fields(input: &NativeType, output: &NativeType, what: &str) -> Re ensure_field_count(output.fields.len(), input.fields.len(), what) } -/// Checks that a node declares `declared` fields where its input provides `expected`. -/// -/// Some nodes compute their layout instead of keeping their input's: a final aggregate produces one -/// value per accumulator the state holds, and a vector-vector binary operation produces one field -/// per matched pair, which is the shorter side's count. Both are checked against the count the -/// kernel produces, so the message names the node and both numbers. fn ensure_field_count(declared: usize, expected: usize, what: &str) -> Result<()> { if declared != expected { return Err(invalid(&format!( @@ -3298,17 +2503,12 @@ fn ensure_field_count(declared: usize, expected: usize, what: &str) -> Result<() Ok(()) } -/// Checks that `ty` produces samples and returns them. fn ensure_samples<'a>(ty: &'a NativeType, what: &str) -> Result<&'a Arc> { ty.samples() .ok_or_else(|| invalid(&format!("{what} does not produce samples"))) } -/// Checks that `ty` is evaluated on the grid `expected` describes. -/// -/// The comparison is by [`EvalGrid::spec`], not by allocation: that is the rule the kernels apply -/// (`vector_match::same_grid`), so a compiler that allocates one grid per window but binds equal -/// specs produces a tree the kernel runs correctly. +/// Grids compare by [`EvalGrid::spec`], as the kernels do (`vector_match::same_grid`). fn ensure_grid(ty: &NativeType, expected: &Arc, what: &str) -> Result<()> { match ty.grid() { Some(actual) if actual.spec() == expected.spec() => Ok(()), @@ -3319,13 +2519,8 @@ fn ensure_grid(ty: &NativeType, expected: &Arc, what: &str) -> Result< } } -/// Checks that `input`, when it is a [`NativeExpr::Input`], does not declare interleaved series. -/// -/// A native evaluation reads one series to its last chunk before the next: a range evaluator folds -/// a series completely before it starts another, and an instant selection's consumer collects one -/// series' chunks into one buffer. Neither can be handed chunks of different series that -/// interleave, which is the one rule both consumers state. Only an input node carries an ordering, -/// so only there is there one to check. +/// Instant selections and windows read one series to its last chunk before the next, so an input +/// leaf under them must not interleave. fn ensure_not_interleaved(input: &NativeNode) -> Result<()> { if let NativeExpr::Input(binding) = &input.expr && binding.ordering == SeriesOrdering::Interleaved @@ -3339,13 +2534,10 @@ fn ensure_not_interleaved(input: &NativeNode) -> Result<()> { } fn invalid(reason: &str) -> DataFusionError { - // A rejected tree is a compiler defect, not a query error: the compiler only builds a node - // after deciding that this combination is supported. `Internal` keeps that meaning on the wire - // instead of reporting a mistake in the client's statement, which `Plan` would. + // A rejected tree is a compiler defect, not a mistake in the client's statement. DataFusionError::Internal(reason.to_string()) } -// Tests for native plan validation and execution contracts. #[cfg(test)] pub(crate) mod tests; diff --git a/src/promql/src/native/plan/tests.rs b/src/promql/src/native/plan/tests.rs index 115261f57d7..60fa7f68696 100644 --- a/src/promql/src/native/plan/tests.rs +++ b/src/promql/src/native/plan/tests.rs @@ -81,8 +81,6 @@ fn input() -> NativeNode { } fn input_on(grid: Arc) -> NativeNode { - // One schema allocation shared by the binding and the output: `validate` checks that the output - // is the binding it was bound to, which is about the binding itself, not the grid's spec. let output = evaluated(Arc::new([]), grid); NativeNode { expr: NativeExpr::Input(BoundInput { @@ -94,7 +92,7 @@ fn input_on(grid: Arc) -> NativeNode { } } -/// A scan of `count` fields, so a consumer's field check has something to disagree with. +/// A scan of `count` fields. fn input_with_fields(count: usize) -> NativeNode { let output = NativeType::Samples(Arc::new(SeriesSchema { fields: fields(count), @@ -361,13 +359,7 @@ fn parameterized_topk_validates_scalar_and_grid() { ); } -/// A per-point `quantile` whose argument is a literal is refused by the tree's own check. -/// -/// A literal is one value on a binding, not a series a node hands over: the fold reads its `φ` per -/// point from the series its parameter child hands over, so a literal leaves it waiting for a chunk -/// that never arrives. It would run to the end of its input and only then refuse the run, after -/// every chunk was retained and folded. `validate` is where a tree says what it is, so the shape is -/// refused there, and the admission predicate agrees so a decoded tree never reaches that wait. +/// A literal hands over no chunk, so the fold would wait for a `φ` that never arrives. #[test] fn a_literal_quantile_parameter_is_refused() { let out = grid(0, 60_000, 4); @@ -397,8 +389,6 @@ fn a_literal_quantile_parameter_is_refused() { !native_node_supported(&literal), "the admission predicate admits a tree `validate` refuses" ); - // A parameter that hands over a series is what the fold reads, so the check is the literal and - // not a scalar output. assert!( node(NativeNode { expr: NativeExpr::EvalTime { date: None }, @@ -484,7 +474,6 @@ fn binary_histogram_float_kind_matches_supported_operations() { } } -/// Arithmetic kinds cover both histogram/float directions without declining empty results. #[test] fn binary_arithmetic_field_kind_matrix() { use super::binary_output_field_kind; @@ -529,7 +518,6 @@ fn binary_arithmetic_field_kind_matrix() { } } -/// Fill pairs contribute their real payload kind; unsupported pairs contribute no kind. #[test] fn binary_arithmetic_field_kind_accounts_for_fill() { use super::binary_output_field_kind; @@ -568,7 +556,6 @@ fn binary_arithmetic_field_kind_accounts_for_fill() { Some(expected), "{op:?} {fill:?}" ); - // The tree-level walk must pass the same fill on to the shared kind helper. let histogram = input_on(grid(0, 60_000, 1)); let node = NativeNode { expr: NativeExpr::Binary { @@ -585,9 +572,7 @@ fn binary_arithmetic_field_kind_accounts_for_fill() { ); } - // The real mixed-kind operation and a fill may emit different kinds in one field, and neither - // silently claims homogeneity. A comparison over two kinds is a different question - it emits - // no sample whatever the fill says - and answers the empty float layout below. + // A comparison over two kinds emits no sample whatever the fill says. assert_eq!( binary_output_field_kind(Histogram, Float, BinaryOp::Mul, false, left), None @@ -618,12 +603,8 @@ fn binary_arithmetic_field_kind_accounts_for_fill() { ); } -/// A comparison answers a float when its two sides carry different kinds. -/// -/// The kernel skips every mixed pair without counting a match - `(Float, Histogram)` and -/// `(Histogram, Float)` included (`vector_match::elem_binop`) - so no sample can end under either -/// side's type. What is declared is the layout arithmetic keeps for a pair that emits nothing: one -/// float. Two sides of one kind keep it, and a `bool` comparison answers `1`/`0` whatever it read. +/// The kernel skips every mixed-kind comparison pair (`vector_match::elem_binop`), so the column is +/// the empty float layout. #[test] fn binary_comparison_names_a_mixed_pair_as_a_float() { use super::binary_output_field_kind; @@ -664,8 +645,6 @@ fn binary_comparison_names_a_mixed_pair_as_a_float() { ); } - // The tree-level walk asks the same helper, so a mixed pair over two inputs answers the float - // layout there too, and the answer is the one the statement's column is declared with. let histogram = input_on(grid(0, 60_000, 1)); let float = NativeNode { expr: NativeExpr::Timestamp { @@ -692,13 +671,6 @@ fn binary_comparison_names_a_mixed_pair_as_a_float() { } } -/// A whole-vector operation answers either the series it selected or a value it computed. -/// -/// `topk`, `bottomk`, `limitk`, `limit_ratio` and the `sort`s hand on the samples they read under -/// the labels those samples carry, so a histogram stays a histogram - the same rule the per-point -/// `k` form states for the same `TopK`. `absent` writes `1.0`, `histogram_quantile` and -/// `histogram_fraction` reduce a classic histogram to one float, and `count_values` counts samples -/// as floats: each answers a float whatever its input holds. #[test] fn vector_operation_field_kinds_follow_what_each_op_answers() { use crate::extension_plan::FieldKind::{Float, Histogram}; @@ -772,11 +744,6 @@ fn vector_operation_field_kinds_follow_what_each_op_answers() { } } -/// `info` answers the base's samples, so its field is the base's field. -/// -/// The info side is read as sample times (`InstantValue::InfoTimestamp`), which is a float the -/// kernel compares rather than a value it answers with: a base carrying native histograms therefore -/// keeps its histogram column. #[test] fn info_keeps_the_kind_of_its_base() { let out = grid(0, 60_000, 4); @@ -816,11 +783,6 @@ fn info_keeps_the_kind_of_its_base() { ); } -/// A parameterized map applies a math function, and math skips histograms rather than converting -/// them, so the field shape is unchanged and keeps its input's kind. -/// -/// `round` and the three `clamp`s map a vector onto the same fields; `max_of`/`min_of` answer one -/// scalar from one, which is a float whatever the statement's sources hold. #[test] fn parameterized_map_keeps_the_kind_of_its_input() { let out = grid(0, 60_000, 4); @@ -851,7 +813,6 @@ fn parameterized_map_keeps_the_kind_of_its_input() { "{op:?}" ); } - // A function of two scalars answers a scalar, whose kind is a float either way. let node = NativeNode { expr: NativeExpr::ParameterizedMap { input: Box::new(scalar_on(1.0, Arc::clone(&out))), @@ -867,39 +828,6 @@ fn parameterized_map_keeps_the_kind_of_its_input() { ); } -/// A compiled tree is accepted when every node's contract holds. -#[test] -fn a_window_over_raw_samples_is_valid() { - let root = window_over(input(), None); - assert!(NativeTree::try_new(root).is_ok()); -} - -/// Adding a map to a window changes the tree and nothing else: no new shape is recognised. -#[test] -fn adding_a_map_only_changes_the_tree() { - let bare = window_over(input(), None); - let mapped = map_over(window_over(input(), None)); - // Both trees are legal, so the comparison below is about the shape and not about both failing. - assert!(bare.validate().is_ok(), "{}", bare.validate().unwrap_err()); - assert!( - mapped.validate().is_ok(), - "{}", - mapped.validate().unwrap_err() - ); - // The mapped tree is that map over that window over that input, and nothing else: the map on - // top is the one node the bare tree gained, and what is below it is the tree it was built from. - let NativeExpr::Map { input, .. } = &mapped.expr else { - unreachable!("the mapped tree's root is a map") - }; - let NativeExpr::Window { input: leaf, .. } = &input.expr else { - unreachable!("the map is not over the window the bare tree is") - }; - assert!( - matches!(leaf.expr, NativeExpr::Input(_)), - "the window is not over the input the bare tree reads" - ); -} - #[test] fn merge_rejects_raw_and_mismatched_input_shapes() { let raw_merge = NativeNode { @@ -962,7 +890,6 @@ fn merge_rejects_raw_and_mismatched_input_shapes() { assert!(fields_error.to_string().contains("field"), "{fields_error}"); } -/// A map is point-wise over values, so raw samples are not something it can consume. #[test] fn a_map_cannot_consume_raw_samples() { let node = NativeNode { @@ -1002,7 +929,6 @@ fn timestamp_requires_evaluated_vector_and_preserves_its_layout() { ); } -/// A scalar is one value per grid point, not a vector, so there are no fields to map. #[test] fn a_map_cannot_consume_a_scalar() { let out = grid(0, 60_000, 4); @@ -1019,7 +945,6 @@ fn a_map_cannot_consume_a_scalar() { assert!(error.to_string().contains("not a scalar"), "{error}"); } -/// A map with no operation would be a node that does nothing, which is a compiler mistake. #[test] fn a_map_needs_an_operation() { let inner = window_over(input(), None); @@ -1035,9 +960,6 @@ fn a_map_needs_an_operation() { assert!(error.to_string().contains("no operation"), "{error}"); } -/// A map reports one value per input field, so it cannot declare a layout its input does not -/// have. Without this check the tree would validate and only fail when the runtime compared the -/// node's schema against the one its input actually produces. #[test] fn a_map_cannot_change_the_field_count() { let inner = window_over(input(), None); @@ -1065,12 +987,9 @@ fn a_map_cannot_change_the_field_count() { ); } -/// A window reports one value per input field, so it carries the same rule as a map. #[test] fn a_window_cannot_change_the_field_count() { let inner = window_over(input(), None); - // The output grid is the input's, so the grid check passes and the field check is what the - // test actually exercises. let out = inner.output.grid().unwrap().clone(); let node = NativeNode { expr: NativeExpr::Window { @@ -1103,13 +1022,9 @@ fn a_window_cannot_change_the_field_count() { ); } -/// An instant selection picks one row of the source per grid point, so it carries one value per -/// input field. A tree that declares anything else would only fail at run time, against a schema -/// the tree was supposed to have validated. #[test] fn an_instant_selection_cannot_change_the_field_count() { let out = grid(0, 60_000, 4); - // The source has two fields; the selection declares one value. let node = NativeNode { expr: NativeExpr::Instant { input: Box::new(input_with_fields(2)), @@ -1132,8 +1047,6 @@ fn an_instant_selection_cannot_change_the_field_count() { ); } -/// An instant selection reads raw samples; feeding it evaluated values would re-anchor a grid -/// that is already fixed. #[test] fn an_instant_selection_reads_raw_samples() { let out = grid(0, 60_000, 4); @@ -1154,7 +1067,6 @@ fn an_instant_selection_reads_raw_samples() { assert!(error.to_string().contains("reads evaluated"), "{error}"); } -/// Aggregate state is not a sample stream, so an instant selection cannot read it. #[test] fn an_instant_selection_cannot_consume_state() { let out = grid(0, 60_000, 4); @@ -1179,12 +1091,10 @@ fn an_instant_selection_cannot_consume_state() { assert!(error.to_string().contains("aggregate state"), "{error}"); } -/// A window's declared input grid has to be the grid its input actually produces. #[test] fn a_window_checks_its_declared_input_grid() { let inner_grid = grid(0, 60_000, 4); let other_grid = grid(0, 30_000, 8); - // The input produces `inner_grid`, but the window claims a different one. let node = window_over(input_on(inner_grid), Some(other_grid)); let error = node.validate().unwrap_err(); assert!( @@ -1195,8 +1105,6 @@ fn a_window_checks_its_declared_input_grid() { ); } -/// A range evaluator reads one raw series to its last chunk before it starts the next, so raw -/// chunks of different series may not interleave. #[test] fn a_window_cannot_read_interleaved_input() { let error = window_over(interleaved_input(), None) @@ -1210,9 +1118,6 @@ fn a_window_cannot_read_interleaved_input() { ); } -/// An instant selection's consumer collects one series' chunks into one buffer, so it reads a -/// series to its last chunk before the next: it refuses an interleaved input for the reason a -/// window does. #[test] fn an_instant_selection_cannot_read_interleaved_input() { let out = grid(0, 60_000, 4); @@ -1236,9 +1141,16 @@ fn an_instant_selection_cannot_read_interleaved_input() { .contains("interleaved chunks cannot be fed to it"), "{error}" ); + // The map itself is well-typed; only validating its input finds the interleaved scan. + let error = NativeTree::try_new(map_over(node)).unwrap_err(); + assert!( + error + .to_string() + .contains("interleaved chunks cannot be fed to it"), + "{error}" + ); } -/// A window whose range is empty or negative reads nothing at every grid point. #[test] fn a_window_reads_a_non_empty_range() { let mut node = window_over(input(), None); @@ -1250,8 +1162,6 @@ fn a_window_reads_a_non_empty_range() { assert!(error.to_string().contains("empty range"), "{error}"); } -/// A node that declares an output grid its output does not carry would be addressed on one grid -/// and hand out positions on another. #[test] fn a_window_checks_its_output_grid() { let mut node = window_over(input(), None); @@ -1268,7 +1178,6 @@ fn a_window_checks_its_output_grid() { ); } -/// A window consumes samples: state holds accumulators, not a sample stream to range over. #[test] fn a_window_cannot_consume_state() { let out = grid(0, 60_000, 4); @@ -1281,7 +1190,6 @@ fn a_window_cannot_consume_state() { assert!(error.to_string().contains("aggregate state"), "{error}"); } -/// A window ranges over timestamps, and a scalar has none of its own. #[test] fn a_window_cannot_consume_a_scalar() { let out = grid(0, 60_000, 4); @@ -1294,7 +1202,6 @@ fn a_window_cannot_consume_a_scalar() { assert!(error.to_string().contains("not a scalar"), "{error}"); } -/// A binary node aligns two inputs, so two different grids cannot be aligned implicitly. #[test] fn a_binary_operation_rejects_two_grids() { let left = window_over(input(), None); @@ -1312,30 +1219,9 @@ fn a_binary_operation_rejects_two_grids() { assert!(error.to_string().contains("different grids"), "{error}"); } -/// Two inputs on the same grid are a legal binary operation, which is how -/// `rate(a[5m]) + rate(b[5m])` becomes an ordinary tree. -#[test] -fn a_binary_operation_over_one_grid_is_valid() { - // Both sides evaluate on the statement's grid, so the compiler binds one grid to both. - let shared = grid(0, 60_000, 4); - let node = NativeNode { - expr: NativeExpr::Binary { - left: Box::new(window_on(input(), None, Arc::clone(&shared))), - right: Box::new(window_on(input(), None, Arc::clone(&shared))), - matching: add(), - }, - output: evaluated(Arc::new([]), shared), - }; - assert!(node.validate().is_ok()); -} - -/// A compiler that allocates one grid per window still produces one grid: the kernel aligns -/// operands by `EvalGrid::spec` (`vector_match::same_grid`), so `validate` compares specs too and -/// does not reject a tree the runtime would run correctly. +/// The kernel aligns operands by `EvalGrid::spec` (`vector_match::same_grid`), not by allocation. #[test] fn a_binary_operation_aligns_separately_allocated_equal_specs() { - // Two windows, one fresh `EvalGrid` each, and the statement's grid a third: equal specs, no - // shared allocation anywhere in the tree. let node = NativeNode { expr: NativeExpr::Binary { left: Box::new(window_on(input(), None, grid(0, 60_000, 4))), @@ -1346,7 +1232,6 @@ fn a_binary_operation_aligns_separately_allocated_equal_specs() { }; assert!(node.validate().is_ok(), "{}", node.validate().unwrap_err()); - // The same tree with a different spec is still rejected: the kernel rejects that pair too. let node = NativeNode { expr: NativeExpr::Binary { left: Box::new(window_on(input(), None, grid(0, 60_000, 4))), @@ -1359,8 +1244,6 @@ fn a_binary_operation_aligns_separately_allocated_equal_specs() { assert!(error.to_string().contains("different grids"), "{error}"); } -/// A scalar side is broadcast, not matched: `sum by(job)(rate(x[5m])) + time()` has no labels to -/// line up, so `matching` is not consulted and the output keeps the vector side's fields. #[test] fn a_binary_operation_broadcasts_a_scalar() { let shared = grid(0, 60_000, 4); @@ -1375,7 +1258,6 @@ fn a_binary_operation_broadcasts_a_scalar() { }; assert!(node.validate().is_ok()); - // The mirror case: the scalar on the left keeps the right side's fields. let node = NativeNode { expr: NativeExpr::Binary { left: Box::new(scalar_on(1.0, Arc::clone(&shared))), @@ -1387,28 +1269,9 @@ fn a_binary_operation_broadcasts_a_scalar() { assert!(node.validate().is_ok()); } -/// A broadcast side carries no labels, so the labels a binary operation reports are the vector -/// side's - whichever side the vector is written on. -/// -/// Three kinds of constant can sit beside a vector and only one of them is typed as a scalar: -/// `time()` answers a scalar ([`NativeExpr::EvalTime`]), `vector(1)` is a materialized one-field -/// vector with no label set ([`NativeExpr::VectorOf`]), and `clamp_max(x, 1)` is a -/// [`NativeExpr::ParameterizedMap`] whose parameter is a scalar. None of them names a label -/// column, so a tree that reported one would declare a column no row fills; and a tree that -/// dropped the vector side's labels instead would lose the identity every series of the answer is -/// routed by. -/// -/// `vector(1)` is the one of the three that a vector-vector match reads, because its value is a -/// vector rather than a scalar: written on the left it is the one-to-one match's label source, so -/// the answer carries the (empty) label set the match key names - and no label of the vector on -/// the right. Either way nothing of `vector(1)` reaches the output as a label. -/// -/// The same constants also decide nothing about a series' *identity*, which is the other half of -/// what a node reports: a broadcast reaches each series of its vector side as it is, so whether two -/// series can end under one label set is that side's answer. That half is read against a vector -/// whose answer is `true` - a rewrite of a label its input already carries can fold two series into -/// one - because a comparison against a vector that never aliases would pass for an implementation -/// that always answered `false`. +/// `time()`, `vector(1)` and a parameterized map's scalar parameter contribute no labels on either +/// side. Ownership is checked against an aliasing vector, so an implementation that always answered +/// `false` would fail. #[test] fn a_broadcast_side_contributes_no_labels() { let shared = grid(0, 60_000, 4); @@ -1424,8 +1287,6 @@ fn a_broadcast_side_contributes_no_labels() { }, output: evaluated(fields(1), Arc::clone(&shared)), }; - // A vector whose answer can alias: the rewrite writes a label its input already carries, which - // is what lets two series end under one label set. let aliasing = || { map_over(rewritten( window_on(input(), None, Arc::clone(&shared)), @@ -1455,8 +1316,7 @@ fn a_broadcast_side_contributes_no_labels() { let tags = |node: &NativeNode| fused_output_tags(node, &source_tags); let scan = vec!["host".to_string(), "zone".to_string()]; - // `rate(x[5m]) + time()` and `time() + rate(x[5m])`: the evaluation time is a scalar, so the - // operation is a broadcast over the vector and reports exactly the vector's labels. + // `rate(x[5m]) + time()` and `time() + rate(x[5m])`. assert_eq!( Some(scan.clone()), tags(&vector()), @@ -1473,7 +1333,6 @@ fn a_broadcast_side_contributes_no_labels() { "`time()` contributes no label with the vector on the right either" ); - // `vector(1)` answers one series without labels, so it adds none whichever side it is on. assert_eq!( Some(Vec::new()), tags(&vector_of_one()), @@ -1490,8 +1349,7 @@ fn a_broadcast_side_contributes_no_labels() { "`vector(1)` on the left is the match key, and it names no label" ); - // `clamp_max(rate(x[5m]), 1)` reads a scalar parameter, which carries no labels: the node - // reports its input's labels, and so does a broadcast over it. + // `clamp_max(rate(x[5m]), 1)`. assert_eq!( Some(scan.clone()), tags(&clamp_max(vector())), @@ -1508,9 +1366,6 @@ fn a_broadcast_side_contributes_no_labels() { "the same with the constant written first" ); - // Ownership follows the vector side as well, and it is read against the aliasing vector: a - // broadcast reaches each series of its vector side as it is, so whether two series can end - // under one label set is that side's answer, not the constant's. assert!( duplicates_canonical_labels(&aliasing(), &source_tags, &[]), "the fixture aliases: a rewrite of a label its input carries can fold two series into one" @@ -1532,10 +1387,7 @@ fn a_broadcast_side_contributes_no_labels() { "a broadcast keeps the series identity of its vector side" ); } - // `vector(1)` is the exception of the three: it is a vector, so a binary with it is a match, - // and the kernel files its rows by the label set a sample ends under and refuses two values of - // one field at one point. An alias below it therefore cannot reach the answer, whichever side - // the match reads it from. + // With `vector(1)` the binary is a vector match, which files rows by result label set. for node in [ binary(aliasing(), vector_of_one()), binary(vector_of_one(), aliasing()), @@ -1547,12 +1399,9 @@ fn a_broadcast_side_contributes_no_labels() { } } -/// A scalar has no fields of its own, so a broadcast that declares a different count than the -/// vector side would report a layout the kernel does not produce. #[test] fn a_scalar_broadcast_cannot_change_the_field_count() { let shared = grid(0, 60_000, 4); - // The vector side has two fields; the broadcast declares one. let node = NativeNode { expr: NativeExpr::Binary { left: Box::new(window_fields(input_with_fields(2), Arc::clone(&shared), 2)), @@ -1570,13 +1419,10 @@ fn a_scalar_broadcast_cannot_change_the_field_count() { ); } -/// Two vectors pair their fields by position, so the match reports the shorter side's count -/// (`vector_match::binary_output_schema` takes `min(lhs, rhs)`); a tree declaring anything else is -/// rejected instead of failing at run time. +/// `vector_match::binary_output_schema` keeps `min(lhs, rhs)` fields. #[test] fn a_binary_operation_over_two_vectors_matches_the_shorter_side() { let shared = grid(0, 60_000, 4); - // Two fields matched against one: the match produces one field, not two. let node = NativeNode { expr: NativeExpr::Binary { left: Box::new(window_fields(input_with_fields(2), Arc::clone(&shared), 2)), @@ -1593,7 +1439,6 @@ fn a_binary_operation_over_two_vectors_matches_the_shorter_side() { "{error}" ); - // Declaring the shorter side's count is the legal tree, so the check is not vacuous. let node = NativeNode { expr: NativeExpr::Binary { left: Box::new(window_fields(input_with_fields(2), Arc::clone(&shared), 2)), @@ -1605,22 +1450,6 @@ fn a_binary_operation_over_two_vectors_matches_the_shorter_side() { assert!(node.validate().is_ok(), "{}", node.validate().unwrap_err()); } -/// Two scalars make a scalar, because there is nothing to attach labels or fields to. -#[test] -fn two_scalars_make_a_scalar() { - let shared = grid(0, 60_000, 4); - let node = NativeNode { - expr: NativeExpr::Binary { - left: Box::new(scalar_on(1.0, Arc::clone(&shared))), - right: Box::new(scalar_on(2.0, Arc::clone(&shared))), - matching: add(), - }, - output: NativeType::Scalar(Arc::clone(&shared)), - }; - assert!(node.validate().is_ok()); -} - -/// Two scalars have nothing to attach labels or fields to, so they cannot produce a vector. #[test] fn two_scalars_cannot_produce_a_vector() { let shared = grid(0, 60_000, 4); @@ -1641,8 +1470,6 @@ fn two_scalars_cannot_produce_a_vector() { ); } -/// `vector(s)` materializes its scalar on the grid that scalar is evaluated on, so an output on -/// another grid would address positions the scalar does not have. #[test] fn vector_of_keeps_its_scalars_grid() { let shared = grid(0, 60_000, 4); @@ -1653,11 +1480,9 @@ fn vector_of_keeps_its_scalars_grid() { output, }; - // The same spec on another allocation is the grid the scalar is on. let same = vector_of(evaluated(fields(1), grid(0, 60_000, 4))); assert!(same.validate().is_ok(), "{}", same.validate().unwrap_err()); - // Without a grid there are no positions to materialize the scalar on. let missing = vector_of(NativeType::Samples(Arc::new(SeriesSchema { fields: fields(1), eval_grid: None, @@ -1670,7 +1495,6 @@ fn vector_of_keeps_its_scalars_grid() { "{error}" ); - // Another grid addresses positions that scalar has no value at. let mismatched = vector_of(evaluated(fields(1), grid(0, 30_000, 8))); let error = mismatched.validate().unwrap_err(); assert!( @@ -1681,12 +1505,6 @@ fn vector_of_keeps_its_scalars_grid() { ); } -/// A constant operand is broadcast to each series the other side answers, so such an operation reads -/// one series at a time exactly when that other side does. -/// -/// Two vectors are a match over the whole vector, and an aggregate folds a group, so either of them -/// under the constant still reads across series. Two constants answer the same value for every series -/// there is, so they read none. #[test] fn a_constant_operand_reads_one_series_at_a_time() { let shared = grid(0, 60_000, 4); @@ -1722,12 +1540,12 @@ fn a_constant_operand_reads_one_series_at_a_time() { "a broadcast reaches each series the vector side answers: {node:?}" ); } - // `sum(rate(v0[5m])) + 100` folds a group first, so the constant is broadcast to each group. + // `sum(rate(v0[5m])) + 100`. assert!(reads_across_series(&binary( aggregate, scalar_on(100.0, Arc::clone(&shared)) ))); - // `scalar(rate(v0[5m]))` must inspect all the series at each point. + // `scalar(rate(v0[5m]))`. let scalar_of = NativeNode { expr: NativeExpr::ScalarOf { input: Box::new(vector()), @@ -1735,17 +1553,15 @@ fn a_constant_operand_reads_one_series_at_a_time() { output: NativeType::Scalar(Arc::clone(&shared)), }; assert!(reads_across_series(&scalar_of)); - // `rate(v0[5m]) + rate(v0[5m])` matches two vectors by label. + // `rate(v0[5m]) + rate(v0[5m])`. assert!(reads_across_series(&binary(vector(), vector()))); - // `1 + 2` answers one value for every series there is. + // `1 + 2`. assert!(!reads_across_series(&binary( scalar_on(1.0, Arc::clone(&shared)), scalar_on(2.0, Arc::clone(&shared)) ))); } -/// A binary operation is point-wise on a grid, so a side of raw samples has no positions to line -/// up with the other side. #[test] fn a_binary_operation_cannot_consume_raw_samples() { let shared = grid(0, 60_000, 4); @@ -1780,7 +1596,6 @@ fn a_binary_operation_cannot_consume_raw_samples() { ); } -/// State is not a value, so neither side of a binary operation may be state. #[test] fn a_binary_operation_cannot_consume_state() { let shared = grid(0, 60_000, 4); @@ -1800,57 +1615,9 @@ fn a_binary_operation_cannot_consume_state() { assert!(error.to_string().contains("aggregate state"), "{error}"); } -/// A partial aggregate produces state, not a value; a complete one produces a value on the same -/// grid as its input. -#[test] -fn an_aggregate_output_matches_its_stage() { - let inner = window_over(input(), None); - let value_grid = inner.output.grid().unwrap().clone(); - - let complete = NativeNode { - expr: NativeExpr::Aggregate { - input: Box::new(inner.clone()), - op: BoundAggregate { - kind: AggregateKind::Sum, - group: Grouping::By(Arc::new(["job".into()])), - stage: AggregateStage::Complete, - field_kind: FieldKind::Float, - }, - }, - output: evaluated(Arc::new([]), Arc::clone(&value_grid)), - }; - assert!(complete.validate().is_ok()); - - let partial = NativeNode { - expr: NativeExpr::Aggregate { - input: Box::new(inner), - op: BoundAggregate { - kind: AggregateKind::Sum, - group: Grouping::By(Arc::new(["job".into()])), - stage: AggregateStage::Partial, - field_kind: FieldKind::Float, - }, - }, - output: NativeType::AggregateState(Arc::new(super::AggregateStateSchema { - group: Grouping::By(Arc::new(["job".into()])), - kind: datatypes::series::aggregate_state::AggregateStateKind::Sum, - components: Arc::from([ - datatypes::series::aggregate_state::StateComponent::Value, - datatypes::series::aggregate_state::StateComponent::Compensation, - ]), - accumulators: Arc::new([]), - grid: value_grid, - })), - }; - assert!(partial.validate().is_ok()); -} - -/// A complete aggregate folds each field on its own, so it reports one value per input field -/// (`aggregate::aggregate_float` builds its rows from the input schema's fields). #[test] fn a_complete_aggregate_cannot_change_the_field_count() { let out = grid(0, 60_000, 4); - // The input is a legal two-field window; the aggregate declares one value. let node = NativeNode { expr: NativeExpr::Aggregate { input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), @@ -1872,7 +1639,6 @@ fn a_complete_aggregate_cannot_change_the_field_count() { ); } -/// Declaring a value where the stage produces state is a compiler mistake, and is rejected. #[test] fn an_aggregate_stage_must_agree_with_its_type() { let inner = window_over(input(), None); @@ -1896,12 +1662,9 @@ fn an_aggregate_stage_must_agree_with_its_type() { ); } -/// A `Partial` aggregate keeps one accumulator per input field (`aggregate_float` lays its state -/// out in `schema.fields.len()`-sized points), so state declaring another count is rejected. #[test] fn a_partial_aggregate_cannot_change_the_accumulator_count() { let out = grid(0, 60_000, 4); - // The input is a legal two-field window; the state declares one accumulator. let node = NativeNode { expr: NativeExpr::Aggregate { input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), @@ -1932,8 +1695,6 @@ fn a_partial_aggregate_cannot_change_the_accumulator_count() { ); } -/// A `Partial` aggregate's state is grouped by the binding's group labels, so state declaring -/// other labels is not the state this aggregate produces. #[test] fn a_partial_aggregate_groups_its_state_like_its_binding() { let mut node = partial_aggregate(window_over(input(), None)); @@ -1948,8 +1709,6 @@ fn a_partial_aggregate_groups_its_state_like_its_binding() { ); } -/// A `Partial` aggregate indexes its state on the grid its input produces, so state on another -/// grid is addressed with positions the input never wrote. #[test] fn a_partial_aggregate_indexes_its_state_on_the_inputs_grid() { let node = NativeNode { @@ -1982,8 +1741,6 @@ fn a_partial_aggregate_indexes_its_state_on_the_inputs_grid() { ); } -/// A `Final` aggregate merges into the binding's group labels, so the state it reads has to be -/// grouped the same way. #[test] fn a_final_aggregate_groups_its_state_like_its_binding() { let mut node = final_aggregate(partial_aggregate(window_over(input(), None))); @@ -1998,11 +1755,6 @@ fn a_final_aggregate_groups_its_state_like_its_binding() { ); } -/// `by` and `without` are not interchangeable, even over the same label. -/// -/// `by(job)` keeps `job` and drops every other label; `without(job)` drops `job` and keeps the -/// rest. A binding that spelled `without` as a label list could only produce the first, so state -/// built for one has to be refused for the other rather than merged under the wrong labels. #[test] fn a_grouping_cannot_swap_by_for_without() { let mut node = final_aggregate(partial_aggregate(window_over(input(), None))); @@ -2016,7 +1768,6 @@ fn a_grouping_cannot_swap_by_for_without() { "{error}" ); - // The same labels under the same shape validate, so the refusal is about the shape. let mut node = final_aggregate(partial_aggregate(window_over(input(), None))); let NativeExpr::Aggregate { op, .. } = &mut node.expr else { unreachable!("a final aggregate tree has an aggregate root") @@ -2025,25 +1776,9 @@ fn a_grouping_cannot_swap_by_for_without() { assert!(node.validate().is_ok()); } -/// A `Final` aggregate consumes the state a `Partial` produced, which is what an exchange -/// boundary hands over between the two stages. -#[test] -fn a_final_aggregate_merges_partial_state() { - let shared = grid(0, 60_000, 4); - let state = partial_aggregate(window_on(input(), None, Arc::clone(&shared))); - let merged = final_aggregate(state); - assert!(merged.validate().is_ok()); - assert!( - matches!(&merged.output, NativeType::Samples(schema) if schema.eval_grid.as_ref().is_some_and(|grid| Arc::ptr_eq(grid, &shared))) - ); -} - -/// A `Final` aggregate merges the state into one value per accumulator, so it reports the state's -/// count and nothing else. #[test] fn a_final_aggregate_cannot_change_the_field_count() { let out = grid(0, 60_000, 4); - // A legal partial aggregate: two input fields, two accumulators. let state = NativeNode { expr: NativeExpr::Aggregate { input: Box::new(window_fields(input_with_fields(2), Arc::clone(&out), 2)), @@ -2071,7 +1806,6 @@ fn a_final_aggregate_cannot_change_the_field_count() { state.validate().unwrap_err() ); - // The merge declares one value for the state's two accumulators. let node = NativeNode { expr: NativeExpr::Aggregate { input: Box::new(state), @@ -2093,7 +1827,6 @@ fn a_final_aggregate_cannot_change_the_field_count() { ); } -/// A `Final` aggregate consumes state, so a vector is not something it can merge. #[test] fn a_final_aggregate_cannot_consume_a_window() { let inner = window_over(input(), None); @@ -2117,7 +1850,6 @@ fn a_final_aggregate_cannot_consume_a_window() { ); } -/// A `Complete` aggregate aggregates vectors, so state is not something it can consume. #[test] fn a_complete_aggregate_cannot_consume_state() { let state = partial_aggregate(window_over(input(), None)); @@ -2141,55 +1873,6 @@ fn a_complete_aggregate_cannot_consume_state() { ); } -/// The first-phase walkthrough shapes compile to trees, which is the acceptance the RFC states -/// for composition. -#[test] -fn the_walkthrough_shapes_are_trees() { - // Every node in one query evaluates on the statement's grid; `validate` compares the specs of - // the grids, not their allocations, which is the rule the kernels apply. - let statement_grid = grid(0, 60_000, 4); - - // `abs(rate(x[5m]))` - let abs_rate = map_over(window_over(input(), None)); - assert!(abs_rate.validate().is_ok()); - - // `sum by(job)(rate(x[5m]))`, complete because one execution sees every contribution. - let sum = NativeNode { - expr: NativeExpr::Aggregate { - input: Box::new(window_on(input(), None, Arc::clone(&statement_grid))), - op: BoundAggregate { - kind: AggregateKind::Sum, - group: Grouping::By(Arc::new(["job".into()])), - stage: AggregateStage::Complete, - field_kind: FieldKind::Float, - }, - }, - output: evaluated(Arc::new([]), Arc::clone(&statement_grid)), - }; - assert!(sum.validate().is_ok()); - - // `sum by(job)(rate(x[5m])) + 1`: the aggregate is complete, and the scalar side is - // broadcast, so `matching` is not consulted for it. - let plus_one = NativeNode { - expr: NativeExpr::Binary { - left: Box::new(sum.clone()), - right: Box::new(scalar_on(1.0, Arc::clone(&statement_grid))), - matching: add(), - }, - output: evaluated(Arc::new([]), statement_grid), - }; - assert!(plus_one.validate().is_ok()); -} - -/// A scalar node's output is the scalar type, which is what keeps a broadcast from turning into -/// label matching. -#[test] -fn a_scalar_node_is_valid() { - let node = scalar_on(1.0, grid(0, 60_000, 4)); - assert!(node.validate().is_ok()); -} - -/// A scalar node declared as a vector would let a broadcast be planned as a match. #[test] fn a_scalar_node_must_produce_a_scalar() { let node = NativeNode { @@ -2203,7 +1886,6 @@ fn a_scalar_node_must_produce_a_scalar() { ); } -/// An input whose declared output is not the binding it was bound to cannot be trusted. #[test] fn an_input_must_report_the_binding_it_was_bound_to() { let node = NativeNode { @@ -2221,7 +1903,6 @@ fn an_input_must_report_the_binding_it_was_bound_to() { assert!(error.to_string().contains("not the binding"), "{error}"); } -/// An exchange boundary binds state, and the node has to report that same state. #[test] fn an_input_can_bind_aggregate_state() { let state = partial_aggregate(window_over(input(), None)); @@ -2235,7 +1916,6 @@ fn an_input_can_bind_aggregate_state() { }; assert!(bound.validate().is_ok()); - // A `Final` aggregate can then consume it, which is the shape of a distributed aggregate. assert!(final_aggregate(bound).validate().is_ok()); // Equivalent independent allocations are accepted; field, order, grid, and group changes remain invalid. @@ -2347,8 +2027,6 @@ fn an_input_can_bind_aggregate_state() { ); } -/// A vector operation reads the values at each grid point, so raw samples, which have no shared points, -/// are not something it can consume. #[test] fn a_vector_operation_cannot_consume_raw_samples() { let node = NativeNode { @@ -2362,12 +2040,7 @@ fn a_vector_operation_cannot_consume_raw_samples() { assert!(error.to_string().contains("an evaluated vector"), "{error}"); } -/// A root that reports samples while its expression is a constant breaks its own contract. -/// -/// The tree is constructed directly here — a child module of `native::plan` may — because the node -/// is one the public constructors decline: a constant does not produce samples, and a zero-input -/// tree has no scan that would refuse it later. Every public constructor therefore stays a checked -/// one. +/// Built directly, because every public constructor declines this node. #[test] fn a_scalar_root_claiming_samples_is_refused() { let statement_grid = grid(0, 60_000, 4); @@ -2399,7 +2072,6 @@ fn a_scalar_root_claiming_samples_is_refused() { ); } -/// A samples root without an input is refused by FusedSeries. #[test] fn a_samples_root_without_an_input_is_refused() { let tree = NativeTree::try_new(input()).unwrap(); @@ -2420,9 +2092,6 @@ fn a_samples_root_without_an_input_is_refused() { assert!(error.to_string().contains("source indexes"), "{error}"); } -/// `info` reads its info side's values as sample times, so it accepts only the instant selection -/// that reports them: one that reports the samples themselves would compare every info series as -/// equally new. #[test] fn info_reads_the_sample_times_of_one_field() { let out = grid(0, 60_000, 4); @@ -2504,13 +2173,9 @@ fn named_scan_tags() -> Vec> { vec![vec!["host".to_string(), "__name__".to_string()]] } -/// A rewrite that writes a label the input does not carry cannot make two series equal, which is -/// what lets a query like `label_replace(x, "dst", "$1", "host", "(.*)")` keep every partition. #[test] fn a_fresh_destination_does_not_alias() { let out = grid(0, 60_000, 4); - // A window that keeps the metric name hands its input's identity on, so the rewrite is the only - // node that could make two series equal. let inner = keeping_window_fields(input_with_fields(1), Arc::clone(&out), 1); assert!(!duplicates_canonical_labels( &rewritten(inner, "dst", "host"), @@ -2519,8 +2184,6 @@ fn a_fresh_destination_does_not_alias() { )); } -/// A rewrite that writes a label the input carries can fold two series into one, which is what a -/// canonical merge has to collect. #[test] fn a_rewrite_of_an_existing_label_aliases() { let out = grid(0, 60_000, 4); @@ -2532,9 +2195,7 @@ fn a_rewrite_of_an_existing_label_aliases() { )); } -/// A scan bound to one metric names every series it hands over, so `__name__` is one of its runtime -/// labels even though it is not a tag column. A rewrite of that name writes an existing label and -/// can fold two metrics whose ordinary labels are equal into one identity. +/// `__name__` is a runtime label of a named scan even though it is not a tag column. #[test] fn a_rewrite_of_the_metric_name_aliases_a_named_source() { let out = grid(0, 60_000, 4); @@ -2545,7 +2206,6 @@ fn a_rewrite_of_the_metric_name_aliases_a_named_source() { &named, &[] )); - // The delete-only form can fold the same two identities, so it is collected too. let inner = input_on(Arc::clone(&out)); assert!(duplicates_canonical_labels( &replaced(inner, "__name__", "", "__name__"), @@ -2554,12 +2214,8 @@ fn a_rewrite_of_the_metric_name_aliases_a_named_source() { )); } -/// A name write is collected even above a kernel that dropped the name: the scan below `abs`, a -/// `timestamp` or a range function can still hold several metrics whose ordinary labels are equal, -/// so writing one name puts those identities under one label set. A fresh ordinary destination over -/// a kernel that keeps the name is still uncollected, because no scan can carry an ordinary label it -/// does not declare -- while over a name-dropping kernel the answer is `true` for the kernel's own -/// sake, which is what [`dropping_the_metric_name_is_a_new_source`] pins. +/// The scan below a name-dropping kernel may still hold several metrics whose ordinary labels are +/// equal. #[test] fn a_name_rewrite_above_a_dropped_name_is_collected() { let out = grid(0, 60_000, 4); @@ -2574,7 +2230,6 @@ fn a_name_rewrite_above_a_dropped_name_is_collected() { for (name, dropped) in [ ("abs", map_over(selected())), ("timestamp", timestamp(selected())), - // `rate` computes a value of its own, so it drops the name too. ( "rate", window_fields(input_with_fields(1), Arc::clone(&out), 1), @@ -2589,8 +2244,7 @@ fn a_name_rewrite_above_a_dropped_name_is_collected() { "{name}: a name write may alias metrics the kernel left indistinguishable" ); } - // The fresh destination is judged against a kernel that keeps the name, which is the only shape - // where the rewrite alone decides the answer. + // Over a name-keeping kernel the rewrite alone decides the answer. let keeping = keeping_window_fields(input_with_fields(1), Arc::clone(&out), 1); assert!( !duplicates_canonical_labels(&rewritten(keeping, "dst", "host"), &named, &[]), @@ -2598,13 +2252,10 @@ fn a_name_rewrite_above_a_dropped_name_is_collected() { ); } -/// The label walk keeps a name a rewrite writes and drops it wherever the kernel does, so the -/// query's output columns never claim a name the runtime does not report. #[test] fn a_written_name_survives_only_where_the_tree_keeps_it() { let out = grid(0, 60_000, 4); let selected = || input_on(Arc::clone(&out)); - // A scan bound to one metric: its runtime labels carry the name, its columns do not. let runtime = vec![vec!["host".to_string(), "__name__".to_string()]]; let columns = vec![vec!["host".to_string()]]; let written = || rewritten(selected(), "__name__", "__name__"); @@ -2616,18 +2267,15 @@ fn a_written_name_survives_only_where_the_tree_keeps_it() { Some(vec!["host".to_string(), "__name__".to_string()]), fused_output_tags(&written(), &runtime) ); - // A column set gains the name because the rewrite writes a value into it. assert_eq!( Some(vec!["host".to_string(), "__name__".to_string()]), fused_output_tags(&written(), &columns) ); - // A delete-only rewrite over a scan that publishes no name column publishes none. assert_eq!( Some(vec!["host".to_string()]), fused_output_tags(&replaced(selected(), "__name__", "", "__name__"), &columns) ); - // The delete-only rewrite over a set that carries the name keeps it: whether a series keeps its - // value depends on the regex, so the label is still part of the set. + // Whether a delete-only rewrite removes the name depends on the regex, so the label stays. assert_eq!( Some(vec!["host".to_string(), "__name__".to_string()]), fused_output_tags(&replaced(selected(), "__name__", "", "__name__"), &runtime) @@ -2659,9 +2307,8 @@ fn a_written_name_survives_only_where_the_tree_keeps_it() { } } -/// `group_left(__name__)` copies the one side's name onto an arithmetic result: the kernel drops the -/// metadata before it copies an included label, so the name the one side carries is what the result -/// reports, while a one side without the name removes it from the result. +/// `result_metric` drops the name before it copies include labels, so `group_left(__name__)` takes +/// the one side's name. #[test] fn an_included_metric_name_survives_an_arithmetic_match() { let out = grid(0, 60_000, 4); @@ -2700,13 +2347,11 @@ fn an_included_metric_name_survives_an_arithmetic_match() { ]; let tagged = |source_index: usize| input(source_index); - // The one side (right) carries a rewritten name, so the include puts it on the result. let renamed = replaced(tagged(1), "__name__", "renamed", "__name__"); assert_eq!( Some(vec!["host".to_string(), "__name__".to_string()]), fused_output_tags(&binary(tagged(0), renamed, group_left()), &source_tags) ); - // A one side without the name cannot give the include one, so the result drops it. let unnamed_tags = vec![ vec!["host".to_string(), "__name__".to_string()], vec!["host".to_string()], @@ -2715,7 +2360,6 @@ fn an_included_metric_name_survives_an_arithmetic_match() { Some(vec!["host".to_string()]), fused_output_tags(&binary(tagged(0), tagged(1), group_left()), &unnamed_tags) ); - // `group_right` trades the sides: the include is read from the left (one) side there. let group_right = || BinaryMatching { op: BinaryOp::Mul, return_bool: false, @@ -2728,8 +2372,6 @@ fn an_included_metric_name_survives_an_arithmetic_match() { Some(vec!["host".to_string(), "__name__".to_string()]), fused_output_tags(&binary(renamed, tagged(1), group_right()), &source_tags) ); - // A `bool` comparison drops the name like arithmetic does, and the include still copies the one - // side's name afterwards: the drop happens before the include. let bool_comparison = || BinaryMatching { op: BinaryOp::Eq, return_bool: true, @@ -2743,9 +2385,7 @@ fn an_included_metric_name_survives_an_arithmetic_match() { fused_output_tags(&binary(tagged(0), renamed, bool_comparison()), &source_tags) ); - // A filtering comparison keeps the name of the side it reports, but an included name the one - // side does not carry still leaves the set: `result_metric` removes an included label it cannot - // copy, and the base name is not exempt. + // `result_metric` removes an include label the one side lacks, the base name included. let filtering = || BinaryMatching { op: BinaryOp::Eq, return_bool: false, @@ -2759,8 +2399,6 @@ fn an_included_metric_name_survives_an_arithmetic_match() { ); } -/// A source the caller says nothing about proves nothing: the pass has to assume the destination -/// was one of its labels, because two series sharing one is exactly the wrong answer to ship. #[test] fn an_unknown_source_may_alias() { let out = grid(0, 60_000, 4); @@ -2772,39 +2410,23 @@ fn an_unknown_source_may_alias() { )); } -/// Dropping the metric name is a source of duplicates in its own right, and a window that keeps it -/// is not. -/// -/// The name is part of the identity a merge groups by, so a kernel that computes a value of its own -/// and reports the name dropped can leave two series under one label set - but only when something -/// below it could be told apart by that name. -/// -/// A scan bound to one metric names every series it hands over, so no name of its tells two of them -/// apart, and the labels are the whole proof. A scan that may hand over several metrics is collected, -/// and so is one carrying `__type__` or `__unit__` among its tags, because only those labels told -/// the two series apart. The scan's key columns are not asked: a key column that holds `NULL` in one -/// series and `''` in another decodes to an absent and to an empty label, both of which the drop -/// normalizes into one, and that pair is deliberately left outside the proof - see -/// [`metadata_labels_keep_series_apart`]. +/// A name drop is proved only over a single-metric source without `__type__`/`__unit__` tags. The +/// `NULL`/`''` key pair is deliberately outside the proof. #[test] fn dropping_the_metric_name_is_a_new_source() { let out = grid(0, 60_000, 4); let single = [Some(Arc::::from("some_metric"))]; let dropped = window_fields(input_with_fields(1), Arc::clone(&out), 1); - // A caller that says nothing about the metric is not proved. assert!(duplicates_canonical_labels( &dropped, &named_scan_tags(), &[] )); - // The scan reads one metric, so the name it drops told none of its series apart. assert!(!duplicates_canonical_labels( &dropped, &named_scan_tags(), &single )); - // A source that may hand over several metrics is not proved, and neither is one that carries a - // metadata label of its own: both can hold two series that only that label told apart. assert!(duplicates_canonical_labels( &dropped, &named_scan_tags(), @@ -2818,28 +2440,17 @@ fn dropping_the_metric_name_is_a_new_source() { "{metadata}" ); } - // A key column that can hold `NULL` in one series and `''` in another is *not* part of that - // proof: the empty value leaves with the name, but the pair is a property of a nullable tag - // column rather than of the labels, and every tag column of a metric-engine table is nullable. - // Nothing is collected for it, above the window or above a map that drops the name again. - assert!(!duplicates_canonical_labels( - &dropped, - &named_scan_tags(), - &single - )); assert!(!duplicates_canonical_labels( &map_over(input_on(Arc::clone(&out))), &named_scan_tags(), &single )); - // A window that keeps the name passes its input's answer on instead. let keeping = keeping_window_fields(input_with_fields(1), Arc::clone(&out), 1); assert!(!duplicates_canonical_labels( &keeping, &named_scan_tags(), &[] )); - // `timestamp` reports a sample's own time under the name dropped, in both of its forms. let stamps = |inner: NativeNode| NativeNode { expr: NativeExpr::Timestamp { input: Box::new(inner), @@ -2861,7 +2472,6 @@ fn dropping_the_metric_name_is_a_new_source() { &named_scan_tags(), &single )); - // A sample-preserving selection keeps the name it read, so it is no source of its own. assert!(!duplicates_canonical_labels( &instant_sample(input_on(Arc::clone(&out)), Arc::clone(&out)), &named_scan_tags(), @@ -2869,22 +2479,13 @@ fn dropping_the_metric_name_is_a_new_source() { )); } -/// The plan-time counter's question: which statements drop the metadata labels over series whose -/// labels prove them apart and whose keys do not. -/// -/// The labels are what the walk reads; the key columns are stated by the caller, and a drop is -/// counted exactly when the labels prove it, nothing below it has collected already, and the scan's -/// key columns cannot tell the pair apart - a key column holding `NULL` in one series and `''` in -/// another, which is a fact about the physical table. Nothing is collected for that pair, so the -/// count is what keeps the statements it leaves unproved observable. This is the tree half of that -/// count: the planner pairs it with the fact it read from the resolved table. +/// Counted when the labels prove the drop, no merge sits below it, and `keys_survive` is `false`. #[test] fn a_drop_the_labels_prove_is_counted_only_when_its_keys_do_not() { let out = grid(0, 60_000, 4); let single = [Some(Arc::::from("some_metric"))]; let named = named_scan_tags(); - // `rate(x[5m])` and `abs(abs(x))` over one metric: the drop removes a name every series shares, - // and nothing below either node is collected, so the key columns are what decides the answer. + // `rate(x[5m])` and `abs(abs(x))` over one metric. for keys in [false, true] { let counted = !keys; assert_eq!( @@ -2909,15 +2510,12 @@ fn a_drop_the_labels_prove_is_counted_only_when_its_keys_do_not() { "`abs(abs(x))` with keys_survive = {keys}" ); } - // A source that may hand over several metrics is collected by the labels, so nothing is left to - // the key columns. assert!(!leaves_a_drop_to_the_storage_keys( &NativeTree::try_new(window_fields(input_with_fields(1), Arc::clone(&out), 1)).unwrap(), &named, &[None], false, )); - // A window that keeps the name drops nothing. assert!(!leaves_a_drop_to_the_storage_keys( &NativeTree::try_new(keeping_window_fields( input_with_fields(1), @@ -2929,8 +2527,6 @@ fn a_drop_the_labels_prove_is_counted_only_when_its_keys_do_not() { &single, false, )); - // A merge below the drop hands over one series per canonical label set, which is unique even - // where the grouping treats an empty label value as no label, so the key columns decide nothing. assert!(!leaves_a_drop_to_the_storage_keys( &NativeTree::try_new(window_on( merge_over(input_on(Arc::clone(&out))), @@ -2944,12 +2540,11 @@ fn a_drop_the_labels_prove_is_counted_only_when_its_keys_do_not() { )); } -/// A rewrite can alias distinct outputs of a whole-vector operation, even when they were unique -/// before the rewrite. Grouped topk(1) and an aggregate can each produce more than one series. +/// Grouped `topk(1)` and an aggregate can each produce more than one series, which a rewrite above +/// them can alias. #[test] fn a_rewrite_after_ranking_or_grouping_may_alias() { let out = grid(0, 60_000, 4); - // A name-keeping window, so the ranking below is the only node whose answer is in question. let selected = || keeping_window_fields(input_with_fields(1), Arc::clone(&out), 1); let vector = |op| NativeNode { expr: NativeExpr::Vector { @@ -3016,9 +2611,6 @@ fn a_rewrite_after_ranking_or_grouping_may_alias() { } } -/// `count_values` reports the grouping applied to the labels its input carries, plus the label it -/// writes. What it does not report is the input's own set: a `by` narrows it, a `without` narrows -/// it the other way, and the destination is a column no scan has. #[test] fn count_values_reports_its_grouping_and_the_label_it_writes() { let out = grid(0, 60_000, 4); @@ -3042,7 +2634,6 @@ fn count_values_reports_its_grouping_and_the_label_it_writes() { ) }; - // `by (zone)` keeps one of the input's labels and adds the one the node writes. assert_eq!( tags(&["zone", "value"]), fused_output_tags( @@ -3050,7 +2641,6 @@ fn count_values_reports_its_grouping_and_the_label_it_writes() { &source_tags ) ); - // `without (host)` keeps the rest, and the destination with it. assert_eq!( tags(&["zone", "value"]), fused_output_tags( @@ -3058,7 +2648,6 @@ fn count_values_reports_its_grouping_and_the_label_it_writes() { &source_tags ) ); - // A `without` naming the destination removes the label the node just wrote. assert_eq!( tags(&["zone"]), fused_output_tags( @@ -3066,8 +2655,6 @@ fn count_values_reports_its_grouping_and_the_label_it_writes() { &source_tags ) ); - // A destination naming the metric name writes the name, which is the one label the node's - // result carries when its grouping names nothing else. assert_eq!( tags(&["__name__"]), fused_output_tags( @@ -3075,51 +2662,12 @@ fn count_values_reports_its_grouping_and_the_label_it_writes() { &source_tags ) ); - // An empty destination cannot be a label, so the walk declines rather than name a column. assert_eq!( None, fused_output_tags(&counted("", Grouping::By(Arc::new([]))), &source_tags) ); } -/// A consumer that files its rows by the label set a sample ends under answers one series per set, -/// so a rewrite beneath it is not something above it has to collect again. -#[test] -fn a_whole_vector_consumer_answers_one_series_per_set() { - let out = grid(0, 60_000, 4); - let aliasing = || { - rewritten( - window_fields(input_with_fields(1), Arc::clone(&out), 1), - "host", - "host", - ) - }; - for op in [ - BoundVectorOp::TopK { - k: 1.0, - top: true, - group: Grouping::By(Arc::new([])), - }, - BoundVectorOp::Absent { - labels: datatypes::series::SeriesLabels::try_new(None, Vec::new()).unwrap(), - }, - BoundVectorOp::CountValues { - label: Arc::from("v"), - group: Grouping::By(Arc::new([])), - }, - ] { - let node = NativeNode { - expr: NativeExpr::Vector { - input: Box::new(aliasing()), - op, - }, - output: evaluated(fields(1), Arc::clone(&out)), - }; - assert!(node.validate().is_ok()); - } -} - -/// The merge is the collection, so a second pass over a collected node finds nothing to collect. #[test] fn a_merge_answers_one_series_per_set() { let out = grid(0, 60_000, 4); @@ -3135,11 +2683,8 @@ fn a_merge_answers_one_series_per_set() { )); } -/// A window answers for the labels it keeps. A function that keeps the metric name hands over one -/// series per label set once its child answers either `Some(true)` (already one per set) or -/// `Some(false)` (fragments the window's `MergeInput` collects); only a boundary child (`None`) -/// leaves the answer aliasing. A function that drops the metric name can always alias, whatever -/// the child answered. +/// A name-keeping window answers `Some(true)` unless its child is a boundary; a name-dropping window +/// answers whether the labels prove the drop. #[test] fn a_window_unifies_its_own_contributions() { let out = grid(0, 60_000, 4); @@ -3191,9 +2736,7 @@ fn a_window_unifies_its_own_contributions() { boundary leaves it aliasing" ); } - // A function that drops the metadata labels can give two series one label set, so the window - // reports it whatever its child said - and a caller that cannot say which metric the child reads - // has no proof to offer on the child's behalf. + // Without source facts a name-dropping window has no proof, whatever its child said. for child in [collected(), fragments()] { assert_eq!( Some(false), @@ -3201,16 +2744,11 @@ fn a_window_unifies_its_own_contributions() { "a name-dropping window over an unproved source may alias" ); } - // A boundary is the one child the proof says nothing about: the window folds the pieces of one - // series one at a time, so what it emits aliases them whatever the labels say. assert_eq!( Some(false), unifies_its_own_contributions(&window_of(boundary(), RangeFunction::Rate), &[], &[]), "a boundary leaves the window's own answer aliasing" ); - // The proof is the one the canonical pass reads: a child whose labels lost the name, over a - // source bound to a single metric without a metadata tag of its own, keeps the name-dropping - // window from reporting fragments. let named = [vec!["host".to_string(), "__name__".to_string()]]; let single = [Some(Arc::::from("some_metric"))]; let dropped = map_over(input_on(Arc::clone(&out))); @@ -3234,8 +2772,6 @@ fn a_window_unifies_its_own_contributions() { ); let mut typed = named.clone(); typed[0].push("__type__".to_string()); - // A metadata tag of the source is one the drop removes, and two series that differed only in it - // end under one label set - so a window reading the tagged scan directly is not proved. assert_eq!( Some(false), unifies_its_own_contributions( @@ -3245,8 +2781,7 @@ fn a_window_unifies_its_own_contributions() { ), "a metadata tag the window drops is not proved constant" ); - // A map below the window drops that tag first, and its own drop is what the pass collects: what - // the window reads has already lost it, so the window above the map is proved. + // The map below already dropped `__type__`, so the window's own drop is proved. assert_eq!( Some(true), unifies_its_own_contributions(&window_of(dropped, RangeFunction::Rate), &typed, &single), @@ -3254,8 +2789,6 @@ fn a_window_unifies_its_own_contributions() { ); } -/// `info` reads its info side through a canonical merge: the merge only collects the pieces of one -/// label set, so the sample times it hands over are the ones the selection produced. #[test] fn info_sees_through_a_canonical_merge() { let out = grid(0, 60_000, 4); @@ -3288,8 +2821,6 @@ fn info_sees_through_a_canonical_merge() { .expect("a merge above the info selection keeps its meaning"); } -/// The same tree without the merge is the tree the check was written for, so the check is not -/// simply accepting every info side. #[test] fn info_still_refuses_an_evaluated_value_vector() { let out = grid(0, 60_000, 4); @@ -3341,7 +2872,6 @@ fn native_tree_deeper_than_64_round_trips_and_validates() { NativeTree { root: node } } - // This tests a representative depth, not a guarantee about the available worker stack. let deep = nested_maps(80); let checked = NativeTree::try_new(deep.root.clone()).unwrap(); let bytes = postcard::to_stdvec(&checked).unwrap(); @@ -3349,7 +2879,6 @@ fn native_tree_deeper_than_64_round_trips_and_validates() { assert_eq!(checked, decoded); decoded.root().validate().unwrap(); - // Decoding must still validate the tree's structural contract. let mut invalid = nested_maps(80); invalid.root.output = NativeType::Scalar(grid(0, 60_000, 1)); assert!(NativeTree::try_new(invalid.root.clone()).is_err()); @@ -3357,18 +2886,13 @@ fn native_tree_deeper_than_64_round_trips_and_validates() { assert!(postcard::from_bytes::(&bytes).is_err()); } -/// The index postcard writes for a [`NativeExpr`] variant is a wire contract, not an implementation -/// detail: postcard encodes a variant as its index, and a version 3 `FusedSeries` envelope carries -/// the whole tree rather than a prefix of it, so a variant inserted anywhere but the end renames -/// every variant after it for a reader of an earlier build. -/// -/// The numbers here are the ones already written to the wire. New variants are appended after -/// `Info`; every variant above them keeps the index below. +/// Postcard encodes a variant by its index and a `FusedSeries` carries the whole tree, so these +/// indices must not change. New variants are appended at the end. #[test] fn native_expr_variant_indices_are_a_wire_contract() { use crate::histogram_eval::HistogramFunction; - // A node carries its expression first, so this is also the tag of any node or tree holding it. + // A node serializes its expression first, so this byte is also the node's and the tree's. fn tag(expr: &NativeExpr) -> u8 { let encoded = postcard::to_stdvec(expr).expect("a native expression encodes"); *encoded.first().expect("a variant tag is the first byte") @@ -3423,7 +2947,6 @@ fn native_expr_variant_indices_are_a_wire_contract() { 10, "Aggregate", ), - // The dynamic forms are the last four, which is what keeps every index above them. ( NativeExpr::ScalarOf { input: Box::new(vector()), @@ -3494,15 +3017,6 @@ fn native_tree_postcard_float_fidelity_round_trip() { } } -#[test] -fn native_tree_postcard_rejects_trailing_bytes() { - let tree = NativeTree::try_new(input()).unwrap(); - let mut bytes = postcard::to_stdvec(&tree).unwrap(); - bytes.push(0); - let (_, remainder) = postcard::take_from_bytes::(&bytes).unwrap(); - assert!(!remainder.is_empty()); -} - #[test] fn native_tree_non_prefix_shapes_round_trip() { let grid = grid(0, 60_000, 4); @@ -3557,9 +3071,7 @@ fn independently_allocated_binding_mismatch_is_rejected() { assert!(mismatch.validate().is_err()); } -/// Asserts the admission verdict for `node`, and that the runtime's own construction answers the -/// same: a predicate that stopped agreeing with it would either admit a tree the executor cannot -/// build, or decline a shape the executor can run. +/// Asserts the admission verdict for `node`, and that `NativeExecutionState::try_new` agrees. fn assert_admission(node: NativeNode, admitted: bool, shape: &str) { use datafusion::execution::memory_pool::UnboundedMemoryPool; @@ -3576,7 +3088,7 @@ fn assert_admission(node: NativeNode, admitted: bool, shape: &str) { ); } -/// `outer` over `inner`, with `function` and `modifier` bound as written. +/// A window over `inner` with `function` and `modifier` as written. fn window_with( inner: NativeNode, input_grid: Option>, @@ -3603,13 +3115,11 @@ fn window_with( } } -/// Every shape the runtime refuses is refused here, and each one is a shape a tree can hold. #[test] fn native_tree_supported_declines_the_shapes_the_runtime_refuses() { use crate::select::SortOrder; let out = grid(0, 60_000, 4); - // A leaf whose chunks of different series may interleave: no consumer of a leaf orders them. let interleaved = NativeNode { expr: NativeExpr::Input(BoundInput { output: evaluated(Arc::new([]), Arc::clone(&out)), @@ -3825,18 +3335,12 @@ fn native_tree_supported_declines_the_shapes_the_runtime_refuses() { } } -/// A refusal below the root is still a refusal: admission reads the whole tree, not its root. -/// -/// Each case below holds an aggregate grouping by a value field — a shape the runtime refuses, at -/// any depth — under a node whose own shape the runtime does build. A predicate that stopped -/// recursing into one of these variants' inputs, or into a parameterised node's parameters, would -/// admit a tree the runtime then refuses, and a refusal raised while the runtime is built cannot -/// fall back: the statement loses the plan it had instead of keeping it. +/// Each case nests an aggregate grouped by a value field under a node the runtime builds, so +/// admission must recurse into every input and parameter. #[test] fn native_tree_supported_declines_a_refused_shape_nested_under_another() { let out = grid(0, 60_000, 4); let one_field = || window_fields(input_with_fields(1), Arc::clone(&out), 1); - // The declined shape every case nests, one level down from a node the runtime builds. let refused = || { aggregate_with( one_field(), @@ -3846,8 +3350,6 @@ fn native_tree_supported_declines_a_refused_shape_nested_under_another() { AggregateStage::Complete, ) }; - // The info side `info` reads, which `validate` requires to be the times of an instant - // selection; only the base side of the node carries the refused shape. let info_times = || { merge_over(NativeNode { expr: NativeExpr::Instant { @@ -3935,19 +3437,10 @@ fn native_tree_supported_declines_a_refused_shape_nested_under_another() { } } -/// A window whose timestamps do not fit is refused by the runtime, so admission refuses it too. -/// -/// These two are not shapes and every term of their arithmetic fits: an `@` anchor is folded into -/// an offset from the grid's first point, which is a difference of two timestamps, and -/// `predict_linear` adds that offset to the first and last point of the grid. A tree carrying -/// either is still one the runtime cannot build, and admitting it is what made a query the -/// existing plan answered fail while its runtime was built instead of keeping that plan, because a -/// refusal raised during physical planning cannot fall back. +/// Not shapes: the `@` fold offset or the `predict_linear` instants overflow `i64`. #[test] fn native_tree_supported_declines_the_instants_that_overflow() { - // The first point of a statement reaching far into the future, a step apart: this is the grid - // `predict_linear(some_metric[1m] @ 0, 60)` is planned over, whose anchor makes the fold offset - // the grid's own start and whose horizon then adds the two. + // `predict_linear(some_metric[1m] @ 0, 60)` over a grid starting at 5e18 ms. let far = grid(5_000_000_000_000_000_000, 5_000, 3); let window = |function: RangeFunction, anchor_ms: Option, out: Arc| NativeNode { expr: NativeExpr::Window { @@ -3966,8 +3459,7 @@ fn native_tree_supported_declines_the_instants_that_overflow() { }, output: evaluated(Arc::new([]), out), }; - // The fold offset is 5e18 ms and `predict_linear` adds it to a point of the grid: 1e19 ms is - // what an `i64` cannot hold, so the kernel would read an instant that does not exist. + // Fold offset 5e18 ms plus a grid point of 5e18 ms overflows `i64`. let horizon = window( RangeFunction::PredictLinear(60.0), Some(0), @@ -3978,15 +3470,13 @@ fn native_tree_supported_declines_the_instants_that_overflow() { false, "a predict_linear horizon over the grid that overflows", ); - // The same overflow without `predict_linear`: `@ -5e18` over that grid is a fold offset of - // 1e19 ms on its own, so even `rate` reads a window the runtime cannot place. + // `@ -5e18` over that grid is a 1e19 ms fold offset on its own. let anchored = window( RangeFunction::Rate, Some(-5_000_000_000_000_000_000), Arc::clone(&far), ); assert_admission(anchored, false, "an `@` anchor whose fold offset overflows"); - // The same shapes over a grid near the epoch fit, so the check does not narrow the route. let fitting = window( RangeFunction::PredictLinear(60.0), Some(0), @@ -3995,7 +3485,6 @@ fn native_tree_supported_declines_the_instants_that_overflow() { assert_admission(fitting, true, "a predict_linear horizon near the epoch"); } -/// Every shape the runtime builds is admitted, so the predicate does not narrow the route. #[test] fn native_tree_supported_admits_the_shapes_the_runtime_builds() { use crate::select::SortOrder; @@ -4013,8 +3502,6 @@ fn native_tree_supported_admits_the_shapes_the_runtime_builds() { let cases = vec![ ("an evaluated input leaf", input_on(Arc::clone(&out))), ( - // A quantile is one Complete fold: it keeps no state, so there is nothing to merge and - // nothing the runtime refuses. "the quantile aggregate", aggregate_with( one_field(), @@ -4225,11 +3712,6 @@ fn inner_field_count(inner: &NativeNode) -> usize { .map_or(0, |schema| schema.fields.len()) } -/// The state an aggregate binds follows the kind its direct input carries. -/// -/// The two families differ in both the kind and the components, so a node bound over one kind can -/// never be merged as a node bound over the other: the frame's kind is what says which merge rules -/// apply, and its component list is what the merge reads. #[test] fn aggregate_state_binding_follows_the_input_kind() { for (kind, numeric, histogram) in [ @@ -4250,7 +3732,6 @@ fn aggregate_state_binding_follows_the_input_kind() { let (histogram_kind, histogram_components) = aggregate_state_binding(kind, FieldKind::Histogram).expect("a histogram state"); assert_eq!(histogram_kind, histogram, "{kind:?}"); - // The histogram layout is the kind's own canonical list, which is what a frame accepts. assert_eq!(histogram_components, histogram.components().to_vec()); assert_ne!( float_components, histogram_components, @@ -4265,8 +3746,7 @@ fn aggregate_state_binding_follows_the_input_kind() { "{kind:?} keeps the payload over a histogram input" ); } - // An aggregate that answers a float whatever it reads keeps its numeric state over a histogram - // input as well: a count is a count of samples, not of payloads. + // A count is a count of samples, so it keeps numeric state over histograms. for kind in [ AggregateKind::Count, AggregateKind::Min, @@ -4281,7 +3761,6 @@ fn aggregate_state_binding_follows_the_input_kind() { "{kind:?}" ); } - // A quantile has no mergeable state at all, whatever it reads. for field_kind in [FieldKind::Float, FieldKind::Histogram] { assert!( aggregate_state_binding(AggregateKind::Quantile { quantile: 0.5 }, field_kind) diff --git a/src/promql/src/native/segment.rs b/src/promql/src/native/segment.rs index e7d25b0a09e..e77f4b881a3 100644 --- a/src/promql/src/native/segment.rs +++ b/src/promql/src/native/segment.rs @@ -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]) -> Option>; -/// 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; -/// 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], &str, FieldKind) -> Option; -/// 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) -> Vec { 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) -> Vec 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) -> Arc { 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, @@ -589,19 +472,11 @@ pub fn canonical_boundary_stages( .map(|field| field.name.to_string()) .collect::>(); 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::>>()?; 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, @@ -958,31 +797,13 @@ pub fn segment_tree( field_names: FieldNames, root_schema: RootSchema, ) -> Option { - // 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::>(); 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]| -> (Option>, 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) -> 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" diff --git a/src/promql/src/native/split.rs b/src/promql/src/native/split.rs index 0444c064882..963de537b7a 100644 --- a/src/promql/src/native/split.rs +++ b/src/promql/src/native/split.rs @@ -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, /// 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> { tree.root() .inputs() @@ -380,13 +316,8 @@ pub(crate) fn prefix_fields(tree: &NativeTree) -> DfResult> { .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> { 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 { let NativeNode { expr, output } = node; let rejected = || { @@ -573,13 +480,9 @@ fn enter_suffix(node: NativeNode, merged: &NativeNode) -> DfResult { }; 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 { 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 { 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, } } diff --git a/src/promql/src/native/state.rs b/src/promql/src/native/state.rs index 6ebb5c214dd..ee1c228a17b 100644 --- a/src/promql/src/native/state.rs +++ b/src/promql/src/native/state.rs @@ -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, state_schema: Arc, - /// 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, }, 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, @@ -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 { 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::>>()); 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 diff --git a/src/promql/src/range_array.rs b/src/promql/src/range_array.rs index dccc199181c..7b01ea99247 100644 --- a/src/promql/src/range_array.rs +++ b/src/promql/src/range_array.rs @@ -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]) } diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index e0223b4ac58..7fbeaccae60 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -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, &mut Vec, /// 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, - /// 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, /// 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, - /// 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`: 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]) -> 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 { &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::>(); @@ -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, 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> { 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> { 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> { 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 { - // 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 { 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 { }) } -/// 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] { diff --git a/src/promql/src/range_eval/function.rs b/src/promql/src/range_eval/function.rs index ce54432ed28..a7825760ba3 100644 --- a/src/promql/src/range_eval/function.rs +++ b/src/promql/src/range_eval/function.rs @@ -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 { match self { Self::Rate => Some(Box::new(extrapolated_rate_batch::)), @@ -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( } /// 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 { 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( batch: &FloatWindows<'_>, out: &mut Vec>, @@ -470,12 +445,9 @@ pub(crate) fn extrapolated_rate_batch 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, diff --git a/src/promql/src/range_eval/histogram.rs b/src/promql/src/range_eval/histogram.rs index 140840bed20..5c8ef202134 100644 --- a/src/promql/src/range_eval/histogram.rs +++ b/src/promql/src/range_eval/histogram.rs @@ -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( (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) { diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index 562b10b0a75..6fa32e81a09 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -30,8 +30,7 @@ use datatypes::series::histogram::{ }; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; use datatypes::series::samples::{ - DenseSamplesRef, FieldSpec, HistogramSamples, SampleRef, Samples, Series, SeriesFields, - SeriesSchema, + FieldSpec, HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema, }; use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis}; use datatypes::series::{Label, SeriesLabels}; @@ -105,7 +104,7 @@ fn probe(window: FloatWindow<'_>) -> Option { Some((hash >> 11) as f64) } -/// The resets of a window by scanning it, the way the kernels used to before the index. +/// The resets of a window by scanning it, independent of the evaluator's reset index. fn scanned_resets(values: &[f64]) -> Vec { (1..values.len()) .filter(|&index| values[index] < values[index - 1]) @@ -224,14 +223,6 @@ fn random_chunks(rng: &mut StdRng, rows: &[Row], fields: usize, host: u64) -> Ve chunks } -/// The absolute grid position `series` starts at. -fn grid_start(series: &Series) -> usize { - series - .time - .first_position() - .unwrap_or_else(|| panic!("expected a grid series, got {:?}", series.time)) -} - /// How many rows of `series` hold a value in any field. fn rows_with_a_value(series: &Series) -> usize { if series.time.grid().is_none() { @@ -284,17 +275,10 @@ fn evaluate_series(evaluator: &mut RangeEvaluator, series: &Series) -> Vec) -> Option { let metric = chunks .first() @@ -311,8 +295,6 @@ fn fold_chunks(chunks: &[EvaluatedChunk], schema: &Arc) -> Option< assert!(!closing, "a chunk follows the closing chunk"); closing = chunk.is_last; assert_eq!(chunk.series.metric, metric, "a chunk changed the series"); - // The chunk says which absolute positions it holds: a chunk of several runs must not be - // read as the envelope from its first to its last one. let mut first = None; let mut rows_run: Vec<(usize, usize)> = Vec::new(); for (position, row) in chunk.series.time.positions() { @@ -330,7 +312,6 @@ fn fold_chunks(chunks: &[EvaluatedChunk], schema: &Arc) -> Option< .unwrap_or(first); previous_end = last + 1; } - // One forward cursor per field, driven by the rows the chunk carries. let mut fields: Vec<_> = chunk .series .fields @@ -353,7 +334,6 @@ fn fold_chunks(chunks: &[EvaluatedChunk], schema: &Arc) -> Option< } }) .collect(); - // Positions only increase across chunks, so an overlap is an error here. if values.iter().any(|value| value.is_some()) { assert!( rows[position].is_none(), @@ -372,11 +352,8 @@ fn fold_chunks(chunks: &[EvaluatedChunk], schema: &Arc) -> Option< dense_series(&rows, schema.clone(), metric) } -/// Builds one series covering every row of `rows`, with a null where no chunk held a value. -/// -/// This is deliberately not the builder: the builder hands out one piece per run of valued -/// positions, and a value comparison wants a single dense series. Row counts must never be read -/// off this -- doing so would hide exactly the allocation this change removes. +/// Builds one dense series over `rows`, with a null where no chunk held a value. Unlike the +/// builder, it does not skip empty rows. fn dense_series( rows: &[Option>>], schema: Arc, @@ -858,18 +835,9 @@ fn assert_same_series(actual: Option<&Series>, expected: Option<&Series>, contex } } -/// `rate` and `increase` over random input, computed twice: by the batch kernel and by the -/// per-window path. -/// -/// Both evaluators are built by `try_new` and differ in nothing but the dispatch shape, and both -/// kernels reach `extrapolated_rate_of`, so the results have to be bit-identical. A difference -/// means the batch read a different set of samples, evaluated at a different time, or corrected a -/// different reset: a window bound that disagrees with the per-window path. -/// -/// The rows mix gaps, stale markers, counter resets and native histogram samples, the last so -/// that some grid points take the mixed-window fallback, where a pending batch has to flush -/// before the point is decided on the per-window path. The random chunk splits are what make -/// `advance` drop samples mid-series, so spans that outlived one would read shifted samples. +/// The batch and per-window paths must agree to the bit. Histograms in the input force the +/// mid-batch flush to the per-window path, and random chunk splits make `advance` drop samples +/// under pending spans. #[test] fn batch_counter_functions_match_the_per_window_path_on_random_input() { let mut batch_calls = 0; @@ -889,10 +857,8 @@ fn batch_counter_functions_match_the_per_window_path_on_random_input() { RangeEvaluator::try_new(&raw_schema(fields), grid.clone(), window, function).unwrap(); let mut per_window = RangeEvaluator::try_new(&raw_schema(fields), grid.clone(), window, function).unwrap(); - // The per-window path is the same evaluator without the batch kernel. `with_kernel`, - // which the other differential tests use, rejects native histogram samples, and these - // series carry some, so removing the batch form is the only switch that leaves the rest - // of the evaluation identical. + // The per-window path is the same evaluator with the batch kernel removed; `with_kernel` + // would reject the histogram samples. per_window.batch = None; // One evaluator serves several series, so state must not leak between them. for host in 0..3 { @@ -927,9 +893,6 @@ fn batch_counter_functions_match_the_per_window_path_on_random_input() { ); } -/// A chunk of entirely present float columns is appended in bulk, and that is the path the test -/// asserts: the per-sample loop produces the same output, so comparing values alone could not -/// tell whether the bulk path ran. #[test] fn an_ordinary_float_chunk_is_appended_in_bulk() { let rows: Vec = (0..5) @@ -949,9 +912,7 @@ fn an_ordinary_float_chunk_is_appended_in_bulk() { assert_eq!(evaluator.bulk_ingest_count(), 1); } -/// A field holding native histogram samples keeps its windows on the histogram path, where the -/// mixed-window rules decide the result. Letting such a chunk take the bulk path would drop the -/// histograms and read the floats alone, so the chunk has to fall back to the per-sample loop. +/// The bulk path reads floats only, so a chunk holding histograms must take the per-sample loop. #[test] fn a_chunk_with_histograms_is_not_appended_in_bulk() { let histogram = "0/0/0/4014000000000000/4014000000000000/1/0_1/4014000000000000///"; @@ -1040,9 +1001,6 @@ fn histogram_chunk(schema: &SeriesSchema, buckets: i32, ts: i64) -> RawSeriesChu } /// The single histogram sample of [`histogram_chunk`], read with `start_timestamp`. -/// -/// A sample carries the start timestamp a scan read it with, and it is payload rather than a -/// property of the value. fn histogram_chunk_from( schema: &SeriesSchema, buckets: i32, @@ -1092,12 +1050,8 @@ fn histogram_chunk_from( .unwrap() } -/// A counter histogram whose only sample in the window carries a start timestamp answers a rate. -/// -/// The existing planner allows this with a single sample: the start timestamp is a synthetic zero -/// inside the window, so the increase since it is the sample itself and the rate is that over the -/// range. A window too narrow to hold that start, or a sample without one, has nothing to measure -/// against and answers nothing - which is what the second half checks. +/// The start timestamp of a single sample is a synthetic zero inside the window, so the sample +/// itself is the increase. Without a start inside the window there is no answer. #[test] fn a_single_histogram_with_a_start_timestamp_answers_a_rate() { let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(60_000, 60_000, 1).unwrap()).unwrap()); @@ -1318,15 +1272,9 @@ fn synthetic_zero_still_extrapolates_to_the_window_end() { } } - // Two real samples, where the two spans finally differ: the sampled interval runs from the - // synthetic zero (3000 - 1000) while the average interval is measured between the real samples - // (3000 - 2000 over one step). That is 2000ms against 1000ms, so both ends fall past - // 1.1 * 1000ms and back to half of it, and the counter's zero point then takes the start to 0: - // the factor is (2000 + 0 + 500) / 2000 = 1.25. Measuring the average from the synthetic zero - // instead makes it 2000ms, leaves both ends inside 1.1 * 2000ms and answers 1.75 -- the swap - // this geometry fails on rather than passes by agreeing with itself. The zero adds its own - // sample back, so the count is (4 - 2) + 2 = 4, and Prometheus answers 4 * 1.25 = 5 for the - // increase and 4 * 1.25 / 4 = 1.25 for the rate. + // Sampled interval 2000ms from the synthetic zero, average interval 1000ms between the real + // samples: factor (2000 + 0 + 500) / 2000 = 1.25 (1.75 if the average were measured from the + // zero). The zero adds the first sample back: count (4 - 2) + 2 = 4, so increase 5, rate 1.25. for (function, expected) in [(RangeFunction::Increase, 5.0), (RangeFunction::Rate, 1.25)] { let mut evaluator = RangeEvaluator::try_new( &schema, @@ -1383,9 +1331,7 @@ fn single_histogram_start_timestamp_is_compared_on_shifted_axis() { ); let series = fold_chunks(&chunks, evaluator.output_schema()).unwrap(); match series.fields.as_slice()[0].cursor().at(0).unwrap() { - // A computed rate carries no start timestamp of its own, so the shifted comparison is - // pinned by the value alone: this sample answers only if its start timestamp was compared - // after the offset moved the window, and an empty position otherwise. + // Answers only if the start timestamp is compared on the shifted axis. SampleRef::Histogram(histogram) => { assert!((histogram.count - 2.0 / 3.0).abs() < 1e-12); assert_eq!(histogram.start_timestamp, None); @@ -1397,11 +1343,8 @@ fn single_histogram_start_timestamp_is_compared_on_shifted_axis() { } } -/// Two samples sharing a start timestamp never restarted between them, even when that start is -/// later than the earlier sample: Prometheus `isStartTimestampReset` answers false on -/// `prevStartTimestamp == currStartTimestamp` before any other check (promql/functions.go:761). -/// That only removes the start-timestamp evidence: a bucket drop under the same start is still a -/// reset, because `resets()` ORs in `DetectReset`. +/// Prometheus `isStartTimestampReset` answers false for equal start timestamps before any other +/// check; a bucket drop under the same start is still a reset (`DetectReset`). #[test] fn equal_histogram_start_timestamps_are_not_a_reset() { let schema = raw_schema(1); @@ -1435,12 +1378,8 @@ fn equal_histogram_start_timestamps_are_not_a_reset() { } } -/// A first histogram whose count is negative is not extrapolated towards zero. -/// -/// The zero point is `first.count / increase`, and a negative one would pull the sampled start -/// *backwards* (`duration_to_zero < duration_to_start`), handing the counter time it never spent -/// below zero. Prometheus guards it with `first.count >= 0`, which is what the histogram route now -/// reads too: without the guard this window answers 15 instead of 24. +/// Prometheus extrapolates towards zero only when `first.count >= 0`; without the guard this +/// window answers 15 instead of 24. #[test] fn a_negative_first_histogram_count_is_not_extrapolated_towards_zero() { let schema = raw_schema(1); @@ -1530,18 +1469,9 @@ fn describe_sample(sample: Option>) -> String { } } -/// A function that hands back the sample it selected hands back that sample's payload. -/// -/// `last_over_time` and `first_over_time` select a sample instead of computing one, so the -/// histogram that leaves them is the histogram that arrived, start timestamp included. The window -/// here holds two samples that differ in bucket count and in start timestamp, so the count and the -/// timestamp together say which one was selected rather than only that some timestamp survived: -/// the last sample for `last_over_time`, the first one for `first_over_time`. What this pins is -/// that the selection passes the stored payload through; it does not pin a Prometheus result, whose -/// histogram values carry no such field, and it does not claim that a native rate reads the field -/// afterwards. A histogram computed from samples carries none, as -/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one` -/// pins for the operations that build one. +/// `last_over_time` and `first_over_time` pass the selected sample through, start timestamp +/// included. The two samples differ in both count and start, so the pair identifies which one +/// was selected. #[test] fn a_selected_histogram_keeps_its_start_timestamp() { let schema = raw_schema(1); @@ -1553,9 +1483,6 @@ fn a_selected_histogram_keeps_its_start_timestamp() { histogram_chunk_from(&schema, 1, 0, Some(first_start), false), histogram_chunk_from(&schema, 2, 5_000, Some(last_start), true), ]; - // The histogram of every row the function hands out, read off the output's own views: the - // bucket count tells the selected sample apart from any other, the start timestamp is the - // payload this test is about. let selected = |function: RangeFunction| -> Vec<(usize, f64, Option)> { let mut evaluator = RangeEvaluator::try_new( &schema, @@ -1601,14 +1528,8 @@ fn a_selected_histogram_keeps_its_start_timestamp() { ); } -/// A histogram computed from a window carries no start timestamp, even when the window holds one. -/// -/// `sum_over_time` computes a histogram rather than selecting one, so the timestamp the sample was -/// read with is not part of the result -- the rule the histogram operations themselves follow, as -/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one` -/// pins. The fold clears the field while adding, so a window holding two histograms already loses -/// it; a window holding one must not depend on that, or whether a result carries the field would -/// say how many samples the window held rather than what the function did. +/// A computed histogram carries no start timestamp, even from a single-sample window, where the +/// fold performs no add that would clear it. #[test] fn a_computed_histogram_drops_its_start_timestamp() { let schema = raw_schema(1); @@ -1653,15 +1574,8 @@ fn a_computed_histogram_drops_its_start_timestamp() { ); } -/// A window retaining a native histogram is charged for the payload it owns, not only the slot. -/// -/// The histogram sample below stays ahead of the second grid point's window, so the evaluator keeps -/// it, and the two runs differ in nothing but the number of buckets on the positive side: 4 and -/// 4096. Those buckets are `(index, count)` pairs on the heap, which no `size_of` of the struct -/// shows -- about 64 KiB for the wider one. The property is that this payload dominates the -/// estimate, not that it is counted to the byte: the wider histogram alone has to be reported as at -/// least half the physical width of its buckets, and the narrow one has to stay far below that. A -/// figure counting slots alone would report one number for both. +/// A retained histogram is charged for its heap buckets, not only its slot: 4096 buckets must +/// show up in the estimate where 4 do not. #[test] fn a_retained_histogram_is_charged_for_its_buckets() { let retained = |buckets: i32| -> usize { @@ -1677,9 +1591,7 @@ fn a_retained_histogram_is_charged_for_its_buckets() { anchor_ms: None, modifier: None, }, - // A function that counts the histogram, so what the row holds is a float: the two - // figures then differ in the payload of the retained sample alone, not in what the row - // boxes beside it. + // Counts the histogram, so the row holds a float and only the retained payload differs. RangeFunction::CountOverTime, ) .unwrap(); @@ -1704,15 +1616,8 @@ fn a_retained_histogram_is_charged_for_its_buckets() { ); } -/// The payload a retained histogram is charged for is released with the sample. -/// -/// The histogram below is most of what the evaluator holds, and it stays inside the second grid -/// point's window: a push that only reaches the first point retains it. The chunk at 30 s is beyond -/// the window of every later point, so the evaluation that push triggers drops the histogram while -/// the series is still open. The estimate must come back down by its payload: one that charges at -/// admission and never releases it would keep reporting the history of every histogram the series -/// carried. The closing chunk then drains what is left and ends the series, so the estimate falls -/// back to the field and row buffers' capacity, with no series identity and no histogram payload. +/// A histogram's payload is released when a later window drops it while the series is still +/// open, and nothing of the series is charged after the close. #[test] fn an_evicted_histogram_releases_its_payload() { let schema = raw_schema(1); @@ -1764,11 +1669,7 @@ fn an_evicted_histogram_releases_its_payload() { ); } -/// A fixed-size window over a long series of histograms reports a fixed size. -/// -/// Each push adds one histogram and the next point's window drops the one before it, so the -/// payload charged at admission has to come back at eviction. A counter that only grew would make -/// the estimate follow the length of the series instead of the window over it. +/// A fixed window over a long series of histograms keeps a bounded estimate. #[test] fn a_fixed_window_over_histograms_keeps_the_estimate_bounded() { let peak_retained = |chunks: i64| -> usize { @@ -1802,13 +1703,8 @@ fn a_fixed_window_over_histograms_keeps_the_estimate_bounded() { ); } -/// A batch spanning more grid points than `EVALUATION_BATCH` flushes in the middle of one -/// evaluation, and each field's windows come from that field's own samples. -/// -/// Both properties are invisible to value comparisons over small single-field inputs: every field -/// sharing field 0's spans, or the mid-evaluation flush never running, would still pass the -/// golden cases (at most 20 points, one field). The comparison is against the per-window path, -/// which is the same kernel without batching, so a disagreement is the batching's fault alone. +/// More grid points than `EVALUATION_BATCH` and several fields: the golden cases (at most 20 +/// points, one field) reach neither the mid-evaluation flush nor per-field spans. #[test] fn a_batch_spanning_fields_and_the_flush_threshold_matches_the_per_window_path() { let points = 600; @@ -1820,10 +1716,8 @@ fn a_batch_spanning_fields_and_the_flush_threshold_matches_the_per_window_path() anchor_ms: None, modifier: None, }; - // Counter-like values, each field resetting at a different point, growing at a different - // rate, and missing at a different interval. The gaps are what make the fields' windows - // differ: a field reading another field's windows would then get a different number, which a - // shared dense layout would hide. + // Each field resets, grows and misses samples at its own interval, so the fields' windows + // differ. let mut totals = [0.0f64; 3]; let rows: Vec = (0..points) .map(|index| { @@ -1874,9 +1768,6 @@ fn a_batch_spanning_fields_and_the_flush_threshold_matches_the_per_window_path() .unwrap() .expect("the series completes"); - // Fold the chunk back into one series first: a chunk's range reports the positions its push - // decided, which can include leading and trailing positions holding no value, while the - // comparison is against the trimmed series the per-window path produced. let schema = batch.output_schema(); let batched = fold_chunks(std::slice::from_ref(&batched), schema); let expected = expand(&expected.series); @@ -1887,12 +1778,7 @@ fn a_batch_spanning_fields_and_the_flush_threshold_matches_the_per_window_path() ); } -/// A window holding a native histogram sample keeps its grid point on the per-window path, since -/// the batch kernel reads the floats alone and cannot reproduce the mixed-window rules. -/// -/// The series is laid out so every grid point's window contains the histogram: three samples -/// 10 s apart with the histogram on the first, and a window reaching 30 s back, so a window -/// covering any grid point reaches timestamp 0. +/// Every window here holds the histogram at 0 s, so no grid point may take the batch path. #[test] fn a_histogram_window_keeps_rate_on_the_per_window_path() { let histogram = "0/0/0/4014000000000000/4014000000000000/1/0_1/4014000000000000///"; @@ -1971,9 +1857,7 @@ fn empty_input_and_series_without_results() { }; probe_evaluator(1, grid(0, 10, 4), window).finish().unwrap(); - // A series whose samples all miss the grid still closes, and its closing chunk says the whole - // grid was decided: every point is a settled missing value, not a point still waiting. A - // settled point that holds no value is reported by the close itself, not by a row. + // A series whose samples all miss the grid still closes, on an empty chunk. let mut evaluator = probe_evaluator(1, grid(0, 10, 4), window); let after_grid = chunk(&[(31, vec![Some(1.0)])], 1, 0, true); let closed = evaluator @@ -1988,8 +1872,7 @@ fn empty_input_and_series_without_results() { "no point of the grid holds a value" ); assert!(all_missing(&closed.series)); - // A series whose only sample is stale does the same: the row is dropped, the points behind it - // are decided. + // So does a series whose only sample is stale. let only_stale = chunk(&[(5, vec![Some(stale())])], 1, 1, true); let closed = evaluator .push(&only_stale) @@ -2004,11 +1887,6 @@ fn empty_input_and_series_without_results() { evaluator.finish().unwrap(); } -/// A push that completes nothing must not hand out a chunk. -/// -/// A position that settles to no value is not a row, so a push that settled only such positions -/// has no run to hand out. Emitting an empty chunk instead would report progress the push did not -/// make, and a consumer that keys on chunks would see a decision that never happened. #[test] fn a_push_that_completes_nothing_hands_out_no_chunk() { let window = RangeWindow { @@ -2018,16 +1896,13 @@ fn a_push_that_completes_nothing_hands_out_no_chunk() { modifier: None, }; let mut evaluator = probe_evaluator(1, grid(10, 10, 3), window); - // The only sample sits inside the first window, so the first point cannot be settled yet: no - // position is completed and the push has nothing to report. + // The only sample sits inside the first window, so no point is decided yet. let partial = chunk(&[(5, vec![Some(1.0)])], 1, 0, false); assert!( evaluator.push(&partial).unwrap().is_none(), "a push that completed no position must not hand out a chunk" ); - // The closing push hands out the one position of the grid that holds a value, and that same - // chunk is the close: nothing follows it. The two positions without a value cost no row. let mut chunks = Vec::new(); chunks.extend( evaluator @@ -2053,9 +1928,7 @@ fn a_push_that_completes_nothing_hands_out_no_chunk() { evaluator.finish().unwrap(); } -/// A series whose last sample is behind the end of the grid still closes, on a chunk holding no -/// positions: the remaining points have no values, and only the closing chunk tells the consumer -/// that the series is over rather than still waiting for input. +/// A series whose remaining points hold no value closes on an empty chunk after its last run. #[test] fn a_series_that_ends_early_still_closes() { let window = RangeWindow { @@ -2076,9 +1949,7 @@ fn a_series_that_ends_early_still_closes() { (0, 2) ); - // The last sample lies past every remaining window, so points 2 to 4 are decided to hold no - // value. They cost no row: the close is what reports that they are settled, and it starts - // where the last handed-out run ended. + // The last sample lies past every remaining window, so points 2 to 4 hold no value. let last = chunk(&[(45, vec![Some(3.0)])], 1, 0, true); let closed = evaluator.push(&last).unwrap().expect("a series closes"); assert!(closed.is_last); @@ -2090,68 +1961,7 @@ fn a_series_that_ends_early_still_closes() { assert_eq!(rows_with_a_value(&closed.series), 0); } -/// A stretch of decided positions holding no value costs no row, and does not delay the close. -/// -/// The positions are settled as soon as the sampler pushes past them, but settling them allocates -/// nothing: a consumer learns they hold no value from the run that follows them, or from the -/// close when nothing follows. -#[test] -fn decided_missing_positions_cost_no_rows_and_do_not_delay_the_close() { - // `rate` over a one-second window on grid 0,1,2,3,4s. - let window = RangeWindow { - range_ms: 1_000, - offset_ms: 0, - anchor_ms: None, - modifier: None, - }; - let mut evaluator = RangeEvaluator::try_new( - &raw_schema(1), - grid(0, 1_000, 5), - window, - RangeFunction::Rate, - ) - .unwrap(); - - // A: samples at -0.5s and 0s decide the point at 0s. - let a = chunk( - &[(-500, vec![Some(1.0)]), (0, vec![Some(2.0)])], - 1, - 0, - false, - ); - let first = evaluator.push(&a).unwrap().expect("point 0 is decided"); - assert!(!first.is_last); - assert_eq!((chunk_run(&first).start(), chunk_run(&first).len()), (0, 1)); - - // B settles 1s and 2s: neither yields a rate, and neither point can change once a sample at - // 4s arrives, since that sample lies past both windows. Nothing is handed out, because a - // position holding no value is not a row -- and the series has not ended, so there is no - // close to report yet. - let b = chunk(&[(2_000, vec![Some(3.0)])], 1, 0, false); - assert!( - evaluator.push(&b).unwrap().is_none(), - "settled positions holding no value are not rows" - ); - - // C closes the series. 3s and 4s hold no rate either, so the close carries the progress: it - // starts where the last row ended and holds none. - let c = chunk(&[(4_000, vec![Some(4.0)])], 1, 0, true); - let mut chunks = vec![first]; - chunks.extend(evaluator.push(&c).unwrap()); - let last = chunks.last().expect("a series always closes"); - assert!(last.is_last); - assert_eq!((chunk_run(last).start(), chunk_run(last).len()), (1, 0)); - - // Folding the chunks reproduces the one point that holds a value; the empty stretch cost no - // row at any point along the way. - let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); - assert_eq!(folded.metric, output_metric(RangeFunction::Rate, 0)); - assert_eq!((grid_start(&folded), rows_with_a_value(&folded)), (0, 1)); -} - -/// The closing chunk of a series is labelled like the chunks before it, including the metadata -/// labels a function drops: `rate` removes `__name__`, and a consumer that keyed series by label -/// set would see the same series split in two if the closing chunk kept it. +/// An empty closing chunk drops `__name__` like the chunks before it. #[test] fn the_closing_chunk_is_labelled_like_the_chunks_before_it() { let window = RangeWindow { @@ -2171,8 +1981,6 @@ fn the_closing_chunk_is_labelled_like_the_chunks_before_it() { assert!(!handed.is_last); assert_eq!(handed.series.metric.name(), None); - // The last sample is past every remaining window, so the close reports the settled positions - // that hold no value, and it must be labelled the same as the chunk before it. let last = chunk(&[(45, vec![Some(5.0)])], 1, 0, true); let mut chunks = vec![handed]; chunks.extend(evaluator.push(&last).unwrap()); @@ -2195,11 +2003,8 @@ fn chunk_run(chunk: &EvaluatedChunk) -> &GridRange { .expect("this chunk was expected to cover a single run") } -/// The `(start, len)` of every run of every chunk handed out, in order. -/// -/// One chunk may carry several runs, separated by stretches holding no value; each is reported on -/// its own, so a test comparing chunk boundaries always sees the positions that hold a value. A -/// chunk holding no row at all reports the position it closes at, with a length of zero. +/// The `(start, len)` of every run of every chunk, in order; an empty chunk reports +/// `(position, 0)`. fn chunk_ranges(chunks: &[EvaluatedChunk]) -> Vec<(usize, usize)> { let mut ranges = Vec::new(); for chunk in chunks { @@ -2244,8 +2049,7 @@ fn one_ms() -> RangeWindow { } } -/// Two samples a million positions apart cost two rows: a position holding no value is not a -/// row, so the empty stretch between them is never materialised. +/// Two samples a million positions apart cost two rows. #[test] fn a_huge_gap_costs_one_row_per_value() { let mut evaluator = pinpoint(one_ms()); @@ -2271,50 +2075,9 @@ fn a_huge_gap_costs_one_row_per_value() { evaluator.finish().unwrap(); } -/// A series whose first value comes late is addressed at that position: nothing is allocated for -/// the positions before it. +/// The blank stretch skipped across pushes costs no row, and the value after it is kept. #[test] -fn a_very_late_first_value_allocates_nothing_before_it() { - let mut evaluator = pinpoint(one_ms()); - let chunks = collect_chunks( - &mut evaluator, - &[chunk(&[(999_000, vec![Some(1.0)])], 1, 0, true)], - ); - - assert_eq!(chunk_ranges(&chunks), vec![(999_000, 1)]); - assert_eq!(total_rows(&chunks), 1); - assert!(chunks[0].is_last); - evaluator.finish().unwrap(); -} - -/// A series whose last value comes early closes on the value it has: the positions after it are -/// settled and hold nothing, which the close reports without a row for any of them. -#[test] -fn a_very_early_last_value_closes_without_rows_for_the_rest() { - let mut evaluator = pinpoint(one_ms()); - let first = chunk(&[(0, vec![Some(1.0)])], 1, 0, false); - let mut chunks = vec![evaluator.push(&first).unwrap().expect("point 0 is decided")]; - assert!(!chunks[0].is_last); - chunks.extend( - evaluator - .push(&chunk(&[(5, vec![Some(2.0)])], 1, 0, true)) - .unwrap(), - ); - - assert_eq!(chunk_ranges(&chunks), vec![(0, 1), (5, 1)]); - assert_eq!( - total_rows(&chunks), - 2, - "the two positions holding a value, and no others" - ); - assert!(chunks.last().unwrap().is_last); - evaluator.finish().unwrap(); -} - -/// A push that advances over a long blank stretch hands out nothing for it, and a later push still -/// yields its own value: skipping the stretch loses no sample. -#[test] -fn a_blank_stretch_hands_out_nothing_and_loses_the_next_value() { +fn a_blank_stretch_hands_out_nothing_and_keeps_the_next_value() { let mut evaluator = pinpoint(one_ms()); let mut chunks = Vec::new(); chunks.extend( @@ -2347,94 +2110,6 @@ fn a_blank_stretch_hands_out_nothing_and_loses_the_next_value() { evaluator.finish().unwrap(); } -/// A series with no value anywhere still closes, exactly once, on a chunk holding no rows. -#[test] -fn a_series_without_any_result_closes_once() { - // The only sample lies before the grid, so no window contains it. - let mut evaluator = probe_evaluator(1, grid(5, 1, 1_000_000), one_ms()); - let mut chunks = Vec::new(); - chunks.extend( - evaluator - .push(&chunk(&[(0, vec![Some(1.0)])], 1, 0, true)) - .unwrap(), - ); - - assert_eq!(chunks.len(), 1, "a series closes exactly once"); - assert!(chunks[0].is_last); - assert_eq!(chunk_ranges(&chunks), vec![(0, 0)]); - assert_eq!(total_rows(&chunks), 0); - evaluator.finish().unwrap(); -} - -/// A valued prefix followed by an all-empty remainder still closes, and the remainder costs no -/// row. -#[test] -fn a_valued_prefix_and_an_empty_remainder_still_close() { - let mut evaluator = pinpoint(one_ms()); - let mut chunks = vec![ - evaluator - .push(&chunk(&[(3, vec![Some(1.0)])], 1, 0, false)) - .unwrap() - .expect("point 3 is decided"), - ]; - assert_eq!(chunk_ranges(&chunks), vec![(3, 1)]); - assert!(!chunks[0].is_last); - - // The last row is stale, so it is dropped and the remainder holds no value at all. - let last = chunk(&[(900_000, vec![Some(stale())])], 1, 0, true); - chunks.extend(evaluator.push(&last).unwrap()); - - assert_eq!(chunk_ranges(&chunks), vec![(3, 1), (4, 0)]); - assert_eq!(total_rows(&chunks), 1, "the remainder holds no rows"); - assert!(chunks.last().unwrap().is_last); - evaluator.finish().unwrap(); -} - -/// Folding the chunks of a sparse series gives the same series as folding the same samples with a -/// row for every position holding no value: a missing position and an uncovered one mean the same -/// thing to a consumer. -#[test] -fn a_sparse_series_folds_like_the_same_data_with_explicit_nulls() { - let grid = grid(0, 1_000, 40); - let window = RangeWindow { - range_ms: 3_000, - offset_ms: 0, - anchor_ms: None, - modifier: None, - }; - let rows = [ - (0, vec![Some(1.0)]), - (1_000, vec![Some(2.0)]), - (2_000, vec![Some(3.0)]), - (20_000, vec![Some(4.0)]), - (21_000, vec![Some(5.0)]), - (39_000, vec![Some(6.0)]), - ]; - let mut evaluator = probe_evaluator(1, grid.clone(), window); - let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 1, 0, true)]); - let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); - - let expected = reference(&rows, &grid, window, 1, true, true); - let spread = expected.iter().filter(|row| row[0].is_some()).count(); - assert_eq!( - total_rows(&chunks), - spread, - "a row per position holding a value, and none for the rest" - ); - assert_eq!( - expand(&folded), - expected, - "the sparse result equals the one written as null rows" - ); - evaluator.finish().unwrap(); -} - -/// The runs of one evaluated series share the evaluator's retained samples: a window reaching -/// back across the gap to an earlier run reads both. -/// -/// This is what makes a sparse inner result usable. Closing the series after its first run, or -/// promoting each run to a series of its own, would leave the window at 10ms reading 3 alone -/// instead of 2 + 3. #[test] fn a_window_reads_across_the_gap_between_runs_of_one_series() { let inner = grid(0, 1, 11); @@ -2480,8 +2155,7 @@ fn a_window_reads_across_the_gap_between_runs_of_one_series() { evaluator.finish().unwrap(); } -/// The samples decide the rows, not the input chunking: the same logical data split at different -/// boundaries folds to the same series over the same number of rows. +/// The same data split at different chunk boundaries folds to the same series and row count. #[test] fn raw_chunk_boundaries_do_not_change_the_rows() { let grid = grid(0, 1_000, 40); @@ -2514,8 +2188,6 @@ fn raw_chunk_boundaries_do_not_change_the_rows() { } let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); assert_eq!(expand(&folded), expected, "split {split:?} differs"); - // No run ever spans a position holding no value, whatever the chunking: the rows of a run - // are consecutive grid positions, and the positions between two runs are the empty ones. for (start, len) in chunk_ranges(&chunks) { assert!( len <= 3, @@ -2525,9 +2197,6 @@ fn raw_chunk_boundaries_do_not_change_the_rows() { outcomes.push(total_rows(&chunks)); evaluator.finish().unwrap(); } - // Which chunk a run lands in follows the input boundaries, since a push has to hand its - // decided positions out before the next one changes them. What must not depend on chunking is - // the number of rows: an empty position never costs one. assert!( outcomes.windows(2).all(|pair| pair[0] == pair[1]), "chunking changed the rows handed out: {outcomes:?}" @@ -2535,8 +2204,7 @@ fn raw_chunk_boundaries_do_not_change_the_rows() { assert_eq!(outcomes, vec![expected_rows; outcomes.len()]); } -/// Values and nulls alternating: one row per value and one chunk per value, which is what this -/// design costs for data that never holds two consecutive positions. +/// Values and nulls alternating: one row and one run per value, all in one chunk. #[test] fn alternating_values_and_nulls_hand_out_one_row_per_value() { let mut evaluator = probe_evaluator(1, grid(0, 1, 10), one_ms()); @@ -2564,54 +2232,7 @@ fn alternating_values_and_nulls_hand_out_one_row_per_value() { evaluator.finish().unwrap(); } -/// Values and nulls alternating over 200,000 positions: 100,000 valued positions cost 100,000 -/// rows, not one per position, and each value is its own run. -/// -/// The run count is the accepted cost of this design; the row count is what must not regress. -#[test] -fn interleaved_values_over_a_long_grid_cost_one_row_per_value() { - const GRID: u64 = 200_000; - let mut evaluator = probe_evaluator(1, grid(0, 1, GRID), one_ms()); - let rows: Vec = (0..GRID) - .map(|index| { - let value = (index % 2 == 0).then_some(index as f64); - (index as i64, vec![value]) - }) - .collect(); - let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 1, 0, true)]); - - assert_eq!( - total_rows(&chunks), - (GRID / 2) as usize, - "one row per valued position, never one per position" - ); - assert_eq!( - chunks.len(), - 1, - "the whole series is decided by one push, so it arrives as one chunk" - ); - assert!(chunks.last().unwrap().is_last); - assert_eq!(chunks.iter().filter(|chunk| chunk.is_last).count(), 1); - let runs: Vec<(usize, usize)> = chunks[0] - .series - .time - .runs() - .map(|run| (run.position, run.len)) - .collect(); - assert_eq!( - runs.len(), - (GRID / 2) as usize, - "every valued position is its own run" - ); - for (start, len) in runs { - assert_eq!(len, 1, "every valued position is its own run"); - assert_eq!(start % 2, 0, "only even positions hold a value"); - } - evaluator.finish().unwrap(); -} - -/// An anchored selector broadcasts one value over every grid point, so every position holds one: -/// the result is a single contiguous piece, not one piece per position. +/// An `@`-anchored result fills every grid point, so it is one contiguous run. #[test] fn an_anchored_replay_stays_one_contiguous_piece() { let window = RangeWindow { @@ -2643,8 +2264,7 @@ fn an_anchored_replay_stays_one_contiguous_piece() { } } -/// Fields of one run stay row-aligned: a field with no value at a position another field fills -/// keeps a null row there. That null is the layout, not a bridged gap. +/// Fields of one run stay row-aligned: a field missing where another holds a value keeps a null. #[test] fn a_run_keeps_its_fields_aligned_and_nulls_only_the_missing_one() { let mut evaluator = probe_evaluator(2, grid(0, 1, 6), one_ms()); @@ -2871,8 +2491,7 @@ fn retains_only_samples_later_windows_need() { } } -/// A counter whose every window contains resets, so the index holds entries the way a real -/// counter does, still releases them as the samples they reach back to are dropped. +/// Resets are released with the samples they reach back to. #[test] fn reset_index_is_released_with_the_samples_it_reaches_back_to() { let window = RangeWindow { @@ -2890,8 +2509,6 @@ fn reset_index_is_released_with_the_samples_it_reaches_back_to() { evaluator .push(&chunk(piece, 1, 0, (index + 1) * 100 == rows.len())) .unwrap(); - // Resets are released with the samples behind the next window, so they stay bounded by - // the same window plus one grid step the samples do, one reset per 10 samples. assert!( evaluator.fields[0].resets.len() <= 6, "{} resets after {} chunks: the index kept history no window can reach", @@ -2901,11 +2518,8 @@ fn reset_index_is_released_with_the_samples_it_reaches_back_to() { } } -/// The reset index, not a rescan of the window, decides which samples a window corrects. The -/// samples are laid out so each rule is visible point by point: a reset is the first sample of a -/// later chunk, a reset's predecessor sits exactly on a window's left edge and must not count, -/// and a reset enters a window whole. The reported resets are compared instead of the function's -/// output so a wrong position cannot hide inside a float's last bits. +/// Pins each reset-index rule point by point: a reset as the first sample of a later chunk, a +/// predecessor exactly on a window's left edge (not counted), and a reset entering a window whole. #[test] fn counter_resets_follow_the_window_and_survive_chunking() { // A counter that drops at index 3 (20 -> 5) and again at index 6 (25 -> 7), one sample per @@ -2971,10 +2585,8 @@ fn counter_resets_follow_the_window_and_survive_chunking() { }; // Windows (10 s, 30 s], (20 s, 40 s], (30 s, 50 s] and (40 s, 60 s]. - // The first holds 20 and 5, so the reset at index 3 corrects it. The second's left edge is - // the sample before that reset, which a left-open window excludes, so the same reset must not - // count there. The fourth holds 25 and 7, corrected by the reset at index 6. The second field - // never corrects anything. + // The first holds 20 and 5 (reset at index 3). The second's left edge is the sample before + // that reset, so it does not count there. The fourth holds 25 and 7 (reset at index 6). let expected = [ (vec![20_000, 30_000], vec![20.0], vec![]), (vec![30_000, 40_000], vec![], vec![]), @@ -2998,9 +2610,7 @@ fn counter_resets_follow_the_window_and_survive_chunking() { ); } - // The same samples pushed as a second series through the same evaluator: no buffer, cursor or - // index state of the first series may survive, so the second series reports exactly the same - // windows and resets. + // A second series through the same evaluator must report the same: no state may leak. recorded.lock().unwrap().clear(); for (start, end) in pieces { let closed = end == rows.len(); @@ -3032,9 +2642,7 @@ fn recorded_of(expected: &[(Vec, Vec, Vec)]) -> Vec<(Vec, Ve .collect() } -/// Missing samples shift which neighbours a reset sits between, and the shift differs per -/// field. The resets each window reports are checked position by position instead of through a -/// function's output, so a field paying for another field's resets shows up directly. +/// Missing samples change which neighbours a reset sits between, independently per field. #[test] fn nulls_change_the_reset_positions_of_each_field_independently() { let rows: Vec = vec![ @@ -3079,8 +2687,7 @@ fn nulls_change_the_reset_positions_of_each_field_independently() { } // Field 0 never sees the missing 15, so 20 is followed directly by 5 and it resets once. - // Field 1 keeps the 15 and resets twice: 20 -> 15 and 15 -> 5. Both fields report their own - // resets even though they share a window and a chunk. + // Field 1 keeps the 15 and resets twice: 20 -> 15 and 15 -> 5. let reported = reported.lock().unwrap().clone(); assert_eq!(reported.len(), 10, "five grid points, two fields"); let expected = [ @@ -3096,9 +2703,8 @@ fn nulls_change_the_reset_positions_of_each_field_independently() { } } -/// A random evaluated series on `grid`; values may carry the stale bit pattern, which computed -/// input keeps as an ordinary NaN. The rows hold holes, so the series carries one run per stretch -/// of positions holding a value. +/// A random evaluated series on `grid`, with holes; values may carry the stale bit pattern, which +/// computed input keeps as an ordinary NaN. fn random_evaluated( rng: &mut StdRng, grid: &Arc, @@ -3219,8 +2825,6 @@ fn subquery_series_match_references() { ) .unwrap(); let expected = reference(&rows, &outer, window, fields, false, true); - // The same logical series arrives as a prefix and its closing rows, as a stream delivers - // it: the runs of both deliveries are folded together for the comparison. let evaluated = deliver_as_a_stream(&mut probe, &schema, &series, &mut rng); assert!(evaluated.last().expect("the input closes").is_last); let result = fold_chunks(&evaluated, probe.output_schema()); @@ -3639,8 +3243,8 @@ fn quantile_picks_the_signed_zero_go_picks() { } } -/// Chunks after the last grid point are only validated, so nothing accumulates and the outcome -/// does not depend on where the series is split. +/// Samples past the last window are not retained, but a sample whose offset overflows still +/// fails the series. #[test] fn samples_after_the_last_window_are_validated_but_not_retained() { let window = RangeWindow { @@ -4085,9 +3689,8 @@ fn evaluated_schema(grid: &Arc) -> Arc { }) } -/// A delivery holding no position decides nothing, so inside a series it is refused: it cannot be -/// told from a stall, and the caller would wait for a result that is not coming. The same empty -/// delivery carrying `is_last` is the series' close, and the identity initialises and closes. +/// An empty evaluated delivery is an error unless it is `last`, where it opens and closes the +/// series. #[test] fn an_empty_delivery_closes_only_when_it_is_last() { let outer = grid(0, 10, 4); @@ -4099,7 +3702,6 @@ fn an_empty_delivery_closes_only_when_it_is_last() { .unwrap(); execution_error(mid_series.push_series(&empty, false)); - // The identity never produced a value, so the only chunk it hands out is the empty close. let mut evaluator = RangeEvaluator::try_new(&schema, outer.clone(), one_ms(), RangeFunction::SumOverTime) .unwrap(); @@ -4170,46 +3772,6 @@ fn a_valued_prefix_composes_with_an_empty_closing_chunk() { ); } -/// The empty closing chunk an evaluator produces is legal input for the next one: a pipeline that -/// composes two evaluators must not reject its own output. -#[test] -fn an_empty_chunk_from_one_evaluator_closes_the_next() { - let outer = grid(0, 1_000, 4); - // A sample far past the grid closes a series whose every window stays empty, so the only chunk - // the evaluator hands out is the empty close. - let rows = [(100_000, vec![Some(1.0)])]; - let mut upstream = probe_evaluator(1, outer.clone(), one_ms()); - let produced = collect_chunks(&mut upstream, &[chunk(&rows, 1, 0, true)]); - upstream.finish().unwrap(); - let closed = produced.last().expect("the series closes"); - assert!(closed.is_last); - assert!( - closed.series.time.is_empty(), - "the closing chunk carries no row" - ); - - let schema = evaluated_schema(&outer); - let mut downstream = - RangeEvaluator::try_new(&schema, outer.clone(), one_ms(), RangeFunction::SumOverTime) - .unwrap(); - let chunk = downstream - .push_series(&closed.series, true) - .unwrap() - .expect("the downstream series still closes"); - assert!(chunk.is_last); - assert!(chunk.series.time.is_empty()); - downstream.finish().unwrap(); -} - -// --------------------------------------------------------------------------------------------- -// Acceptance: a fragmented result, end to end through the evaluator. -// -// These tests pin the observable shape of a sparse result as well as its values: one series per -// logical output, one row per position that holds a value, and an axis that names where those rows -// sit. The dense matrices they compare against are built by this module's reference and are never -// fed back into the evaluator. -// --------------------------------------------------------------------------------------------- - /// A window of one step over a grid of `step_ms`: the point at `t` reads the sample sitting /// exactly on `t`, so a kernel that reports its last sample reports the input value unchanged. fn one_step_window(step_ms: i64) -> RangeWindow { @@ -4221,97 +3783,7 @@ fn one_step_window(step_ms: i64) -> RangeWindow { } } -/// A: a million-position grid holding two values, one a long way into the grid. -/// -/// The span between them costs neither a row nor a field sample: the axis carries two rows and -/// names two runs, and the shared grid -- one timestamp buffer for every result of the query -- is -/// what turns a row into an instant. -#[test] -fn a_million_position_grid_with_two_values_is_one_series_of_two_rows() { - const SPAN: u64 = 1_000_000; - let grid = grid(0, 1_000, SPAN); - // `last_over_time` over a one-step window reports the sample sitting on the point. - let mut evaluator = RangeEvaluator::try_new( - &raw_schema(1), - grid.clone(), - one_step_window(1_000), - RangeFunction::LastOverTime, - ) - .unwrap(); - let rows = [(10_000, vec![Some(1.0)]), (900_000_000, vec![Some(2.0)])]; - let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 1, 0, true)]); - - // One series, not a piece per run: a push hands its decided rows over in one `Series`. - assert_eq!( - chunks.len(), - 1, - "one push decides the whole series, so it arrives as one chunk, got {}", - chunks.len() - ); - let closing = &chunks[0]; - assert!( - closing.is_last, - "a one-push series closes on its only chunk" - ); - let series = &closing.series; - assert_eq!( - run_ranges_of(closing), - vec![(10, 1), (900_000, 1)], - "two values a million positions apart are two runs" - ); - assert_eq!( - series.time.len(), - 2, - "the axis carries two rows, not the span" - ); - assert_eq!( - series.fields.len(), - 1, - "the evaluator kept its input's field" - ); - let field = &series.fields.as_slice()[0]; - assert_eq!(field.len(), 2, "the field holds one sample per carried row"); - let values = match field.dense() { - Some(DenseSamplesRef::Float(values)) => values, - _ => panic!("the field is one dense float array"), - }; - assert_eq!( - values.len(), - 2, - "the value buffer is sized by the values, not by the span" - ); - assert_eq!(values.values().as_ref(), &[1.0, 2.0]); - - // What the axis does carry is the shared grid: every result of the query addresses rows on it. - assert_eq!( - series.time.grid().expect("a grid series").spec().len as usize, - SPAN as usize, - "the grid really holds a million positions" - ); - assert_eq!( - series.time.timestamps().unwrap().len(), - 2, - "the axis hands out two timestamps, not one per grid position" - ); - assert_eq!(series.time.timestamp(0), Some(10_000)); - assert_eq!(series.time.timestamp(1), Some(900_000_000)); - - // The reference: the result expands to a million slots, and exactly the two valued positions - // carry anything. - let expanded = expand(series); - assert_eq!(expanded.len(), SPAN as usize); - assert_eq!( - expanded.iter().filter(|row| row[0].is_some()).count(), - 2, - "only the two pushed positions hold a value" - ); - assert_eq!(expanded[10], vec![Some(1.0)]); - assert_eq!(expanded[900_000], vec![Some(2.0)]); - evaluator.finish().unwrap(); -} - -/// B: every position valued, so the result is one contiguous run and keeps the fast path: the -/// axis is a `TimeAxis::Grid`, not a span list of one element. +/// Every position valued: the axis is a single `GridRange`, not a run list of one element. #[test] fn a_contiguous_result_still_takes_the_single_range_fast_path() { const POINTS: u64 = 8; @@ -4344,219 +3816,6 @@ fn a_contiguous_result_still_takes_the_single_range_fast_path() { evaluator.finish().unwrap(); } -/// B: alternating valued and missing positions: one series whose axis names one run per value, and -/// one delivery for the whole series rather than one per run. -/// -/// The measured numbers are 8 runs for 16 positions, handed out by 1 chunk. -#[test] -fn alternating_values_and_holes_arrive_in_one_delivery_over_many_runs() { - const POINTS: usize = 16; - let grid = grid(0, 1_000, POINTS as u64); - let mut evaluator = RangeEvaluator::try_new( - &raw_schema(1), - grid.clone(), - one_step_window(1_000), - RangeFunction::LastOverTime, - ) - .unwrap(); - // Every even position holds a value, every odd one holds none. - let rows: Vec = (0..POINTS) - .map(|index| { - let value = (index % 2 == 0).then_some(index as f64); - (index as i64 * 1_000, vec![value]) - }) - .collect(); - let chunks = collect_chunks(&mut evaluator, &[chunk(&rows, 1, 0, true)]); - - assert_eq!(chunks.len(), 1, "one push decides the whole series"); - let series = &chunks[0].series; - let runs = run_ranges_of(&chunks[0]); - let expected: Vec<(usize, usize)> = (0..POINTS).step_by(2).map(|index| (index, 1)).collect(); - assert_eq!( - runs, expected, - "every valued position is its own run, at its own absolute position" - ); - assert_eq!(runs.len(), POINTS / 2, "8 runs over 16 positions"); - assert!( - chunks.len() * 4 <= runs.len(), - "deliveries ({}) must stay far below the runs ({}): one delivery per run would be the \ - envelope strategy this change removes", - chunks.len(), - runs.len() - ); - assert_eq!(series.time.len(), POINTS / 2, "one row per value"); - assert_eq!(chunks.iter().filter(|chunk| chunk.is_last).count(), 1); - evaluator.finish().unwrap(); -} - -/// B: the same positions delivered as one series with holes and as several pushes of the same -/// logical series give the same dense result. -/// -/// A stream hands a series over in pieces, so where the piece boundaries fall must not decide the -/// answer: only the axis does. -#[test] -fn a_series_with_holes_and_the_same_positions_in_several_pushes_expand_alike() { - let outer = grid(0, 1_000, 16); - let schema = evaluated_schema(&outer); - let window = one_step_window(1_000); - let labels = Labels::from([("job".to_string(), "x".to_string())]); - let points = Points::from([ - (0, f64::to_bits(1.0)), - (1, f64::to_bits(2.0)), - (3, f64::to_bits(4.0)), - (8, f64::to_bits(8.0)), - (9, f64::to_bits(16.0)), - (15, f64::to_bits(32.0)), - ]); - - // One series, holes as explicit nulls between the valued positions. - let holed = series_of(&schema, &labels, &points).expect("six positions hold a value"); - assert_eq!( - holed.time.len(), - 16, - "the fixture spans the whole grid with nulls" - ); - let mut one_push = - RangeEvaluator::try_new(&schema, outer.clone(), window, RangeFunction::LastOverTime) - .unwrap(); - let whole = fold_chunks( - &evaluate_series(&mut one_push, &holed), - one_push.output_schema(), - ) - .expect("the series completed"); - one_push.finish().unwrap(); - let expected = expand(&whole); - assert_eq!( - expected.iter().filter(|row| row[0].is_some()).count(), - 6, - "the one-piece result carries the six values" - ); - - // The same positions as a fragmented axis, delivered in three pushes of the one series. - let sparse = sparse_series(&schema, &labels, &points).expect("six positions hold a value"); - assert_eq!( - sparse.time.len(), - 6, - "the fragmented fixture carries six rows" - ); - assert_eq!( - sparse.time.runs().count(), - 4, - "positions 0-1, 3, 8-9 and 15 are four runs" - ); - let cuts = [1, 3]; - let mut delivered = - RangeEvaluator::try_new(&schema, outer.clone(), window, RangeFunction::LastOverTime) - .unwrap(); - let mut chunks: Vec = Vec::new(); - let mut start = 0; - for end in cuts - .iter() - .copied() - .chain(std::iter::once(sparse.time.len())) - { - let piece = rows_of(&schema, &sparse, start, end - start); - chunks.extend( - delivered - .push_series(&piece, end == sparse.time.len()) - .unwrap(), - ); - start = end; - } - assert!( - chunks.len() >= 2, - "the pushes hand out more than one chunk, got {}", - chunks.len() - ); - assert!(chunks.last().expect("a closing chunk").is_last); - let several = fold_chunks(&chunks, delivered.output_schema()).expect("the series completed"); - delivered.finish().unwrap(); - - assert_eq!( - expand(&several), - expected, - "where a push ends changed the answer" - ); -} - -/// E (5): the input chunk boundaries do not change the evaluated rows. -/// -/// Runs compare only across the variants whose settled axis is genuinely the same: a push settles -/// the points it decides, so the same logical data split differently may hand a run over as two -/// adjacent spans. What must not depend on the split is the set of carried positions, which is -/// what the expanded matrix compares. -#[test] -fn input_chunk_boundaries_do_not_change_the_evaluated_rows() { - let grid = grid(0, 1_000, 12); - let window = one_step_window(1_000); - let rows = [ - (0, vec![Some(1.0)]), - (1_000, vec![Some(2.0)]), - (3_000, vec![Some(4.0)]), - (4_000, vec![Some(8.0)]), - (10_000, vec![Some(16.0)]), - ]; - let splits: [&[usize]; 3] = [&[], &[2], &[1, 3, 4]]; - let mut expanded = Vec::new(); - let mut covered = Vec::new(); - for split in splits { - let mut evaluator = RangeEvaluator::try_new( - &raw_schema(1), - grid.clone(), - window, - RangeFunction::LastOverTime, - ) - .unwrap(); - let mut chunks = Vec::new(); - let mut start = 0; - for end in split.iter().copied().chain(std::iter::once(rows.len())) { - let piece = chunk(&rows[start..end], 1, 0, end == rows.len()); - chunks.extend(evaluator.push(&piece).unwrap()); - start = end; - } - let folded = fold_chunks(&chunks, evaluator.output_schema()).expect("the series completed"); - // The split decides how many chunks a run is handed out in, never which positions hold a - // value: compare those, and the dense matrix, not the raw span count. - let mut positions: Vec = chunk_ranges(&chunks) - .into_iter() - .filter(|(_, len)| *len > 0) - .flat_map(|(start, len)| start..start + len) - .collect(); - positions.sort_unstable(); - covered.push(positions); - expanded.push(expand(&folded)); - evaluator.finish().unwrap(); - } - assert_eq!(covered[0], vec![0, 1, 3, 4, 10], "split {:?}", splits[0]); - assert_eq!( - covered[1], covered[0], - "split {:?} moved the valued positions", - splits[1] - ); - assert_eq!( - covered[2], covered[0], - "split {:?} moved the valued positions", - splits[2] - ); - assert_eq!(expanded[1], expanded[0], "split {:?}", splits[1]); - assert_eq!(expanded[2], expanded[0], "split {:?}", splits[2]); - // The one-piece variant's axis is the maximal-run one, so its runs are pinned exactly. - assert_eq!( - expanded[0] - .iter() - .enumerate() - .filter(|(_, row)| row[0].is_some()) - .map(|(index, _)| index) - .collect::>(), - vec![0, 1, 3, 4, 10] - ); -} - -/// G: a series hands its rows out before it ends. -/// -/// The chunks of a prefix arrive with `is_last` still false, and the positions they carry are a -/// prefix of the positions the whole series ends up holding: a consumer can act on them without -/// waiting for the last chunk of the input. #[test] fn a_prefix_hands_out_its_rows_before_the_series_ends() { let grid = grid(0, 1_000, 12); @@ -4582,7 +3841,6 @@ fn a_prefix_hands_out_its_rows_before_the_series_ends() { "the series keeps going, so the prefix chunk does not close it" ); let mut chunks = vec![first]; - assert_eq!(chunks.len(), 1, "one push hands out one chunk"); assert_eq!( run_ranges_of(&chunks[0]), vec![(0, 2)], @@ -4602,7 +3860,6 @@ fn a_prefix_hands_out_its_rows_before_the_series_ends() { Some((3, 1)) ); - // The one-piece form of the same input: the prefix must be a prefix of it. let mut one_piece = RangeEvaluator::try_new( &raw_schema(1), grid.clone(), @@ -4678,11 +3935,6 @@ fn dense_sum_over_time(rows: &[Row], grid: &EvalGrid, window: RangeWindow) -> De .collect() } -/// G: a window at a later run reads the samples of an earlier run of the same series. -/// -/// The two runs arrive in two deliveries, and the single outer point's window reaches back across -/// the hole to the first delivery's sample. A run-local read would report 3 + 4 = 7; the window -/// holds 2 + 3 + 4 = 9. #[test] fn a_window_at_a_later_run_reads_the_earlier_run() { let inner = grid(0, 1_000, 20); @@ -4756,10 +4008,6 @@ fn a_window_at_a_later_run_reads_the_earlier_run() { evaluator.finish().unwrap(); } -/// G: a fragmented prefix closed by an empty chunk equals the one-piece result. -/// -/// The prefix carries several runs, so it is a genuinely sparse delivery; the empty chunk only -/// ends the series. Delivering the same rows in one piece must give the same values. #[test] fn a_fragmented_prefix_closed_by_an_empty_chunk_equals_one_piece() { let outer = grid(0, 1_000, 8); @@ -4780,7 +4028,6 @@ fn a_fragmented_prefix_closed_by_an_empty_chunk_equals_one_piece() { "positions 0-1, 3 and 6 are three runs" ); - // One piece: the whole sparse series in one delivery. let mut one_piece = RangeEvaluator::try_new(&schema, outer.clone(), window, RangeFunction::LastOverTime) .unwrap(); @@ -4791,7 +4038,6 @@ fn a_fragmented_prefix_closed_by_an_empty_chunk_equals_one_piece() { .expect("the series completed"); one_piece.finish().unwrap(); - // A prefix, then the empty chunk that closes the series. let mut composed = RangeEvaluator::try_new(&schema, outer.clone(), window, RangeFunction::LastOverTime) .unwrap(); @@ -4843,50 +4089,8 @@ fn a_fragmented_prefix_closed_by_an_empty_chunk_equals_one_piece() { composed.finish().unwrap(); } -/// G: a series none of whose samples falls into any window produces nothing, so the only chunk it -/// hands out is the empty closing one. -#[test] -fn a_series_outside_every_window_closes_on_an_empty_chunk() { - let inner = grid(0, 1_000, 20); - let schema = Arc::new(SeriesSchema { - fields: raw_schema(1).fields.clone(), - eval_grid: Some(inner.clone()), - }); - // The one outer point sits at 0ms and its window looks back one step, so a sample at 15ms - // decides nothing. - let outer = grid(0, 1_000, 1); - let mut evaluator = RangeEvaluator::try_new( - &schema, - outer.clone(), - one_step_window(1_000), - RangeFunction::SumOverTime, - ) - .unwrap(); - let labels = Labels::from([("job".to_string(), "x".to_string())]); - let input = mixed_series( - &schema, - &labels, - &Points::from([(15, f64::to_bits(7.0))]), - &std::collections::BTreeMap::new(), - ) - .expect("position 15 holds a value"); - let chunks = evaluate_series(&mut evaluator, &input); - - assert_eq!(chunks.len(), 1, "the identity hands out one chunk"); - let closing = &chunks[0]; - assert!(closing.is_last, "the one chunk closes the series"); - assert!( - closing.series.time.is_empty(), - "nothing was decided, so the chunk carries no row: {:?}", - closing.series.time - ); - assert_eq!(chunks.iter().filter(|chunk| chunk.is_last).count(), 1); - evaluator.finish().unwrap(); -} - -/// G: two evaluators composed -- the first one's chunks fed into the second as its input -- agree -/// with the dense reference of the same two stages, and with handing the first stage's result to -/// the second in one piece. +/// Two chained evaluators, the first streaming its chunks into the second, agree with the dense +/// reference of both stages and with a one-piece hand-over. #[test] fn two_composed_evaluators_agree_with_the_dense_reference() { let inner = grid(0, 1_000, 24); @@ -4961,7 +4165,6 @@ fn two_composed_evaluators_agree_with_the_dense_reference() { let streamed = fold_chunks(&chunks, composed.output_schema()).expect("the series completed"); composed.finish().unwrap(); - // The one-piece form: stage one's result handed to a fresh stage two in a single delivery. let mut one_piece = RangeEvaluator::try_new( &input_schema, outer.clone(), @@ -5180,9 +4383,8 @@ fn smoothed_delta_with_histogram( Ok(chunks) } -/// The smoothed point at 61s is decided by the float at 61s, before a histogram at 62s inside its -/// extended window arrives. The histogram is still refused, however the input is chunked, rather -/// than refused in one chunk and swallowed after the point was handed over in another. +/// A histogram at 62s inside the extended window of the already decided point at 61s is refused +/// however the input is chunked. #[test] fn a_smoothed_window_refuses_a_histogram_whatever_the_chunking() { for one_chunk in [true, false] { @@ -5302,12 +4504,8 @@ fn histogram_chunk_with( .unwrap() } -/// `offset` moves a window's timestamps without moving the stored start timestamps, so a reset -/// check that reads the two on different axes answers differently for the same two samples. -/// -/// Both queries below read the window `{2s, 3s}` of the same series: the first because it is -/// evaluated at 3s, the second because `offset 2m` moves it there. A start timestamp of 2.5s on the -/// second sample lies inside that window on both, and a counter restart is what it means on both. +/// `offset` shifts sample timestamps but not stored start timestamps; the reset check must +/// compare them on one axis. Both queries read the same window `{2s, 3s}`. #[test] fn offset_does_not_change_the_counter_reset_a_window_reports() { let schema = raw_schema(1); @@ -5349,84 +4547,7 @@ fn offset_does_not_change_the_counter_reset_a_window_reports() { } } -/// A comparison over a histogram drops the positions it holds instead of failing the query. -/// -/// Prometheus compares float samples only, and the existing planner states the same rule by -/// answering no value for a histogram while recording an info (`NativeHistogramDrop`). The float -/// sample beside it in the same series still answers, which is what separates dropping a sample -/// from dropping the chunk. -#[test] -fn comparing_a_mixed_series_with_a_scalar_drops_only_the_histogram_positions() { - let schema = Arc::new(SeriesSchema { - fields: raw_schema(1).fields.clone(), - eval_grid: Some(grid(1_000, 2_000, 2)), - }); - // One field over two positions: a float at 1s and a histogram at 3s. - let mut histogram = FloatHistogram::try_from_view(&HistogramView { - schema: 0, - zero_threshold: 0.0, - zero_count: 0.0, - count: 7.0, - sum: 7.0, - reset_hint: CounterResetHint::Unknown, - start_timestamp: None, - custom_values: &[], - positive: BucketSideView { - span_offsets: &[0], - span_lengths: &[1], - buckets: &[7.0], - }, - negative: BucketSideView { - span_offsets: &[], - span_lengths: &[], - buckets: &[], - }, - }) - .unwrap(); - histogram.compact(); - let mut builder = GridSeriesBuilder::try_new(Arc::clone(&schema)).unwrap(); - builder.push(0, &[Some(2.0)]).unwrap(); - builder - .push_samples(1, &[Some(GridSample::Histogram(Box::new(histogram)))]) - .unwrap(); - let series = builder.finish(metric(0)).unwrap().unwrap(); - - let (output, dropped) = crate::map::map_compare_literal( - &schema, - &series, - crate::map::Comparison::Filter(crate::map::ComparisonOp::Greater), - crate::map::ScalarOperand::Right(0.0), - ) - .unwrap(); - assert!( - dropped, - "the histogram position was not reported as dropped" - ); - let output = output.expect("the float sample passed the filter"); - let kept = output - .time - .positions() - .filter_map( - |(point, row)| match output.fields.as_slice()[0].cursor().at(row) { - Some(SampleRef::Float(value)) => Some((point, value)), - _ => None, - }, - ) - .collect::>(); - assert_eq!( - kept, - vec![(0, 2.0)], - "only the float position survives the comparison" - ); -} - -/// `resets` counts the restarts the payload alone does not show, as the existing planner does. -/// -/// The existing planner's `NativeHistogramRangeFloatKind::Resets` counts three things: a gauge to -/// counter edge (a gauge does not continue a counter), a start timestamp inside the window (a -/// restarted counter whose counts already grew again), and the payload's own drop. Counting only -/// the payload makes an aggregate over `resets` answer 0 where the existing plan answers 1, which -/// is a regression: before this route admitted histograms the statement kept the existing plan. +/// `resets` counts a start timestamp inside the window as a restart even when the counts grew. #[test] fn resets_counts_a_start_timestamp_restart_the_counts_do_not_show() { let schema = raw_schema(1); @@ -5451,8 +4572,7 @@ fn resets_counts_a_start_timestamp_restart_the_counts_do_not_show() { } }; - // Counts grow from 6 to 7, so the payload shows no reset; the second sample's start of 2.5s - // lies inside the window, which is the restart the existing planner counts. + // Counts grow from 6 to 7, but the second sample's start of 2.5s lies inside the window. assert_eq!( resets(&[ histogram_chunk_hinted(&schema, 2_000, 6.0, CounterResetHint::Unknown, None, false), @@ -5469,10 +4589,8 @@ fn resets_counts_a_start_timestamp_restart_the_counts_do_not_show() { "a start timestamp inside the window is a reset even when the counts grew" ); - // The same counts across a gauge-to-counter edge: Prometheus counts no reset there, and the - // golden case `resets 25000 0` pins that. The existing planner counts one, so this is a place - // where the two routes deliberately differ — the golden decides, because reproducing the - // existing planner's count would make this route answer what Prometheus does not. + // A gauge-to-counter edge is no reset in Prometheus (golden case `resets 25000 0`), unlike + // the legacy planner. assert_eq!( resets(&[ histogram_chunk_hinted(&schema, 2_000, 6.0, CounterResetHint::Gauge, None, false), @@ -5507,12 +4625,8 @@ fn resets_counts_a_start_timestamp_restart_the_counts_do_not_show() { ); } -/// An `offset` that cancels a start timestamp onto zero must not turn it into "no start". -/// -/// A start of `0` on the stored histogram means the sender stated none, so the check reads it as -/// absent. Moving a real start forward by a negative offset could land it exactly on that marker: -/// 2500ms under `offset -2.5s` becomes 0. Restoring the sample times instead of moving the start -/// keeps the two meanings apart, which is what this pins. +/// A stored start of `0` means "no start". A real start of 2500ms under `offset -2.5s` lands on +/// 0 when shifted and must still read as a start. #[test] fn an_offset_that_cancels_a_start_timestamp_still_reads_it_as_a_reset() { let schema = raw_schema(1); @@ -5553,11 +4667,8 @@ fn an_offset_that_cancels_a_start_timestamp_still_reads_it_as_a_reset() { ); } -/// `irate` reads the counter reset its two points witness, start timestamps included. -/// -/// The existing planner's `idelta_value` is this query's oracle: it uses `detect_counter_reset`, -/// not the payload-only `detect_reset`. A restarted counter whose counts happen to grow again is -/// therefore a reset, and the answer is the last sample rather than their difference. +/// `irate` treats a start-timestamp restart as a reset and answers the last sample, as the +/// legacy planner's `idelta_value` does. #[test] fn irate_reads_a_reset_the_start_timestamp_witnesses() { let schema = raw_schema(1); @@ -5565,8 +4676,7 @@ fn irate_reads_a_reset_the_start_timestamp_witnesses() { &schema, grid(3_000, 1_000, 1), RangeWindow { - // The window `(2000, 3000]` holds both samples: `irate` reads the last two points of - // its window, so both have to be inside it. + // The window `(2000, 3000]` holds both samples. range_ms: 2_000, offset_ms: 0, anchor_ms: None, @@ -5594,12 +4704,7 @@ fn irate_reads_a_reset_the_start_timestamp_witnesses() { } } -/// A `rate` over gauge histograms reports the flavor warning into the collector the evaluator was -/// given. -/// -/// This is the warning the HTTP response is supposed to carry, checked at the point that decides -/// it rather than end to end: the kernel recording nothing and the channel losing it look the same -/// from an HTTP assertion, and only this test separates them. +/// A `rate` over gauge histograms records the flavor warning in the evaluator's collector. #[test] fn rate_over_gauge_histograms_records_the_flavor_warning() { let schema = raw_schema(1); diff --git a/src/promql/src/select.rs b/src/promql/src/select.rs index 50c66a33e16..3ef84b65ea0 100644 --- a/src/promql/src/select.rs +++ b/src/promql/src/select.rs @@ -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> { 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 = (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, Arc)>> = 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![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 = 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> = 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> { 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 { 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 { 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 { /// 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> { 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 { let must_be_set: Vec<&str> = matchers .iter() @@ -610,15 +567,10 @@ pub(crate) fn k_param(k: f64, series: usize) -> Result> { 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]) -> 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, Arc)], grouping: &Grouping) -> GroupKey { let mut key: Vec<_> = labels .iter() @@ -747,16 +698,12 @@ fn grid_points(schema: &SeriesSchema, series: &[Series]) -> Result { 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, 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 Result> { 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> { match sample { SampleRef::Missing => Ok(None), @@ -807,36 +744,30 @@ fn cursor_value(cursor: &mut RowCursor<'_>, row: usize) -> Result> { 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 = const { Cell::new(0) }; - /// Candidate pairs [`super::rank`] looked at on this thread. static RANKS: Cell = 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)) } diff --git a/src/promql/src/select/tests.rs b/src/promql/src/select/tests.rs index 8e739a9563c..8a2ba0506b1 100644 --- a/src/promql/src/select/tests.rs +++ b/src/promql/src/select/tests.rs @@ -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 { 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)> { 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 = (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 = (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)> = 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 = 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); diff --git a/src/promql/src/source.rs b/src/promql/src/source.rs index 8ad9c086964..39cfd2352db 100644 --- a/src/promql/src/source.rs +++ b/src/promql/src/source.rs @@ -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 { diff --git a/src/promql/src/source/merge.rs b/src/promql/src/source/merge.rs index 42a4ca434b6..0cee3695a1a 100644 --- a/src/promql/src/source/merge.rs +++ b/src/promql/src/source/merge.rs @@ -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) } diff --git a/src/promql/src/source/merge/tests.rs b/src/promql/src/source/merge/tests.rs index 1bbc927cbf0..cfba60c14db 100644 --- a/src/promql/src/source/merge/tests.rs +++ b/src/promql/src/source/merge/tests.rs @@ -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 diff --git a/src/promql/src/source/tests.rs b/src/promql/src/source/tests.rs index 366f27f62c6..e858fda752a 100644 --- a/src/promql/src/source/tests.rs +++ b/src/promql/src/source/tests.rs @@ -91,8 +91,8 @@ fn metadata(encoding: PrimaryKeyEncoding) -> Arc { 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::::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(), diff --git a/src/promql/src/vector_match.rs b/src/promql/src/vector_match.rs index f1c9e0db5a6..073f1b7acac 100644 --- a/src/promql/src/vector_match.rs +++ b/src/promql/src/vector_match.rs @@ -14,11 +14,10 @@ //! Vector–vector binary and set operations over evaluated series on one grid. //! -//! Semantics follow Prometheus `VectorBinop`, `VectorAnd`, `VectorOr` and `VectorUnless` -//! evaluated at every grid point. Series are processed whole, over their own grid ranges, and -//! the cardinality rules are checked per point: series sharing a match group only conflict at -//! points where both are present. Each field is matched on its own, as if the operands held -//! only that field; the results of all fields with one label set form one series. +//! Semantics follow Prometheus `VectorBinop`, `VectorAnd`, `VectorOr` and `VectorUnless` at every +//! grid point. Cardinality rules are checked per point: series sharing a match group conflict only +//! where both are present. Each field is matched on its own; the results of all fields with one +//! label set form one series. use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; @@ -42,29 +41,20 @@ use crate::map::{ArithmeticOp, ComparisonOp}; #[cfg(test)] mod tests; -// How many candidate pairs the binary kernel visited on this thread. -// -// Test-only, and per thread: the pairs a query considers are what says whether a series delivered in -// many chunks is still one candidate, and that is not visible in the result. A thread of its own -// keeps one test's chunks out of another test's figure, and the counter is compiled out of the -// kernel otherwise. +// Candidate pairs the binary kernel visited on this thread, so tests can check work that is not +// visible in the result. Per thread to isolate concurrent tests. #[cfg(test)] thread_local! { static VISITED_PAIRS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Resets the candidate-pair counter of this thread to zero. #[cfg(test)] pub(crate) fn reset_visited_pairs() { VISITED_PAIRS.with(|visited| visited.set(0)); } -/// The candidate pairs the binary kernel has visited on this thread since the last -/// [`reset_visited_pairs`]. -/// -/// A pair is visited once per one-side candidate the kernel looks up for a many-side series, before -/// the pairing's label set and axis intersection are built, so the count is what the kernel actually -/// does rather than what its operands' sizes imply it would. +/// Candidate pairs visited on this thread since [`reset_visited_pairs`]: one per one-side candidate +/// looked up for a many-side series. #[cfg(test)] pub(crate) fn visited_pairs() -> usize { VISITED_PAIRS.with(std::cell::Cell::get) @@ -96,9 +86,8 @@ pub enum BinaryKind { } impl BinaryOp { - /// The kernel operation this operator names. Every path that evaluates a binary operator over - /// two floats, the broadcast of a scalar and a constant fold included, reads it from here, so - /// they cannot disagree about which operator is which or about what it computes. + /// The kernel operation this operator names. Every float evaluation path, broadcast and + /// constant folding included, must go through this. #[inline] pub fn kind(self) -> BinaryKind { match self { @@ -223,15 +212,7 @@ pub fn binary_vectors( binary_vectors_inner(matching, lhs_schema, lhs, rhs_schema, rhs, None, None, None) } -/// [`binary_vectors`], handing the live workspace it holds to `reserve` as it allocates. -/// -/// What the operation will allocate cannot be known before it allocates: which series match each -/// other, where their axes overlap and which rows the operator keeps all come out of the operands -/// as they are read. So `reserve` receives the **total** live workspace the operation holds, and it -/// is asked at the three granularities [`Budget`] describes: where a long-lived result buffer grows, -/// once per phase, and in the blocks a growing result buffer is reserved in. It is never asked per -/// grid point or per row. A total `reserve` refuses ends the operation with that error, and what it -/// admitted stays the caller's to release. +/// The plan node and its shared duplicate-match evidence, for a binary operator that reports it. #[derive(Clone, Copy)] pub(crate) struct NodeEvidence<'a> { pub(crate) node: usize, @@ -244,6 +225,9 @@ struct FieldEvidence<'a> { evidence: &'a DuplicateEvidence, } +/// [`binary_vectors`], reporting its total live workspace to `reserve` at the granularities +/// [`Budget`] describes, never per point or row. A refusal fails the operation with that error; +/// releasing what was admitted is the caller's job. #[allow(clippy::too_many_arguments)] pub(crate) fn binary_vectors_with_reservation( matching: &BinaryMatching, @@ -268,8 +252,7 @@ pub(crate) fn binary_vectors_with_reservation( ) } -/// The one binary kernel: one walk, one lookup and one error order, whether or not a caller -/// accounts for the workspace. Every figure is reserved only when `budget` is held. +/// The binary kernel, with or without a budget. #[allow(clippy::too_many_arguments)] fn binary_vectors_inner( matching: &BinaryMatching, @@ -281,11 +264,7 @@ fn binary_vectors_inner( annotations: Option<&PromqlAnnotationCollector>, mut budget: Option<&mut Budget<'_>>, ) -> Result> { - // The grid both operands are evaluated on, checked before anything is reserved for them. let grid = same_grid(lhs_schema, rhs_schema)?; - // The fields paired by position and the descriptors they are handed back in: one result table - // per field, the field list both the results and the output schema keep, and the schema itself. - // The schema is what these bytes cover, so they are reserved before it is built. let width = lhs_schema.fields.len().min(rhs_schema.fields.len()); if let Some(budget) = budget.as_deref_mut() { budget.hold(output_bytes(width))?; @@ -311,51 +290,46 @@ fn binary_vectors_inner( annotations, budget.as_deref_mut(), )?; - // The field's flags, tables and sort are destroyed with its frame, so its phase ends here: - // what the field filed is what stays live, and the next field's phase is charged on its own. + // The field's working tables are dropped here; only its filed results stay live. if let Some(budget) = budget.as_deref_mut() { budget.phase(0)?; } fields.push(results); } earliest_error(errors)?; - // The merge is the operation's last phase: it enters its own figure from the results the fields - // filed, which is where every term of it is read. merge_fields(fields, output, budget) } -/// The capacity a fresh `Vec` holds: a first push allocates four entries, and a full one doubles. +/// The smallest non-zero capacity assumed when estimating the next growth of a `Vec`, or of the +/// one-to-one `HashSet` whose growth this approximates. const VEC_MIN_CAPACITY: usize = 4; -/// One label of a match key, charged twice because `group_key` grows its `Vec` by doubling. +/// One label of a match key, doubled for `Vec` growth slack. const KEY_LABEL_BYTES: usize = 2 * std::mem::size_of::<(Arc, Arc)>(); -/// One name of [`MatchingLabels`], which `result_metric` collects into a reference vector. The -/// vector is collected from an exact-size iterator, so its buffer holds one `&str` per name. +/// One name of [`MatchingLabels`] in the exact-size reference vector `result_metric` collects. const MATCHING_NAME_BYTES: usize = std::mem::size_of::<&str>(); -/// One entry of a match-group table, with the control byte and spare capacity it keeps. +/// One entry of a match-group table, doubled for control bytes and spare capacity. const GROUP_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, Vec)>(); -/// One entry of the one-to-one match set, charged the same way. +/// One entry of the one-to-one match set, doubled likewise. const MATCH_SLOT_BYTES: usize = 2 * std::mem::size_of::<(usize, usize)>(); -/// One entry of a field's result table, charged the same way. +/// One entry of a field's result table, doubled likewise. const RESULT_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, ResultRows)>(); -/// One row of a field's results: its point, its match group and its value. The three vectors grow -/// together, so one slot of each is what a row takes, and a block of the vectors is charged a row's -/// bytes per slot it grew by. +/// One row of a field's results: one slot each of the point, group and value vectors, which grow +/// together. const RESULT_ROW_BYTES: usize = 2 * std::mem::size_of::() + std::mem::size_of::>(); -/// One row while a label set is sorted: the old and the new copy of its point, group and value -/// vectors, and the row order the sort reads. The sort copies a label set's rows when they are not -/// already in order, so this is what one row costs while it runs. +/// One row while an unsorted label set is sorted: old and new copies of its point, group and value +/// slots, plus the order vector. const SORT_ROW_BYTES: usize = 4 * std::mem::size_of::() + 2 * std::mem::size_of::>(); -/// One row of the merge's table, charged the same way. +/// One row of the merge's table, doubled for spare capacity. const MERGE_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, (SeriesLabels, Vec<(usize, usize, GridSample)>))>(); @@ -368,36 +342,25 @@ pub(crate) const HISTOGRAM_ROW_BYTES: usize = 4 * std::mem::size_of::() /// The fixed text of one error message, around the label set it renders. const ERROR_TEXT_BYTES: usize = 256; -/// The bytes the operation's own descriptors cost: one result table per paired field, the field -/// list the results and the output schema each keep, and the schema struct. +/// Bytes of the per-field result tables and the output schema. fn output_bytes(fields: usize) -> usize { fields .saturating_mul(std::mem::size_of::() + 2 * std::mem::size_of::()) .saturating_add(std::mem::size_of::()) } -/// The live workspace a binary, set or `info` operation admits as it allocates, at three -/// granularities. +/// Turns the allocations of a binary, set or `info` operation into the total live workspace the +/// caller's `reserve` admits, charged at allocation boundaries rather than per value: /// -/// A resource limit belongs at an allocation boundary, not at a value: -/// -/// - [`Budget::hold`]: what the results keep until the operation returns -- rows, the label sets they -/// are filed under, the values boxed along them, the messages an error reports. Each is charged -/// where its container grows. -/// - [`Budget::phase`]: one figure for the workspace of one walk, read from the operands before it -/// allocates and replacing the phase before it, so the total is the phase being run beside what is -/// held and never the sum of every phase. -/// - [`Budget::grow`]: a block a container of that phase took when it outgrew what it held. -/// -/// It exists because the caller is handed a *total*, and this turns those figures into that total. +/// - [`Budget::hold`]: results kept until the operation returns. +/// - [`Budget::phase`]: the workspace of one walk, estimated up front and replacing the previous +/// phase. +/// - [`Budget::grow`]: a block a container of the current phase took when it outgrew its capacity. pub(crate) struct Budget<'a> { - /// Admits the live workspace, or refuses it. reserve: &'a mut dyn FnMut(usize) -> Result<()>, - /// The bytes the results keep until the operation returns. held: usize, - /// The bytes of the phase being run, beside what is held. phase: usize, - /// The total handed to `reserve` last, so an unchanged one is not asked for twice. + /// The last total passed to `reserve`, to skip asking again for the same figure. requested: Option, } @@ -417,20 +380,19 @@ impl<'a> Budget<'a> { self.admit() } - /// Admits `bytes` as the whole workspace of the phase being run, replacing the phase before it. + /// Sets the current phase's workspace to `bytes`, replacing the previous phase. pub(crate) fn phase(&mut self, bytes: usize) -> Result<()> { self.phase = bytes; self.admit() } - /// Adds `bytes` to the phase for a container of it that has outgrown what was reserved. + /// Adds `bytes` to the current phase. pub(crate) fn grow(&mut self, bytes: usize) -> Result<()> { self.phase = self.phase.saturating_add(bytes); self.admit() } - /// Hands the live total to `reserve` when it differs from the last one. It falls as well as - /// rises, and only a repeated figure is left out. + /// Passes the live total, which may fall as well as rise, to `reserve` unless it is unchanged. fn admit(&mut self) -> Result<()> { let total = self.held.saturating_add(self.phase); if self.requested != Some(total) { @@ -441,29 +403,22 @@ impl<'a> Budget<'a> { } } -/// The figures one field's phases are charged from, read once from its operands. +/// The byte figures one field's phases are charged from, read once from its operands. #[derive(Default)] struct FieldMetadata { - /// The presence flags and the one side's match groups. + /// Three presence flags per grid point and the one side's match groups. tables: usize, - /// The allowance for the messages the field can report, which its sort reserves before it knows - /// which of them it appends; only the ones it writes are kept. + /// An allowance for the at most three messages the field can report. errors: usize, /// The largest key a row of the field is filed under. largest_key: usize, - /// The widest pairing's label set and the histogram workspace one row of the walk reads. + /// The widest pairing's label set and one row's histogram workspace. pairing: usize, } -/// The figures one field's phases are charged from. -/// -/// The presence of each side and of the points both are present at are three flags per grid point; -/// the one side's groups are a key, the values `on(...)` matching copies and a member list per -/// series; one series of the many side is looked up by a key of its own; and a field reports at most -/// three messages, each a fixed frame around one rendering. The duplicate scan's list is not part of -/// these tables: a group of one member collects nothing, and a wider group's list is charged by -/// [`overlap`] as it grows. The pairing's own terms are read from the widest series of each side -/// rather than from every pair, since one pairing's label set replaces the one before it. +/// Computes [`FieldMetadata`]. The duplicate scan's list is charged separately by [`overlap`]. The +/// pairing figure comes from the widest series of each side, since each pairing's scratch replaces +/// the previous one. fn field_metadata_bytes( matching: &BinaryMatching, include: &[Arc], @@ -487,8 +442,7 @@ fn field_metadata_bytes( lookup = lookup.max(match_key_bytes(&series.metric, &matching.labels)); largest_key = largest_key.max(result_key_bytes(&series.metric)); } - // A result label set carries the many side's labels and the `group_*` ones copied into it, so - // the widest rendering over both operands bounds the text an error writes. + // The widest rendering over both operands, plus the `group_*` labels, bounds an error's text. let include_text = include.iter().fold(0usize, |bytes, name| { bytes.saturating_add(name.len()).saturating_add(6) }); @@ -499,8 +453,6 @@ fn field_metadata_bytes( .fold(include_text, |bytes, series| { bytes.max(label_text_bytes(&series.metric).saturating_add(include_text)) }); - // The widest series of each side: one pairing's label set replaces the one before it, so the - // widest is what the phase holds at its peak. let pairing = widest_metric(many) .zip(widest_metric(one)) .map_or(0, |(many, one)| pair_bytes(many, one, matching, include)); @@ -512,8 +464,7 @@ fn field_metadata_bytes( } } -/// The series of `operand` with the most labels: the widest label set one pairing of its field can -/// build. +/// The series of `operand` with the most labels. fn widest_metric<'a>(operand: &'a Operand<'_>) -> Option<&'a SeriesLabels> { operand .series @@ -522,26 +473,16 @@ fn widest_metric<'a>(operand: &'a Operand<'_>) -> Option<&'a SeriesLabels> { .max_by_key(|metric| metric.tags().len()) } -/// The bytes one pairing allocates before it files a row: the result label set `result_metric` -/// rewrites, the `group_*` labels it copies in, the reference vector it collects the matching label -/// names into, and the key its rows are looked up by. -/// -/// Each rewrite filters the tag list into a `Vec` and turns that into a shared slice, so the list it -/// replaces is alive while two copies of the new one are built, and an included label the many side -/// does not carry is inserted, which costs its descriptor too. The matching names are collected into -/// a reference vector of their own before the rewrite, for `on(...)` and `ignoring(...)` alike and -/// whether or not the series carries them. This is one pairing's scratch: the next pairing replaces -/// it, and a pairing whose axes share no position still pays it, because the label set is built -/// before the axes are intersected. +/// The scratch one pairing allocates before it files a row: the result label set `result_metric` +/// builds (the old list alive beside two copies of the new one), the copied `group_*` labels, the +/// matching-name vector, and the row key. Paid even when the axes share no position, because the +/// label set is built before the axes are intersected. fn pair_bytes( many: &SeriesLabels, one: &SeriesLabels, matching: &BinaryMatching, include: &[Arc], ) -> usize { - // The label list each rewrite builds and the one it replaces, then the key `key_of` builds for - // a row: every label with a value and the name, each charged twice for the growth of the key's - // `Vec`, and the name string it copies. let labels = 3usize .saturating_mul(many.tags().len().saturating_add(include.len())) .saturating_mul(std::mem::size_of::