From 43856a7dbf34ea0f58af2d37805baeb4deaa8736 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:47:15 +0800 Subject: [PATCH] refactor(promql): simplify native execution memory estimates Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- .../src/histogram_eval/float_histogram.rs | 14 +- src/promql/src/native/execute.rs | 955 +++++------------- src/promql/src/native/execute/tests.rs | 718 ++++--------- src/promql/src/range_eval.rs | 190 ++-- src/promql/src/range_eval/tests.rs | 118 ++- 5 files changed, 658 insertions(+), 1337 deletions(-) diff --git a/src/promql/src/histogram_eval/float_histogram.rs b/src/promql/src/histogram_eval/float_histogram.rs index 30147d01645..acce48c1776 100644 --- a/src/promql/src/histogram_eval/float_histogram.rs +++ b/src/promql/src/histogram_eval/float_histogram.rs @@ -80,18 +80,10 @@ impl FloatHistogram { }) } - /// The bytes this histogram's own heap buffers hold, by capacity. + /// Estimates the heap held by the bucket lists, custom bounds and preserved span layout. /// - /// Everything a histogram keeps besides its scalars is on the heap: the bucket lists of both - /// sides, the custom bounds, and the span layout of a histogram read from a view, with the - /// `[Vec; 2]` array that holds the two layout vectors. No scalar of the struct shows any of it: - /// a histogram of 4096 positive buckets is 64 KiB of buckets, and a window that retains one - /// histogram per grid point retains that much per point. - /// - /// The layout array is stored inline in the histogram, so a ledger charging - /// `size_of::()` per slot already pays for those 48 bytes. Counting the whole - /// footprint as one figure here costs a header of over-estimate on a reservation, against a - /// payload of tens of kilobytes that would otherwise be missing from it entirely. + /// 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. pub(crate) fn heap_bytes(&self) -> usize { fn buckets(side: &Buckets) -> usize { side.capacity() * std::mem::size_of::<(i32, f64)>() diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index b1e2afe9a28..ada6cbe323c 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -15,9 +15,9 @@ //! Running a bound tree, node by node. //! //! [`NativeExecutionState`] owns the run-time state one execution of a [`NativeTree`] needs, keyed -//! by the position [`metrics::walk`] gives each node. The tree is what the compiler produced and -//! carries no state of its own, so a second execution builds a second state from the same tree and -//! the two never share a buffer, an evaluator or a memory reservation. +//! by the position [`crate::native::metrics::walk`] gives each node. The tree is what the compiler +//! produced and carries no state of its own, so a second execution builds a second state from the +//! same tree and the two never share a buffer, an evaluator or a memory reservation. //! //! [`NativeExecutor`] drives that state one chunk at a time. Nodes hand each other //! [`EvaluatedChunk`]s: a source hands over raw samples, and everything above a window hands over @@ -62,8 +62,8 @@ use datatypes::series::{MetricName, SeriesOrdering}; use crate::grid_series::{LabelSet, label_set}; use crate::map::{MathOp, drop_metric_name, map_math}; use crate::native::batch::EvaluatedChunk; -use crate::native::metrics::{self, NodeMetrics, NodePath}; -use crate::native::plan::{BoundWindow, NativeExpr, NativeTree}; +use crate::native::metrics::{NodeMetrics, NodePath}; +use crate::native::plan::{NativeExpr, NativeTree}; use crate::range_eval::RangeEvaluator; #[cfg(test)] @@ -110,232 +110,18 @@ impl NativeChunk { } } - /// The bytes this chunk holds, counting each shared allocation it references that `charged` has - /// not met yet. - fn bytes(&self, charged: &mut ChargedAllocations) -> usize { + /// An estimate of the bytes this chunk holds. + /// + /// It is what the chunk alone stands for, so a buffer or a histogram table two chunks share is + /// counted once per chunk. That over-count is the price of a figure that costs one pass over + /// the chunk it names and keeps no state between chunks; it is bounded by the number of queued + /// chunks, not by the data they carry together. + fn bytes(&self) -> usize { match self { - Self::Raw(chunk) => raw_bytes(chunk, charged), - Self::Evaluated(chunk) => evaluated_bytes(chunk, charged), + Self::Raw(chunk) => raw_bytes(chunk), + Self::Evaluated(chunk) => evaluated_bytes(chunk), } } - - /// The bytes this chunk occupies on its own, which no other chunk holds a reference to. - /// - /// It is the struct term of [`Self::bytes`] and nothing else: everything beside it is a buffer or - /// a histogram table, which a sibling chunk of the series can share and which the queue counts - /// per allocation rather than per chunk. - fn own_bytes(&self) -> usize { - match self { - Self::Raw(_) => std::mem::size_of::(), - Self::Evaluated(_) => std::mem::size_of::(), - } - } -} - -/// The shared allocations one accounting pass has already counted. -/// -/// A chunk holds very little of what it costs: a field of native histograms holds no floats at all, -/// only indices into an immutable `Arc` table, and both that table and the buffers -/// behind the field's Arrow arrays are batch-wide allocations that a chunk can hold a slice of. Two -/// chunks of one series can share one table by cloning the `Arc`, and both can hold sibling slices -/// of one buffer, so a pass counts an allocation the first time it meets it. Charging it per -/// referencing chunk instead would make the reservation grow with the number of chunks a node holds -/// rather than with the data in them -- the figure the pool has to rank. -/// -/// One pass walks one chunk, so the list stays as short as the allocations that chunk met and is -/// dropped with the pass; nothing outlives the call it was made for. The queue of one node is not -/// recounted by such a pass: [`QueuedCharge`] folds a chunk in as it enters and out as it leaves, -/// carrying the same dedupe across the queue. -#[derive(Default)] -struct ChargedAllocations { - /// The address of every histogram table this pass has counted, with the bytes it contributes. - tables: Vec<(*const HistogramBatch, usize)>, - /// The address of every Arrow buffer this pass has counted, with the bytes it contributes. - buffers: Vec<(*const u8, usize)>, -} - -impl ChargedAllocations { - /// The bytes `table` holds, or zero when this pass has already counted it. - fn table(&mut self, table: &Arc) -> usize { - let address = Arc::as_ptr(table); - if self.tables.iter().any(|(counted, _)| *counted == address) { - return 0; - } - // The batch struct holds the struct array and the column arrays beside it, which are views - // of that array's children: the array reports the buffers of all of them, once. - let bytes = std::mem::size_of::() - .saturating_add(table.as_arrow().get_array_memory_size()); - self.tables.push((address, bytes)); - bytes - } - - /// The bytes the allocation `buffer` is a slice of, or zero when this pass has already counted - /// it. - /// - /// The capacity is the whole allocation, which is what a slice keeps alive: a key of a few - /// bytes sliced out of a decoded dictionary values buffer pins that buffer. A buffer that owns - /// no memory of its own reports no capacity, and then the bytes it shows are all there is. - fn buffer(&mut self, buffer: &Buffer) -> usize { - let address = buffer.data_ptr().as_ptr().cast_const(); - if self.buffers.iter().any(|(counted, _)| *counted == address) { - return 0; - } - let bytes = buffer.capacity().max(buffer.len()); - self.buffers.push((address, bytes)); - bytes - } - - /// The bytes the buffers of one Arrow array hold. - fn array(&mut self, array: &dyn Array) -> usize { - let data = array.to_data(); - let values = data.buffers().iter().fold(0usize, |total, buffer| { - total.saturating_add(self.buffer(buffer)) - }); - // The validity bitmap is not one of `buffers`: a field of a series with a missing sample - // carries one, and it is an allocation like any other. - let nulls = data - .nulls() - .map_or(0, |nulls| self.buffer(nulls.inner().inner())); - values.saturating_add(nulls) - } -} - -/// The bytes the chunks one node queues hold, kept as chunks enter and leave the queue. -/// -/// A node is asked for its queue's figure on every enqueue and every pop, and the queue can hold a -/// whole series at once, for a caller that pushes a series before pulling it. Recounting the queue -/// with a [`ChargedAllocations`] pass each time is one pass over every queued chunk per operation, -/// which is quadratic in the chunks that caller queues. What is kept here instead is a count per -/// shared allocation, with the bytes that allocation contributes and the running total they add up -/// to, so an operation walks only the allocations of the one chunk it names. -/// -/// The dedupe is the one [`ChargedAllocations`] makes inside a chunk, carried across the queue. It -/// is per queued chunk that references an allocation, not per field or per segment that does: the -/// chunk is walked with one pass, so a chunk whose two fields index one table is one reference to -/// it, and the walk a pop makes of the same chunk meets the same references. A chunk is therefore -/// charged its own struct once, and an allocation once for as long as at least one queued chunk -/// references it -- the figure a whole-queue pass would give, without the pass. -#[derive(Default)] -struct QueuedCharge { - /// Every histogram table the queued chunks reference, by address, with how many queued chunks - /// reference it and the bytes it contributes to the total while at least one does. - tables: HashMap, - /// Every Arrow buffer the queued chunks reference, likewise: two chunks of one series hold - /// sibling slices of one buffer, and the address of the allocation is what makes them one. - buffers: HashMap, - /// What the queued chunks hold: their own structs, and the allocations above added once each. - /// This is what the node reserves for its queue. - bytes: usize, - /// How many chunks the accounting has walked, test-only. - /// - /// An enqueue or a pop walks the chunk it names, so this grows by one per operation whatever - /// the queue holds. A figure recounted from the whole queue would grow with the depth of the - /// queue, which is what a test refuses. - #[cfg(test)] - walked: usize, -} - -/// How many queued chunks reference one shared allocation, and the bytes it contributes while at -/// least one of them does. -#[derive(Clone, Copy)] -struct Counted { - chunks: usize, - bytes: usize, -} - -impl QueuedCharge { - /// Counts the allocations `chunk` references, as that chunk enters the queue, and returns the - /// queue's new total. - fn enqueue(&mut self, chunk: &NativeChunk) -> usize { - let charged = self.walk(chunk); - // The struct a chunk is held by is its own; only what it points at can be shared. - self.bytes = self.bytes.saturating_add(chunk.own_bytes()); - for &(table, bytes) in &charged.tables { - count_reference(&mut self.tables, &mut self.bytes, table as usize, bytes); - } - for &(buffer, bytes) in &charged.buffers { - count_reference(&mut self.buffers, &mut self.bytes, buffer as usize, bytes); - } - self.bytes - } - - /// Gives the allocations `chunk` references back, as that chunk leaves the queue, and returns - /// the queue's new total. - /// - /// An allocation another queued chunk still references stays charged: only the last reference - /// takes its bytes out, which is what keeps a shared table counted once for as long as the - /// queue holds it. - fn pop(&mut self, chunk: &NativeChunk) -> usize { - let charged = self.walk(chunk); - self.bytes = self.bytes.saturating_sub(chunk.own_bytes()); - for &(table, _) in &charged.tables { - drop_reference(&mut self.tables, &mut self.bytes, table as usize); - } - for &(buffer, _) in &charged.buffers { - drop_reference(&mut self.buffers, &mut self.bytes, buffer as usize); - } - self.bytes - } - - /// The shared allocations one chunk references, each met once. - /// - /// The pass is over `chunk` alone: what the queue holds is folded in from the allocations the - /// pass met rather than recounted by walking the queue. The same chunk walked again meets the - /// same addresses, which is what makes the subtraction on the way out match the addition on the - /// way in. - fn walk(&mut self, chunk: &NativeChunk) -> ChargedAllocations { - let mut charged = ChargedAllocations::default(); - // The figure this sums is the chunk's own; the queue needs the allocations behind it, which - // `charged` now holds. - let _ = chunk.bytes(&mut charged); - #[cfg(test)] - { - self.walked += 1; - } - charged - } -} - -/// Counts one more reference to the allocation at `address`, which contributes `bytes`, and adds -/// those bytes to `total` when the queue did not already hold it. -fn count_reference( - counts: &mut HashMap, - total: &mut usize, - address: usize, - bytes: usize, -) { - let entry = counts - .entry(address) - .or_insert(Counted { chunks: 0, bytes }); - if entry.chunks == 0 { - // The first chunk to meet the allocation is what makes the queue pay for it: a chunk - // sharing it afterwards adds a reference, not bytes. - *total = total.saturating_add(entry.bytes); - } - entry.chunks += 1; -} - -/// Gives one reference to the allocation at `address` back, and takes its bytes out of `total` when -/// it was the last one, so a queue that emptied leaves no entry and no bytes behind. -fn drop_reference(counts: &mut HashMap, total: &mut usize, address: usize) { - let last = match counts.get_mut(&address) { - // The chunk entered the queue before it left it, so one leaving cannot reach zero while - // another chunk of the queue still references the allocation. - Some(entry) if entry.chunks > 1 => { - entry.chunks -= 1; - false - } - Some(_) => true, - // Every chunk that leaves was queued, so its allocations were counted on the way in. An - // address missing here is exactly the asymmetry that would leak or undercharge silently. - None => { - debug_assert!(false, "the queue released an allocation it never counted"); - false - } - }; - if last && let Some(entry) = counts.remove(&address) { - *total = total.saturating_sub(entry.bytes); - } } /// The bytes a raw chunk holds: its identity, its timestamps and the Arrow buffers behind its @@ -343,55 +129,66 @@ fn drop_reference(counts: &mut HashMap, total: &mut usize, addre /// /// The figure is what the chunk keeps alive rather than one float per field and row: a histogram /// field holds no floats at all, only indices into the table its samples live in. -fn raw_bytes(chunk: &RawSeriesChunk, charged: &mut ChargedAllocations) -> usize { +fn raw_bytes(chunk: &RawSeriesChunk) -> usize { std::mem::size_of::() - .saturating_add(charged.buffer(&chunk.primary_key)) - .saturating_add(charged.buffer(chunk.time.as_buffer().inner())) - .saturating_add(fields_bytes(&chunk.fields, charged)) + .saturating_add(buffer_bytes(&chunk.primary_key)) + .saturating_add(chunk.metric.as_ref().map_or(0, metric_bytes)) + .saturating_add(buffer_bytes(chunk.time.as_buffer().inner())) + .saturating_add(fields_bytes(&chunk.fields)) } /// The bytes an evaluated chunk holds: its struct and the Arrow buffers behind its fields. /// -/// The figure is what the chunk keeps alive rather than one float per field and decided position: -/// a histogram field holds no floats at all, only indices into the table its samples live in. The -/// grid itself is shared by every chunk addressed on it, so it is not counted per chunk. -fn evaluated_bytes(chunk: &EvaluatedChunk, charged: &mut ChargedAllocations) -> usize { - std::mem::size_of::() - .saturating_add(fields_bytes(&chunk.series.fields, charged)) +/// The grid is shared by every chunk addressed on it, so it is not counted per chunk. +fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize { + std::mem::size_of::().saturating_add(fields_bytes(&chunk.series.fields)) } /// The bytes the fields of a chunk hold: the sample buffers of every segment, and the histogram /// tables those segments reference. -fn fields_bytes(fields: &SeriesFields, charged: &mut ChargedAllocations) -> usize { +fn fields_bytes(fields: &SeriesFields) -> usize { fields .iter() .map(|field| { - field - .segments() - .iter() - .map(|segment| segment_bytes(segment, charged)) - .fold(0usize, usize::saturating_add) + field.segments().iter().fold(0usize, |total, segment| { + total.saturating_add(segment_bytes(segment)) + }) }) .fold(0usize, usize::saturating_add) } /// The bytes one dense segment of samples holds. -fn segment_bytes(segment: &Samples, charged: &mut ChargedAllocations) -> usize { +fn segment_bytes(segment: &Samples) -> usize { match segment.dense() { - Some(DenseSamplesRef::Float(values)) => charged.array(values), - Some(DenseSamplesRef::Histogram(histograms)) => charged - .array(histograms.indices()) - .saturating_add(charged.table(histograms.batch())), - Some(DenseSamplesRef::Mixed(mixed)) => charged - .array(mixed.floats()) - .saturating_add(charged.array(mixed.histograms().indices())) - .saturating_add(charged.table(mixed.histograms().batch())), - // `segments` hands out dense segments only, so a nested chunk never reaches here; one that - // somehow did is charged for the descriptor alone rather than for buffers it nests. + Some(DenseSamplesRef::Float(values)) => values.get_array_memory_size(), + Some(DenseSamplesRef::Histogram(histograms)) => histograms + .indices() + .get_array_memory_size() + .saturating_add(table_bytes(histograms.batch())), + Some(DenseSamplesRef::Mixed(mixed)) => mixed + .floats() + .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. None => 0, } } +/// The bytes one histogram table holds: the batch struct and the arrays its columns view. +fn table_bytes(table: &Arc) -> usize { + std::mem::size_of::().saturating_add(table.as_arrow().get_array_memory_size()) +} + +/// The bytes the allocation `buffer` is a slice of. +/// +/// The capacity is the whole allocation, which is what a slice keeps alive: a key of a few bytes +/// sliced out of a decoded dictionary values buffer pins that buffer. A buffer that owns no memory +/// of its own reports no capacity, and then the bytes it shows are all there is. +fn buffer_bytes(buffer: &Buffer) -> usize { + buffer.capacity().max(buffer.len()) +} + /// Which node kinds the runtime executes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum NodeTag { @@ -414,31 +211,11 @@ impl NodeTag { } } -/// The operation a node binds, kept aside until the whole tree has been visited. -/// -/// A window's evaluator needs its input's schema, and the input is visited after the window, so -/// the binding is collected first and the run-time state is built from the complete set. -enum Seed { - Input, - Window(BoundWindow), - Map(Arc<[MathOp]>), -} - -/// One visited node, before its input's position is resolved. -struct PendingNode { - tag: NodeTag, - path: NodePath, - metrics: Arc, - /// What this node produces, when it produces samples. - output_schema: Option>, - seed: Seed, -} - /// One node of the flattened tree. #[derive(Clone, Copy, Debug)] struct NodeSpec { tag: NodeTag, - /// The position of this node's input, resolved from the tree's own positions. + /// The index of this node's input, which is the node the build pass reaches next. input: Option, } @@ -446,12 +223,11 @@ struct NodeSpec { /// /// The reservation is the pool's, so a node that buffers input competes with every other operator /// in the query; the metrics report the same figure so a slow node can be told apart from a wide -/// one. +/// one. The reservation is also the figure itself: a node holds nothing beside what it reserved, so +/// a gauge reads its size rather than a copy that could drift from it. struct NodeBuffer { metrics: Arc, reservation: MemoryReservation, - /// The bytes `reservation` holds, mirrored so a chunk leaving returns exactly them. - held: usize, } impl NodeBuffer { @@ -461,35 +237,43 @@ impl NodeBuffer { Self { metrics, reservation: consumer.register(pool), - held: 0, } } - /// Reserves the bytes of a chunk this node starts holding. - fn hold(&mut self, bytes: usize) -> Result<()> { + /// Reserves `bytes` beside what this node already holds. + fn grow(&mut self, bytes: usize) -> Result<()> { self.reservation.try_grow(bytes)?; - self.held += bytes; - self.metrics.record_reserved_bytes(self.held); + self.record(); Ok(()) } /// Reserves exactly `bytes`, which is what this node holds from now on. /// - /// A node that consumes its input chunk by chunk what it holds afterwards is not the sum of - /// what it consumed, so the reservation is set from the state that is left rather than grown - /// per chunk. - fn hold_exactly(&mut self, bytes: usize) -> Result<()> { + /// What a node that consumes its input chunk by chunk holds afterwards is not the sum of what + /// it consumed, so the reservation is set from the state that is left rather than grown per + /// chunk. + fn resize(&mut self, bytes: usize) -> Result<()> { self.reservation.try_resize(bytes)?; - self.held = bytes; - self.metrics.record_reserved_bytes(bytes); + self.record(); Ok(()) } + /// Gives `bytes` of what this node holds back to the pool. + fn shrink(&mut self, bytes: usize) -> Result<()> { + self.reservation.try_shrink(bytes)?; + self.record(); + Ok(()) + } + + /// Reports what this node now reserves. + fn record(&self) { + self.metrics.record_reserved_bytes(self.reservation.size()); + } + /// Returns every byte this node holds to the pool. fn release(&mut self) { - self.held = 0; self.reservation.free(); - self.metrics.record_reserved_bytes(0); + self.record(); } } @@ -525,13 +309,28 @@ impl Run { #[derive(Default)] struct Emitted { sets: HashMap, - /// The bytes the entries in `sets` hold, kept as a running total. + /// How many run vectors, runs and label payload bytes every entry holds, counted as the entries + /// change rather than by walking them. /// - /// A node records every label set it has ever handed out and must charge for all of them, so - /// the figure is read after every output. Recomputing it there walks every entry recorded so - /// far, which is quadratic over a series that keeps producing label sets; folding one entry's - /// change in as it happens keeps the read constant. - entries: usize, + /// A node records every label set it has ever handed out and charges for all of them, so the + /// figure is read after every output; walking the table there would cost a pass over every entry + /// recorded so far for each output. Folding one entry's change in as it happens keeps the read + /// constant, and the update is the shape of the change itself: a vector's length before and + /// after [`absorb`], one vector per field a history gains, and one terminal pass over a closing + /// history's vector lengths. + counts: Counts, +} + +/// What the entries of an [`Emitted`] table hold, as running totals. +#[derive(Default)] +struct Counts { + /// The run vectors, one per field of one entry. + vectors: usize, + /// The occupied runs in every vector. + runs: usize, + /// The payload of every label set and of every owner: the bytes of their names and values with + /// one row per label. + payload: usize, } /// What one node has handed out under one output label set. @@ -549,10 +348,6 @@ struct History { owner: Option, /// Whether the series on this label set closed. A second series cannot close it again. closed: bool, - /// The heap this entry owns: the runs its per-field vectors hold and the owner's name and tags, - /// kept current by [`Emitted::occupy`]. The header and the slot it sits in are charged by the - /// table's capacity. - bytes: usize, } impl History { @@ -594,22 +389,6 @@ fn metric_bytes(metric: &MetricName) -> usize { .sum::() } -/// The bytes a history holds: the per-field vectors, the runs in them and its owner. -/// -/// This is what the entry itself allocates, not the slot it is filed under: the `History` lives in -/// the map's slot, and that slot is what [`Emitted::bytes`] charges with the table's capacity. A -/// `size_of::()` term here billed every entry one header for a value it does not own, -/// once in this figure and again in the slot term beside it. -fn history_bytes(history: &History) -> usize { - history.fields.capacity() * std::mem::size_of::>() - + history - .fields - .iter() - .map(|runs| runs.capacity() * std::mem::size_of::()) - .sum::() - + history.owner.as_ref().map_or(0, metric_bytes) -} - impl Emitted { /// Records what `chunk` occupies, rejecting it against what this node already handed out. /// @@ -678,69 +457,61 @@ impl Emitted { return Ok(()); } let fields = chunk.series.fields.len(); - // The change is folded in here rather than recomputed when the figure is read: a node - // keeps every label set it has ever handed out, so a fresh walk after each output costs a - // pass over the whole table for a table that only ever grows. let history = match self.sets.entry(labels) { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => { - self.entries += label_bytes(entry.key()); + self.counts.payload += label_bytes(entry.key()); entry.insert(History::default()) } }; - let before = history.bytes; // The series that contributes the values is the one that owns the label set, so a chunk of // another one cannot close it later on. if !empty && let Some(source) = source && history.owner.as_ref() != Some(source) { + self.counts.payload = self + .counts + .payload + .saturating_sub(history.owner.as_ref().map_or(0, metric_bytes)) + .saturating_add(metric_bytes(source)); history.owner = Some(source.clone()); } if history.fields.len() < fields { + self.counts.vectors += fields - history.fields.len(); history.fields.resize_with(fields, Vec::new); } for (index, runs) in occupied.into_iter().enumerate() { - absorb(&mut history.fields[index], &runs); + let stored = &mut history.fields[index]; + let before = stored.len(); + absorb(stored, &runs); + self.counts.runs = self.counts.runs - before + stored.len(); } if chunk.is_last { history.closed = true; // No later chunk reads these runs: a closed label set refuses every series that would // use them. Keeping them charges the pool for a series that has already been answered. + self.counts.runs -= history.fields.iter().map(Vec::len).sum::(); + self.counts.vectors -= history.fields.len(); history.fields = Vec::new(); } - let after = history_bytes(history); - history.bytes = after; - self.entries = self.entries - before + after; Ok(()) } /// An estimate of the bytes this table holds, which the node reserves for. /// - /// It counts each label's name and value bytes with a tuple per label, the runs a history keeps - /// in its per-field vectors, the owner each entry keeps with its name and tags, and the table's - /// capacity at one label-set slot plus one history slot per entry -- which is where a `History` - /// header itself is charged, once, for the entry that lives in it. It leaves out the map's - /// buckets and the `Arc` headers of the strings it shares, so it is a lower bound rather than a - /// measurement. - /// - /// The per-entry part is a running total, so reading this after every output does not walk the - /// table: only the entry that changed and the table's own capacity are read here. + /// It counts one label-set slot and one history header per entry, one vector per field of a + /// history, the runs in those vectors, and the payload of every label set and owner. Each of + /// those is a running total, so the figure is read in constant time however many series the node + /// has handed out; it leaves out the map's buckets, the slack of a vector's capacity and the + /// `Arc` headers of the strings it shares, so it is an approximation rather than a measurement. fn bytes(&self) -> usize { - self.entries - + self.sets.capacity() - * (std::mem::size_of::() + std::mem::size_of::()) - } - - /// The same figure by walking every entry, used by a test to keep the running total honest. - #[cfg(test)] - fn bytes_recomputed(&self) -> usize { - self.sets - .iter() - .map(|(labels, history)| label_bytes(labels) + history_bytes(history)) - .sum::() - + self.sets.capacity() - * (std::mem::size_of::() + std::mem::size_of::()) + let slots = + self.sets.len() * (std::mem::size_of::() + std::mem::size_of::()); + slots + + self.counts.vectors * std::mem::size_of::>() + + self.counts.runs * std::mem::size_of::() + + self.counts.payload } } @@ -934,88 +705,15 @@ struct MapRuntime { schema: Arc, } -/// What a window node holds. -struct WindowRuntime { - /// This window's own evaluator, with its own input and output grid; `None` once closed. - evaluator: Option, -} - -impl WindowRuntime { - /// The run-time state of the window `op`, reading the samples of `input`. - fn try_new(input: &SeriesSchema, op: &BoundWindow) -> Result { - // One evaluator per window, with the grids the node was bound to: the output grid is the - // node's own grid, which is also the grid its chunks are addressed on. - let evaluator = - RangeEvaluator::try_new(input, Arc::clone(&op.output_grid), op.window, op.function)?; - Ok(Self { - evaluator: Some(evaluator), - }) - } - - /// The bytes this window's charge accounts for, as its evaluator's storage stands now. - /// - /// Between pushes this is the accounted retained size: the sample buffers the evaluator keeps - /// per field, by capacity, with the payload of every native histogram they retain, the row a - /// push fills with the histograms it boxes, the pending batch's inner vectors, and the identity - /// payload of the series still open -- the allocation behind its primary key, not the bytes the - /// key shows. It is a lower bound on what is held, not a measurement of it. - /// - /// The kernel's scratch is left out, being a constant factor of the window samples already - /// counted. The `Emitted` table's own map overhead and the `Arc` headers of the strings it - /// shares are charged for beside this figure rather than inside it. Of the pending batch only - /// the inner vectors are counted, not the outer `spans` and `columns` that hold them. - /// - /// During a push the evaluator also holds the incoming chunk, which the caller charges while - /// the call runs; vector growth during a push is not reserved at all, and is not bounded by one - /// doubling either, since a bulk append can allocate more than twice the previous capacity and - /// several vectors can grow at once. So this is the storage's current size, not a peak over a - /// push. - /// - /// The evaluator is the only one that knows: it keeps samples per field, each field with its - /// own timestamps, values, reset index and native histograms, and it drops them by its own - /// rule. Mirroring that rule here would be a second copy of it, free to drift from the first. - fn retained_bytes(&self) -> usize { - self.evaluator - .as_ref() - .map_or(0, RangeEvaluator::retained_bytes) - } - - /// Feeds one input chunk to the evaluator and returns the chunk it yields, if any. - fn push(&mut self, path: &NodePath, chunk: &NativeChunk) -> Result> { - let evaluator = self.evaluator.as_mut().ok_or_else(|| closed(path))?; - match chunk { - // Raw samples are read window by window by the evaluator itself. - NativeChunk::Raw(chunk) => evaluator.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. - // Handing each chunk over as it arrives is what lets this window report a decision - // before its input series has ended; buffering the chunks into a whole series first - // would hold the input's bytes and delay every result to the end of the series. - NativeChunk::Evaluated(chunk) => evaluator.push_series(&chunk.series, chunk.is_last), - } - } - - /// Closes this window, reporting an input that ended mid-series. - /// - /// The evaluator is what knows whether a series is still open, for evaluated input as much as - /// for raw: a chunk that did not say `is_last` leaves it holding the series. - fn finish(&mut self) -> Result<()> { - match self.evaluator.take() { - Some(evaluator) => evaluator.finish(), - None => Ok(()), - } - } -} - /// The per-node run-time state of a node. struct NodeRuntime { buffer: NodeBuffer, - /// Source chunks queued by the caller, for an input node. - queued: VecDeque, - /// What `queued` holds, folded in as chunks enter and out as they leave. - queued_charge: QueuedCharge, - /// What a window node holds. - window: Option, + /// Source chunks queued by the caller, for an input node, each with the estimate it was queued + /// with: what a chunk is worth is read once, as it enters, and given back as it leaves. + queued: VecDeque<(NativeChunk, usize)>, + /// A window node's evaluator, with its own input and output grid; `None` before it is built and + /// once it is closed. + window: Option, /// What a map node applies. map: Option, /// What this node has already handed out under each output label set, for a node that rewrites @@ -1039,58 +737,38 @@ struct NodeRuntime { } impl NodeRuntime { - /// Queues a source chunk, holding the bytes it needs until it leaves. + /// Queues a source chunk, holding what it is worth until it leaves. /// - /// What this node holds is its queue and nothing else, so the reservation is the queue's - /// running total: a chunk of a series can share its histogram table with a chunk of the same - /// series beside it, and counting the queue chunk by chunk would charge that one table once per - /// chunk instead of once for the allocation. - /// - /// The total is kept incrementally rather than recounted from the queue: recomputing it here - /// costs a pass over every queued chunk per chunk queued, so a caller that queues a whole series - /// before pulling it pays quadratically in the chunks it holds. What this costs instead is one - /// pass over the chunk entering, and the same on the way out. + /// What this node holds is its queue and nothing else, so the reservation is the sum of the + /// estimates of the chunks in it. A chunk is measured once, as it enters, and the figure it was + /// queued with is given back as it leaves, so neither operation walks the queue. fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> { let positions = chunk.positions(); - let bytes = self.queued_charge.enqueue(&chunk); - self.queued.push_back(chunk); - self.buffer.hold_exactly(bytes)?; + 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(()) } - /// The bytes the chunks this node still queues hold, counted as one accounting pass. - /// - /// Test-only: what the node reserves for its queue is the running total of [`QueuedCharge`], so - /// this walk is the figure that total is checked against rather than the figure it is read from. - #[cfg(test)] - fn queued_bytes_recomputed(&self) -> usize { - let mut charged = ChargedAllocations::default(); - self.queued - .iter() - .map(|chunk| chunk.bytes(&mut charged)) - .fold(0usize, usize::saturating_add) - } - /// 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. fn pop_source(&mut self) -> Result> { - let Some(chunk) = self.queued.pop_front() else { + let Some((chunk, bytes)) = self.queued.pop_front() else { return Ok(None); }; - // The leaving chunk gives back only what it alone held: an allocation a chunk still in the - // queue references stays charged, and no chunk left behind is walked to find that out. - let bytes = self.queued_charge.pop(&chunk); 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. + // nothing its producer did. The chunk leaves this node, so the pool no longer has to + // hold it. let _timer = metrics.timer(); - // The chunk leaves this node, so the pool no longer has to hold it. - self.buffer.hold_exactly(bytes)?; + self.buffer.shrink(bytes)?; } metrics.record_output(1, chunk.positions()); // An evaluated source is already addressed on its grid, so its decided positions are grid @@ -1112,12 +790,9 @@ impl NodeRuntime { /// `None` means the operation emptied every position and the chunk does not close its series: /// there is nothing to hand on, and the input may still decide more. fn map(&mut self, path: &NodePath, chunk: EvaluatedChunk) -> Result> { - let (bytes, positions, closing) = ( - evaluated_bytes(&chunk, &mut ChargedAllocations::default()), - chunk.series.time.len(), - chunk.is_last, - ); - self.buffer.hold(bytes)?; + let (positions, closing) = (chunk.series.time.len(), chunk.is_last); + // The chunk is held for as long as this node works on it. + self.buffer.grow(evaluated_bytes(&chunk))?; 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 @@ -1144,18 +819,15 @@ impl NodeRuntime { // the one that arrived. self.track(path, Some(&chunk.series.metric), output)?; } - let bytes = self.emitted_bytes(); - self.buffer.hold_exactly(bytes)?; + // The chunk is gone and the label sets this node has handed out are what is left. + let emitted = self.emitted_bytes(); + self.buffer.resize(emitted)?; Ok(output) } /// Feeds one chunk to this node's window. fn window(&mut self, path: &NodePath, chunk: NativeChunk) -> Result> { - let (bytes, positions, closing) = ( - chunk.bytes(&mut ChargedAllocations::default()), - chunk.positions(), - chunk.is_last(), - ); + let (positions, closing) = (chunk.positions(), chunk.is_last()); // Which series this chunk came from, for the label-set table below. A window consumes one // series to its `is_last` before the next, so the chunk that closes an output label set is // the one of the series that produced its values, which is what lets the table accept a @@ -1163,15 +835,22 @@ impl NodeRuntime { // series, so there is nothing to pass on. let source = chunk.metric(); // The chunk is held for as long as the evaluator consumes it. - self.buffer.hold(bytes)?; + self.buffer.grow(chunk.bytes())?; let metrics = Arc::clone(&self.buffer.metrics); let outcome = { let _timer = metrics.timer(); - match self.window.as_mut() { - Some(window) => window.push(path, &chunk), - None => Err(DataFusionError::Execution(format!( - "the node at {path} holds no window" - ))), + match (self.window.as_mut(), &chunk) { + // Raw samples are read window by window by the evaluator itself. + (Some(evaluator), NativeChunk::Raw(chunk)) => evaluator.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. + // Handing each chunk over as it arrives is what lets this window report a decision + // before its input series has ended; buffering the chunks into a whole series first + // would hold the input's bytes and delay every result to the end of the series. + (Some(evaluator), NativeChunk::Evaluated(chunk)) => { + evaluator.push_series(&chunk.series, chunk.is_last) + } + (None, _) => Err(closed(path)), } }; metrics.record_input(1, positions); @@ -1190,30 +869,17 @@ impl NodeRuntime { self.track(path, source, output)?; } // The chunk has been consumed: what this node still holds is what the evaluator kept of it - // and the label sets it has already handed out. Between pushes the charge for both is the - // accounted size of that storage, a lower bound on what is held rather than a measurement: - // the evaluator's buffers by capacity -- with the payload of the histograms they retain and - // of the ones the row boxes -- and every label set handed out, leaving out the kernel's - // scratch, this table's map overhead with the `Arc` headers of its strings and the outer - // vectors of the pending batch. During one push the evaluator additionally holds the - // incoming chunk, charged by `hold` above for as long as the call runs, and vector growth - // is not reserved and not bounded by one doubling — a bulk append can allocate more than - // twice the previous capacity, and several vectors can grow at once — so this figure is - // what the storage stands at, not a peak over the push. - // - // The reason the figure must not be per-chunk: charging every chunk consumed makes the - // reservation grow with the chunk count, so a fixed window over a long series reads as an - // allocation failure even though the window holds no more samples. - // - // Both terms are charged whether or not this chunk produced one: a chunk that yields - // nothing leaves the evaluator's samples and every earlier series' history exactly where - // they were, so dropping the charge here would release memory this node still holds. + // and the label sets it has already handed out. Both are charged whether or not this chunk + // produced one -- a chunk that yields nothing leaves the evaluator's samples and every + // earlier series' history exactly where they were -- and neither is charged per chunk + // consumed, which would make a fixed window over a long series read as an allocation + // failure even though the window holds no more samples. let retained = self .window .as_ref() - .map_or(0, WindowRuntime::retained_bytes); + .map_or(0, RangeEvaluator::retained_bytes); let emitted = self.emitted_bytes(); - self.buffer.hold_exactly(retained.saturating_add(emitted))?; + self.buffer.resize(retained.saturating_add(emitted))?; Ok(output) } @@ -1259,30 +925,24 @@ impl NodeRuntime { self.open_source_series = false; self.queued.clear(); self.queued.shrink_to_fit(); - // The queue's counts go with the queue: they are what a later chunk would be folded onto, - // and a chunk that is dropped is a chunk the pool no longer has to hold. The reservation is - // returned below, once, for everything this node still held. - self.queued_charge = QueuedCharge::default(); + // The reservation is returned once, below, for everything this node still held. self.buffer.release(); } } /// The run-time state of one execution of a bound tree. /// -/// The state is keyed by tree position: the same positions [`metrics::walk`] derives, so a node's -/// state, its metrics and the name it is shown under cannot drift apart. Because none of it lives -/// on the tree, one compiled tree serves every execution that builds a state from it. +/// The state is keyed by tree position: the same positions [`crate::native::metrics::walk`] +/// derives, so a node's state, its metrics and the name it is shown under cannot drift apart. +/// Because none of it lives on the tree, one compiled tree serves every execution that builds a +/// state from it. pub struct NativeExecutionState { - /// The tree's structure, flattened in traversal order. + /// The tree's structure, flattened in traversal order, so the root is at index 0. nodes: Vec, /// The position of each node, in the same order. paths: Vec, /// The per-node state, in the same order. runtimes: Vec, - /// The index of every node, so a caller names a node the way the metrics do. - by_path: HashMap, - /// The index of the root node. - root: usize, /// The index of the tree's input node. source: usize, /// Whether the source hands over evaluated chunks rather than raw samples. @@ -1300,153 +960,119 @@ impl NativeExecutionState { metrics_set: &ExecutionPlanMetricsSet, partition: usize, ) -> Result { - // One traversal names and registers every node: the same walk `EXPLAIN` uses, so a node - // cannot be shown at one position and registered at another. - let mut pending: Vec = Vec::new(); - let mut unsupported: Option = None; - // The first input whose declared order this runtime cannot execute, and where it says so. - // Every node here reads one series at a time, so an input that interleaves them is one this - // runtime cannot execute. Recorded per input rather than kept from the first one seen: a - // tree with two inputs would otherwise have its second declaration read and dropped. - let mut unsupported_ordering_found: Option<(SeriesOrdering, NodePath)> = None; - metrics::walk(tree.root(), &mut |node, path| { + // One pass down the tree names and registers every node in the order + // `crate::native::metrics::walk` gives it: the same rule `EXPLAIN` uses, so a node cannot be + // shown at one position and registered at another. Every node this runtime executes is + // unary, so that order is the chain from the root to the input, and a node's input is the + // next one the pass reaches. + let mut nodes: Vec = Vec::new(); + let mut paths: Vec = Vec::new(); + let mut runtimes: Vec = Vec::new(); + let mut source: Option<(usize, Arc)> = None; + let mut node = tree.root(); + let mut path = NodePath::root(); + loop { + let index = nodes.len(); let handles = Arc::new(NodeMetrics::default()); - handles.register(path, metrics_set, partition); - let plan = match &node.expr { + handles.register(&path, metrics_set, partition); + let (tag, child) = match &node.expr { NativeExpr::Input(bound) => { + // Every node here reads one series at a time and assumes its chunks arrive + // together: a window feeds a series to its evaluator up to the chunk carrying + // `is_last`, and an input node keeps one flag for the series it handed over, + // which is what reports one that never closed. An input that declares + // `Interleaved` can leave a series open across another series' chunks, which + // either of those would misread, so the tree is refused here rather than run. + // That is a precondition of the runtime, not a limitation to document: the tree + // stays free to declare the ordering -- the compiler's job is not narrowed here + // -- and no tree this runtime executes declares it. if bound.ordering == SeriesOrdering::Interleaved { - unsupported_ordering_found - .get_or_insert_with(|| (bound.ordering, path.clone())); + return Err(unsupported_ordering(bound.ordering, &path)); } - Some((NodeTag::Input, Seed::Input)) - } - NativeExpr::Window { op, .. } => Some((NodeTag::Window, Seed::Window(op.clone()))), - NativeExpr::Map { op, .. } => Some((NodeTag::Map, Seed::Map(Arc::clone(&op.ops)))), - // The kinds below are legal in a bound tree, and `validate` stays the authority on - // that; this runtime simply does not execute them yet. - NativeExpr::Scalar(_) => { - unsupported.get_or_insert_with(|| not_implemented("Scalar", path)); - None - } - NativeExpr::Instant { .. } => { - unsupported.get_or_insert_with(|| not_implemented("Instant", path)); - None - } - NativeExpr::Aggregate { .. } => { - unsupported.get_or_insert_with(|| not_implemented("Aggregate", path)); - None - } - NativeExpr::Binary { .. } => { - unsupported.get_or_insert_with(|| not_implemented("Binary", path)); - None - } - }; - if let Some((tag, seed)) = plan { - pending.push(PendingNode { - tag, - path: path.clone(), - metrics: handles, - output_schema: node.output.samples().cloned(), - seed, - }); - } - }); - // Rejected before a single chunk is read: a tree the runtime cannot execute must not - // start, because a partial answer would be one the caller never asked for. - if let Some(error) = unsupported { - return Err(error); - } - - // Every node here reads one series at a time and assumes its chunks arrive together: a - // window feeds a series to its evaluator up to the chunk carrying `is_last`, and an input - // node keeps one flag for the series it handed over, which is what reports one that never - // closed. An input that declares `Interleaved` can leave a series open across another - // series' chunks, which either of those would misread, so the tree is refused here rather - // than run. That is a precondition of the runtime, not a limitation to document: the tree - // stays free to declare the ordering -- the compiler's job is not narrowed here -- and no - // tree this runtime executes declares it. - if let Some((ordering, source)) = &unsupported_ordering_found { - return Err(unsupported_ordering(*ordering, source)); - } - - // A node's input is the node at the same position extended by the step the traversal took, - // so the structure is read off the positions instead of a second traversal that could - // disagree with the first. - let mut by_path = HashMap::with_capacity(pending.len()); - for (index, node) in pending.iter().enumerate() { - by_path.insert(node.path.clone(), index); - } - - let mut nodes = Vec::with_capacity(pending.len()); - let mut paths = Vec::with_capacity(pending.len()); - let mut runtimes = Vec::with_capacity(pending.len()); - for (index, node) in pending.iter().enumerate() { - let input = match node.tag { - NodeTag::Input => None, - NodeTag::Window | NodeTag::Map => { - let path = node.path.input(); - Some(*by_path.get(&path).ok_or_else(|| { + let samples = node.output.samples().cloned().ok_or_else(|| { DataFusionError::Execution(format!( - "the native tree has no node at the input of {}", - node.path + "the input node at {path} does not produce samples" )) - })?) + })?; + source = Some((index, samples)); + (NodeTag::Input, None) } + NativeExpr::Window { input, .. } => (NodeTag::Window, Some(input.as_ref())), + NativeExpr::Map { input, .. } => (NodeTag::Map, Some(input.as_ref())), + // The kinds below are legal in a bound tree, and `validate` stays the authority on + // that; this runtime simply does not execute them yet. Rejected before a single + // chunk is read: a tree the runtime cannot execute must not start, because a + // partial answer would be one the caller never asked for. + NativeExpr::Scalar(_) => return Err(not_implemented("Scalar", &path)), + NativeExpr::Instant { .. } => return Err(not_implemented("Instant", &path)), + NativeExpr::Aggregate { .. } => return Err(not_implemented("Aggregate", &path)), + NativeExpr::Binary { .. } => return Err(not_implemented("Binary", &path)), }; - let buffer = NodeBuffer::new(&node.path, Arc::clone(&node.metrics), &pool); + let buffer = NodeBuffer::new(&path, handles, &pool); let mut runtime = NodeRuntime { buffer, queued: VecDeque::new(), - queued_charge: QueuedCharge::default(), window: None, map: None, emitted: None, open_source_series: false, }; - match &node.seed { - Seed::Input => {} - Seed::Map(ops) => { - let schema = node.output_schema.clone().ok_or_else(|| { + match &node.expr { + NativeExpr::Input(_) => {} + NativeExpr::Map { op, .. } => { + let schema = node.output.samples().cloned().ok_or_else(|| { DataFusionError::Execution(format!( - "the map node at {} does not produce samples", - node.path + "the map node at {path} does not produce samples" )) })?; runtime.map = Some(MapRuntime { - ops: Arc::clone(ops), + ops: Arc::clone(&op.ops), schema, }); // A map drops the metric name, so it is one of the nodes that can turn two // series into one label set. runtime.emitted = Some(Emitted::default()); } - Seed::Window(window) => { - let child = input.ok_or_else(|| { + NativeExpr::Window { input, op } => { + let input_schema = input.output.samples().ok_or_else(|| { DataFusionError::Execution(format!( - "the window at {} has no input", - node.path + "the window at {path} consumes samples, but its input produces none" )) })?; - let input_schema = pending[child].output_schema.clone().ok_or_else(|| { - DataFusionError::Execution(format!( - "the window at {} consumes samples, but its input produces none", - node.path - )) - })?; - runtime.window = Some(WindowRuntime::try_new(&input_schema, window)?); + // One evaluator per window, with the grids the node was bound to: the output + // grid is the node's own grid, which is also the grid its chunks are addressed + // on. + runtime.window = Some(RangeEvaluator::try_new( + input_schema, + Arc::clone(&op.output_grid), + op.window, + op.function, + )?); // A window drops the metric name and the empty-valued labels, so a `rate` over // a series whose tag is empty and one where it is absent produces one label set // from two series. runtime.emitted = Some(Emitted::default()); } + NativeExpr::Scalar(_) + | NativeExpr::Instant { .. } + | NativeExpr::Aggregate { .. } + | NativeExpr::Binary { .. } => { + // Rejected above, where the pass has the position to name. + } } - debug_assert_eq!(nodes.len(), index); + // The input is the node the pass reaches next: the chain has no other node between + // this one and its input, and nothing is read off the positions afterwards. nodes.push(NodeSpec { - tag: node.tag, - input, + tag, + input: child.map(|_| index + 1), }); - paths.push(node.path.clone()); + paths.push(path.clone()); runtimes.push(runtime); + let Some(child) = child else { + break; + }; + node = child; + path = path.input(); } // The runtime's output is an evaluated chunk. Raw samples have no grid, and a scalar or @@ -1471,27 +1097,13 @@ impl NativeExecutionState { // The supported nodes are unary, so a tree of them has exactly one input node; it is where // the caller's chunks enter. - let root = *by_path.get(&NodePath::root()).ok_or_else(|| { - DataFusionError::Execution("the native tree has no root node".to_string()) - })?; - let source = nodes - .iter() - .position(|node| node.tag == NodeTag::Input) - .ok_or_else(|| { - DataFusionError::Execution("the native tree has no input node".to_string()) - })?; - let source_schema = pending[source].output_schema.clone().ok_or_else(|| { - DataFusionError::Execution(format!( - "the input node at {} does not produce samples", - pending[source].path - )) + let (source, source_schema) = source.ok_or_else(|| { + DataFusionError::Execution("the native tree has no input node".to_string()) })?; Ok(Self { nodes, paths, runtimes, - by_path, - root, source, source_is_evaluated: source_schema.eval_grid.is_some(), }) @@ -1499,7 +1111,7 @@ impl NativeExecutionState { /// The metrics of the node at `path`. pub fn metrics(&self, path: &NodePath) -> Option<&Arc> { - let index = *self.by_path.get(path)?; + let index = self.paths.iter().position(|candidate| candidate == path)?; Some(&self.runtimes[index].buffer.metrics) } @@ -1507,7 +1119,7 @@ impl NativeExecutionState { pub fn reserved_bytes(&self) -> usize { self.runtimes .iter() - .map(|runtime| runtime.buffer.held) + .map(|runtime| runtime.buffer.reservation.size()) .sum() } @@ -1521,63 +1133,6 @@ impl NativeExecutionState { self.nodes.is_empty() } - /// What the node at `path` charges for: the bytes its window's evaluator retains and the bytes - /// of the label sets it has handed out. - /// - /// Test-only: a window's reservation has to be exactly these two numbers, so a test compares - /// the reservation against them rather than against a figure the runtime keeps on the side. - #[cfg(test)] - fn window_charge(&self, path: &NodePath) -> (usize, usize) { - let index = *self - .by_path - .get(path) - .expect("the path names a node of this tree"); - let runtime = &self.runtimes[index]; - ( - runtime - .window - .as_ref() - .map_or(0, WindowRuntime::retained_bytes), - runtime.emitted_bytes(), - ) - } - - /// The bytes the label sets at `path` charge for, and the same figure walked in full. - /// - /// Test-only: the running total is only correct if folding one entry's change in agrees with - /// recounting the table, so a test compares the two after the table has changed shape. - #[cfg(test)] - fn emitted_charge_pair(&self, path: &NodePath) -> (usize, usize) { - let index = *self - .by_path - .get(path) - .expect("the path names a node of this tree"); - self.runtimes[index] - .emitted - .as_ref() - .map_or((0, 0), |emitted| { - (emitted.bytes(), emitted.bytes_recomputed()) - }) - } - - /// The bytes the queue at `path` charges for, and the same figure recounted by walking it. - /// - /// Test-only: the queue's running total is only correct if folding one chunk in as it enters and - /// out as it leaves agrees with one pass over what is left, so a test compares the two after the - /// queue has changed shape. - #[cfg(test)] - fn queued_charge_pair(&self, path: &NodePath) -> (usize, usize) { - let index = *self - .by_path - .get(path) - .expect("the path names a node of this tree"); - let runtime = &self.runtimes[index]; - ( - runtime.queued_charge.bytes, - runtime.queued_bytes_recomputed(), - ) - } - /// How many nodes still hold the state a window buffers into. /// /// Test-only: releasing a stopped execution has to drop the evaluators and their sample @@ -1603,7 +1158,7 @@ impl NativeExecutionState { fn close(&mut self) -> Result<()> { let mut result = Ok(()); for (path, runtime) in self.paths.iter().zip(self.runtimes.iter_mut()) { - if let Some(window) = runtime.window.as_mut() + if let Some(window) = runtime.window.take() && let Err(error) = window.finish() && result.is_ok() { @@ -1668,8 +1223,8 @@ impl NativeExecutor { /// materialises nothing beyond the chunk in hand. pub fn next_chunk(&mut self) -> Result> { self.check_running()?; - let root = self.state.root; - let result = self.pull(root).and_then(|chunk| match chunk { + // The root is the node the state was built from, which the pass puts first. + let result = self.pull(0).and_then(|chunk| match chunk { Some(NativeChunk::Evaluated(chunk)) => Ok(Some(chunk)), // Rejected when the state was built; kept as an error rather than a panic so an // impossible tree cannot take the process down. diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 93f810f83e7..c424ebda404 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -34,11 +34,10 @@ use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis} use datatypes::series::{Label, MetricName, SeriesOrdering}; use super::{ - ChargedAllocations, Emitted, History, NativeChunk, NativeExecutionState, NativeExecutor, - NodeBuffer, NodeRuntime, QueuedCharge, Run, absorb_rebuilds, label_bytes, map_chunk, raw_bytes, + Emitted, NativeChunk, NativeExecutionState, NativeExecutor, NodeBuffer, NodeRuntime, + absorb_rebuilds, map_chunk, raw_bytes, }; use crate::evaluated::EvaluatedChunk; -use crate::grid_series::{LabelSet, label_set}; use crate::map::MathOp; use crate::native::metrics::{NodeMetric, NodeMetrics, NodePath}; use crate::native::plan::{ @@ -345,7 +344,7 @@ fn raw_shared_histogram_chunk( .unwrap() } -/// A source node's runtime: the queue, its accounting and the reservation the two are held for. +/// A source node's runtime: the queue and the reservation it is held for. fn source_runtime(pool: &Arc) -> NodeRuntime { NodeRuntime { buffer: NodeBuffer::new( @@ -354,7 +353,6 @@ fn source_runtime(pool: &Arc) -> NodeRuntime { pool, ), queued: VecDeque::new(), - queued_charge: QueuedCharge::default(), window: None, map: None, emitted: None, @@ -1052,6 +1050,54 @@ fn an_error_releases_the_reservation() { assert_eq!(pool.reserved(), 0); } +/// A chunk the pool cannot admit fails the execution and gives back everything it already held. +/// +/// 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(); + let set = ExecutionPlanMetricsSet::new(); + // 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), &set); + + execution + .push_raw(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(raw_chunk(&schema, ×tamps, &values, true)) + .expect_err("a chunk larger than the pool was admitted"); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "{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 = NodePath::root().metric_name(NodeMetric::CURRENT_RESERVED_BYTES); + assert_eq!(gauge(&set, ¤t), 0); + let peak = NodePath::root().partitioned_metric_name(NodeMetric::PEAK_RESERVED_BYTES, 0); + assert!(gauge(&set, &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}" + ); +} + /// A map that drops the metric name cannot hand two series on under one label set. /// /// `a{job="x"}` and `b{job="x"}` arrive whole, so each says it is the last chunk of its own series, @@ -1411,6 +1457,71 @@ fn two_open_series_that_share_a_label_set_are_accepted_when_no_position_collides ); } +/// 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, which 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. +#[test] +fn a_nan_occupies_its_position_where_a_missing_sample_does_not() { + let map_grid = grid(0, 60_000, 1); + let tree = || { + NativeTree::try_new(map( + evaluated_input_with_ordering(Arc::clone(&map_grid), SeriesOrdering::Contiguous), + vec![MathOp::Abs], + )) + .unwrap() + }; + let schema = evaluated_schema(Arc::clone(&map_grid)); + + // The first series' sample at position 0, the second series' sample there, and whether the two + // can share the label set `abs` leaves them. + let cases = [ + (vec![Some(f64::NAN)], vec![Some(1.0)], false), + (vec![Some(1.0)], vec![Some(f64::NAN)], false), + (vec![Some(f64::NAN)], vec![None], true), + (vec![Some(1.0)], vec![None], true), + (vec![None], vec![Some(f64::NAN)], true), + ]; + // Both chunks are open, so the label set is still open when the second series arrives: a closed + // set refuses every second series, and this test is about what occupies a position. + let drain = |execution: &mut NativeExecutor| -> Result<(), DataFusionError> { + while execution.next_chunk()?.is_some() {} + Ok(()) + }; + for (first, second, accepted) in cases { + let mut execution = executor(&tree(), pool(), &ExecutionPlanMetricsSet::new()); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("a", "x"), + 0, + first.clone(), + false, + )) + .unwrap(); + drain(&mut execution).expect("the first open chunk is handed on"); + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric("b", "x"), + 0, + second.clone(), + false, + )) + .unwrap(); + let outcome = drain(&mut execution); + assert_eq!( + outcome.is_ok(), + accepted, + "{first:?} and {second:?} were {}: {:?}", + if accepted { "refused" } else { "handed on" }, + outcome.err(), + ); + } +} + /// One series arriving in pieces is not two series: a chunk that continues where its label set /// ended is handed on. /// @@ -1466,15 +1577,12 @@ fn a_series_that_continues_where_it_ended_is_not_a_second_series() { /// 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 -/// reservation reaches the same figure whether the data is split into 64 chunks or into 1024. -/// -/// What the reservation has to be is not left to a constant: after every pull it is compared with -/// what the same window's evaluator says it retains and what the label sets it handed out hold. A -/// figure that merely did not grow with the chunk count would fail that, as would one that let the -/// emitted table go. +/// 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. #[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. @@ -1507,23 +1615,20 @@ fn a_window_reserves_what_it_retains_not_what_it_consumed() { }); // The output of every chunk is dropped: a consumer reading the series as it arrives // never holds it, and neither may the node. - let pulled = execution.next_chunk().unwrap_or_else(|error| { + drop(execution.next_chunk().unwrap_or_else(|error| { panic!("chunk {index} of the {count}-chunk series did not fit: {error}") - }); - drop(pulled); + })); let held = execution.state().reserved_bytes(); - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); assert_eq!( held, - retained.saturating_add(emitted), - "chunk {index} of {count} holds {held} bytes, but the window retains {retained} \ - and handed out {emitted}" + pool.reserved(), + "chunk {index} of {count}: the state and the pool disagree on what is held" ); assert!( - held <= (4 << 10), + held <= (8 << 10), "chunk {index} of {count} holds {held} bytes of a 1 ms window over one sample" ); - peak = peak.max(held).max(pool.reserved()); + peak = peak.max(held); } peak }; @@ -1538,11 +1643,9 @@ 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, and the reservation is compared with what each window retains after every pull. Every -/// field costs its own timestamps, values and row slot, so the figure grows by the same amount per -/// field; a figure counting one timestamp and one float per row would not. The widths are compared -/// by their increments rather than as a multiple of one: the identity of the open series is part of -/// the reservation and is counted once however many fields the series carries. +/// 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. #[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. @@ -1561,31 +1664,20 @@ fn a_window_retains_the_samples_of_every_field() { )) .unwrap(); drop(execution.next_chunk().unwrap()); - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); - let held = execution.state().reserved_bytes(); - assert_eq!( - held, - retained.saturating_add(emitted), - "{width} field(s), chunk {index} of {count}: {held} bytes reserved, but the \ - window retains {retained} and handed out {emitted}" - ); - peak = peak.max(retained); + peak = peak.max(execution.state().reserved_bytes()); } peak }; let (one, two, three) = (peak(1), peak(2), peak(3)); assert!( two > one, - "a window over two fields retained {two} bytes, no more than the {one} bytes a window over \ - one field retains" + "a window over two fields reserved {two} bytes, no more than the {one} bytes a window over \ + one field reserves" ); - assert_eq!( - two - one, - three - two, - "a third field costs {} bytes where a second cost {}: the retention is not one field's \ - storage per field", - three - two, - two - one + assert!( + three > two, + "a window over three fields reserved {three} bytes, no more than the {two} bytes a window \ + over two fields reserves" ); } @@ -1606,7 +1698,8 @@ fn a_chunk_with_no_output_keeps_charging_the_emitted_table() { )) .unwrap(); let schema = raw_schema(); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); execution .push_raw(raw_chunk(&schema, &[0, 60_000], &[1.0, 2.0], false)) @@ -1617,16 +1710,12 @@ fn a_chunk_with_no_output_keeps_charging_the_emitted_table() { .expect("the first chunk decided both points"); assert_eq!(sample_values(&first), vec![Some(1.0), Some(2.0)]); drop(first); - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); + let after_output = execution.state().reserved_bytes(); assert!( - emitted > 0, + after_output > 0, "the window handed out a position, which it has to hold" ); - assert_eq!( - execution.state().reserved_bytes(), - retained.saturating_add(emitted), - "the reservation does not cover the {emitted} bytes the window handed out" - ); + assert_eq!(after_output, pool.reserved()); // Both points are decided, so this chunk decides nothing and the window yields no chunk. execution @@ -1636,16 +1725,11 @@ fn a_chunk_with_no_output_keeps_charging_the_emitted_table() { execution.next_chunk().unwrap().is_none(), "a chunk after every point was decided produced a chunk" ); - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); assert!( - emitted > 0, - "the window's emitted table emptied itself between chunks" - ); - assert_eq!( - execution.state().reserved_bytes(), - retained.saturating_add(emitted), - "a chunk with no output released the {emitted} bytes the emitted table still holds" + execution.state().reserved_bytes() > 0, + "a chunk with no output released the bytes the emitted table still holds" ); + assert_eq!(execution.state().reserved_bytes(), pool.reserved()); } /// A window cannot run over an interleaved input, and the runtime says so before reading a chunk. @@ -1731,52 +1815,6 @@ fn an_interleaved_input_is_refused_without_a_window() { assert!(message.contains("root.input"), "{message}"); } -/// The charge for the label sets a node has handed out does not depend on how it is read. -/// -/// The table only grows, so the figure is folded in as each entry changes rather than walked after -/// every output. Folding it wrong would show up as a running total that drifts from the same figure -/// recounted in full, so both are compared after every chunk: distinct label sets add entries, and -/// later chunks of one set grow its run vectors and the table's own capacity. -#[test] -fn the_emitted_charge_is_the_same_folded_in_as_walked() { - let grid = grid(0, 60_000, 4); - let tree = - NativeTree::try_new(map(evaluated_input(Arc::clone(&grid)), vec![MathOp::Abs])).unwrap(); - let schema = evaluated_schema(Arc::clone(&grid)); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); - - let chunks = [ - ("a", "x", 0, vec![Some(-1.0), None, Some(-2.0), None], false), - ("a", "x", 0, vec![None, Some(-3.0), None, None], true), - ("b", "y", 0, vec![None, None, None, Some(-4.0)], true), - ( - "c", - "z", - 0, - vec![Some(-5.0), Some(-6.0), Some(-7.0), Some(-8.0)], - true, - ), - ]; - for (name, job, start, values, is_last) in chunks { - execution - .push_evaluated(evaluated_chunk_of( - &schema, - named_metric(name, job), - start, - values, - is_last, - )) - .unwrap(); - while execution.next_chunk().unwrap().is_some() {} - let (folded, walked) = execution.state().emitted_charge_pair(&NodePath::root()); - assert!(folded > 0, "the node handed out nothing to charge for"); - assert_eq!( - folded, walked, - "the folded charge of {folded} bytes is not the {walked} bytes the table holds" - ); - } -} - /// 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. @@ -2175,14 +2213,12 @@ fn an_input_that_ends_mid_series_is_reported_without_a_window() { } } -/// A window over native histograms reserves what it retains, payload included, and the label-set -/// ledger it charges beside that agrees with a full walk of the table. +/// A window over native histograms reserves what it retains, payload included. /// -/// The chunk accounting walks the samples a chunk holds instead of charging one float per field and -/// row, so a histogram field -- which holds no float at all -- reaches both figures as the table its -/// indices point into. Neither may drift from what the node says it holds: the reservation is the -/// retained bytes plus the emitted ones, and the running total of the emitted table is the same -/// figure recounted in full. +/// 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. #[test] fn a_window_over_histograms_reserves_what_it_retains() { let out = grid(0, 10_000, 2); @@ -2195,383 +2231,120 @@ fn a_window_over_histograms_reserves_what_it_retains() { )) .unwrap(); let schema = raw_schema(); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + let pool = pool(); + let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new()); for (timestamp, is_last) in [(0, false), (10_000, true)] { execution .push_raw(raw_histogram_chunk(&schema, &[timestamp], 2, is_last)) .unwrap(); while execution.next_chunk().unwrap().is_some() {} - let (retained, emitted) = execution.state().window_charge(&NodePath::root()); - assert!( - emitted > 0, - "the window handed nothing out, so the ledger below charges for nothing" - ); assert_eq!( execution.state().reserved_bytes(), - retained.saturating_add(emitted), - "the reservation is not what the window retains ({retained} bytes) plus what it handed \ - out ({emitted} bytes)", + pool.reserved(), + "the state and the pool disagree on what the window holds" ); - let (folded, walked) = execution.state().emitted_charge_pair(&NodePath::root()); - assert_eq!( - folded, walked, - "the folded charge of {folded} bytes is not the {walked} bytes the table holds", + assert!( + pool.reserved() > 0, + "a window over a histogram series reserves for nothing" ); } -} -/// One histogram table is charged once, however many chunks of the series reference it. -/// -/// The chunks of one series can share the immutable table their histogram indices point into, and a -/// node holding both of them holds one table: the source charges its queue as one accounting pass, -/// which counts the table the first time it meets it and the address the `Arc` holds is what makes -/// two clones one table. -#[test] -fn a_histogram_table_is_charged_once_per_pass() { - let schema = raw_schema(); - let mut builder = HistogramBatchBuilder::new(); - let index = push_histogram(&mut builder, 2); - let table = builder.finish().unwrap(); - let chunk = |timestamp: i64, is_last: bool| { - let samples = - Samples::try_from_histogram(UInt32Array::from(vec![Some(index)]), Arc::clone(&table)) - .unwrap(); - RawSeriesChunk::try_new( - &schema, - Buffer::from_slice_ref(b"series-a"), - Some(metric()), - RawTimestamps::try_new(ScalarBuffer::from(vec![timestamp])).unwrap(), - SeriesFields::one(samples), - is_last, - ) - .unwrap() - }; - let (first, second) = (chunk(0, false), chunk(10_000, true)); - - let mut charged = ChargedAllocations::default(); - let queue = raw_bytes(&first, &mut charged).saturating_add(raw_bytes(&second, &mut charged)); - let alone = raw_bytes(&first, &mut ChargedAllocations::default()) - .saturating_add(raw_bytes(&second, &mut ChargedAllocations::default())); + // The table the indices point into is what the field costs, so the same one-sample chunk is + // worth more as a histogram than as a float. + let histogram = raw_histogram_chunk(&schema, &[0], 2, true); + let float = raw_chunk(&schema, &[0], &[1.0], true); assert!( - queue < alone, - "a queue of two chunks sharing one table is charged {queue} bytes, no less than the \ - {alone} bytes they are charged apart: the table was counted twice", - ); - - // What the source reserves is exactly that one pass: it holds its queue and nothing else, and - // nothing has been pulled yet. - let tree = NativeTree::try_new(window(input(), grid(0, 10_000, 1))).unwrap(); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); - execution.push_raw(first).unwrap(); - execution.push_raw(second).unwrap(); - assert_eq!( - execution.state().reserved_bytes(), - queue, - "the queue of two chunks sharing one table was not charged as one pass", + raw_bytes(&histogram) > raw_bytes(&float), + "a histogram chunk is estimated at {} bytes, no more than the {} bytes of a float chunk of \ + the same shape", + raw_bytes(&histogram), + raw_bytes(&float), ); } -/// A queue of two chunks that share one table charges it once, and the running total is what one -/// pass over the queue counts. +/// A source reserves the estimate of every queued chunk, and gives each one back as it leaves. /// -/// The figure the node reserves while both chunks are queued is the incremental one: the table is -/// met by the first chunk that references it and is not charged again by the second. Charging it -/// per chunk fails the record check, and recounting the queue per enqueue fails the count of -/// chunks walked in the test below. +/// 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. #[test] -fn a_queued_allocation_is_charged_once() { +fn a_source_charges_its_queue_and_gives_it_back() { let pool = pool(); let mut source = source_runtime(&pool); let schema = raw_schema(); let mut builder = HistogramBatchBuilder::new(); let index = push_histogram(&mut builder, 2); let table = builder.finish().unwrap(); - let chunk = |timestamp: i64, is_last: bool| { - raw_shared_histogram_chunk(&schema, &table, index, timestamp, is_last) - }; - let (first, second) = (chunk(0, false), chunk(10_000, true)); - - // What the two chunks cost charged apart, and what the second one costs on its own: the - // difference between the two is what the shared table is worth. - let apart = raw_bytes(&first, &mut ChargedAllocations::default()) - .saturating_add(raw_bytes(&second, &mut ChargedAllocations::default())); - let second_alone = raw_bytes(&second, &mut ChargedAllocations::default()); + let first = raw_shared_histogram_chunk(&schema, &table, index, 0, false); + let second = raw_shared_histogram_chunk(&schema, &table, index, 10_000, true); + let (first_bytes, second_bytes) = (raw_bytes(&first), raw_bytes(&second)); source.enqueue(NativeChunk::Raw(first)).unwrap(); - let one = source.queued_charge.bytes; - assert_eq!( - one, - source.queued_bytes_recomputed(), - "one queued chunk is not charged what one pass over it counts" - ); - assert_eq!( - source.buffer.held, one, - "the reservation is not the queue's figure" - ); - assert_eq!(pool.reserved(), one); + assert_eq!(source.buffer.reservation.size(), first_bytes); + assert_eq!(pool.reserved(), first_bytes); source.enqueue(NativeChunk::Raw(second)).unwrap(); - let two = source.queued_charge.bytes; - let counted = *source - .queued_charge - .tables - .get(&(Arc::as_ptr(&table) as usize)) - .expect("the queue did not count the table both chunks index into"); assert_eq!( - counted.chunks, 2, - "two queued chunks reference the table, but the queue counts {}", - counted.chunks + source.buffer.reservation.size(), + first_bytes + second_bytes, + "the queue is not the sum of the estimates it holds" ); - assert_eq!( - two, - source.queued_bytes_recomputed(), - "the running total is not what one pass over the queue counts" - ); - assert_eq!( - two - one, - second_alone - counted.bytes, - "the chunk that entered charged the shared table a second time" - ); - assert!( - two < apart, - "a queue of two chunks sharing one table is charged {two} bytes, no less than the {apart} \ - bytes they are charged apart: the table was counted twice", - ); - assert_eq!(source.buffer.held, two); - assert_eq!(pool.reserved(), two); -} + assert_eq!(pool.reserved(), first_bytes + second_bytes); -/// A shared table is given back with the last queued chunk that references it, not the first. -/// -/// A leak here shows as a reservation that never returns: the first pop takes one reference away -/// and the table stays charged, the second takes the last one and the table goes with it. -#[test] -fn a_queued_allocation_is_given_back_with_its_last_chunk() { - let pool = pool(); - let mut source = source_runtime(&pool); - let schema = raw_schema(); - let mut builder = HistogramBatchBuilder::new(); - let index = push_histogram(&mut builder, 2); - let table = builder.finish().unwrap(); - let address = Arc::as_ptr(&table) as usize; - let chunk = |timestamp: i64, is_last: bool| { - raw_shared_histogram_chunk(&schema, &table, index, timestamp, is_last) - }; - - source.enqueue(NativeChunk::Raw(chunk(0, false))).unwrap(); - source - .enqueue(NativeChunk::Raw(chunk(10_000, true))) - .unwrap(); - assert_eq!(source.queued_charge.tables[&address].chunks, 2); - - let first = source + let popped = source .pop_source() .unwrap() .expect("the queue held two chunks"); - assert!(!first.is_last()); + assert!(!popped.is_last()); + // One table, two queued chunks, two shares of its estimate: what leaves is what the chunk that + // left was charged, and the other chunk's share stays. assert_eq!( - source.queued_charge.tables[&address].chunks, 1, - "the chunk left in the queue still references the table, so it is still charged" + source.buffer.reservation.size(), + second_bytes, + "the chunk that left did not give its estimate back" ); - assert!( - source.queued_charge.bytes > 0, - "the queue still holds a chunk, but charges for nothing" - ); - assert_eq!( - source.queued_charge.bytes, - source.queued_bytes_recomputed(), - "the pop did not leave the running total at one pass over the queue" - ); - assert_eq!(source.buffer.held, source.queued_charge.bytes); + assert_eq!(pool.reserved(), second_bytes); source .pop_source() .unwrap() .expect("the queue held two chunks"); - assert!( - !source.queued_charge.tables.contains_key(&address), - "the last chunk referencing the table left, but the queue still counts it" - ); - assert!( - source.queued_charge.buffers.is_empty(), - "a buffer outlived the chunks that referenced it" - ); + assert_eq!(source.buffer.reservation.size(), 0); assert_eq!( - source.queued_charge.bytes, 0, - "the queue is empty, but it is still charged for" + pool.reserved(), + 0, + "the queue emptied, but the pool holds its bytes" ); - assert_eq!( - source.buffer.held, 0, - "the reservation did not come back with the queue" - ); - assert_eq!(pool.reserved(), 0); assert!(source.pop_source().unwrap().is_none()); } -/// Queueing a chunk accounts for that chunk alone, however deep the queue is. +/// Releasing a node drops its queue and returns the reservation once. /// -/// The figure is the number of chunks the accounting walked, not wall time: `N` enqueues have to -/// walk `N` chunks and `N` pops another `N`, whatever the queue held. Recounting the queue per -/// operation -- the defect this refuses -- walks `N * (N + 1) / 2` chunks for the enqueues alone. +/// 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. #[test] -fn queueing_a_chunk_walks_one_chunk() { - let pool = pool(); - let mut source = source_runtime(&pool); - let schema = raw_schema(); - let chunks = 64; - for index in 0..chunks { - let timestamp = i64::try_from(index).unwrap() * 10_000; - let chunk = raw_chunk(&schema, &[timestamp], &[1.0], index + 1 == chunks); - source.enqueue(NativeChunk::Raw(chunk)).unwrap(); - } - assert_eq!( - source.queued_charge.walked, chunks, - "queueing {chunks} chunks walked {} chunk(s): the figure is recounted from the queue", - source.queued_charge.walked, - ); - assert_eq!( - source.queued_charge.bytes, - source.queued_bytes_recomputed(), - "the running total is not what one pass over the queue counts" - ); - - let mut popped = 0; - while source.pop_source().unwrap().is_some() { - popped += 1; - } - assert_eq!(popped, chunks, "the queue did not hand back every chunk"); - assert_eq!( - source.queued_charge.walked, - 2 * chunks, - "popping {chunks} chunks walked {} chunk(s): the figure is recounted from the queue", - source.queued_charge.walked, - ); - assert_eq!(source.queued_charge.bytes, 0); -} - -/// A mixed sequence of pushes and pulls leaves the queue's figure equal to one pass over what is -/// left in it, and the reservation equal to that figure. -/// -/// The chunks mix ones that share a table with ones that share nothing, so an allocation is -/// referenced by one, two or no queued chunk as the sequence runs. Both the node's own reservation -/// and the pool's are checked, so a total that drifts from the queue is caught by the figure the -/// memory pool actually holds. -#[test] -fn a_queue_figure_survives_a_mixed_push_and_pull_sequence() { +fn releasing_a_node_drops_its_queue() { let pool = pool(); let mut source = source_runtime(&pool); let schema = raw_schema(); let mut builder = HistogramBatchBuilder::new(); let index = push_histogram(&mut builder, 2); let table = builder.finish().unwrap(); - - for round in 0..6i64 { - for step in 0..2 { - let chunk = - raw_shared_histogram_chunk(&schema, &table, index, round * 10_000 + step, false); - source.enqueue(NativeChunk::Raw(chunk)).unwrap(); - } - let chunk = raw_chunk(&schema, &[round * 10_000 + 2], &[1.0], false); - source.enqueue(NativeChunk::Raw(chunk)).unwrap(); - let folded = source.queued_charge.bytes; - assert_eq!( - folded, - source.queued_bytes_recomputed(), - "round {round}: the running total is not one pass over the queue" - ); - assert_eq!(source.buffer.held, folded); - assert_eq!(pool.reserved(), folded); - - for _ in 0..2 { - if source.pop_source().unwrap().is_none() { - break; - } - } - let folded = source.queued_charge.bytes; - assert_eq!( - folded, - source.queued_bytes_recomputed(), - "round {round}: the running total is not one pass over what is left" - ); - assert_eq!(source.buffer.held, folded); - assert_eq!(pool.reserved(), folded); + for timestamp in [0, 10_000] { + source + .enqueue(NativeChunk::Raw(raw_shared_histogram_chunk( + &schema, &table, index, timestamp, false, + ))) + .unwrap(); } - - while source.pop_source().unwrap().is_some() {} - assert_eq!(source.queued_charge.bytes, 0); - assert!( - source.queued_charge.tables.is_empty(), - "a table outlived the chunks that referenced it" - ); - assert!( - source.queued_charge.buffers.is_empty(), - "a buffer outlived the chunks that referenced it" - ); - assert_eq!(source.buffer.held, 0); - assert_eq!(pool.reserved(), 0); -} - -/// What a source reserves through the executor is the figure one pass over its queue counts. -#[test] -fn the_executor_reserves_what_one_pass_over_the_queue_counts() { - let tree = NativeTree::try_new(window(input(), grid(0, 10_000, 4))).unwrap(); - let schema = raw_schema(); - let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); - for step in 0..3 { - let chunk = raw_chunk(&schema, &[step * 10_000], &[1.0], false); - execution.push_raw(chunk).unwrap(); - } - let (folded, walked) = execution - .state() - .queued_charge_pair(&NodePath::root().input()); - assert_eq!( - folded, walked, - "the executor's queue is not charged what one pass over it counts" - ); - assert_eq!( - execution.state().reserved_bytes(), - folded, - "the source's reservation is not its queue's figure" - ); -} - -/// Releasing a node drops the queue's counts with the queue and returns the reservation once. -/// -/// A count left behind would be folded onto by the next chunk the node queues, and the reservation -/// shown as returned while the counts still hold the bytes is the leak this refuses. -#[test] -fn releasing_a_node_drops_the_queue_and_its_counts() { - let pool = pool(); - let mut source = source_runtime(&pool); - let schema = raw_schema(); - let mut builder = HistogramBatchBuilder::new(); - let index = push_histogram(&mut builder, 2); - let table = builder.finish().unwrap(); - source - .enqueue(NativeChunk::Raw(raw_shared_histogram_chunk( - &schema, &table, index, 0, false, - ))) - .unwrap(); - source - .enqueue(NativeChunk::Raw(raw_shared_histogram_chunk( - &schema, &table, index, 10_000, true, - ))) - .unwrap(); - assert_eq!(pool.reserved(), source.queued_charge.bytes); + assert!(pool.reserved() > 0); source.release(); assert!(source.queued.is_empty(), "the queue outlived its release"); - assert!( - source.queued_charge.tables.is_empty(), - "the queue's table counts outlived the queue" - ); - assert!( - source.queued_charge.buffers.is_empty(), - "the queue's buffer counts outlived the queue" - ); - assert_eq!(source.queued_charge.bytes, 0); - assert_eq!(source.buffer.held, 0); + assert_eq!(source.buffer.reservation.size(), 0); assert_eq!(pool.reserved(), 0, "the reservation was not returned"); assert!(source.pop_source().unwrap().is_none()); } @@ -2608,83 +2381,6 @@ fn a_series_whose_axis_and_fields_disagree_is_rejected() { ); } -/// One entry's figure is the heap it owns, and its `History` header is charged once, by its slot. -/// -/// The `History` of a label set lives in the map's slot, so a `size_of::()` term in the -/// entry's own figure billed one header twice: once here and once in the capacity term beside it. -/// The two assertions below are the definition of the whole figure -- the labels, the vectors and -/// their runs, the owner's name and tags, and one label-set slot plus one history slot per entry -- -/// so either header counted in the wrong place fails them. -#[test] -fn a_history_entry_is_charged_once_for_its_header() { - let grid = grid(0, 10_000, 2); - let schema = evaluated_schema(Arc::clone(&grid)); - let metric = named_metric("requests", "job"); - let labels = label_set(&metric); - // Not the closing chunk: a closed label set drops its runs, and the runs are what the entry's - // own figure is. - let chunk = evaluated_chunk_of( - &schema, - metric.clone(), - 0, - vec![Some(1.0), Some(2.0)], - false, - ); - - let mut emitted = Emitted::default(); - emitted - .occupy(&NodePath::root(), Some(&metric), &chunk) - .unwrap(); - - let history = emitted - .sets - .get(&labels) - .expect("the chunk recorded its label set"); - // The owner the entry keeps is the series that filled it, so its name and each tag cost the - // same bytes the label set of the chunk did. - let owner = metric.name().map_or(0, |name| name.len()) - + std::mem::size_of_val(metric.tags()) - + metric - .tags() - .iter() - .map(|tag| tag.name.len() + tag.value.len()) - .sum::(); - let entry = label_bytes(&labels) - .saturating_add(history.fields.capacity() * std::mem::size_of::>()) - .saturating_add( - history - .fields - .iter() - .map(|runs| runs.capacity() * std::mem::size_of::()) - .sum::(), - ) - .saturating_add(owner); - assert_eq!( - history.owner.as_ref(), - Some(&metric), - "the entry does not name the series that filled it" - ); - assert!( - history.fields.iter().any(|runs| !runs.is_empty()), - "the entry kept no run, so it has no heap of its own to charge for" - ); - assert_eq!( - emitted.entries, - entry, - "the entry's own bytes are not its labels, its runs and its owner: a `History` header in \ - the figure would add the {} bytes its slot already charges", - std::mem::size_of::(), - ); - assert_eq!( - emitted.bytes(), - entry.saturating_add( - emitted.sets.capacity() - * (std::mem::size_of::() + std::mem::size_of::()) - ), - "the table's capacity is where a label-set slot and one `History` per entry are charged", - ); -} - /// A sparse series that only ever moves forward is appended to its history, not merged into it again /// chunk after chunk. /// diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index 8575c91260a..c6c8fcc3d05 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -192,26 +192,12 @@ impl PendingBatch { /// The bytes this batch's own vectors hold, by capacity. fn bytes(&self) -> usize { - let spans = self - .spans - .iter() - .map(|spans| spans.capacity() * std::mem::size_of::>()) - .fold(0usize, usize::saturating_add); - let columns = self - .columns - .iter() - .map(|column| column.capacity() * std::mem::size_of::>()) - .fold(0usize, usize::saturating_add); - self.indices - .capacity() - .saturating_mul(std::mem::size_of::()) - .saturating_add( - self.eval_ts - .capacity() - .saturating_mul(std::mem::size_of::()), - ) - .saturating_add(spans) - .saturating_add(columns) + let spans: usize = self.spans.iter().map(|spans| spans.capacity()).sum(); + let columns: usize = self.columns.iter().map(|column| column.capacity()).sum(); + self.indices.capacity() * std::mem::size_of::() + + self.eval_ts.capacity() * std::mem::size_of::() + + spans * std::mem::size_of::>() + + columns * std::mem::size_of::>() } /// Drops the accumulated points, keeping the allocations. @@ -303,34 +289,23 @@ 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 dictionary-values buffer, so the bytes the - // key shows are not the bytes it keeps: a key of a few bytes pins the whole buffer it was - // sliced out of, which `capacity` reports for the allocation behind the slice. Charging - // the key's length instead would show a handful of bytes for an allocation the size of a - // decoded batch. (A buffer that does not own its memory reports no capacity, and then the - // bytes it shows are all there is.) - // - // No dedupe is needed against a second slice of the same allocation: one evaluator holds - // one series at a time, and a window over an evaluated input holds no key at all, so a - // pass over this state charges one slice of one allocation rather than one per slice. + // 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. let primary_key = self .primary_key .as_ref() .map_or(0, |key| key.capacity().max(key.len())); - let metric: usize = self - .metric - .name() - .map_or(0, |name| name.len()) - .saturating_add( - self.metric - .tags() - .iter() - .map(|tag| tag.name.len() + tag.value.len()) - .fold(0usize, usize::saturating_add), - ); - std::mem::size_of::() - .saturating_add(primary_key) - .saturating_add(metric) + let metric: usize = self.metric.name().map_or(0, |name| name.len()) + + self + .metric + .tags() + .iter() + .map(|tag| tag.name.len() + tag.value.len()) + .sum::(); + std::mem::size_of::() + primary_key + metric } } @@ -356,7 +331,17 @@ struct FieldSamples { head: usize, /// Native histogram samples, kept apart from the floats as Prometheus does. histograms: Vec<(i64, FloatHistogram)>, + /// 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. + 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 @@ -392,37 +377,14 @@ fn resets_between(resets: &[CounterReset], start: u64, end: u64) -> &[CounterRes } impl FieldSamples { - /// The bytes this field's buffers hold, by capacity. - /// - /// The histogram term is the slot of every retained sample plus the payload the histogram in - /// that slot owns: a slot is one `(i64, FloatHistogram)` worth of struct, and the buckets the - /// histogram keeps are on the heap behind it, up to tens of kilobytes per sample. Only the - /// retained slice is walked, which is the storage the windows still read; the samples before - /// `head` are gone, their payloads with them. + /// The bytes this field's buffers hold, by capacity: the samples, the history behind `head` + /// included, plus the estimated payload of the histograms still held. fn bytes(&self) -> usize { - let histograms = self.histograms[self.histogram_head..] - .iter() - .map(|(_, histogram)| histogram.heap_bytes()) - .fold(0usize, usize::saturating_add); - self.timestamps - .capacity() - .saturating_mul(std::mem::size_of::()) - .saturating_add( - self.values - .capacity() - .saturating_mul(std::mem::size_of::()), - ) - .saturating_add( - self.histograms - .capacity() - .saturating_mul(std::mem::size_of::<(i64, FloatHistogram)>()), - ) - .saturating_add(histograms) - .saturating_add( - self.resets - .capacity() - .saturating_mul(std::mem::size_of::()), - ) + self.timestamps.capacity() * std::mem::size_of::() + + self.values.capacity() * std::mem::size_of::() + + self.histograms.capacity() * std::mem::size_of::<(i64, FloatHistogram)>() + + self.resets.capacity() * std::mem::size_of::() + + self.histogram_bytes } fn new(index_resets: bool) -> Self { @@ -498,6 +460,23 @@ impl FieldSamples { self.resets.drain(..dropped); } + /// 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 { + return; + } + let dropped: usize = self.histograms[..head] + .iter() + .map(|(_, histogram)| histogram.heap_bytes()) + .sum(); + self.histogram_bytes = self.histogram_bytes.saturating_sub(dropped); + self.histograms.drain(..head); + } + /// The resets inside the window holding `len` samples from `head`. fn resets_in(&self, len: usize) -> &[CounterReset] { let start = self.base + self.head as u64; @@ -507,22 +486,20 @@ 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, which is all -/// `size_of::>()` is. A result that is a native histogram does not live in that -/// slot itself: the slot points at a `FloatHistogram` on the heap, which owns its bucket -/// lists in turn, and both are what the row keeps alive between pushes. Only slots that hold a -/// histogram are counted, and only those the last evaluated point left in place: a push clears the -/// row, so the slots past its length hold nothing. +/// 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. fn boxed_bytes(row: &[Option]) -> usize { row.iter() .flatten() - .filter_map(|sample| match sample { + .map(|sample| match sample { GridSample::Histogram(histogram) => { - Some(std::mem::size_of::().saturating_add(histogram.heap_bytes())) + std::mem::size_of::() + histogram.heap_bytes() } - GridSample::Float(_) => None, + GridSample::Float(_) => 0, }) - .fold(0usize, usize::saturating_add) + .sum() } impl RangeEvaluator { @@ -645,34 +622,30 @@ impl RangeEvaluator { self.batch_calls } - /// An accounted lower bound on the bytes this evaluator keeps between pushes. + /// 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 and the native histograms with the payload each of - /// them owns), the reset index, the row a push fills with the histograms it boxes, and the - /// pending batch's own vectors. Left out are the kernel's scratch buffers, this struct's `Vec` - /// headers and the grid, which every chunk addressed on it shares. + /// 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 and the pending batch's own vectors. 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; vector growth during a push is neither reserved nor bounded by one - /// doubling, so this is the storage's size, not a peak over the push. 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. + /// 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. pub(crate) fn retained_bytes(&self) -> usize { - let per_field = self - .fields - .iter() - .map(FieldSamples::bytes) - .fold(0usize, usize::saturating_add); + let fields: usize = self.fields.iter().map(FieldSamples::bytes).sum(); let row = self.row.capacity() * std::mem::size_of::>(); - let boxed = boxed_bytes(&self.row); - let series = self.series.as_ref().map_or(0, SeriesState::identity_bytes); - per_field - .saturating_add(row) - .saturating_add(boxed) - .saturating_add(series) - .saturating_add(self.pending.bytes()) + fields + + row + + boxed_bytes(&self.row) + + self.series.as_ref().map_or(0, SeriesState::identity_bytes) + + self.pending.bytes() } /// Schema of the evaluated series: the input fields on the evaluation grid. @@ -1054,6 +1027,8 @@ impl RangeEvaluator { if !raw && h.reset_hint != CounterResetHint::Gauge { h.reset_hint = CounterResetHint::Unknown; } + field.histogram_bytes = + field.histogram_bytes.saturating_add(h.heap_bytes()); field.histograms.push((shifted, h)); } } @@ -1223,8 +1198,7 @@ impl RangeEvaluator { field.histogram_head = field.histograms.len(); } field.advance(); - field.histograms.drain(..field.histogram_head); - field.histogram_head = 0; + field.advance_histograms(); } Ok(()) } diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index beea2c27a31..183df1c4367 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -831,13 +831,15 @@ fn histogram_chunk(schema: &SeriesSchema, buckets: i32, ts: i64) -> RawSeriesChu .unwrap() } -/// A window has to reserve what a native histogram it retains owns, not only the slot it sits in. +/// 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 -- 64 KiB for the wider one -- so the bytes the evaluator reports have to grow by at least -/// that payload between the two. A figure counting slots alone would report one number for both. +/// 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. #[test] fn a_retained_histogram_is_charged_for_its_buckets() { let retained = |buckets: i32| -> usize { @@ -864,12 +866,114 @@ fn a_retained_histogram_is_charged_for_its_buckets() { evaluator.retained_bytes() }; let (few, many) = (4, 4096); - let payload = usize::try_from(many - few).unwrap() * std::mem::size_of::<(i32, f64)>(); + let physical = usize::try_from(many).unwrap() * std::mem::size_of::<(i32, f64)>(); let (narrow, wide) = (retained(few), retained(many)); assert!( - wide >= narrow + payload, - "a window retaining one histogram of {many} buckets reports {wide} bytes, not the {narrow} \ - it reports for {few} buckets plus the {payload} bytes of bucket payload between them", + wide >= physical / 2, + "a window retaining one histogram of {many} buckets reports {wide} bytes, not at least half \ + the {physical} bytes its buckets occupy", + ); + assert!( + narrow < wide / 2, + "a window retaining one histogram of {few} buckets reports {narrow} bytes, not far below \ + the {wide} bytes it reports for {many} buckets: the bucket payload is not what the \ + estimate follows", + ); +} + +/// 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. +#[test] +fn an_evicted_histogram_releases_its_payload() { + let schema = raw_schema(1); + let buckets = 4096; + let payload = usize::try_from(buckets).unwrap() * std::mem::size_of::<(i32, f64)>(); + let mut evaluator = RangeEvaluator::try_new( + &schema, + grid(0, 10_000, 3), + // 20 s of window over 10 s of step: the histogram at 0 is inside the window of the second + // point but outside the third's, so the second push evicts it. + RangeWindow { + range_ms: 20_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::CountOverTime, + ) + .unwrap(); + evaluator + .push(&histogram_chunk(&schema, buckets, 0)) + .unwrap(); + let retained = evaluator.retained_bytes(); + assert!( + retained >= payload, + "a window retaining one histogram of {buckets} buckets reports {retained} bytes, less than \ + the {payload} bytes of buckets it holds", + ); + + // The float chunk keeps the series open, so only the window drops the histogram. + evaluator + .push(&chunk(&[(30_000, vec![Some(1.0)])], 1, 0, false)) + .unwrap(); + let evicted = evaluator.retained_bytes(); + assert!( + retained.saturating_sub(evicted) >= payload / 2, + "dropping one histogram of {payload} bytes left the estimate at {evicted} bytes, down from \ + {retained}: the payload it owned is still counted", + ); + + evaluator + .push(&chunk(&[(40_000, vec![Some(2.0)])], 1, 0, true)) + .unwrap(); + let closed = evaluator.retained_bytes(); + assert!( + closed < payload / 2, + "a closed series still reports {closed} bytes, of which the {payload} bytes of bucket \ + payload were released with their samples", + ); +} + +/// 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. +#[test] +fn a_fixed_window_over_histograms_keeps_the_estimate_bounded() { + let peak_retained = |chunks: i64| -> usize { + let schema = raw_schema(1); + let mut evaluator = RangeEvaluator::try_new( + &schema, + grid(0, 1, 1024), + // One millisecond of window over a one millisecond step: the next point evicts the + // sample of this one. + RangeWindow { + range_ms: 1, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::CountOverTime, + ) + .unwrap(); + let mut peak = 0; + for ts in 0..chunks { + // Left open: the window, not the close, is what releases the sample. + evaluator.push(&histogram_chunk(&schema, 64, ts)).unwrap(); + peak = peak.max(evaluator.retained_bytes()); + } + peak + }; + assert_eq!( + peak_retained(8), + peak_retained(64), + "a fixed-size window over a series of histograms grew with the length of the series" ); }