diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index dc453cdee9e..ebd9fd6fdd3 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -73,7 +73,7 @@ //! collects the root's chunks and merges them with the same helper. use std::collections::hash_map::Entry; -use std::collections::{HashMap, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; use datafusion::error::{DataFusionError, Result}; @@ -205,6 +205,11 @@ fn series_bytes(series: &Series) -> usize { /// counting that buffer once per chunk would make the operand's figure grow with the number of /// chunks rather than with the data in them. The slices of one series add up to the allocation they /// share, which is the figure a deduplication across the chunks would arrive at. +/// +/// The histogram tables a chunk's segments reference are not part of the figure: a table is one +/// allocation however many chunks index into it, so it is not a per-chunk cost at all. Dropping it +/// here is therefore only half the story -- it must not become a figure the operand never charges. +/// [`unbilled_tables`] is the other half, and the operand bills each table once through it. fn operand_chunk_bytes(series: &Series) -> usize { series_bytes(series) .saturating_sub(fields_bytes(&series.fields)) @@ -246,6 +251,45 @@ fn sample_slice_bytes(fields: &SeriesFields) -> usize { .fold(0usize, usize::saturating_add) } +/// The histogram tables `series` is the first to reference, and the bytes they hold. +/// +/// A table is one allocation the chunks of a series share, so it is neither a per-chunk cost -- +/// counting it per chunk would make a series delivered in a thousand chunks cost a thousand tables +/// -- nor no cost at all, which is what leaving it out of every chunk leaves the figure at. What it +/// is, is a cost of the operand that first retains a chunk referencing it: the identities it returns +/// are the tables `billed` does not hold yet, and the figure is what those tables hold +/// ([`table_bytes`]). The caller bills the figure as it stands and adds the identities to `billed` +/// once the chunk is retained, which is what makes the two halves of the figure agree. +/// +/// The identity is the address of the allocation behind the `Arc`. It names one table for as long as +/// it is remembered, because a chunk referencing a table keeps it alive and no later allocation can +/// be given the same address. A table two segments or two fields of the one chunk reference is +/// listed once. Each identity is also one slot in the set that remembers it, which is charged as it +/// is written -- one entry at a time, like the boundary list's, and not from the capacity the set +/// grows to -- so remembering a table is paid for beside the table itself. +fn unbilled_tables(series: &Series, billed: &HashSet) -> (Vec, usize) { + let mut fresh: Vec = Vec::new(); + let mut bytes = 0usize; + for field in series.fields.iter() { + for segment in field.segments() { + let table = match segment.dense() { + Some(DenseSamplesRef::Histogram(histograms)) => histograms.batch(), + Some(DenseSamplesRef::Mixed(mixed)) => mixed.histograms().batch(), + _ => continue, + }; + let identity = Arc::as_ptr(table) as usize; + if billed.contains(&identity) || fresh.contains(&identity) { + continue; + } + fresh.push(identity); + bytes = bytes + .saturating_add(table_bytes(table)) + .saturating_add(std::mem::size_of::()); + } + } + (fresh, bytes) +} + /// A rough workspace estimate for merging fragments that hold `rows` rows between them. /// /// It allows for sorted row indices, readers, sample descriptors and output headers. Like the @@ -1228,37 +1272,60 @@ struct BinaryOperand { /// alone would read them as one. Only a chunk carrying `is_last` records an end, and it does so /// whether or not it carries a row. ends: Vec, + /// The histogram tables the chunks this operand holds index into, by the address of the + /// allocation behind their `Arc`. + /// + /// A table is one allocation however many chunks of a series index into it, so it is billed + /// once -- by the first chunk that references it -- rather than once per chunk, and the tables + /// this set names are the ones already billed. That is what keeps a series delivered in a + /// thousand chunks from costing a thousand tables, and what keeps a table from costing nothing: + /// a chunk's own figure leaves its tables out ([`operand_chunk_bytes`]), so a table billed by + /// neither this operand nor this set is a table no reservation covers. One slot per billed + /// table is charged with it, so the set's own storage is not a figure no reservation covers + /// either. + tables: HashSet, /// The bytes `series` and `ends` hold, folded in as chunks arrive. /// /// Each chunk is measured once, with the figure of what it holds on its own /// ([`operand_chunk_bytes`]): the samples its rows occupy and the descriptors it keeps, not the /// allocation those samples are slices of, so a series delivered in many chunks is charged the - /// data it holds rather than the same buffer once per chunk. + /// data it holds rather than the same buffer once per chunk. The histogram tables the chunks + /// reference are the other half of that figure: one allocation the chunks share, billed once -- + /// with the one slot that remembers it -- the first time a chunk referencing it arrives + /// ([`unbilled_tables`]). held: usize, } impl BinaryOperand { /// The bytes `chunk` would add to what this operand holds, read without retaining it. /// - /// It is what [`Self::enqueue`] adds for the same chunk: what the chunk holds on its own, and the - /// one entry a chunk that closes its series records in the boundary list. The boundary list holds - /// one `usize` per closed series and is charged one entry at a time as it is written, rather than - /// from the capacity it grows to -- following that `Vec`'s first-four-then-double policy would be - /// a second copy of it to keep in step, and one entry within a factor of two is the granularity - /// the accounting aims at. The figure is what a caller reserves before it retains the chunk, so - /// the pool admits it before the operand holds it. + /// It is what [`Self::enqueue`] adds for the same chunk: what the chunk holds on its own, the + /// histogram tables it is the first to reference, and the one entry a chunk that closes its + /// series records in the boundary list. The boundary list holds one `usize` per closed series and + /// is charged one entry at a time as it is written, rather than from the capacity it grows to -- + /// following that `Vec`'s first-four-then-double policy would be a second copy of it to keep in + /// step, and one entry within a factor of two is the granularity the accounting aims at. The + /// figure is what a caller reserves before it retains the chunk, so the pool admits it before + /// the operand holds it. fn pending(&self, chunk: &EvaluatedChunk) -> usize { let end = if chunk.is_last { std::mem::size_of::() } else { 0 }; - operand_chunk_bytes(&chunk.series).saturating_add(end) + let (_, tables) = unbilled_tables(&chunk.series, &self.tables); + tables + .saturating_add(operand_chunk_bytes(&chunk.series)) + .saturating_add(end) } /// Retains one chunk, folding the estimate it is charged with into what the operand holds. fn enqueue(&mut self, chunk: EvaluatedChunk) { let closing = chunk.is_last; + // The tables this chunk is the first to reference, read before they are recorded: the same + // figure `pending` billed, so what is reserved for the chunk and what it grows the operand + // by are one. + let (tables, bytes) = unbilled_tables(&chunk.series, &self.tables); // The boundary list is storage the operand keeps, and it grows before the chunk is recorded // in it: an end is charged for before it exists, the same figure `pending` reported. self.held = self @@ -1268,7 +1335,11 @@ impl BinaryOperand { } else { 0 }) - .saturating_add(operand_chunk_bytes(&chunk.series)); + .saturating_add(operand_chunk_bytes(&chunk.series)) + .saturating_add(bytes); + // From here the operand keeps those tables alive itself, so a chunk arriving later that + // references one is charged its own slices and not the table again. + self.tables.extend(tables); self.series.push(chunk.series); if closing { self.ends.push(self.series.len()); @@ -1414,6 +1485,10 @@ impl BinaryOperand { self.series.shrink_to_fit(); self.ends.clear(); self.ends.shrink_to_fit(); + // The tables the cleared chunks were keeping alive are gone with them, so their addresses + // name nothing this operand holds any more. + self.tables.clear(); + self.tables.shrink_to_fit(); self.held = 0; } } diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 67f8a47f0e5..33020b87e2f 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -21,7 +21,7 @@ use std::sync::Arc; use datafusion::error::DataFusionError; use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool}; use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricValue}; -use datatypes::arrow::array::{Float64Array, UInt32Array}; +use datatypes::arrow::array::{Array, Float64Array, UInt32Array}; use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; use datatypes::series::histogram::{ BucketSideView, CounterResetHint, HistogramBatch, HistogramBatchBuilder, HistogramView, @@ -588,6 +588,48 @@ fn evaluated_array_chunk_of( EvaluatedChunk::try_new(series, is_last).unwrap() } +/// One evaluated chunk of the series `metric` whose one field holds `indices` into `table`, +/// addressed at `start` on `schema`'s grid. +/// +/// Two chunks built with one `table` are two slices of one allocation; two built with tables of the +/// same shape hold two allocations of the same size. +fn evaluated_histogram_chunk_of( + schema: &SeriesSchema, + metric: MetricName, + start: usize, + indices: Vec>, + table: &Arc, + is_last: bool, +) -> EvaluatedChunk { + let samples = + Samples::try_from_histogram(UInt32Array::from(indices), Arc::clone(table)).unwrap(); + let range = + GridRange::try_new(schema.eval_grid.clone().unwrap(), start, samples.len()).unwrap(); + let series = Series { + metric, + time: TimeAxis::Grid(range), + fields: SeriesFields::try_from_vec(vec![samples]).unwrap(), + }; + EvaluatedChunk::try_new(series, is_last).unwrap() +} + +/// One histogram table of `histograms` histograms of `buckets` buckets each. +fn histogram_table(histograms: usize, buckets: i32) -> Arc { + let mut builder = HistogramBatchBuilder::new(); + for _ in 0..histograms { + push_histogram(&mut builder, buckets); + } + builder.finish().unwrap() +} + +/// What `table` holds: the batch struct and the arrays its columns view. +/// +/// Written out here rather than read from the runtime, so a test can size its expectations from the +/// table it built instead of from the figure it is checking. +fn histogram_table_bytes(table: &Arc) -> usize { + std::mem::size_of::() + table.as_arrow().get_array_memory_size() +} + /// The series `name{job="job"}`, so two series can share the label a map leaves behind. fn named_metric(name: &str, job: &str) -> MetricName { MetricName::try_new( @@ -4875,6 +4917,213 @@ fn a_binary_operand_reserves_what_it_retains() { } } +/// Two chunks that are first to reference a histogram table each are billed a table each. +/// +/// A histogram field's samples are a column of indices into a table, and the table is the bulk of +/// what such a chunk costs: the indices are four bytes a row where the table is thousands of bytes +/// of buckets. Two chunks of the same shape hold two tables, so each costs the other, and each +/// costs at least the table it holds -- a figure that charged the column of indices alone would +/// leave both tables outside everything the node reserves. +#[test] +fn a_binary_operand_bills_each_histogram_table_it_retains() { + const BUCKETS: i32 = 4_000; + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let table = histogram_table(2, BUCKETS); + let other = histogram_table(2, BUCKETS); + let bytes = histogram_table_bytes(&table); + assert_eq!( + bytes, + histogram_table_bytes(&other), + "the two tables are not the same shape, so the two chunks are not comparable" + ); + assert!( + bytes > 32 * 1024, + "a table of {bytes} bytes is no bigger than the descriptors of a one-row chunk, so nothing \ + here would tell a billed table from an unbilled one" + ); + let first = evaluated_histogram_chunk_of(&schema, metric(), 0, vec![Some(0)], &table, true); + let second = evaluated_histogram_chunk_of(&schema, metric(), 1, vec![Some(1)], &other, true); + + let pool = pool(); + let mut runtime = binary_runtime(&pool, &schema); + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first)) + .unwrap(); + let first_cost = runtime.buffer.reservation.size() - before; + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second)) + .unwrap(); + let second_cost = runtime.buffer.reservation.size() - before; + + assert_eq!( + first_cost, second_cost, + "two chunks of one shape and one table each cost different figures: {first_cost} and \ + {second_cost}" + ); + for (name, cost) in [("first", first_cost), ("second", second_cost)] { + assert!( + cost >= bytes, + "the {name} chunk costs {cost} bytes, less than the {bytes} its histogram table holds" + ); + assert!( + cost < 2 * bytes, + "the {name} chunk costs {cost} bytes, more than the {bytes} of its table and the rest \ + of a one-row chunk" + ); + } + assert_eq!( + runtime.buffer.reservation.size(), + first_cost + second_cost, + "the operand does not reserve what the two chunks it retains cost" + ); + assert_eq!(pool.reserved(), runtime.buffer.reservation.size()); +} + +/// Two chunks that index one histogram table are billed that table once. +/// +/// A table is one allocation however many chunks of a series index into it, so the second chunk is +/// charged the descriptor, the index and the end it records, and not the table again. The two +/// chunks here are the same shape, so what separates their figures is the table: the pair costs one +/// table plus both chunks' own descriptors, not one table per chunk and not no table at all. +#[test] +fn a_binary_operand_bills_a_shared_histogram_table_once() { + const BUCKETS: i32 = 4_000; + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let table = histogram_table(2, BUCKETS); + let bytes = histogram_table_bytes(&table); + assert!( + bytes > 32 * 1024, + "a table of {bytes} bytes is no bigger than the descriptors of a one-row chunk, so nothing \ + here would tell a shared table from a second one" + ); + let first = evaluated_histogram_chunk_of(&schema, metric(), 0, vec![Some(0)], &table, true); + let second = evaluated_histogram_chunk_of(&schema, metric(), 1, vec![Some(1)], &table, true); + + let pool = pool(); + let mut runtime = binary_runtime(&pool, &schema); + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first)) + .unwrap(); + let first_cost = runtime.buffer.reservation.size() - before; + let before = runtime.buffer.reservation.size(); + runtime + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second)) + .unwrap(); + let second_cost = runtime.buffer.reservation.size() - before; + + assert!( + first_cost >= bytes, + "the chunk that first references the table costs {first_cost} bytes, less than the {bytes} \ + the table holds" + ); + // The two chunks are the same shape, so the second one is charged its own descriptors and not + // the table: it costs a small fraction of what the table holds, where a second table would cost + // the table again. + assert!( + second_cost * 8 < bytes, + "the second slice of one table costs {second_cost} bytes, comparable to the {bytes} the \ + table itself holds" + ); + // What the pair costs past the second chunk is the table the first one billed, and no more than + // the few bytes that remembering it takes. + let difference = first_cost.saturating_sub(second_cost); + assert!( + difference >= bytes, + "the pair costs {difference} bytes more than its second chunk, less than the {bytes} of the \ + one table between them" + ); + assert!( + difference <= bytes + 64, + "the pair costs {difference} bytes more than its second chunk, past the {bytes} of the one \ + table between them: the table is billed twice" + ); + assert!( + runtime.buffer.reservation.size() < bytes + 2 * second_cost + 64, + "the operand charges the one table of its two chunks twice: {} bytes for {} bytes of table", + runtime.buffer.reservation.size(), + bytes + ); + assert_eq!(pool.reserved(), runtime.buffer.reservation.size()); +} + +/// A pool with room for one histogram table admits one chunk of a table, refuses a second chunk +/// holding another table, and admits a second slice of the table it already holds. +/// +/// This is the figure the reservation is made for: a chunk that is the first to reference a table +/// costs that table, so two of them do not fit in room for one, while a chunk that indexes a table +/// the operand already holds costs its own slice and does. The room beside the first chunk is half a +/// table -- far more than the descriptors of a second chunk and far less than a second table -- and +/// the refused chunk leaves the operand where it was. +#[test] +fn a_pool_that_holds_one_histogram_table_refuses_a_second() { + const BUCKETS: i32 = 4_000; + let grid = grid(0, 60_000, 2); + let schema = evaluated_schema(Arc::clone(&grid)); + let table = histogram_table(2, BUCKETS); + let other = histogram_table(2, BUCKETS); + let bytes = histogram_table_bytes(&table); + assert!( + bytes > 32 * 1024, + "a table of {bytes} bytes is no bigger than the descriptors of a one-row chunk, so the room \ + beside one table would hold a second" + ); + let first = evaluated_histogram_chunk_of(&schema, metric(), 0, vec![Some(0)], &table, true); + let second_own = + evaluated_histogram_chunk_of(&schema, metric(), 0, vec![Some(0)], &other, true); + let second_shared = + evaluated_histogram_chunk_of(&schema, metric(), 1, vec![Some(1)], &table, true); + + // What the operand holds once it retains one chunk of a table, measured where the pool admits + // anything; the pool below is sized from it and half a table. + let mut probe = binary_runtime(&pool(), &schema); + probe + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first.clone())) + .unwrap(); + let one_chunk = probe.buffer.reservation.size(); + let budget = one_chunk + bytes / 2; + + // A second chunk holding a table of its own does not fit: the pool refuses it and the operand + // keeps what it had. + let mut refused = binary_runtime(&bounded_pool(budget), &schema); + refused + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first.clone())) + .unwrap(); + let error = refused + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second_own)) + .unwrap_err(); + assert!( + matches!(error, DataFusionError::ResourcesExhausted(_)), + "a second chunk holding a table of its own was admitted beside the first: {error}" + ); + assert_eq!( + refused.buffer.reservation.size(), + one_chunk, + "the refused chunk moved what the operand reserves" + ); + + // The second slice of the one table the operand holds does fit. + let mut shared = binary_runtime(&bounded_pool(budget), &schema); + shared + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(first)) + .unwrap(); + shared + .retain_binary(&NodePath::root(), 0, NativeChunk::Evaluated(second_shared)) + .unwrap(); + assert!( + shared.buffer.reservation.size() > one_chunk, + "the second slice of the table was admitted without being charged its own descriptors" + ); + assert!( + shared.buffer.reservation.size() <= budget, + "the operand reserves past the pool it was admitted in" + ); +} + /// The executor's binary node holds no more than the operands it retains: the peak of its own /// reservation is what every retained chunk holds on its own, not that plus a chunk it was handed /// again. diff --git a/src/promql/src/vector_match/tests.rs b/src/promql/src/vector_match/tests.rs index 6a807824ccd..f8d64b7e966 100644 --- a/src/promql/src/vector_match/tests.rs +++ b/src/promql/src/vector_match/tests.rs @@ -3140,6 +3140,11 @@ fn sparse_wide_results_are_charged_their_index_columns() { /// pair differs in count and sum as well. What this pins is that a comparison passes the stored /// payload through, not a Prometheus result. A `bool` comparison answers in floats, so nothing it /// hands out is a histogram and no start timestamp leaves it. +/// +/// Every comparison is run twice, through both entry points: the public one, and the one the +/// runtime calls with a reservation. They share one kernel, but only the second walks a comparison +/// while a budget holds the workspace it allocates, so the payload this test is about is only +/// pinned under a reservation by the second run. #[test] fn a_histogram_comparison_filter_keeps_the_payload_of_the_operand_it_keeps() { let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1_000, 3).unwrap()).unwrap()); @@ -3215,29 +3220,51 @@ fn a_histogram_comparison_filter_keeps_the_payload_of_the_operand_it_keeps() { fill: FillValues::default(), }; - let eq = binary_vectors(&matching(BinaryOp::Eq), &schema, &lhs, &schema, &rhs).unwrap(); - assert_eq!( - kept(&eq), - [ - ("eq".to_string(), 0, 4.0, 6.0, Some(LEFT_START), 2), - ("eq".to_string(), 2, 4.0, 6.0, Some(LEFT_START), 2), - ], - "`==` did not hand back the left histogram it kept: {eq:?}" - ); + // One comparison through both entry points: the answer the public one gives, and the answer the + // budgeted one gives, which is asserted to have reserved the workspace it walked. + let compare = |matching: &BinaryMatching| -> [Vec; 2] { + let mut reserved = Vec::new(); + let budgeted = + binary_vectors_with_reservation(matching, &schema, &lhs, &schema, &rhs, &mut |total| { + reserved.push(total); + Ok(()) + }) + .unwrap(); + assert!( + !reserved.is_empty(), + "the budgeted comparison reserved nothing, so it did not run under a reservation" + ); + let public = binary_vectors(matching, &schema, &lhs, &schema, &rhs).unwrap(); + [public, budgeted] + }; - let ne = binary_vectors(&matching(BinaryOp::Ne), &schema, &lhs, &schema, &rhs).unwrap(); - assert_eq!( - kept(&ne), - [ - ("ne".to_string(), 0, 4.0, 6.0, Some(LEFT_START), 2), - ("ne".to_string(), 2, 4.0, 6.0, Some(LEFT_START), 2), - ], - "`!=` did not hand back the left histogram it kept: {ne:?}" - ); + let eq = compare(&matching(BinaryOp::Eq)); + for eq in &eq { + assert_eq!( + kept(eq), + [ + ("eq".to_string(), 0, 4.0, 6.0, Some(LEFT_START), 2), + ("eq".to_string(), 2, 4.0, 6.0, Some(LEFT_START), 2), + ], + "`==` did not hand back the left histogram it kept: {eq:?}" + ); + } + + let ne = compare(&matching(BinaryOp::Ne)); + for ne in &ne { + assert_eq!( + kept(ne), + [ + ("ne".to_string(), 0, 4.0, 6.0, Some(LEFT_START), 2), + ("ne".to_string(), 2, 4.0, 6.0, Some(LEFT_START), 2), + ], + "`!=` did not hand back the left histogram it kept: {ne:?}" + ); + } // The right operand's start timestamp is never what comes out, at any point of either // comparison. - for series in eq.iter().chain(&ne) { + for series in eq.iter().chain(&ne).flat_map(|answer| answer.iter()) { let mut cursor = series.fields.as_slice()[0].cursor(); for (point, row) in series.time.positions() { let SampleRef::Histogram(view) = @@ -3260,7 +3287,6 @@ fn a_histogram_comparison_filter_keeps_the_payload_of_the_operand_it_keeps() { return_bool: true, ..matching(BinaryOp::Eq) }; - let compared = binary_vectors(&bool_matching, &schema, &lhs, &schema, &rhs).unwrap(); let answers = |series: &[Series]| -> Vec<(String, usize, f64)> { let mut answers: Vec<(String, usize, f64)> = Vec::new(); for series in series { @@ -3276,16 +3302,19 @@ fn a_histogram_comparison_filter_keeps_the_payload_of_the_operand_it_keeps() { answers.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1))); answers }; - assert_eq!( - answers(&compared), - [ - ("eq".to_string(), 0, 1.0), - ("eq".to_string(), 2, 1.0), - ("ne".to_string(), 0, 0.0), - ("ne".to_string(), 2, 0.0), - ], - "a `bool` comparison of histograms did not answer in floats: {compared:?}" - ); + let compared = compare(&bool_matching); + for compared in &compared { + assert_eq!( + answers(compared), + [ + ("eq".to_string(), 0, 1.0), + ("eq".to_string(), 2, 1.0), + ("ne".to_string(), 0, 0.0), + ("ne".to_string(), 2, 0.0), + ], + "a `bool` comparison of histograms did not answer in floats: {compared:?}" + ); + } } /// A set operation hands back the sample it kept, start timestamp included.