From 82ed828deda9d8902ab4e5ddcbcf1575ba9544ef Mon Sep 17 00:00:00 2001 From: discord9 Date: Mon, 23 Nov 2026 08:26:22 +0000 Subject: [PATCH] perf(promql): hand series chunks between native operators in process (#10506) * perf(promql): introduce the in-process series plan and chunk handover Signed-off-by: discord9 * feat(promql): hand aggregate state between native operators as chunks too Signed-off-by: discord9 * feat(promql): read children as chunks and hand fused outputs over in process Signed-off-by: discord9 * fix(promql): keep the chunk handover's checks and accounting honest Signed-off-by: discord9 * fix(promql): hold a handed-over state to the checks the frame path makes A router that reads chunks applied none of what a router that reads batches applies: it routed state of any kind, layout or grid, and it released the child's charge for a publication while the groups cut from it were still queued, so a retained row was charged for its slice and not for the batch it slices. The chunk path now holds a publication to the declared state - kind, ordered components, grid, field count - and refuses one that differs, with the error the frame path raises for a mismatching batch. The child's charge moves onto every group cut from the publication and travels with the handed value, so a retained row keeps the parent batch charged. State rows gain one constructor for their layout: `StateRowLayout` resolves the field struct, the field count and the grid once per publication and `row` builds the row against them, so a group costs its own encoding, and the grid and no-contribution checks that `state_row_from_frame_row` made now hold for every row rather than being deferred to the consumer. Tests: a held state group outlives the export that produced it; a chunk-fed router keeps the parent batch charged until its row is dropped; a chunk of another state is refused and a duplicated input survives the chunk path as it does the frame path; a state row refuses positions on another grid and a position no field carries. Signed-off-by: discord9 --------- Signed-off-by: discord9 --- src/common/query/src/series_frame.rs | 37 +- src/datatypes/src/series/frame.rs | 459 ++++-- src/datatypes/src/series/frame/tests.rs | 162 ++ src/promql/src/aggregate/state.rs | 2 +- src/promql/src/extension_plan.rs | 5 + src/promql/src/extension_plan/fused_series.rs | 480 +++++- .../src/extension_plan/fused_series/tests.rs | 1450 ++++++++++++++++- .../src/extension_plan/raw_series_source.rs | 128 +- .../src/extension_plan/series_execution.rs | 402 +++++ .../extension_plan/series_execution/tests.rs | 211 +++ .../src/extension_plan/series_repartition.rs | 975 +++++++++-- .../series_repartition/tests.rs | 658 ++++++++ src/promql/src/native/aggregate.rs | 109 +- src/promql/src/native/execute.rs | 20 +- src/promql/src/native/state.rs | 20 +- 15 files changed, 4733 insertions(+), 385 deletions(-) create mode 100644 src/promql/src/extension_plan/series_execution.rs create mode 100644 src/promql/src/extension_plan/series_execution/tests.rs diff --git a/src/common/query/src/series_frame.rs b/src/common/query/src/series_frame.rs index b74fafd6fe3..207e54fac0a 100644 --- a/src/common/query/src/series_frame.rs +++ b/src/common/query/src/series_frame.rs @@ -640,7 +640,13 @@ fn invalid(reason: impl Into) -> DataFusionError { /// the previous owned key (not an Arrow buffer), timestamp, metric, and finality. An `Interleaved` /// chain releases that state on closure, so later fragment chains may recur with the same key, /// labels, and timestamps independently. -struct SequenceValidator { +/// +/// Both frame streams run it - [`pack_raw_series`] over what a producer publishes and +/// [`unpack_raw_series`] over what a consumer receives - and it is reachable on its own for the one +/// reader that has neither a frame nor a batch in between: a consumer handed the chunks in process +/// runs exactly this check over exactly the same sequence, so the shortcut validates what the frame +/// would have carried instead of trusting it. +pub struct SequenceValidator { ordering: SeriesOrdering, previous_key: Option>, previous_timestamp: Option, @@ -649,7 +655,8 @@ struct SequenceValidator { } impl SequenceValidator { - fn new(ordering: SeriesOrdering) -> Self { + /// A validator for a raw stream that declares `ordering`. + pub fn new(ordering: SeriesOrdering) -> Self { Self { ordering, previous_key: None, @@ -659,14 +666,16 @@ impl SequenceValidator { } } - fn finish(&self) -> datafusion_common::Result<()> { + /// Checks that the stream ended between chains, and not inside one. + pub fn finish(&self) -> datafusion_common::Result<()> { if self.previous_key.is_some() && !self.previous_is_last { return Err(invalid("raw series stream ended before key was final")); } Ok(()) } - fn validate(&mut self, chunk: &RawSeriesChunk) -> datafusion_common::Result<()> { + /// Checks `chunk` against the chain this validator has read so far. + pub fn validate(&mut self, chunk: &RawSeriesChunk) -> datafusion_common::Result<()> { let key = chunk.primary_key.as_slice(); let timestamp = chunk .time @@ -732,17 +741,28 @@ impl SequenceValidator { /// them closes itself, so a closed chain may be followed by another chain whose labels happen to be /// equal. Only the still-open chain is remembered, which is what keeps such a contribution from being /// refused as a re-opened series while still refusing a chain that changes identity before it closes. -struct EvaluatedSequenceValidator { +/// +/// Like [`SequenceValidator`] it is the check both evaluated frame streams run and is reachable on +/// its own for a consumer that is handed the chunks in process. +pub struct EvaluatedSequenceValidator { /// The labels of the open chain and the last grid position it carried. open: Option<(SeriesLabels, usize)>, } +impl Default for EvaluatedSequenceValidator { + fn default() -> Self { + Self::new() + } +} + impl EvaluatedSequenceValidator { - fn new() -> Self { + /// A validator with no open chain. + pub fn new() -> Self { Self { open: None } } - fn finish(&self) -> datafusion_common::Result<()> { + /// Checks that the stream ended between chains, and not inside one. + pub fn finish(&self) -> datafusion_common::Result<()> { if self.open.is_some() { return Err(invalid( "evaluated series stream ended before a chain closed", @@ -751,7 +771,8 @@ impl EvaluatedSequenceValidator { Ok(()) } - fn validate(&mut self, series: &Series, is_last: bool) -> datafusion_common::Result<()> { + /// Checks `series` against the chain this validator has read so far. + pub fn validate(&mut self, series: &Series, is_last: bool) -> datafusion_common::Result<()> { let (Some(first), Some(last)) = (series.time.first_position(), series.time.last_position()) else { // No carried position: only a closing chunk may be empty, and it closes the chain it diff --git a/src/datatypes/src/series/frame.rs b/src/datatypes/src/series/frame.rs index 803ffcb8a44..cf7c1d29590 100644 --- a/src/datatypes/src/series/frame.rs +++ b/src/datatypes/src/series/frame.rs @@ -1853,6 +1853,167 @@ fn compact_histogram(values: &HistogramSamples) -> Result<(ArrayRef, UInt32Array Ok((table, UInt32Array::from(remapped))) } +/// The `fields` column of a state frame: one list per row, one item per carried position. +/// +/// A state frame's per-field list carries one item per grid position the row holds, and an item is +/// absent exactly where that field has no contribution at that position. The absence lives on the +/// item - the child struct's validity - not on the list's own validity, which is per row: a row +/// always has a list, with zero or more items in it. +/// +/// One encoder builds this column, so a state frame and a state row handed over in process are the +/// same bytes: [`StateFrameRow::from_state_series`] calls it for a single group, and the frame +/// encoder calls it for the rows it is about to write. +fn encode_state_fields(field_types: &Fields, rows: &[FrameRow]) -> Result { + // A state frame's per-field list carries one item per grid position the row holds, and an + // item is absent exactly where that field has no contribution at that position. The + // absence lives on the item — the child struct's validity — not on the list's own + // validity, which is per row: a row always has a list, with zero or more items in it. + let count = rows.len(); + let mut field_arrays: Vec = Vec::with_capacity(field_types.len()); + for (index, field) in field_types.iter().enumerate() { + let mut lengths = Vec::with_capacity(count); + let mut positions = 0usize; + for row in rows { + let RowPayload::States(fields) = &row.payload else { + return invalid_series("state frame row carries sample payload"); + }; + let values = fields + .get(index) + .ok_or_else(|| err("state field count mismatch"))?; + if values.len() != row.time.len()? { + return invalid_series("state list length mismatch"); + } + lengths.push(values.len()); + positions = add_checked(positions, values.len())?; + } + + let item = match field.data_type() { + DataType::List(item) => item, + _ => return invalid_series("state field schema mismatch"), + }; + let DataType::Struct(components) = item.data_type() else { + return invalid_series("state list item is not a component struct"); + }; + // Absence lives on the item, so the child struct's validity is one flag per position. + // A row of a state frame always carries states; a caller that hands in the wrong payload + // is refused here rather than panicking inside an iterator. + let mut present = Vec::with_capacity(positions); + for row in rows { + let RowPayload::States(fields) = &row.payload else { + return invalid_series("state frame row carries sample payload"); + }; + present.extend(fields[index].iter().map(Option::is_some)); + } + debug_assert_eq!(present.len(), positions); + + // Every component of a field is absent at exactly the same positions - the field's own - + // so they share the one mask, which the child struct already needs. + let nulls = present + .iter() + .any(|present| !present) + .then(|| NullBuffer::from(present.clone())); + // A column's name is the component it declares, so each array is built by reading that + // component off the payload; a payload that does not keep it is refused rather than + // written as a zero. + let arrays: Vec = components + .iter() + .map(|component| { + let declared = StateComponent::parse(component.name())?; + let array: ArrayRef = match declared { + StateComponent::HistogramValue | StateComponent::HistogramCompensation => { + // One histogram per position, so one batch carries the whole column. An + // absent position holds an empty placeholder whose value the shared mask + // makes unreadable, exactly as a null float slot holds a zero. + let mut histograms = HistogramBatchBuilder::new(); + for row in rows { + for state in state_field(row, index)? { + let Some(state) = state else { + histograms.push(empty_histogram())?; + continue; + }; + let histogram = state + .histogram_component(declared) + .ok_or_else(missing_state_component)?; + if histogram.len() != 1 { + return invalid_series( + "a histogram state component carries exactly one histogram", + ); + } + let view = histogram.view(0).ok_or_else(missing_state_component)?; + histograms.push(view)?; + } + } + let batch = histograms.finish()?; + Arc::new( + StructArray::try_new( + histogram_fields(), + batch.as_arrow().columns().to_vec(), + nulls.clone(), + ) + .map_err(|error| err(error.to_string()))?, + ) as ArrayRef + } + StateComponent::Value + | StateComponent::Mean + | StateComponent::Compensation + | StateComponent::Count => { + let mut floats = Vec::with_capacity(positions); + for row in rows { + for state in state_field(row, index)? { + // A missing position's value is unreadable, so it holds the same + // zero a null slot has always held here. + floats.push(match state { + None => 0.0, + Some(state) => state + .float_component(declared) + .ok_or_else(missing_state_component)?, + }); + } + } + Arc::new(Float64Array::new(ScalarBuffer::from(floats), nulls.clone())) + } + _ => { + let mut booleans = Vec::with_capacity(positions); + for row in rows { + for state in state_field(row, index)? { + booleans.push(match state { + None => false, + Some(state) => state + .bool_component(declared) + .ok_or_else(missing_state_component)?, + }); + } + } + Arc::new(BooleanArray::new( + BooleanBuffer::from(booleans), + nulls.clone(), + )) + } + }; + Ok(array) + }) + .collect::>>()?; + + let child = if components.is_empty() { + Arc::new(StructArray::new_empty_fields( + positions, + Some(NullBuffer::from(present)), + )) as ArrayRef + } else { + Arc::new( + StructArray::try_new(components.clone(), arrays, Some(NullBuffer::from(present))) + .map_err(|error| err(error.to_string()))?, + ) as ArrayRef + }; + // The list itself is valid for every row: absence is an absent item, never an absent + // list, so a reader can tell "this field holds nothing here" from "this row has no + // list at all". + let list = list_array(&lengths, child, item.as_ref().clone(), None)?; + field_arrays.push(Arc::new(list) as ArrayRef); + } + struct_array(field_types.clone(), field_arrays) +} + /// Encodes buffered rows as one batch with direct N-row Arrow array construction. /// /// Each histogram segment carries each *distinct* table row it references exactly once, and its @@ -1938,159 +2099,7 @@ fn encode_rows(schema: &SchemaRef, shape: FrameShape, rows: &[FrameRow]) -> Resu }; if shape.content == FrameContent::AggregateState { - // A state frame's per-field list carries one item per grid position the row holds, and an - // item is absent exactly where that field has no contribution at that position. The - // absence lives on the item — the child struct's validity — not on the list's own - // validity, which is per row: a row always has a list, with zero or more items in it. - let mut field_arrays: Vec = Vec::with_capacity(field_types.len()); - for (index, field) in field_types.iter().enumerate() { - let mut lengths = Vec::with_capacity(count); - let mut positions = 0usize; - for row in rows { - let RowPayload::States(fields) = &row.payload else { - return invalid_series("state frame row carries sample payload"); - }; - let values = fields - .get(index) - .ok_or_else(|| err("state field count mismatch"))?; - if values.len() != row.time.len()? { - return invalid_series("state list length mismatch"); - } - lengths.push(values.len()); - positions = add_checked(positions, values.len())?; - } - - let item = match field.data_type() { - DataType::List(item) => item, - _ => return invalid_series("state field schema mismatch"), - }; - let DataType::Struct(components) = item.data_type() else { - return invalid_series("state list item is not a component struct"); - }; - // Absence lives on the item, so the child struct's validity is one flag per position. - // A row of a state frame always carries states; a caller that hands in the wrong payload - // is refused here rather than panicking inside an iterator. - let mut present = Vec::with_capacity(positions); - for row in rows { - let RowPayload::States(fields) = &row.payload else { - return invalid_series("state frame row carries sample payload"); - }; - present.extend(fields[index].iter().map(Option::is_some)); - } - debug_assert_eq!(present.len(), positions); - - // Every component of a field is absent at exactly the same positions - the field's own - - // so they share the one mask, which the child struct already needs. - let nulls = present - .iter() - .any(|present| !present) - .then(|| NullBuffer::from(present.clone())); - // A column's name is the component it declares, so each array is built by reading that - // component off the payload; a payload that does not keep it is refused rather than - // written as a zero. - let arrays: Vec = components - .iter() - .map(|component| { - let declared = StateComponent::parse(component.name())?; - let array: ArrayRef = match declared { - StateComponent::HistogramValue | StateComponent::HistogramCompensation => { - // One histogram per position, so one batch carries the whole column. An - // absent position holds an empty placeholder whose value the shared mask - // makes unreadable, exactly as a null float slot holds a zero. - let mut histograms = HistogramBatchBuilder::new(); - for row in rows { - for state in state_field(row, index)? { - let Some(state) = state else { - histograms.push(empty_histogram())?; - continue; - }; - let histogram = state - .histogram_component(declared) - .ok_or_else(missing_state_component)?; - if histogram.len() != 1 { - return invalid_series( - "a histogram state component carries exactly one histogram", - ); - } - let view = histogram - .view(0) - .ok_or_else(missing_state_component)?; - histograms.push(view)?; - } - } - let batch = histograms.finish()?; - Arc::new( - StructArray::try_new( - histogram_fields(), - batch.as_arrow().columns().to_vec(), - nulls.clone(), - ) - .map_err(|error| err(error.to_string()))?, - ) as ArrayRef - } - StateComponent::Value - | StateComponent::Mean - | StateComponent::Compensation - | StateComponent::Count => { - let mut floats = Vec::with_capacity(positions); - for row in rows { - for state in state_field(row, index)? { - // A missing position's value is unreadable, so it holds the same - // zero a null slot has always held here. - floats.push(match state { - None => 0.0, - Some(state) => state - .float_component(declared) - .ok_or_else(missing_state_component)?, - }); - } - } - Arc::new(Float64Array::new(ScalarBuffer::from(floats), nulls.clone())) - } - _ => { - let mut booleans = Vec::with_capacity(positions); - for row in rows { - for state in state_field(row, index)? { - booleans.push(match state { - None => false, - Some(state) => state - .bool_component(declared) - .ok_or_else(missing_state_component)?, - }); - } - } - Arc::new(BooleanArray::new( - BooleanBuffer::from(booleans), - nulls.clone(), - )) - } - }; - Ok(array) - }) - .collect::>>()?; - - let child = if components.is_empty() { - Arc::new(StructArray::new_empty_fields( - positions, - Some(NullBuffer::from(present)), - )) as ArrayRef - } else { - Arc::new( - StructArray::try_new( - components.clone(), - arrays, - Some(NullBuffer::from(present)), - ) - .map_err(|error| err(error.to_string()))?, - ) as ArrayRef - }; - // The list itself is valid for every row: absence is an absent item, never an absent - // list, so a reader can tell "this field holds nothing here" from "this row has no - // list at all". - let list = list_array(&lengths, child, item.as_ref().clone(), None)?; - field_arrays.push(Arc::new(list) as ArrayRef); - } - let fields = struct_array(field_types.clone(), field_arrays)?; + let fields = encode_state_fields(field_types, rows)?; return assemble_frame_batch(schema, shape, rows, time, fields); } let mut empty_table: Option = None; @@ -2440,7 +2449,151 @@ pub struct StateFrameRow { state: AggregateStateSchema, } +/// The Arrow layout the state rows of one publication are encoded against. +/// +/// Building a row needs three things that depend on the state layout and the series it is of rather +/// than on the group: the `fields` column's item struct, the components each item carries, and the +/// grid the positions are on. Resolving them once makes a group cost its own encoding and nothing +/// else, which is what a consumer merging the groups of one publication wants. +/// +/// One constructor builds every row of every group ([`StateRowLayout::row`]), so a producer that +/// hands a row over in process and a frame a boundary reads cannot disagree about what a row is. +pub struct StateRowLayout { + /// The layout every row is validated against, and the one its fields encode. + state: AggregateStateSchema, + /// How many series fields a row carries. + fields: usize, + /// The grid a row's positions are on. + grid: Arc, + /// The `fields` column's item struct, resolved from the frame schema once. + field_types: Fields, +} + +impl StateRowLayout { + /// The layout `schema`'s export declares, as the rows of its groups are built against it. + /// + /// `state` is the layout the export declares: it is checked against itself once here, so a + /// layout no row could encode is refused before any group is built against it. + pub fn try_new(state: &AggregateStateSchema, schema: &SeriesSchema) -> Result { + let grid = schema + .eval_grid + .clone() + .ok_or_else(|| err("an aggregate state chunk needs an evaluation grid"))?; + let state = AggregateStateSchema::try_new(state.kind, state.components.to_vec())?; + let frame_schema = aggregate_state_frame_schema(&state, schema, FrameLabelMode::Explicit)?; + let DataType::Struct(field_types) = frame_schema.field(3).data_type() else { + return invalid_series("fields schema mismatch"); + }; + Ok(Self { + state, + fields: schema.fields.len(), + grid, + field_types: field_types.clone(), + }) + } + + /// One producer group as the state row a consumer merges. + /// + /// The group already is the row: field-major state on sparse absolute positions, the labels it + /// was folded under, and whether it closes its chain. What the group must also be is a row of + /// this layout: its positions on this grid, its field count the series', and every position it + /// carries a contribution from at least one field. Those are checked here rather than where the + /// row is consumed, so a row that exists is a row a merge can read - exactly what the frame + /// decoder checks of a decoded frame row. + pub fn row(&self, series: StateSeries, is_last: bool) -> Result { + if series.states.len() != self.fields + || series + .states + .iter() + .any(|field| field.len() != series.time.len()) + { + return invalid_series("aggregate state fields do not match the carried positions"); + } + // A position is addressed on the grid this layout declares: a group folded on another grid + // would name positions this node's merge does not have. + if !series + .time + .grid() + .is_some_and(|grid| grid.spec() == self.grid.spec()) + { + return invalid_series("aggregate state positions are not on the series grid"); + } + let spans = series + .time + .runs() + .map(|run| GridSpan::new(run.position, run.len)) + .collect::>(); + let axis = TimeAxis::from_grid_spans(Arc::clone(&self.grid), spans)?; + let row = FrameRow { + key: None, + metric: Some(series.metric.clone()), + is_last, + time: RowTime::Spans( + axis.runs() + .map(|run| GridSpan::new(run.position, run.len)) + .collect(), + ), + payload: RowPayload::States(series.states), + bytes: 0, + }; + let fields = encode_state_fields(&self.field_types, std::slice::from_ref(&row))?; + // The row is checked against the layout it declares, so a consumer that merges it reads the + // components this producer wrote and nothing else - the same check the frame decoder makes. + let validated = StateFieldsBatch::try_from_arrow(fields.clone(), &self.state)?; + if validated.len() != self.fields { + return invalid_series("aggregate state field count mismatch"); + } + for field in 0..validated.len() { + let items = validated + .field(field) + .ok_or_else(|| err("null state field list"))?; + if items.len() != axis.len() { + return invalid_series("state list length does not match carried positions"); + } + } + // A carried position exists because a field has a contribution there; one no field carries + // is a position the merge would have to invent a state for, so it is refused here. + for position in 0..axis.len() { + let mut present = false; + for field in 0..validated.len() { + present |= validated.is_present(field, position)?; + } + if !present { + return invalid_series("aggregate state names a position with no contribution"); + } + } + Ok(StateFrameRow { + metric: series.metric, + time: axis, + is_last, + fields, + state: self.state.clone(), + }) + } +} + impl StateFrameRow { + /// One producer group as the state row a consumer merges. + /// + /// The group already is the row: field-major state on sparse absolute positions, the labels it + /// was folded under, and whether it closes its chain. Building it here is what lets a producer + /// hand the row over in process instead of packing a frame and decoding it back, and it is the + /// same construction the frame encoder uses ([`encode_state_fields`]), so the two readings of + /// one export cannot disagree. + /// + /// `state` is the layout the export declares and `schema` the series it is of: both are checked + /// against the group before anything is built, exactly as the frame decoder checks them against + /// the frame it reads. Building many groups of one export is what [`StateRowLayout`] is for; this + /// is that layout resolved for one row. + pub fn from_state_series( + state: &AggregateStateSchema, + schema: &SeriesSchema, + series: StateSeries, + is_last: bool, + ) -> Result { + StateRowLayout::try_new(state, schema)?.row(series, is_last) + } + /// Complete group identity for this row. pub fn metric(&self) -> &SeriesLabels { &self.metric diff --git a/src/datatypes/src/series/frame/tests.rs b/src/datatypes/src/series/frame/tests.rs index 6101d445675..35793635a01 100644 --- a/src/datatypes/src/series/frame/tests.rs +++ b/src/datatypes/src/series/frame/tests.rs @@ -4773,6 +4773,168 @@ mod aggregate_state_acceptance { (batch, decoder) } + /// The row a producer builds is the row the frame it would have written carries. + /// + /// One encoder builds both: `from_state_series` for the single group a consumer merges in + /// process, and the frame encoder for the columns a boundary consumer decodes. So the labels, + /// the carried positions, the finality and every component value have to be identical - which is + /// what makes handing the row over a saving rather than a second semantics. + #[test] + fn a_state_row_is_the_row_the_frame_carries() { + let schema = state_schema(&["v"], 3); + let state = AggregateStateSchema::try_new( + Kind::Sum, + vec![Component::Value, Component::Compensation], + ) + .unwrap(); + let series = StateSeries { + metric: metric(Some("m"), &[("job", "x")]), + time: TimeAxis::from_grid_spans( + schema.eval_grid.clone().unwrap(), + vec![GridSpan::new(0, 2), GridSpan::new(2, 1)], + ) + .unwrap(), + states: vec![values(3, 1.0)], + }; + let direct = + StateFrameRow::from_state_series(&state, &schema, series.clone(), true).unwrap(); + + let (batch, decoder) = state_frame( + Kind::Sum, + &schema, + vec![GridSpan::new(0, 2), GridSpan::new(2, 1)], + series.states.clone(), + true, + ); + let framed = decoder.decode_aggregate_state(&batch).unwrap(); + assert_eq!(1, framed.len(), "one group is one row"); + let framed = &framed[0]; + + assert_eq!(direct.metric(), framed.metric()); + assert_eq!(direct.is_last(), framed.is_last()); + assert_eq!( + direct.time().positions().collect::>(), + framed.time().positions().collect::>(), + "the same positions, in the same order" + ); + let built = direct.fields().unwrap(); + let decoded = framed.fields().unwrap(); + assert_eq!(built.kind(), decoded.kind()); + assert_eq!(built.components(), decoded.components()); + assert_eq!(built.len(), decoded.len(), "the same fields"); + for field in 0..built.len() { + let items = built.field(field).expect("the field is present"); + for position in 0..items.len() { + assert_eq!( + built.is_present(field, position).unwrap(), + decoded.is_present(field, position).unwrap(), + "field {field} at {position} is present on both" + ); + } + assert_eq!( + built.field_values(field, Component::Value).unwrap(), + decoded.field_values(field, Component::Value).unwrap(), + "field {field} carries the same values" + ); + assert_eq!( + built.field_values(field, Component::Compensation).unwrap(), + decoded + .field_values(field, Component::Compensation) + .unwrap(), + "field {field} carries the same compensations" + ); + } + } + + /// A group whose positions are on another grid is refused where the row is built. + /// + /// A row addresses positions on the grid its export declares; one folded on a different grid + /// names positions that grid does not have, so a merge reading it would either drop the + /// contribution or read another point's. The frame decoder never meets such a row - it builds + /// every axis on the grid the frame declares - so the in-process construction is where the + /// claim has to be checked, once, instead of at the merge. + #[test] + fn a_state_row_refuses_positions_on_another_grid() { + let schema = state_schema(&["v"], 3); + let state = AggregateStateSchema::try_new( + Kind::Sum, + vec![Component::Value, Component::Compensation], + ) + .unwrap(); + let other_grid = Arc::new( + crate::series::time::EvalGrid::try_new( + crate::series::time::GridSpec::try_new(0, 2, 3).unwrap(), + ) + .unwrap(), + ); + let series = StateSeries { + metric: metric(Some("m"), &[("job", "x")]), + time: TimeAxis::from_grid_spans(other_grid, vec![GridSpan::new(0, 1)]).unwrap(), + states: vec![values(1, 1.0)], + }; + let error = match StateFrameRow::from_state_series(&state, &schema, series, true) { + Ok(_) => panic!("a group on another grid is not a row of this export"), + Err(error) => error, + }; + assert!( + error + .to_string() + .contains("aggregate state positions are not on the series grid"), + "{error}" + ); + } + + /// A carried position no field contributes to is refused where the row is built. + /// + /// A position exists because a field has a contribution there: an all-absent one is a position + /// the merge would have to invent a state for, which is the same refusal `merge_row` makes of a + /// decoded row. Checking it here means both readings of one export refuse it in the same place, + /// before any row exists to merge. + #[test] + fn a_state_row_refuses_a_position_no_field_carries() { + let schema = state_schema(&["v"], 2); + let state = AggregateStateSchema::try_new( + Kind::Sum, + vec![Component::Value, Component::Compensation], + ) + .unwrap(); + let mut states = values(2, 1.0); + states[1] = None; + let series = StateSeries { + metric: metric(Some("m"), &[("job", "x")]), + time: TimeAxis::from_grid_spans( + schema.eval_grid.clone().unwrap(), + vec![GridSpan::new(0, 2)], + ) + .unwrap(), + states: vec![states], + }; + let error = match StateFrameRow::from_state_series(&state, &schema, series, true) { + Ok(_) => panic!("a position no field carries is not a row of this export"), + Err(error) => error, + }; + assert!( + error + .to_string() + .contains("aggregate state names a position with no contribution"), + "{error}" + ); + + // The same group with a contribution at that position is a row. + let series = StateSeries { + metric: metric(Some("m"), &[("job", "x")]), + time: TimeAxis::from_grid_spans( + schema.eval_grid.clone().unwrap(), + vec![GridSpan::new(0, 2)], + ) + .unwrap(), + states: vec![values(2, 1.0)], + }; + let row = StateFrameRow::from_state_series(&state, &schema, series, true) + .expect("a contribution at every carried position is a row"); + assert_eq!(2, row.time().len()); + } + fn floats(n: usize, seed: f64) -> Vec> { (0..n) .map(|i| { diff --git a/src/promql/src/aggregate/state.rs b/src/promql/src/aggregate/state.rs index 92cb6e70ac1..1680e13ddfa 100644 --- a/src/promql/src/aggregate/state.rs +++ b/src/promql/src/aggregate/state.rs @@ -99,7 +99,7 @@ pub struct PartialAggregate { /// One Arrow-backed aggregate state row, independent of executor plumbing. #[derive(Clone, Debug)] -pub(crate) struct StateRow { +pub struct StateRow { pub metric: SeriesLabels, pub time: TimeAxis, pub fields: StateFieldsBatch, diff --git a/src/promql/src/extension_plan.rs b/src/promql/src/extension_plan.rs index 71674ac5fbf..0ee951b2cd4 100644 --- a/src/promql/src/extension_plan.rs +++ b/src/promql/src/extension_plan.rs @@ -23,6 +23,7 @@ mod range_manipulate; mod raw_series_source; mod scalar_calculate; mod series_divide; +mod series_execution; mod series_repartition; #[cfg(test)] mod test_util; @@ -57,6 +58,10 @@ pub use range_manipulate::{RangeManipulate, RangeManipulateExec, RangeManipulate pub use raw_series_source::{RawSeriesSource, RawSeriesSourceExec}; pub use scalar_calculate::ScalarCalculate; pub use series_divide::{SeriesDivide, SeriesDivideExec, SeriesDivideStream}; +pub use series_execution::{ + HandedSeriesChunk, SendableSeriesStream, SeriesCharge, SeriesChunk, SeriesExecutionPlan, + checked_series_stream, series_execution_plan, +}; pub use series_repartition::{IdentityCompletion, SeriesRepartitionExec, SeriesRouting}; pub use union_distinct_on::{UnionDistinctOn, UnionDistinctOnExec, UnionDistinctOnStream}; diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index 7774117b51c..db71f3b3c98 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -17,7 +17,14 @@ //! [`FusedSeries`] is the logical half: it holds the PromQL text the tree was compiled from, the //! tree itself and the binding its input was compiled against. [`FusedSeriesExec`] is the physical //! half: it owns one execution of that tree per partition, decodes its input frames into raw -//! series chunks, and converts evaluated chunks back into batches. +//! series chunks, and converts evaluated chunks back into batches. An input that is one of our own +//! in-process operators hands its chunks over instead of frames +//! ([`crate::extension_plan::SeriesExecutionPlan`]), which is the same chunks with no round trip +//! through a batch. The decision is per input and taken by asking the input +//! ([`crate::extension_plan::series_execution_plan`]): one source can be read in process while +//! another is decoded from its frames, because each input is either one of ours or it is not. Every +//! content a native input publishes goes the same way, aggregate state included: a state row is +//! handed over as the row it is, not left on a frame path of its own. //! //! Both halves show their own compiled tree in `EXPLAIN`, rendered by [`NativeTree`]'s display. //! The logical node shows its tree without metrics; the physical node includes each tree node's @@ -37,6 +44,7 @@ //! batch arrives: a tree the native runtime does not execute, a frame whose schema the tree's input //! was not compiled against, or an output schema the conversion cannot classify. +use std::any::Any; use std::cmp::Ordering; use std::collections::VecDeque; use std::fmt::{self, Formatter}; @@ -92,6 +100,10 @@ use store_api::region_engine::RawLabelSource; use table::table::scan::SeriesScanExec; use crate::evaluated::EvaluatedChunk; +use crate::extension_plan::series_execution::{ + HandedSeriesChunk, SendableSeriesStream, SeriesCharge, SeriesChunk, SeriesExecutionPlan, + checked_series_stream, series_execution_plan, +}; use crate::extension_plan::series_repartition::SeriesRepartitionExec; use crate::extension_plan::{RawSeriesSourceExec, SeriesRouting}; use crate::grid_series::METADATA_LABELS; @@ -99,8 +111,8 @@ use crate::histogram_eval::HISTOGRAM_ROUTING_EXCLUDED_LABELS; use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor}; use crate::native::metrics::{NodeMetricsSnapshot, is_node_metric}; use crate::native::plan::{ - AggregateStage, BoundMap, Grouping, InstantValue, MapOp, NativeExpr, NativeNode, NativeTree, - NativeType, reads_across_series, + AggregateStage, AggregateStateSchema, BoundInput, BoundMap, Grouping, InstantValue, MapOp, + NativeExpr, NativeNode, NativeTree, NativeType, reads_across_series, }; use crate::native::state::{StateChunk, state_row_from_frame_row}; use crate::source::materialize_raw_labels; @@ -2949,6 +2961,82 @@ impl ExecutionPlan for FusedSeriesExec { partition: usize, context: Arc, ) -> DataFusionResult { + let FusedExecution { stream, state } = self.output_stream(partition, context)?; + match (self.format, state) { + (FusedOutputFormat::SeriesFrame, Some(state)) => { + let source: SendableStateSeriesStream = Box::pin(FusedStateStream { + source: stream, + pending: Vec::new().into_iter(), + reservation: None, + }); + Ok(pack_aggregate_state(source, state.declared, state.series)?) + } + (FusedOutputFormat::SeriesFrame, None) => { + let schema = evaluated_output(&self.tree)?; + let source: SendableEvaluatedSeriesStream = + Box::pin(FusedEvaluatedStream { source: stream }); + Ok(pack_evaluated_series(source, schema)?) + } + // A row table is the query's answer, not a publication another native operator reads. + (FusedOutputFormat::PlainRows, _) => Ok(Box::pin(stream)), + } + } +} + +impl SeriesExecutionPlan for FusedSeriesExec { + fn as_any(&self) -> &dyn Any { + self + } + + /// One partition's tree, handed over as the chunks a native consumer reads. + /// + /// The same execution the frame entry point runs, without the encode: the evaluated values the + /// tree settled, each with the finality the packer would have given it, or - for a `Partial` + /// root - the groups it folded, handed over exactly as its own aggregate produced them. + fn execute_series( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + if self.format != FusedOutputFormat::SeriesFrame { + return Err(DataFusionError::Execution(format!( + "FusedSeries partition {partition} answers a row table, which is read as rows" + ))); + } + let FusedExecution { stream, state } = self.output_stream(partition, context)?; + match state { + Some(state) => Ok(Box::pin(FusedStateChunks { + source: stream, + declared: state.binding, + pending: Vec::new().into_iter(), + })), + None => { + let source: SendableEvaluatedSeriesStream = + Box::pin(FusedEvaluatedStream { source: stream }); + Ok(Box::pin(FusedEvaluatedChunks { source })) + } + } + } +} + +impl FusedSeriesExec { + /// Whether this node's output is a publication another native operator can read in process. + /// + /// A `SeriesFrame` - of values or of exported state - is one. The plain row table this node + /// answers a statement with is not: rows are the query's answer, and `execute` hands them out. + pub fn hands_over_series(&self) -> bool { + self.format == FusedOutputFormat::SeriesFrame + } + + /// One partition's execution, before it is put in the form a consumer asked for. + /// + /// Both entry points start here, so the tree, its input and the evidence one execution claims are + /// built once and the same way; they differ only in what they do with what the tree produced. + fn output_stream( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { if partition >= self.properties.partitioning.partition_count() { return Err(DataFusionError::Execution( "FusedSeries output partition is out of range".into(), @@ -3000,9 +3088,39 @@ impl ExecutionPlan for FusedSeriesExec { let mut streams: Vec>> = Vec::new(); let bound_inputs = self.tree.root().inputs(); - for (source, (input, _, _)) in self.inputs.iter().enumerate() { + for (source, (input, _, ordering)) in self.inputs.iter().enumerate() { + let kind = self.source_kinds[source]; + // One input, one answer, asked of the input itself: an operator that can hand its + // chunks over is asked for them, and everything else is asked for its frames. Asking + // the input is what makes the two paths one decision - calling `execute_series` *is* + // the statement that this input is read in process - and it is asked of every content + // alike, aggregate state included. + if let Some(series_plan) = series_execution_plan(input.as_ref()) { + let chunks = series_plan.execute_series(partition, Arc::clone(&context))?; + let chunks = checked_series_stream(chunks, *ordering); + // What the frame path would compare a state publication against before it folds a + // row of it: the series layout this node binds, and - per row, inside + // `in_process_feed` - the state layout this node's aggregate declared. + let state = match kind { + FusedInputKind::AggregateState => { + Some(state_binding_of(&bound_inputs, source)?) + } + FusedInputKind::Raw | FusedInputKind::Evaluated => None, + }; + let series = Arc::clone(&self.series_schemas[source]); + streams.push( + chunks + .map(move |item| { + item.and_then(|chunk| { + in_process_feed(source, kind, &series, state.as_ref(), chunk) + }) + }) + .boxed(), + ); + continue; + } let frames = input.execute(partition, Arc::clone(&context))?; - match self.source_kinds[source] { + match kind { FusedInputKind::Evaluated => { let decoded = unpack_evaluated_series( frames, @@ -3013,6 +3131,7 @@ impl ExecutionPlan for FusedSeriesExec { .map(move |item| { item.map(|(series, is_last)| FusedFeed { source, + charge: None, chunk: FusedChunk::Evaluated(EvaluatedChunk { series, is_last, @@ -3023,19 +3142,7 @@ impl ExecutionPlan for FusedSeriesExec { ); } FusedInputKind::AggregateState => { - let bound = bound_inputs - .iter() - .find(|bound| bound.source_index == source) - .ok_or_else(|| { - DataFusionError::Plan(format!( - "FusedSeries state source {source} has no bound input" - )) - })?; - let NativeType::AggregateState(binding) = bound.output.clone() else { - return Err(DataFusionError::Plan(format!( - "FusedSeries source {source} is declared aggregate state but its binding is not" - ))); - }; + let binding = state_binding_of(&bound_inputs, source)?; let declared = Arc::new( datatypes::series::aggregate_state::AggregateStateSchema::try_new( binding.kind, @@ -3054,6 +3161,7 @@ impl ExecutionPlan for FusedSeriesExec { Ok(row) => state_row_from_frame_row(row, &binding) .map(|row| FusedFeed { source, + charge: None, chunk: FusedChunk::State(StateChunk::Row(row)), }) .map_err(|error| { @@ -3073,6 +3181,7 @@ impl ExecutionPlan for FusedSeriesExec { raw.map(move |item| { item.map(|chunk| FusedFeed { source, + charge: None, chunk: FusedChunk::Raw(chunk), }) }) @@ -3136,38 +3245,19 @@ impl ExecutionPlan for FusedSeriesExec { evidence_completed: false, evidence_claim: claim, }; - if self.format == FusedOutputFormat::SeriesFrame { - if state_mode { - let binding = state_binding.as_ref().ok_or_else(|| { - DataFusionError::Plan( - "FusedSeries Partial root has no aggregate-state binding".into(), - ) - })?; - let schema = Arc::new(SeriesSchema { + Ok(FusedExecution { + state: state_binding.as_ref().map(|binding| FusedStateOutput { + declared: state_schema + .clone() + .expect("a binding declares a frame state layout"), + binding: Arc::clone(binding), + series: Arc::new(SeriesSchema { fields: binding.accumulators.clone(), eval_grid: Some(Arc::clone(&binding.grid)), - }); - let source: SendableStateSeriesStream = Box::pin(FusedStateStream { - source: stream, - pending: Vec::new().into_iter(), - reservation: None, - }); - Ok(pack_aggregate_state( - source, - state_schema.ok_or_else(|| { - DataFusionError::Plan("FusedSeries Partial state schema is missing".into()) - })?, - schema, - )?) - } else { - let schema = evaluated_output(&self.tree)?; - let source: SendableEvaluatedSeriesStream = - Box::pin(FusedEvaluatedStream { source: stream }); - Ok(pack_evaluated_series(source, schema)?) - } - } else { - Ok(Box::pin(stream)) - } + }), + }), + stream, + }) } } @@ -3290,10 +3380,163 @@ enum FusedChunk { State(StateChunk), } -/// One chunk and the source index it belongs to. +/// One partition's execution: the tree's own output, and its state layout when it exports state. +struct FusedExecution { + /// The tree's output, which a consumer reads as values, as state, or as rows. + stream: FusedSeriesStream, + /// What a `Partial` root exports. + state: Option, +} + +/// The aggregate state a `Partial` root exports. +struct FusedStateOutput { + /// The layout as the frame path declares it, which is what the packer takes. + declared: Arc, + /// The same layout as the tree's binding, which is what a handed-over chunk names. + binding: Arc, + /// The series schema the export is of. + series: Arc, +} + +/// One chunk and the source index it belongs to, and what the producer charged it to. +/// +/// The charge is held for as long as this value is: it is dropped once the chunk has been pushed +/// into the tree, which is the point where the executor's copy of the values is its own and the +/// producer's accounting of them is over. A framed input has no charge here - its charge lives in +/// the packer's handoff - so the field is empty on that path and nothing changes for it. struct FusedFeed { source: usize, chunk: FusedChunk, + charge: Option, +} + +/// One chunk a native input handed over, as the form this node's runtime reads that source in. +/// +/// The variant has to be the one the tree bound the source to: a source compiled as raw samples +/// cannot be read as evaluated values, and treating one as the other would misread the plan rather +/// than merely slow it down, so a mismatch is reported. +fn in_process_feed( + source: usize, + kind: FusedInputKind, + series: &Arc, + state: Option<&Arc>, + handed: HandedSeriesChunk, +) -> Result { + let (chunk, charge) = handed.into_parts(); + let chunk = match (kind, chunk) { + (FusedInputKind::Raw, SeriesChunk::Raw(chunk)) => FusedChunk::Raw(chunk), + (FusedInputKind::Evaluated, SeriesChunk::Evaluated(chunk)) => FusedChunk::Evaluated(chunk), + (FusedInputKind::AggregateState, SeriesChunk::State(chunk)) => { + let Some(binding) = state else { + return Err(failed(format!( + "FusedSeries state source {source} binds no aggregate state" + ))); + }; + // The two checks the frame path makes before it folds state, on the same two properties: + // the state layout the export was declared on is the kind and component layout this + // node's aggregate declared, and the series it was exported on is the series this node + // binds. After them the chunk travels as it is - a `Final` merges the groups a producer + // folded exactly as it merges the row a frame decodes to. + match &chunk { + StateChunk::Row(row) => { + if row.kind != binding.kind + || row.fields.components() != binding.components.as_ref() + { + return Err(failed(format!( + "FusedSeries state source {source} was handed {:?} state, not the {:?} \ + state it binds", + row.kind, binding.kind + ))); + } + } + StateChunk::Series { state_schema, .. } => { + if state_schema.kind != binding.kind + || state_schema.components.as_ref() != binding.components.as_ref() + { + return Err(failed(format!( + "FusedSeries state source {source} was handed {:?} state, not the {:?} \ + state it binds", + state_schema.kind, binding.kind + ))); + } + let declared = SeriesSchema { + fields: state_schema.accumulators.clone(), + eval_grid: Some(Arc::clone(&state_schema.grid)), + }; + ensure_declared_series(&declared, series, source)?; + } + } + FusedChunk::State(chunk) + } + (kind, chunk) => { + return Err(failed(format!( + "FusedSeries source {source} is bound to {kind:?} but its operator handed over \ + {chunk:?}" + ))); + } + }; + Ok(FusedFeed { + source, + chunk, + charge, + }) +} + +/// The aggregate-state binding `source` was compiled with. +/// +/// Both entry points read it from the same place, so a source declared aggregate state is folded +/// against the layout its tree declared whether its operator published frames or rows. +fn state_binding_of( + inputs: &[&BoundInput], + source: usize, +) -> DataFusionResult> { + let bound = inputs + .iter() + .find(|bound| bound.source_index == source) + .ok_or_else(|| { + DataFusionError::Plan(format!( + "FusedSeries state source {source} has no bound input" + )) + })?; + let NativeType::AggregateState(binding) = bound.output.clone() else { + return Err(DataFusionError::Plan(format!( + "FusedSeries source {source} is declared aggregate state but its binding is not" + ))); + }; + Ok(binding) +} + +/// `declared` is the series layout `expected` binds, as `unpack_aggregate_state` checks it. +/// +/// A frame says which series its state is of in its declaration; a chunk carries that declaration's +/// series schema instead, so the check the decoder makes on the frame is made here on the same two +/// properties: the field names in order, and the evaluation grid. +fn ensure_declared_series( + declared: &SeriesSchema, + expected: &SeriesSchema, + source: usize, +) -> Result<(), BoxedError> { + let same_fields = expected.fields.len() == declared.fields.len() + && expected + .fields + .iter() + .zip(declared.fields.iter()) + .all(|(left, right)| left.name == right.name); + let same_grid = expected.eval_grid.as_ref().map(|grid| grid.spec()) + == declared.eval_grid.as_ref().map(|grid| grid.spec()); + if same_fields && same_grid { + return Ok(()); + } + Err(failed(format!( + "FusedSeries source {source} was handed state of a series layout it does not bind" + ))) +} + +/// A failure in the handover's own error type. +fn failed(reason: String) -> BoxedError { + BoxedError::new(common_query::error::Error::from( + DataFusionError::Execution(reason), + )) } /// The native histogram column of one evaluated field. @@ -3408,15 +3651,24 @@ impl Drop for EvidenceClaim { impl FusedSeriesStream { /// Hands one raw chunk over and queues what it settled. fn push(&mut self, feed: FusedFeed) -> DataFusionResult<()> { + let FusedFeed { + source, + chunk, + charge, + } = feed; + // What the producer charged this chunk is released when this call returns. That is the + // whole point of holding it here rather than in the handover stream: the tree reads the + // chunk below, so the reservation covers the bytes for as long as they are read and not one + // poll less - and the copy the executor keeps, when it keeps one, is accounted by the tree. + let _charge = charge; let Some(executor) = self.executor.as_mut() else { return Err(DataFusionError::Execution( "FusedSeriesExec stream pushed a chunk after its execution closed".to_string(), )); }; - let input_ids = self.input_ids.get(feed.source).ok_or_else(|| { + let input_ids = self.input_ids.get(source).ok_or_else(|| { DataFusionError::Execution(format!( - "FusedSeries has no runtime input IDs for source {}", - feed.source + "FusedSeries has no runtime input IDs for source {source}" )) })?; // One source feeding several runtime inputs hands each the same value, cloned per input, @@ -3424,20 +3676,13 @@ impl FusedSeriesStream { // copy: the chunk moves into it. A producer's state batch carries the charge for its whole // payload, so it is never bound to several inputs -- and it stays refused either way. if let [input_id] = input_ids.as_slice() { - match feed.chunk { + match chunk { FusedChunk::Raw(value) => executor.push_raw(*input_id, value)?, FusedChunk::Evaluated(value) => executor.push_evaluated(*input_id, value)?, - FusedChunk::State(StateChunk::Row(row)) => { - executor.push_state(*input_id, StateChunk::Row(row))? - } - FusedChunk::State(StateChunk::Series { .. }) => { - return Err(DataFusionError::Execution( - "one producer state batch cannot feed several runtime inputs".to_string(), - )); - } + FusedChunk::State(chunk) => executor.push_state(*input_id, chunk)?, } } else { - let chunk = Some(feed.chunk); + let chunk = Some(chunk); for input_id in input_ids { match chunk.as_ref().expect("the feed is read at most twice") { FusedChunk::Raw(value) => executor.push_raw(*input_id, value.clone())?, @@ -3676,6 +3921,117 @@ impl Stream for FusedSeriesStream { } } +/// The tree's evaluated output, handed over as the chunks a native consumer reads. +struct FusedEvaluatedChunks { + source: SendableEvaluatedSeriesStream, +} + +impl Stream for FusedEvaluatedChunks { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match Pin::new(&mut self.source).poll_next(cx) { + Poll::Ready(Some(Ok((series, is_last)))) => { + Poll::Ready(Some(Ok(HandedSeriesChunk::uncharged( + SeriesChunk::Evaluated(EvaluatedChunk { series, is_last }), + )))) + } + Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))), + Poll::Ready(None) => Poll::Ready(None), + Poll::Pending => Poll::Pending, + } + } +} + +/// Exported state, handed over one group at a time as the chunks a `Final` merges. +/// +/// The charge the tree's own export carried rides on the groups it is cut into: a reader that takes +/// one group and holds it is holding the bytes of the batch that group was folded in, so the +/// reservation is shared by every group of that batch and released with the last of them. +struct FusedStateChunks { + source: FusedSeriesStream, + /// The layout every group of this export was folded on. + declared: Arc, + /// The groups of the batch last taken off the tree, in the order it folded them, each with a + /// reference to the charge that batch carried. + /// + /// The reference is taken once per group rather than held by this stream, so the batch's charge + /// is released when the last group a consumer holds is dropped - not when this stream is polled + /// again, and not when it goes away either. + pending: std::vec::IntoIter<( + datatypes::series::aggregate_state::StateSeries, + Option>, + )>, +} + +impl Stream for FusedStateChunks { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + loop { + if let Some((series, held)) = this.pending.next() { + // A `Partial` closes every group it exports: the fold of one partition is whole, and + // the `Final` above merges the partitions' publications rather than continuing one + // chain. + let chunk = SeriesChunk::State(StateChunk::Series { + series: vec![series], + state_schema: Arc::clone(&this.declared), + reservation: None, + }); + return Poll::Ready(Some(Ok(match held { + Some(held) => { + HandedSeriesChunk::charged(chunk, SeriesCharge::shared(vec![held])) + } + None => HandedSeriesChunk::uncharged(chunk), + }))); + } + match Pin::new(&mut this.source).poll_output(cx) { + Poll::Ready(Some(Ok(FusedOutput::State(chunk)))) => { + let StateChunk::Series { + series, + reservation, + .. + } = chunk + else { + Pin::new(&mut this.source).fail(); + return Poll::Ready(Some(Err(BoxedError::new( + common_query::error::Error::from(DataFusionError::Internal( + "row state reached the state chunk stream".into(), + )), + )))); + }; + this.pending = { + // One reference per group, so none of them is this stream's to hold. + let held = reservation.map(Arc::new); + series + .into_iter() + .map(|group| (group, held.clone())) + .collect::>() + .into_iter() + }; + } + Poll::Ready(Some(Ok(_))) => { + Pin::new(&mut this.source).fail(); + return Poll::Ready(Some(Err(BoxedError::new( + common_query::error::Error::from(DataFusionError::Internal( + "non-state output reached the state chunk stream".into(), + )), + )))); + } + Poll::Ready(Some(Err(error))) => { + Pin::new(&mut this.source).fail(); + return Poll::Ready(Some(Err(BoxedError::new( + common_query::error::Error::from(error), + )))); + } + Poll::Ready(None) => return Poll::Ready(None), + Poll::Pending => return Poll::Pending, + } + } + } +} + struct FusedEvaluatedStream { source: FusedSeriesStream, } diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index 9b5c7a02000..e2398cac58a 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -38,12 +38,17 @@ use std::task::{Context, Poll}; use api::v1::SemanticType; use common_error::ext::BoxedError; -use common_query::series_frame::{pack_evaluated_series, unpack_evaluated_series}; +use common_query::native_histogram::NativeHistogram; +use common_query::series_frame::{ + frame_schema_with, pack_evaluated_series, unpack_evaluated_series, unpack_raw_series, +}; use common_recordbatch::adapter::{NATIVE_TREE_METRIC, format_metric}; use common_recordbatch::{ EmptyRecordBatchStream, SendableRecordBatchStream as CommonSendableRecordBatchStream, }; -use datafusion::arrow::array::{Array, Float64Array, StringArray, TimestampMillisecondArray}; +use datafusion::arrow::array::{ + Array, Float64Array, StringArray, TimestampMillisecondArray, UInt32Array, +}; use datafusion::arrow::buffer::{Buffer, ScalarBuffer}; use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit}; use datafusion::arrow::record_batch::RecordBatch; @@ -78,8 +83,13 @@ use datatypes::series::frame::{ LabelDecodeSpec, LabelDecodeTag, SeriesFrameDeclaration, StateFrameRow, pack_raw_series_chunk, raw_series_frame_schema, series_frame_schema, }; +use datatypes::series::histogram::{ + BucketSideView, CounterResetHint, HistogramBatch, HistogramBatchBuilder, HistogramView, +}; use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; -use datatypes::series::samples::{FieldSpec, Samples, Series, SeriesFields, SeriesSchema}; +use datatypes::series::samples::{ + FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, +}; use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis}; use datatypes::series::{Label, SeriesLabels, SeriesOrdering}; use futures::{Stream, StreamExt, TryStreamExt}; @@ -94,10 +104,11 @@ mod frame_output; use super::{ FieldKind, FusedOutputFormat, FusedSeries, FusedSeriesBinding, FusedSeriesExec, OutputColumn, - POLL_BUDGET, series_to_record_batch, + POLL_BUDGET, canonical_histogram, series_to_record_batch, }; use crate::evaluated::EvaluatedChunk; use crate::extension_plan::raw_series_source::tests::{per_series_scan, raw_source}; +use crate::extension_plan::series_execution::{SeriesChunk, series_execution_plan}; use crate::extension_plan::{RawSeriesSourceExec, SeriesRepartitionExec, SeriesRouting}; use crate::histogram_eval::HistogramFunction; use crate::info::InfoSelector; @@ -109,6 +120,7 @@ use crate::native::plan::{ BoundMap, BoundScalar, BoundVectorOp, BoundWindow, Grouping, InstantValue, MapOp, NativeExpr, NativeNode, NativeTree, NativeType, ParameterizedOp, }; +use crate::native::state::{StateChunk, state_bytes}; use crate::range_eval::{RangeFunction, RangeWindow}; use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels}; use common_query::series_frame::series_frame_ordering; @@ -6948,7 +6960,7 @@ async fn a_partial_root_exports_state_frames_from_every_partition() { /// /// This is lifecycle coverage, not the regression for the producer hand-off: other reservations are /// alive at the same moment, so a positive figure here would not by itself prove the batch is the -/// charged one. `a_handed_over_state_chunk_keeps_its_charge_until_it_is_dropped` owns that claim. +/// charged one. `a_handed_state_chunk_holds_its_charge_until_it_is_dropped` owns that claim. #[tokio::test] async fn a_state_export_releases_its_charge_on_drain_and_on_early_drop() { const GROUPS: usize = 600; @@ -9698,3 +9710,1431 @@ async fn a_real_three_owner_repartition_between_two_real_fuseds_merges_every_pie .await .expect("the composition finishes instead of waiting for an owner nobody reads"); } + +// --------------------------------------------------------------------------- +// The in-process handover +// --------------------------------------------------------------------------- + +// The two ends of the handover, each checked against the frame path it replaces. +// +// A raw source decodes a region's frames into chunks, and a fused node decodes frames into the same +// chunks; between two of our own operators neither has to. The fixtures below are the same for both +// ends, so the tests live together: what has to hold is that skipping the encode changes nothing a +// consumer can see - the raw source's frames and its chunks carry the same values, and a tree run +// over the chunks answers the same batches as one run over the frames. +// +// The fixtures carry what a raw frame can carry and a naive comparison would miss: several series, +// a null sample in each, one series whose field holds native histograms rather than floats, and a +// series split over two chunks. + +/// One sample as these tests compare it. +#[derive(Clone, Debug, PartialEq)] +enum DecodedSample { + /// No sample at this position. + Missing, + /// The bits of the value, so a signed zero or a NaN payload is compared rather than coerced. + Float(u64), + /// A native histogram, in the canonical form both paths encode it as. + Histogram(NativeHistogram), +} + +/// One chunk as these tests compare it: the decoded values, in the order they arrived. +/// +/// The buffers a chunk happens to share are left out on purpose. The two paths may hand over +/// different buffers, and what has to be identical is what a consumer reads. +#[derive(Clone, Debug, PartialEq)] +struct DecodedChunk { + /// The key the series was read under, byte for byte. + key: Vec, + /// Its complete labels, when the frame named it by them. + metric: Option, + /// Its timestamps, in the order the chunk carries them. + time: Vec, + /// One sample per timestamp, one list per field. + fields: Vec>, + /// Whether this chunk closes its series. + is_last: bool, +} + +/// `chunk` as these tests compare it. +fn decoded_chunk(chunk: &RawSeriesChunk) -> DecodedChunk { + DecodedChunk { + key: chunk.primary_key.as_slice().to_vec(), + metric: chunk.metric.clone(), + time: (0..chunk.time.len()) + .map(|index| chunk.time.timestamp(index).expect("the index is in range")) + .collect(), + fields: chunk.fields.iter().map(decoded_field).collect(), + is_last: chunk.is_last, + } +} + +/// One field of a chunk as these tests compare it. +fn decoded_field(field: &Samples) -> Vec { + field.iter().map(decoded_sample).collect() +} + +/// One sample as these tests compare it, whichever way a chunk carries it. +fn decoded_sample(sample: SampleRef) -> DecodedSample { + match sample { + SampleRef::Missing => DecodedSample::Missing, + SampleRef::Float(value) => DecodedSample::Float(value.to_bits()), + SampleRef::Histogram(view) => DecodedSample::Histogram(canonical_histogram(&view)), + } +} + +/// The histogram batch `sums` describes, one histogram per entry. +fn histogram_batch(sums: &[f64]) -> Arc { + let mut builder = HistogramBatchBuilder::new(); + let positive_offsets = [1]; + let positive_lengths = [2]; + let positive_buckets = [1.5, 2.5]; + for (index, sum) in sums.iter().enumerate() { + builder + .push(HistogramView { + schema: 1, + zero_threshold: 0.5, + sum: *sum, + count: 8.0, + zero_count: 1.0, + reset_hint: CounterResetHint::Unknown, + start_timestamp: Some(index as i64 * 1_000), + custom_values: &[], + positive: BucketSideView { + span_offsets: &positive_offsets, + span_lengths: &positive_lengths, + buckets: &positive_buckets, + }, + negative: BucketSideView { + span_offsets: &[], + span_lengths: &[], + buckets: &[], + }, + }) + .expect("the fixture histogram is legal"); + } + builder.finish().expect("the fixture batch finishes") +} + +/// The chunks these tests hand over: four timestamps in all, spread over several series, with a +/// null sample, a series in two chunks, and one series whose field holds native histograms. +fn handover_chunks() -> Vec { + let times = [60_000_i64, 120_000, 180_000, 240_000]; + // A float series with a hole in it: the field carries one null, which both paths have to keep + // as a missing sample rather than as a zero. + let floats = |values: Vec>| vec![values]; + let mut chunks = vec![ + chunk_of( + &raw_schema(), + "web-1", + metric(&[(HOST, "web-1")], Some(METRIC)), + ×, + floats(vec![Some(1.0), None, Some(3.0), Some(4.0)]), + false, + ), + // The same series, closed by a second chunk, so a chain has to be read in order. + chunk_of( + &raw_schema(), + "web-1", + metric(&[(HOST, "web-1")], Some(METRIC)), + &[300_000, 360_000], + floats(vec![Some(5.0), Some(6.0)]), + true, + ), + chunk_of( + &raw_schema(), + "web-2", + metric(&[(HOST, "web-2")], Some(METRIC)), + ×, + floats(vec![None, Some(2.5), Some(2.5), None]), + true, + ), + ]; + // The histogram series: two histograms and one position with no sample, in the same field name + // the float series use, because a raw frame's field is a payload that can hold either. + let histograms = Samples::try_from_histogram( + UInt32Array::from(vec![Some(0), None, Some(1), None]), + histogram_batch(&[10.5, 20.5]), + ) + .expect("the fixture histograms are aligned with the timestamps"); + chunks.push( + RawSeriesChunk::try_new( + &raw_schema(), + Buffer::from_slice_ref(b"web-3".as_slice()), + Some(metric(&[(HOST, "web-3")], Some(METRIC))), + RawTimestamps::try_new(ScalarBuffer::from(times.to_vec())).expect("ascending times"), + SeriesFields::try_from_vec(vec![histograms]).expect("one field over four positions"), + true, + ) + .expect("the fixture histogram series is a legal chunk"), + ); + chunks +} + +/// `chunks` as one frame batch each, declared under `schema`. +/// +/// The packer writes the schema it declares, so a caller that wants another one - an ordering this +/// node does not publish, say - re-declares the packed columns under it. +fn frames_under(schema: &SchemaRef, chunks: &[RawSeriesChunk]) -> Vec { + chunks + .iter() + .map(|chunk| { + let packed = + pack_raw_series_chunk(&raw_schema(), FrameLabelMode::Explicit, None, chunk) + .expect("a chunk of this schema packs"); + assert_eq!(1, packed.len(), "one small chunk is one frame batch"); + RecordBatch::try_new(Arc::clone(schema), packed[0].columns().to_vec()) + .expect("the packed columns match the declared frame") + }) + .collect() +} + +/// The frame schema of these series under `ordering`. +fn frame_schema_with_ordering(ordering: SeriesOrdering) -> SchemaRef { + frame_schema_with(&raw_schema(), FrameLabelMode::Explicit, None, ordering) + .expect("explicit labels are a frame under any ordering") +} + +/// The producer's two entry points decode the same chunks. +/// +/// The frame path here is the published frame decoded back, which is exactly what a consumer on the +/// other side of a boundary does with it; the in-process path is what a consumer that is native +/// like this one receives instead. They have to agree chunk for chunk, including the labels, the +/// nulls, the finality and the native histograms - otherwise the shortcut would be a second decoder +/// rather than the same one without the encode. +#[tokio::test] +async fn the_raw_source_hands_over_the_chunks_its_frames_decode_to() { + // The child's frames arrive two ways. Under `Contiguous` they are already this node's own + // frame, so the frame path re-declares them without decoding at all. Under `Interleaved` they + // are in an order this node does not publish, so the frame path decodes them and packs them + // again - which is where the in-process path and the frame path share their decode. + for pass_through in [true, false] { + let chunks = handover_chunks(); + let child = if pass_through { + memory_exec(frames_under(&frame_schema(), &chunks)) + } else { + let schema = frame_schema_with_ordering(SeriesOrdering::Interleaved); + memory_exec_partitioned_with(Arc::clone(&schema), vec![frames_under(&schema, &chunks)]) + }; + let source = raw_source(child); + let exec = source + .downcast_ref::() + .expect("the fixture root is the region's raw source"); + let context = SessionContext::default().task_ctx(); + + // What a consumer behind a boundary reads: the published frame, decoded. + let published = exec + .execute(0, Arc::clone(&context)) + .expect("the node has one partition"); + let from_frames = unpack_raw_series(published, Some(raw_schema())) + .expect("the node publishes a raw frame of these fields") + .try_collect::>() + .await + .expect("the published frames decode"); + + // What a native consumer reads: the chunks themselves. + let handed_over = series_execution_plan(source.as_ref()) + .expect("the raw source hands its chunks over") + .execute_series(0, context) + .expect("the node has one partition") + .try_collect::>() + .await + .expect("the chunks arrive"); + let in_process = handed_over + .into_iter() + .map(|handed| match handed.into_parts().0 { + SeriesChunk::Raw(chunk) => decoded_chunk(&chunk), + other => panic!("a raw source handed over a chunk it cannot produce: {other:?}"), + }) + .collect::>(); + + assert_eq!( + handover_chunks().len(), + in_process.len(), + "every fixture chunk is handed over, pass-through: {pass_through}" + ); + assert_eq!( + from_frames.iter().map(decoded_chunk).collect::>(), + in_process, + "the in-process chunks are the published frame decoded, pass-through: {pass_through}" + ); + } +} + +/// A tree run over in-process chunks answers the same batches as one run over their frames. +/// +/// This is the consumer's half of the handover: the node reads chunks instead of decoding frames, +/// and everything above it - the tree, its kernels, the row conversion - sees the same input, so +/// the answer has to be identical batch for batch, including where each batch ends. +#[tokio::test] +async fn the_in_process_handover_answers_the_batches_the_frames_answer() { + let chunks = handover_chunks(); + // Only the float series: a tree binds one value kind for its whole output, so a fixture that + // holds histograms in some series would have to be read by a histogram tree. + let chunks = chunks + .into_iter() + .filter(|chunk| { + chunk + .metric + .as_ref() + .and_then(|metric| metric.get(HOST)) + .is_some_and(|host| host != "web-3") + }) + .collect::>(); + let source = raw_source(memory_exec(frames_under(&frame_schema(), &chunks))); + let context = SessionContext::default().task_ctx(); + + // The same frames the second plan reads, taken from the node that publishes them, so both plans + // read one input rather than two that are assumed to be alike. + let published = collect(Arc::clone(&source), Arc::clone(&context)) + .await + .expect("the raw source publishes its frames"); + let framed = memory_exec_partitioned_with(source.schema(), vec![published]); + + let in_process = + plan(rate_tree(), Arc::clone(&source)).expect("the runtime executes a rate tree"); + let over_frames = plan(rate_tree(), framed).expect("the runtime executes a rate tree"); + assert!( + uses_in_process_series(&in_process), + "every input of this plan is a native operator, so the node reads it in process" + ); + assert!( + !uses_in_process_series(&over_frames), + "a memory leaf publishes frames, so the node reads them" + ); + + let in_process_batches = collect(Arc::clone(&in_process), context.clone()) + .await + .expect("the node runs over the chunks"); + let frame_batches = collect(Arc::clone(&over_frames), context) + .await + .expect("the node runs over the frames"); + assert!( + !in_process_batches.is_empty(), + "the fixture is a grid the tree answers on" + ); + assert_eq!( + frame_batches, in_process_batches, + "the two paths answer the same batches, in the same order" + ); + // Nothing a reader observes may change with the representation. The figures the tree records + // are recorded per chunk it was fed, and the fast path feeds the producer's own chunks, which + // are the ones the frame path decodes back - every fixture chunk here is one dense field + // segment, so a frame row is a chunk and the counts agree exactly, not just the rows. + assert_eq!( + node_counters(&over_frames), + node_counters(&in_process), + "the tree records the same figures either way" + ); +} + +/// The counters the fused node of `plan` registered, by name, so two executions can be compared. +fn node_counters(plan: &Arc) -> Vec<(String, usize)> { + let mut counters = node_metric_set(plan) + .iter() + .filter_map(|metric| match metric.value() { + MetricValue::Count { count, .. } => { + Some((metric.value().name().to_string(), count.value())) + } + _ => None, + }) + .collect::>(); + counters.sort(); + counters +} + +// --------------------------------------------------------------------------- +// The routing in front of a native consumer +// --------------------------------------------------------------------------- + +/// Whether the fused node at the top of `plan` reads any of its inputs in process. +/// +/// This is the question the node asks itself, one input at a time, before it decides how to read that +/// input - so a test that says "this plan goes through the handover" states what the node does, +/// rather than what some build-time flag was set to. There is no content the node reads another way: +/// every input whose operator answers is read in process, aggregate state included. +fn uses_in_process_series(plan: &Arc) -> bool { + let fused = plan + .downcast_ref::() + .expect("the plan under test is one fused node"); + (0..fused.inputs.len()) + .any(|source| series_execution_plan(fused.inputs[source].0.as_ref()).is_some()) +} + +/// The frames each partition of `plan` publishes, in order, read once. +/// +/// This is what a consumer behind a boundary receives from each owner: the batches exactly as the +/// producer wrote them, which is the fixture the frame path of these tests is then given. +async fn published_frames(plan: &Arc) -> Vec> { + let context = SessionContext::default().task_ctx(); + let mut partitions = Vec::new(); + for partition in 0..plan.properties().partitioning.partition_count() { + let mut stream = plan + .execute(partition, Arc::clone(&context)) + .expect("every partition of the fixture executes"); + let mut batches = Vec::new(); + while let Some(batch) = stream.next().await { + batches.push(batch.expect("the fixture publishes frames instead of failing")); + } + partitions.push(batches); + } + partitions +} + +/// The raw chunks `batches` decode to, as a consumer behind the boundary recovers them. +async fn raw_frames_decoded(schema: SchemaRef, batches: Vec) -> Vec { + let leaf = memory_exec_partitioned_with(schema, vec![batches]); + let frames = leaf + .execute(0, SessionContext::default().task_ctx()) + .expect("the fixture's frames are re-read"); + unpack_raw_series(frames, Some(raw_schema())) + .expect("the owner publishes a raw frame of these fields") + .try_collect::>() + .await + .expect("the frames decode") + .iter() + .map(decoded_chunk) + .collect() +} + +/// One evaluated chunk as these tests compare it. +/// +/// The samples, the labels and the finality are what a consumer reads; the buffers they sit in are +/// not, and the two paths are allowed to aim at different ones. +#[derive(Clone, Debug, PartialEq)] +struct DecodedSeries { + /// The complete labels the series belongs to. + metric: SeriesLabels, + /// The grid positions it carries, in order. + positions: Vec, + /// One list of samples per field. + fields: Vec>, + /// Whether this chunk closes its series. + is_last: bool, +} + +/// `series` as these tests compare it. +fn decoded_evaluated(series: &Series, is_last: bool) -> DecodedSeries { + DecodedSeries { + metric: series.metric.clone(), + positions: series + .time + .positions() + .map(|(position, _)| position as i64) + .collect(), + fields: series.fields.as_slice().iter().map(decoded_field).collect(), + is_last, + } +} + +/// `chunks` joined into whole series, in a fixed order, so two lists of them can be compared. +/// +/// A frame row never spans two segments of one field, so a series whose values sit in two dense +/// segments is one chunk in process and two rows in a frame - the split-segment difference the +/// handover documents. What both paths have to agree on is the series, not how many rows it was +/// encoded as, so adjacent pieces of one series are joined before they are compared. +fn join_raw(mut chunks: Vec) -> Vec { + chunks.sort_by(|left, right| { + (left.key.clone(), left.time.first()).cmp(&(right.key.clone(), right.time.first())) + }); + let mut joined: Vec = Vec::new(); + for chunk in chunks { + match joined.last_mut() { + Some(open) if open.key == chunk.key && !open.is_last => { + open.time.extend(chunk.time); + for (into, from) in open.fields.iter_mut().zip(chunk.fields) { + into.extend(from); + } + open.is_last = chunk.is_last; + } + _ => joined.push(chunk), + } + } + joined +} + +/// [`join_raw`] for evaluated pieces. +fn join_evaluated(mut series: Vec) -> Vec { + series.sort_by(|left, right| { + (format!("{:?}", left.metric), &left.positions) + .cmp(&(format!("{:?}", right.metric), &right.positions)) + }); + let mut joined: Vec = Vec::new(); + for chunk in series { + match joined.last_mut() { + Some(open) if open.metric == chunk.metric && !open.is_last => { + open.positions.extend(chunk.positions); + for (into, from) in open.fields.iter_mut().zip(chunk.fields) { + into.extend(from); + } + open.is_last = chunk.is_last; + } + _ => joined.push(chunk), + } + } + joined +} + +/// The evaluated series `batches` decode to, as a consumer behind the boundary recovers them. +async fn evaluated_frames_decoded( + schema: SchemaRef, + batches: Vec, +) -> Vec { + let leaf = memory_exec_partitioned_with(schema, vec![batches]); + let frames = leaf + .execute(0, SessionContext::default().task_ctx()) + .expect("the fixture's frames are re-read"); + unpack_evaluated_series(frames, None) + .expect("the owner publishes an evaluated frame") + .try_collect::>() + .await + .expect("the frames decode") + .iter() + .map(|(series, is_last)| decoded_evaluated(series, *is_last)) + .collect() +} + +/// The raw chunks `owner` of `plan` hands over, decoded, as a native consumer receives them. +async fn handed_raw_chunks(plan: &Arc, owner: usize) -> Vec { + let handed = series_execution_plan(plan.as_ref()) + .expect("the router hands its chunks over") + .execute_series(owner, SessionContext::default().task_ctx()) + .expect("the owner hands its chunks over") + .try_collect::>() + .await + .expect("the chunks arrive"); + handed + .into_iter() + .map(|handed| match handed.into_parts().0 { + SeriesChunk::Raw(chunk) => decoded_chunk(&chunk), + other => panic!("a raw owner handed over {other:?}"), + }) + .collect() +} + +/// The evaluated chunks `owner` of `plan` hands over, decoded, as a native consumer receives them. +async fn handed_evaluated_chunks( + plan: &Arc, + owner: usize, +) -> Vec { + let handed = series_execution_plan(plan.as_ref()) + .expect("the router hands its chunks over") + .execute_series(owner, SessionContext::default().task_ctx()) + .expect("the owner hands its chunks over") + .try_collect::>() + .await + .expect("the chunks arrive"); + handed + .into_iter() + .map(|handed| match handed.into_parts().0 { + SeriesChunk::Evaluated(chunk) => decoded_evaluated(&chunk.series, chunk.is_last), + other => panic!("an evaluated owner handed over {other:?}"), + }) + .collect() +} + +/// A router over `partitions`' raw frames, publishing `owners` outputs. +fn raw_router(partitions: Vec>, owners: usize) -> Arc { + Arc::new( + SeriesRepartitionExec::try_new( + memory_exec_partitioned_with(frame_schema(), partitions), + owners, + ) + .expect("raw frames route by the stored primary key"), + ) +} + +/// The raw series the routing tests route: thirteen identities over two input partitions. +/// +/// Twelve of them are closed chains that arrive whole from one partition each, so what the routing +/// has to do is send each to its owner and leave it alone. The thirteenth, `web-split`, arrives as +/// two closed chains of the same stored key, one from each partition - a frame input has to end +/// between chains, so a chain cannot be left open at the end of a partition - and the owner it is +/// routed to has to merge them into one identity: the raw form of the merge a router exists for. +fn routed_raw_partitions() -> Vec> { + let times = [60_000_i64, 120_000]; + let closed = |host: &str| { + frame(&chunk_of( + &raw_schema(), + host, + metric(&[(HOST, host)], Some(METRIC)), + ×, + vec![vec![Some(1.0), Some(2.0)]], + true, + )) + }; + let piece = |host: &str, time: i64, value: f64, last: bool| { + frame(&chunk_of( + &raw_schema(), + host, + metric(&[(HOST, host)], Some(METRIC)), + &[time], + vec![vec![Some(value)]], + last, + )) + }; + let mut early = (0..6) + .map(|index| closed(&format!("web-{index}"))) + .collect::>(); + let mut late = (6..12) + .map(|index| closed(&format!("web-{index}"))) + .collect::>(); + early.push(piece("web-split", 60_000, 1.0, true)); + late.push(piece("web-split", 120_000, 2.0, true)); + vec![early, late] +} + +/// The evaluated series the routing tests route, through the window-and-rewrite producer. +/// +/// Four canonical label sets over two input partitions and three owners: `web-1` and `web-2` are two +/// raw identities the rewrite folds onto `{host="same"}`, and their pieces sit on disjoint grid +/// positions, so that one label set only becomes one series once both halves reach one owner. +fn routed_evaluated_partitions() -> Vec> { + let piece = |host: &str, times: &[i64]| frame(&piece_chunk(host, times)); + vec![ + vec![ + piece("web-1", &EARLY_PIECE_MS), + piece(PLAIN, &EARLY_PIECE_MS), + piece("third", &EARLY_PIECE_MS), + ], + vec![ + piece("web-2", &LATE_PIECE_MS), + piece("fourth", &EARLY_PIECE_MS), + ], + ] +} + +/// A three-owner raw router hands over the chunks its frames decode to, owner by owner. +/// +/// The producer's half of the handover for a router: what it publishes as frames and what it hands +/// over in process have to be the same series - the same key, labels, samples and finality - and +/// the merge it performs on an identity that arrived from two partitions has to have happened in +/// both, not in one. Owner by owner, because which owner an identity lands on is the routing +/// decision itself, and per owner as whole series, because how many rows one series is encoded as +/// is the encoder's business. +#[tokio::test] +async fn a_three_owner_raw_router_hands_over_what_its_frames_decode_to() { + tokio::time::timeout(std::time::Duration::from_secs(30), async { + // The frame side: one router's publication, read owner by owner, which is both what a + // boundary consumer reads and the fixture the frame path below is given. + let publishing = raw_router(routed_raw_partitions(), 3); + let published = published_frames(&publishing).await; + assert_eq!(3, published.len(), "one publication per owner"); + assert_eq!( + 3, + published + .iter() + .filter(|batches| !batches.is_empty()) + .count(), + "thirteen identities over three owners reach all three, which is the re-routing this \ + test needs: {published:?}" + ); + + // The chunk side reads the same fixture through a router of its own. + let handing = raw_router(routed_raw_partitions(), 3); + let mut in_process = Vec::new(); + for owner in 0..3 { + in_process.push(handed_raw_chunks(&handing, owner).await); + } + assert_eq!( + 13, + in_process.iter().flatten().count(), + "every identity is published once, and the identity that arrived in two halves once" + ); + for (owner, handed) in in_process.iter().enumerate() { + // An owner publishes the identities that became ready together in the order they + // completed, and neither path promises that order - the frame a consumer decodes is + // read for its chains, not for a sequence of keys. So the two are compared as the same + // series, sorted by the key that names each one. + let from_frames = raw_frames_decoded(frame_schema(), published[owner].clone()).await; + assert_eq!( + join_raw(from_frames), + join_raw(handed.clone()), + "owner {owner} hands over the series its frames decode to" + ); + } + // The identity that arrived from two partitions is the merge: two halves in, one closed + // chunk out, on whichever owner the routing put it on. + let split = in_process + .iter() + .flatten() + .filter(|chunk| chunk.key == b"web-split") + .collect::>(); + assert_eq!( + 1, + split.len(), + "the split identity is published once: {in_process:?}" + ); + let mut merged_times = split[0].time.clone(); + merged_times.sort_unstable(); + assert_eq!( + vec![60_000, 120_000], + merged_times, + "the two halves are one chunk: {split:?}" + ); + assert!(split[0].is_last, "the identity the owner merged is closed"); + + // And the whole composition above it: a real tree over the chunks and the same tree over + // the frames answer the same batches. + let over_frames = plan( + rate_tree(), + memory_exec_partitioned_with(frame_schema(), published), + ) + .expect("the runtime executes a rate tree"); + let in_process = + plan(rate_tree(), raw_router(routed_raw_partitions(), 3)).expect("the same here"); + assert!( + uses_in_process_series(&in_process), + "the router hands its chunks over, so the node reads them" + ); + assert!( + !uses_in_process_series(&over_frames), + "a memory leaf publishes frames, so the node reads them" + ); + // Owner by owner, because a row belongs to the owner the routing put its series on, and + // per owner the rows are compared as the same rows: an owner answers the identities it was + // routed in the order they completed, which is not a promise either path makes. + let frame_rows = polled_partition_rows(&over_frames).await; + let chunk_rows = polled_partition_rows(&in_process).await; + assert_eq!(3, chunk_rows.len(), "the tree runs once per owner"); + for owner in 0..chunk_rows.len() { + assert!(chunk_rows[owner].1, "owner {owner} reports its end"); + let mut answered_over_frames = frame_rows[owner].0.clone(); + answered_over_frames + .sort_by(|left, right| left.partial_cmp(right).expect("rows compare")); + let mut answered_over_chunks = chunk_rows[owner].0.clone(); + answered_over_chunks + .sort_by(|left, right| left.partial_cmp(right).expect("rows compare")); + assert_eq!( + answered_over_frames, answered_over_chunks, + "owner {owner} answers the same rows over the chunks and over the frames" + ); + } + assert!( + chunk_rows.iter().any(|(rows, _)| !rows.is_empty()), + "the fixture answers on the grid" + ); + }) + .await + .expect("the composition finishes"); +} + +/// A three-owner evaluated router hands over the chunks its frames decode to, owner by owner. +/// +/// The same contract as the raw half, on the content a router publishes after an owner merged it: the +/// owner's merged series is what is handed over, already closed, so the `is_last` a frame carries is +/// the one the chunk carries. The identity the rewrite folded out of two partitions is one series in +/// both, and the tree above folds it to the same batches. +#[tokio::test] +async fn a_three_owner_evaluated_router_hands_over_what_its_frames_decode_to() { + tokio::time::timeout(std::time::Duration::from_secs(30), async { + let publishing: Arc = Arc::new( + SeriesRepartitionExec::try_new(aliasing_producer(routed_evaluated_partitions()), 3) + .expect("the router is built over the producer's evaluated frames"), + ); + let published = published_frames(&publishing).await; + assert_eq!(3, published.len(), "one publication per owner"); + // The router routes by a hash of the label set, so which owners carry a series is not this + // test's to fix - only that every label set is published, on whichever owner owns it, and + // that the chunks match the frames there. A merged series whose pieces sit on disjoint grid + // positions is encoded as one row per dense segment, so the rows of an owner are not the + // count of its series and are not compared against it. + + let handing: Arc = Arc::new( + SeriesRepartitionExec::try_new(aliasing_producer(routed_evaluated_partitions()), 3) + .expect("the router is built over the producer's evaluated frames"), + ); + let mut in_process = Vec::new(); + for owner in 0..3 { + in_process.push(handed_evaluated_chunks(&handing, owner).await); + } + assert_eq!( + 4, + in_process.iter().flatten().count(), + "four canonical label sets, each published once: {in_process:?}" + ); + for (owner, handed) in in_process.iter().enumerate() { + // As in the raw half: the order an owner publishes in is the order its series + // completed, so the two paths are compared as the same series rather than as one + // sequence. + let from_frames = + evaluated_frames_decoded(publishing.schema(), published[owner].clone()).await; + assert_eq!( + join_evaluated(from_frames), + join_evaluated(handed.clone()), + "owner {owner} hands over the series its frames decode to" + ); + } + // The merged label set is one closed series carrying both pieces, which is the `is_last` the + // frame declares for it as well. + let merged = in_process + .iter() + .flatten() + .filter(|series| series.metric.get(HOST).is_some_and(|host| host == ALIASED)) + .collect::>(); + assert_eq!(1, merged.len(), "the aliased label set is published once"); + assert!( + merged[0].is_last, + "an owner publishes a merged identity closed" + ); + assert!( + merged[0].positions.len() > 1, + "both pieces are in the one series: {:?}", + merged[0].positions + ); + + let over_frames = + summed_window_over(memory_exec_partitioned_with(publishing.schema(), published)); + let in_process = summed_window_over(Arc::new( + SeriesRepartitionExec::try_new(aliasing_producer(routed_evaluated_partitions()), 3) + .expect("the router is built over the producer's evaluated frames"), + ) as Arc); + assert!( + uses_in_process_series(&in_process), + "the router hands its chunks over, so the node reads them" + ); + assert!( + !uses_in_process_series(&over_frames), + "a memory leaf publishes frames, so the node reads them" + ); + let frame_rows = polled_partition_rows(&over_frames).await; + let chunk_rows = polled_partition_rows(&in_process).await; + assert_eq!(3, chunk_rows.len(), "the tree runs once per owner"); + for owner in 0..chunk_rows.len() { + assert!(chunk_rows[owner].1, "owner {owner} reports its end"); + let mut answered_over_frames = frame_rows[owner].0.clone(); + answered_over_frames + .sort_by(|left, right| left.partial_cmp(right).expect("rows compare")); + let mut answered_over_chunks = chunk_rows[owner].0.clone(); + answered_over_chunks + .sort_by(|left, right| left.partial_cmp(right).expect("rows compare")); + assert_eq!( + answered_over_frames, answered_over_chunks, + "owner {owner} answers the same rows over the chunks and over the frames" + ); + } + assert!( + chunk_rows.iter().any(|(rows, _)| !rows.is_empty()), + "the fixture answers on the grid" + ); + }) + .await + .expect("the composition finishes"); +} + +/// A state input is read in process, like every other content a native operator publishes. +/// +/// `SeriesChunk::State` is the exported row itself, not a second encoding of it, so the node folds +/// the row its operator hands over instead of decoding a frame on a state path of its own. +#[test] +fn a_state_input_is_read_in_process() { + let router: Arc = Arc::new( + SeriesRepartitionExec::try_new(state_producer(), 2) + .expect("the producer declares aggregate-state frames"), + ); + assert!( + series_execution_plan(router.as_ref()).is_some(), + "a state publication is a row this crate holds, so it is handed over" + ); + let fused = final_state_over(router); + assert!( + uses_in_process_series(&fused), + "the state input is handed over, not decoded from a frame" + ); +} + +// --------------------------------------------------------------------------- +// Aggregate state over the same handover +// --------------------------------------------------------------------------- + +/// One exported state row as these tests compare it. +/// +/// Which group it belongs to, where it has contributions, and whether it closes its chain: the +/// payload is compared where it is read, by the answer the two paths fold. +#[derive(Clone, Debug, PartialEq)] +struct DecodedState { + metric: SeriesLabels, + runs: Vec<(usize, usize)>, + is_last: bool, +} + +/// `row` as these tests compare it. +fn decoded_state(row: &StateFrameRow) -> DecodedState { + DecodedState { + metric: row.metric().clone(), + runs: row + .time() + .runs() + .map(|run| (run.position, run.len)) + .collect(), + is_last: row.is_last(), + } +} + +/// `rows` in a fixed order, so two lists of them can be compared as sets. +fn state_rows_sorted(mut rows: Vec) -> Vec { + rows.sort_by_key(|row| format!("{:?}|{:?}", row.metric, row.runs)); + rows +} + +/// A real `Partial` producer over two partitions, both carrying the same group. +/// +/// Grouping by `job` puts both partitions' state in one group, so the router routes both rows to the +/// owner that folds them and the `Final` above has to merge what it is given: that merge is what +/// this differential is about. +fn state_producer() -> Arc { + let rows = series_samples(1.0); + let first = [(HOST, "web-0"), (JOB, "shared")]; + let second = [(HOST, "web-1"), (JOB, "shared")]; + let partitions = vec![ + frames(&[labelled_chunk("web-0", &first, &rows[..4], true)]), + vec![frame(&labelled_chunk("web-1", &second, &rows, true))], + ]; + partial_plan( + rate_tree(), + memory_exec_partitioned(partitions), + partial_op(AggregateKind::Sum, &[JOB]), + &[JOB], + ) + .expect("a rate tree with a partial sum is executable") +} + +/// A real `Final` fold over `input`, answering rows: the aggregate that reads exported state. +fn final_state_over(input: Arc) -> Arc { + let state = Arc::new(AggregateStateSchema { + group: Grouping::By(Arc::new([Arc::from(JOB)])), + kind: AggregateStateKind::Sum, + components: Arc::from([StateComponent::Value, StateComponent::Compensation]), + accumulators: raw_schema().fields.clone(), + grid: grid(), + }); + let tree = state_tree(AggregateStage::Final, NativeType::AggregateState(state)); + plan_of(fused(tree), input).expect("the runtime executes a final fold") +} + +/// The state rows `owner` of `plan` hands over, as these tests compare them. +async fn handed_state_rows(plan: &Arc, owner: usize) -> Vec { + let handed = series_execution_plan(plan.as_ref()) + .expect("the router hands its rows over") + .execute_series(owner, SessionContext::default().task_ctx()) + .expect("the owner hands its rows over") + .try_collect::>() + .await + .expect("the rows arrive"); + handed + .into_iter() + .map(|handed| match handed.into_parts().0 { + SeriesChunk::State(chunk) => match chunk { + StateChunk::Series { series, .. } => { + let series = series.first().expect("one group per handed chunk"); + DecodedState { + metric: series.metric.clone(), + runs: series + .time + .runs() + .map(|run| (run.position, run.len)) + .collect(), + // A handed-over group is a whole publication: the producer folded it + // completely, which is what the frame row it would have been says too. + is_last: true, + } + } + StateChunk::Row(row) => DecodedState { + metric: row.metric.clone(), + runs: row.time.runs().map(|run| (run.position, run.len)).collect(), + is_last: true, + }, + }, + other => panic!("a state owner handed over {other:?}"), + }) + .collect() +} + +/// The state rows `batches` decode to, as a consumer behind the boundary recovers them. +async fn state_rows_decoded(schema: SchemaRef, batches: Vec) -> Vec { + let declaration = + SeriesFrameDeclaration::parse(schema.as_ref()).expect("the export declares a series frame"); + let state = declaration + .aggregate_state() + .expect("the export declares aggregate state"); + let binding = Arc::new( + datatypes::series::aggregate_state::AggregateStateSchema::try_new( + state.kind, + state.components.to_vec(), + ) + .expect("the declared layout is legal"), + ); + let series = Arc::new(declaration.series().clone()); + let leaf = memory_exec_partitioned_with(schema, vec![batches]); + let frames = leaf + .execute(0, SessionContext::default().task_ctx()) + .expect("the export's frames are re-read"); + unpack_aggregate_state(frames, Some(binding), Some(series)) + .expect("the export decodes") + .try_collect::>() + .await + .expect("the rows decode") + .iter() + .map(decoded_state) + .collect() +} + +/// A state publication is one publication read two ways: the rows have to be the same, and so does +/// the fold above them. +/// +/// The rows are compared per owner - the group they name, the grid positions they carry and their +/// finality, labels included - and the fold is compared per owner as the rows it answers, because +/// that is where the payload is read. +#[tokio::test] +async fn a_state_router_hands_over_the_rows_its_frames_decode_to() { + tokio::time::timeout(std::time::Duration::from_secs(30), async { + // The frame side: one router's export, read owner by owner, which is both what a boundary + // consumer decodes and the fixture the frame path below is given. + let publishing: Arc = Arc::new( + SeriesRepartitionExec::try_new(state_producer(), 2) + .expect("the producer declares aggregate-state frames"), + ); + let published = published_frames(&publishing).await; + assert_eq!(2, published.len(), "one publication per owner"); + + // The chunk side reads the same fixture through a router of its own. + let handing: Arc = Arc::new( + SeriesRepartitionExec::try_new(state_producer(), 2) + .expect("the producer declares aggregate-state frames"), + ); + let mut in_process = Vec::new(); + for owner in 0..2 { + in_process.push(handed_state_rows(&handing, owner).await); + } + let handed = in_process.iter().flatten().count(); + assert!(handed > 0, "the producer exports at least one group"); + for (owner, handed) in in_process.iter().enumerate() { + let from_frames = + state_rows_decoded(publishing.schema(), published[owner].clone()).await; + assert_eq!( + state_rows_sorted(from_frames), + state_rows_sorted(handed.clone()), + "owner {owner} hands over the rows its frames decode to" + ); + } + // Every exported row closes its chain: a partial producer exports a group once. + assert!( + in_process.iter().flatten().all(|row| row.is_last), + "the export closes what it publishes: {in_process:?}" + ); + + // And the fold above: the same tree over the rows and over the frames answers the same rows + // per owner, which is where the payload itself is read. + let over_frames = + final_state_over(memory_exec_partitioned_with(publishing.schema(), published)); + let in_process = final_state_over(Arc::new( + SeriesRepartitionExec::try_new(state_producer(), 2) + .expect("the producer declares aggregate-state frames"), + ) as Arc); + assert!( + uses_in_process_series(&in_process), + "a state input is handed over like any other content" + ); + // And so is the framed fixture: a `Final` normalizes every state input onto a router, and a + // router now hands its rows over whatever its content, so there is no state consumer left + // that decodes a frame here. The frame branch of `execute` stays for the one state producer + // this crate does not own - a merge scan reading another process's frames - which a + // single-process fixture cannot build, so this comparison runs through the frames the + // producer published and the rows they decode back to. + assert!( + uses_in_process_series(&over_frames), + "a state input is normalized onto a router, which hands its rows over" + ); + let frame_rows = polled_partition_rows(&over_frames).await; + let chunk_rows = polled_partition_rows(&in_process).await; + assert_eq!(2, chunk_rows.len(), "the fold runs once per owner"); + for owner in 0..chunk_rows.len() { + assert!(chunk_rows[owner].1, "owner {owner} reports its end"); + let mut answered_over_frames = frame_rows[owner].0.clone(); + answered_over_frames + .sort_by(|left, right| left.partial_cmp(right).expect("rows compare")); + let mut answered_over_chunks = chunk_rows[owner].0.clone(); + answered_over_chunks + .sort_by(|left, right| left.partial_cmp(right).expect("rows compare")); + assert_eq!( + answered_over_frames, answered_over_chunks, + "owner {owner} folds the same answer over the rows and over the frames" + ); + } + assert!( + chunk_rows.iter().any(|(rows, _)| !rows.is_empty()), + "the fixture folds something" + ); + }) + .await + .expect("the composition finishes"); +} + +/// A state chunk's charge is released with the chunk, exactly as an evaluated one's is. +/// +/// The state frame path keeps the router's reservation until the poll after the batch it backed, so +/// `Final` can admit what it kept of it. A handed-over row has no batch to flush and no next poll to +/// wait for: the reservation travels with the row, which is the same moment - the row is admitted by +/// the push that reads it, and the charge goes when the value it accounts for goes. +#[tokio::test] +async fn a_handed_state_chunk_holds_its_charge_until_it_is_dropped() { + let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); + let context = task_context(&pool); + let plan: Arc = Arc::new( + SeriesRepartitionExec::try_new(state_producer(), 2) + .expect("the producer declares aggregate-state frames"), + ); + let mut chunks = series_execution_plan(plan.as_ref()) + .expect("the router hands its rows over") + .execute_series(0, Arc::clone(&context)) + .expect("the output is claimed once"); + + let first = futures::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)) + .await + .expect("the producer exports a row") + .expect("the row arrives"); + assert!( + matches!(first.chunk(), SeriesChunk::State(_)), + "a state owner hands over state rows" + ); + let held = pool.reserved(); + assert!( + held > 0, + "a held state row keeps the export it points into charged" + ); + + drop(first); + let after = pool.reserved(); + assert!( + after < held, + "dropping the state row releases what it was charged: {held} held, {after} still reserved" + ); + + // The rest of the export, then the rows themselves: nothing is left charged once both are gone. + let mut rest = chunks + .by_ref() + .try_collect::>() + .await + .expect("the export ends instead of failing"); + rest.clear(); + drop(chunks); + // The other owner of this router is never claimed, so the read it belongs to ends with the plan. + drop(plan); + assert_eq!(0, pool.reserved(), "the finished export holds nothing"); +} + +/// Whether `plan` is answered by the guard. +fn guard_answers(plan: &Arc) -> bool { + series_execution_plan(plan.as_ref()).is_some() +} + +/// A frame the guard answers for, and the row table it does not. +/// +/// A `SeriesFrame` - of values, or of the state a `Partial` folded - is a publication another native +/// operator reads in process. The row table a statement is answered with is the query's own answer, +/// and only `execute` hands that out, so the guard says no and no consumer above reads a chunk. +#[test] +fn the_guard_answers_for_frames_and_not_for_rows() { + let values = aliasing_producer(routed_evaluated_partitions()); + assert!( + guard_answers(&values), + "a node publishing a frame of values hands its chunks over" + ); + + let state = state_producer(); + assert!( + guard_answers(&state), + "the state a Partial folds is handed over as the chunk it is" + ); + + let rows = plan_of( + fused(rate_tree()), + memory_exec(frames(&[series_chunk("web-0", &series_samples(1.0), true)])), + ) + .expect("the runtime executes a rate tree"); + assert!( + !guard_answers(&rows), + "a node answering rows is the query's answer, not a chunk" + ); +} + +/// A fused node above another reads its chunks, and answers what the frames would have. +/// +/// The same tree over the same publication: `over_chunks` reads the node below in process, and +/// `over_frames` decodes what that node publishes for a boundary consumer. The answer has to be the +/// same batch for batch, which is what makes the handover a saving rather than a second semantics. +#[tokio::test] +async fn a_fused_node_hands_over_what_the_frames_above_it_would_decode() { + tokio::time::timeout(std::time::Duration::from_secs(30), async { + let context = SessionContext::default().task_ctx(); + // What the node below publishes, taken from the node itself so both plans read one input. + let lower = aliasing_producer(routed_evaluated_partitions()); + let published = published_frames(&lower).await; + let lower_frames = memory_exec_partitioned_with(lower.schema(), published); + + let over_chunks = summed_window_over(aliasing_producer(routed_evaluated_partitions())); + let over_frames = summed_window_over(lower_frames); + assert!( + uses_in_process_series(&over_chunks), + "the node below is one of ours, so its chunks are read" + ); + assert!( + !uses_in_process_series(&over_frames), + "a memory leaf publishes frames, so the node above decodes them" + ); + + let chunk_batches = collect(Arc::clone(&over_chunks), Arc::clone(&context)) + .await + .expect("the chunk path completes"); + let frame_batches = collect(Arc::clone(&over_frames), context) + .await + .expect("the frame path completes"); + assert!(!chunk_batches.is_empty(), "the fixture answers on the grid"); + assert_eq!( + frame_batches, chunk_batches, + "the two paths answer the same batches" + ); + }) + .await + .expect("the composition finishes"); +} + +// --------------------------------------------------------------------------- +// The handover's contract, held to the same standard as a frame +// --------------------------------------------------------------------------- + +/// A child's chunks are checked at the order its own plan declares, exactly as its frames are. +/// +/// The producer here names its keys by an `Interleaved` promise and then closes the same key twice. +/// Its frames cannot carry that - it publishes them under the contiguous order it declares, and the +/// packer refuses the recurrence - so a consumer reading its chunks has to refuse it too: the +/// handover is a way to read a producer, not a way around what it promised. +#[tokio::test] +async fn a_router_refuses_the_chunk_sequence_the_frames_refuse() { + let closed = |time: i64, last: bool| { + chunk_of( + &raw_schema(), + "web-1", + metric(&[(HOST, "web-1")], Some(METRIC)), + &[time], + vec![vec![Some(1.0)]], + last, + ) + }; + // Two closed chunks of one key, which the contiguous order of the node above forbids. + let batches = || { + vec![frames_under( + &frame_schema_with_ordering(SeriesOrdering::Interleaved), + &[closed(60_000, true), closed(120_000, true)], + )] + }; + let context = SessionContext::default().task_ctx(); + let refused = |error: BoxedError| { + error + .to_string() + .contains("raw series key recurred after final chunk") + }; + + // The frame path: the producer cannot pack this under the order it publishes. + let source = raw_source(memory_exec_partitioned_with( + frame_schema_with_ordering(SeriesOrdering::Interleaved), + batches(), + )); + let mut frames = source + .execute(0, Arc::clone(&context)) + .expect("the node executes"); + let error = frames + .next() + .await + .expect("the producer answers instead of ending") + .expect_err("the frame path refuses a key that recurs after it closed"); + assert!( + refused(BoxedError::new(common_query::error::Error::from(error))), + "the frame path refuses a key that recurs after it closed" + ); + + // The chunk path: read through a router, which asks the child for its chunks. + let router: Arc = Arc::new( + SeriesRepartitionExec::try_new( + raw_source(memory_exec_partitioned_with( + frame_schema_with_ordering(SeriesOrdering::Interleaved), + batches(), + )), + 1, + ) + .expect("the child declares a raw frame"), + ); + let chunks = series_execution_plan(router.as_ref()) + .expect("the router hands its publication over") + .execute_series(0, context) + .expect("the output is claimed"); + let error = chunks + .try_collect::>() + .await + .expect_err("the chunk path refuses what the frame path refuses"); + let message = error.to_string(); + assert!(refused(error), "{message}"); +} + +/// A state group is charged for as long as the reader holds it, with no router in between. +/// +/// The tree's own export carries the fold's reservation; handing the groups of that export over has +/// to carry it too, or a reader of a `Partial` holds uncharged bytes between the fold and its own +/// accounting. +#[tokio::test] +async fn a_handed_state_group_keeps_the_export_charged() { + let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); + let context = task_context(&pool); + let producer = state_producer(); + let mut chunks = series_execution_plan(producer.as_ref()) + .expect("a Partial hands its state over") + .execute_series(0, Arc::clone(&context)) + .expect("the output is claimed"); + + let group = futures::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)) + .await + .expect("the partial exports a group") + .expect("the group arrives"); + assert!( + matches!(group.chunk(), SeriesChunk::State(StateChunk::Series { .. })), + "a partial hands its folded groups over" + ); + let held = pool.reserved(); + assert!( + held > 0, + "a held state group keeps the export it was folded in charged" + ); + + drop(group); + let after = pool.reserved(); + assert!( + after < held, + "dropping the group gives its charge back: {held} held, {after} still reserved" + ); + + drop(futures::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)).await); + drop(chunks); + drop(producer); + assert_eq!(0, pool.reserved(), "the finished export holds nothing"); +} + +/// A state export whose first partition folds two groups, so a reader can keep one and read on. +fn two_group_state_producer() -> Arc { + let rows = series_samples(1.0); + let first = [(HOST, "web-0"), (JOB, "first")]; + let second = [(HOST, "web-1"), (JOB, "second")]; + let partitions = vec![frames(&[ + labelled_chunk("web-0", &first, &rows[..4], true), + labelled_chunk("web-1", &second, &rows[..4], true), + ])]; + partial_plan( + rate_tree(), + memory_exec_partitioned(partitions), + partial_op(AggregateKind::Sum, &[JOB]), + &[JOB], + ) + .expect("a rate tree with a partial sum is executable") +} + +/// A group a reader keeps stays charged after the export that produced it is gone. +/// +/// The reviewer's case, and the one the sibling above does not cover: a consumer polls a group, keeps +/// it, and then exhausts or drops the export. The reservation the export carried has to travel with +/// the group rather than stay in the stream, or reading to the end - or letting the stream go - would +/// release bytes the reader is still holding, and the pool would hand them to somebody else. +/// +/// The figures are read once the export and its producer are gone, so what the pool counts is the +/// group's alone; the second figure is what that group holds by itself, so a reservation released +/// with the stream cannot pass on the strength of the group's own bytes. +#[tokio::test] +async fn a_held_state_group_outlives_the_export_that_produced_it() { + let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); + let context = task_context(&pool); + let producer = two_group_state_producer(); + let mut chunks = series_execution_plan(producer.as_ref()) + .expect("a Partial hands its state over") + .execute_series(0, Arc::clone(&context)) + .expect("the output is claimed"); + + let kept = futures::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)) + .await + .expect("the partial exports a group") + .expect("the group arrives"); + // The export's other group, read and dropped: the reservation the two share is the kept group's + // to hold, so letting the sibling go must not release it. + let sibling = futures::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)) + .await + .expect("the partial exports its second group") + .expect("the group arrives"); + let held = pool.reserved(); + drop(sibling); + assert!(held > 0, "a held state group keeps its export charged"); + + // Drain the rest of the export and drop everything but the group: the stream, the rows it + // handed over and the plan that produced them. + let rest = chunks + .by_ref() + .try_collect::>() + .await + .expect("the export ends instead of failing"); + drop(rest); + drop(chunks); + drop(producer); + let after = pool.reserved(); + let group_bytes = match kept.chunk() { + SeriesChunk::State(chunk) => state_bytes(chunk), + other => panic!("a partial hands its groups over, not {other:?}"), + }; + assert!( + after >= group_bytes, + "the group alone keeps its export charged: {held} held while it was read, {after} still \ + reserved once the export and its producer are gone, and the group alone holds {group_bytes}" + ); + assert!( + after <= held, + "nothing the export held is left besides the reservation the group keeps: {after} reserved, \ + {held} while the export was being read" + ); + + drop(kept); + assert_eq!( + 0, + pool.reserved(), + "dropping the last group of a finished export releases everything" + ); +} + +/// The two entry points cannot be mixed on one execution, and the refusal names both. +/// +/// The child is read once for every output of one execution, so the way it is read is fixed by the +/// first output that claims it. A later output asking for the other form would be handed a stream it +/// did not ask for; it is refused instead, naming what the read already is and what it was asked to +/// become. +#[tokio::test] +async fn the_two_entry_points_cannot_be_mixed_on_one_execution() { + let context = SessionContext::default().task_ctx(); + let router: Arc = Arc::new( + SeriesRepartitionExec::try_new( + raw_source(memory_exec_partitioned(vec![frames(&[series_chunk( + "web-0", + &series_samples(1.0), + true, + )])])), + 2, + ) + .expect("the child declares a raw frame"), + ); + router + .execute(0, Arc::clone(&context)) + .expect("the first output reads frames"); + let claimed = series_execution_plan(router.as_ref()) + .expect("the router hands its publication over") + .execute_series(1, context); + // The refusal is an error, and naming it is what the two assertions below are about. + let Err(error) = claimed else { + panic!("a second output cannot read the same execution as chunks"); + }; + let message = error.to_string(); + assert!(message.contains("already read as frames"), "{message}"); + assert!(message.contains("cannot read it as chunks"), "{message}"); +} diff --git a/src/promql/src/extension_plan/raw_series_source.rs b/src/promql/src/extension_plan/raw_series_source.rs index d6bef21efb9..ac3129b9e47 100644 --- a/src/promql/src/extension_plan/raw_series_source.rs +++ b/src/promql/src/extension_plan/raw_series_source.rs @@ -26,6 +26,7 @@ //! scan partition is re-labelled independently, keeping its place in the partition layout and //! each series contiguous within its scan partition. +use std::any::Any; use std::fmt::{self, Formatter}; use std::pin::Pin; use std::sync::Arc; @@ -60,9 +61,12 @@ use datatypes::series::samples::{FieldSpec, SeriesSchema}; use futures::{Stream, StreamExt}; use greptime_proto::substrait_extension::RawSeriesSource as RawSeriesSourceProto; use prost::Message; -use store_api::region_engine::{RawLabelSource, RawSeriesStream, SendableRawSeriesStream}; +use store_api::region_engine::{RawLabelSource, RawSeriesStream}; use table::table::scan::SeriesScanExec; +use crate::extension_plan::series_execution::{ + HandedSeriesChunk, SendableSeriesStream, SeriesChunk, SeriesExecutionPlan, +}; use crate::source::materialize_raw_labels; /// The ordering every frame of this node declares. @@ -247,31 +251,58 @@ impl UserDefinedLogicalNodeCore for RawSeriesSource { } } -/// One partition's relabelled frames, published under this node's declared ordering. +/// One partition's chunks, read by the frame packer as this node's own raw series. /// -/// The scan states its own key order, which the node cannot repeat in a schema it fixed at plan -/// time. Every other property is forwarded unchanged. -struct DeclaredOrdering(SendableRawSeriesStream); +/// The frames this node publishes are packed from exactly what +/// [`SeriesExecutionPlan::execute_series`] hands over, so [`RawSeriesSourceExec::execute`] reads +/// that stream through here. Two things are declared rather than forwarded: the labels are the +/// complete ones [`materialize_raw_labels`] produced - the frames this node writes are explicit and +/// carry no decode description - and the ordering is the [`ORDERING`] it publishes, not the finer +/// one the scan states, because the node fixed its schema at plan time and cannot repeat the scan's +/// promise. +struct DeclaredSeries { + /// The chunks this node hands over in process. + chunks: SendableSeriesStream, + /// The raw schema every chunk of that stream is bound to. + schema: Arc, +} -impl Stream for DeclaredOrdering { +impl Stream for DeclaredSeries { type Item = Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - self.0.as_mut().poll_next(cx) + match self.chunks.as_mut().poll_next(cx) { + // What this node hands over is uncharged: the scan's read is charged where it happens + // and this node reserves nothing of its own, so the packer has nothing of its to hold. + Poll::Ready(Some(Ok(handed))) => match handed.into_parts().0 { + SeriesChunk::Raw(chunk) => Poll::Ready(Some(Ok(chunk))), + // This node answers raw chunks and nothing else. Another variant would mean the + // frame path and the in-process path no longer describe the same output, so it is + // reported rather than reinterpreted. + other => Poll::Ready(Some(Err(BoxedError::new( + common_query::error::Error::from(DataFusionError::Execution(format!( + "RawSeriesSourceExec handed over {other:?}" + ))), + )))), + }, + Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))), + Poll::Ready(None) => Poll::Ready(None), + Poll::Pending => Poll::Pending, + } } } -impl RawSeriesStream for DeclaredOrdering { +impl RawSeriesStream for DeclaredSeries { fn schema(&self) -> &Arc { - self.0.schema() + &self.schema } fn label_source(&self) -> &RawLabelSource { - self.0.label_source() + &RawLabelSource::Explicit } fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> { - self.0.label_decode_spec() + None } fn ordering(&self) -> SeriesOrdering { @@ -291,6 +322,11 @@ fn is_series_scan(plan: &dyn ExecutionPlan) -> bool { } /// The physical node: the region's raw-series leaf, re-labelling each scan partition in place. +/// +/// It decodes the scan's frames once. A consumer behind a boundary reads the frames it publishes; a +/// consumer in this process asks for the chunks instead +/// ([`SeriesExecutionPlan::execute_series`]), +/// which is that same decode without the encode on the way out. #[derive(Debug)] pub struct RawSeriesSourceExec { input: Arc, @@ -404,6 +440,24 @@ impl RawSeriesSourceExec { pub fn is_per_series_scan(&self) -> bool { self.per_series_scan } + + /// The child's frames for `partition`, after checking `partition` is one of this node's. + /// + /// Both entry points read the child through here, so a partition this node does not have is + /// refused the same way whether the caller asked for frames or for series. + fn child_frames( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + let partition_count = self.properties.partitioning.partition_count(); + if partition >= partition_count { + return Err(DataFusionError::Execution(format!( + "RawSeriesSourceExec partition {partition} is out of bounds for {partition_count} partitions" + ))); + } + self.input.execute(partition, context) + } } impl DisplayAs for RawSeriesSourceExec { @@ -476,18 +530,12 @@ impl ExecutionPlan for RawSeriesSourceExec { partition: usize, context: Arc, ) -> DataFusionResult { - let partition_count = self.properties.partitioning.partition_count(); - if partition >= partition_count { - return Err(DataFusionError::Execution(format!( - "RawSeriesSourceExec partition {partition} is out of bounds for {partition_count} partitions" - ))); - } - let frames = self.input.execute(partition, context)?; if let Some(child_schema) = &self.pass_through { // The child already writes this node's frame, so a batch differs only in the ordering // it declares. Re-declaring keeps the child's column data untouched and publishes // exactly the schema the plan was built with; one batch in, one batch out, so the // child's polling and backpressure are unchanged. + let frames = self.child_frames(partition, context)?; let declared = Arc::clone(&self.frame_schema); let child_schema = Arc::clone(child_schema); let batches = frames.map(move |batch| { @@ -505,21 +553,50 @@ impl ExecutionPlan for RawSeriesSourceExec { batches, ))); } - let raw = unpack_raw_series(frames, Some(Arc::clone(&self.series_schema)))?; - let relabelled = materialize_raw_labels(raw) - .map_err(|error| DataFusionError::External(Box::new(error)))?; - // The scan may promise a finer order than this node declares. Exchange the promise here so - // the published frame carries the schema the plan was built with, which is what the region - // and the frontend both compare. + // The frames are the in-process chunks, encoded: `execute_series` is the decode, + // so a consumer reading frames and one reading series read the same values rather than two + // decodings that have to agree. // This node runs inside the query engine's DataFusion execution, whose runtimes enable the // time driver, so the packer may hold a partially filled batch across a pending period. pack_raw_series_with( - Box::pin(DeclaredOrdering(relabelled)), + Box::pin(DeclaredSeries { + chunks: self.execute_series(partition, context)?, + schema: Arc::clone(&self.series_schema), + }), PendingBatching::Deadline, ) } } +impl SeriesExecutionPlan for RawSeriesSourceExec { + fn as_any(&self) -> &dyn Any { + self + } + + /// The child's frames decoded once, named by their complete labels, and handed over as the + /// chunks they are. + /// + /// [`ExecutionPlan::execute`] packs exactly this stream when its consumer reads frames, so the two + /// entry points cannot decode differently: there is one decode, and the in-process one skips + /// only the encode at the end of it. + fn execute_series( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + let frames = self.child_frames(partition, context)?; + let raw = unpack_raw_series(frames, Some(Arc::clone(&self.series_schema)))?; + let relabelled = materialize_raw_labels(raw) + .map_err(|error| DataFusionError::External(Box::new(error)))?; + // The scan may promise a finer order than this node declares. The ordering is a property + // of the schema this node publishes - which is where a consumer reads it - and not of the + // values, so a chunk stream carries none of its own and nothing is re-declared here. + Ok(relabelled + .map(|chunk| chunk.map(|chunk| HandedSeriesChunk::uncharged(SeriesChunk::Raw(chunk)))) + .boxed()) + } +} + #[cfg(test)] pub(crate) mod tests { use api::v1::SemanticType; @@ -553,6 +630,7 @@ pub(crate) mod tests { use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef}; use store_api::region_engine::{ BoundTag, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties, + SendableRawSeriesStream, }; use store_api::storage::{RegionId, ScanRequest}; use table::table::scan::RegionScanExec; diff --git a/src/promql/src/extension_plan/series_execution.rs b/src/promql/src/extension_plan/series_execution.rs new file mode 100644 index 00000000000..126fed04531 --- /dev/null +++ b/src/promql/src/extension_plan/series_execution.rs @@ -0,0 +1,402 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The in-process handover between two adjacent native PromQL operators. +//! +//! Two native operators pass each other a `SeriesFrame` record batch today: the producer packs its +//! chunks into one and the consumer unpacks them again, only because +//! [`ExecutionPlan::execute`] answers a `SendableRecordBatchStream`. No DataFusion operator stands +//! between them, so the frame is written and read back for nobody: a transport type used for a +//! function call. +//! +//! [`SeriesExecutionPlan`] is that call. A native operator that can answer its chunks as they are +//! implements the trait, and a native consumer that receives one calls +//! [`SeriesExecutionPlan::execute_series`] instead of decoding a frame. The chunk is the internal +//! value the operator already holds - a [`RawSeriesChunk`] read from a region, an +//! [`EvaluatedChunk`] a tree settled on its grid, or a [`StateChunk`] a `Partial` folded - so the +//! handover reuses the buffers instead of encoding them. Every content a native node publishes +//! travels this way; there is no second path for one of them to be left on. +//! +//! What keeps the shortcut structural, rather than a convention an operator has to remember, is +//! that the capability is a type: [`series_execution_plan`] answers for the operators this crate +//! implements it on and for nothing else. A plan that produces frames is not one of them - a +//! network exchange, a remote scan, or any node reading a frame it received answers `None` - so no +//! chunk reaches a consumer across a boundary this way. The question is asked once per input and +//! answered by the input alone: calling [`execute_series`](SeriesExecutionPlan::execute_series) is +//! how a consumer says it reads that input's chunks, and calling +//! [`ExecutionPlan::execute`] is how it says it reads its frames. There is no second decision to +//! keep in step with the first. +//! +//! Which edge this is, and which edge it is not: +//! +//! - In process: the two ends are nodes of one plan in one process, and the consumer called +//! [`execute_series`](SeriesExecutionPlan::execute_series) on the operator it was handed as an +//! input. That is the whole of where a chunk can travel. +//! - Still bytes: every edge that leaves the process, or reaches a node this crate does not own. A +//! region's scan and the scan a merge sits on still publish `RecordBatch`es, a remote scan answers +//! frames, and a root output still converts series back into a batch (`series_to_record_batch`). +//! No chunk is serialized and none is sent anywhere, so nothing about the wire changes here. +//! +//! Two things the frame path does are not skipped, because they are not about the encoding: +//! +//! - The sequence is checked. [`SequenceValidator`] and [`EvaluatedSequenceValidator`] are what a +//! frame consumer runs while it decodes; [`checked_series_stream`] runs the same validators over +//! the same sequence of chunks, so a producer whose chains are malformed is refused here exactly +//! as it is through a frame. An exported state row has no such chain - its frame consumer runs no +//! cross-row validator either - so there is nothing for that content to skip. +//! - The memory is charged for as long as it is held. A producer that merges an identity reserves +//! the bytes it merges into and hands them over with the value ([`SeriesCharge`]), so the pool +//! sees them until the consumer drops the chunk that carries them - not until a packer flushed a +//! batch, and not for longer either. +//! +//! What a consumer records does not change with the representation. The figures a native node keeps +//! are recorded per chunk it was fed, and both paths feed it the producer's chunks: a frame carries +//! a chunk as a row, and decoding it yields the chunk back. The one figure that can differ is the +//! count of those chunks, and only for a chunk whose field is itself split into segments - a frame +//! row never spans two segments of one field, so such a chunk is one chunk in process and several +//! rows in a frame. Nothing else, and in particular no sample, value or closed-series count, is +//! recorded on one path and not the other. + +use std::any::Any; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; + +use common_error::ext::BoxedError; +use common_query::series_frame::{EvaluatedSequenceValidator, SequenceValidator}; +use datafusion::error::Result as DataFusionResult; +use datafusion::execution::context::TaskContext; +use datafusion::execution::memory_pool::MemoryReservation; +use datafusion::physical_plan::ExecutionPlan; +use datatypes::series::SeriesOrdering; +use datatypes::series::raw::RawSeriesChunk; +use futures::Stream; + +use crate::evaluated::EvaluatedChunk; +use crate::extension_plan::RawSeriesSourceExec; +use crate::extension_plan::fused_series::FusedSeriesExec; +use crate::extension_plan::series_repartition::SeriesRepartitionExec; +use crate::native::state::StateChunk; + +/// One piece of one series, handed from one native operator to the next. +/// +/// The variants are the three contents the native chain passes between its nodes: raw samples read +/// from a region, values a tree evaluated on the grid its output declares, and one group's exported +/// aggregate state. [`EvaluatedChunk`] is [`Series`](datatypes::series::samples::Series) plus the +/// finality of the chunk, so it is the evaluated half of this enum rather than a `Series` alone: a +/// chunk that cannot say whether it closes its series would make the consumer guess, and "no value +/// here" and "nothing more here" would become the same thing. +/// +/// [`SeriesChunk::State`] is the chunk a producer's aggregate already produces, with no conversion +/// on the way: a `Partial` hands over the groups it folded, on the layout it exported them with, and +/// a `Final` merges that chunk exactly as it merges the row a region's frame decodes to - the two +/// sources meet inside the merge kernel, not at this boundary. +#[derive(Debug)] +pub enum SeriesChunk { + /// One scan series, with its own timestamps and its finality. + Raw(RawSeriesChunk), + /// Values a producer already evaluated on the grid its frame declares. + Evaluated(EvaluatedChunk), + /// The aggregate state its producer exported: the groups a `Partial` folded, or the row a + /// frame-fed producer decoded, as [`StateChunk`] carries them. + State(StateChunk), +} + +/// What one handed chunk is charged to, released when the chunk is. +/// +/// A producer that holds a value on behalf of a consumer has to hold the pool's reservation for it +/// too: the bytes are live, so the pool must not hand them to anybody else. The frame path keeps +/// them in the packer's handoff until the batch they back is flushed; a chunk handed over in +/// process keeps them here, so they are released exactly when the consumer drops the value they +/// account for - never earlier, which would let the pool over-commit, and never for longer, which +/// would hold memory for a chunk nobody has. +/// +/// Two shapes of reservation make up that total. An owner reserves the charges its inputs carried, +/// the descriptor naming the identity, and the workspace it merged or reconstructed into - all of +/// them its own. A state export reserves one batch that several rows are cut from, so those rows +/// share it instead of each holding a copy: that is what [`SeriesCharge::shared`] is, and it is +/// released when the last chunk holding it is dropped. Dropping this value is the whole of what +/// makes either release correct - there is no call to forget - which is why the fields are named as +/// fields nothing reads: holding them is the entire job. The packer's handoff named its own +/// reservations the same way, for the same reason. +#[derive(Debug)] +pub struct SeriesCharge { + /// The reservations this publication holds outright. + _owned: Vec, + /// The reservations it shares with the other chunks cut from the same publication. + _shared: Vec>, +} + +impl SeriesCharge { + /// The charge of one owner publication. + pub(crate) fn new( + fragments: Vec, + descriptor: MemoryReservation, + workspace: Option, + ) -> Self { + let mut owned = fragments; + owned.push(descriptor); + owned.extend(workspace); + Self { + _owned: owned, + _shared: Vec::new(), + } + } + + /// The charge of a publication that several chunks are cut from. + /// + /// Each of those chunks holds a clone of every reservation here, so the bytes stay charged for + /// as long as any of them is alive and are released when the last one is dropped. + pub(crate) fn shared(shared: Vec>) -> Self { + Self { + _owned: Vec::new(), + _shared: shared, + } + } + + /// Every reservation this charge holds, as references a publication can be cut into. + /// + /// A consumer that receives a publication and hands its parts on - a router that routes each + /// group to its owner - cannot keep the charge itself: the charge has to travel with the parts, + /// or the bytes it accounts for would be released while the parts are still held. This is the + /// one conversion that makes that possible from outside this type, whose fields stay private so + /// nothing else can drop a reservation early either. + pub(crate) fn into_shared(self) -> Vec> { + let mut shared = self._shared; + shared.extend(self._owned.into_iter().map(Arc::new)); + shared + } +} + +/// One chunk handed over in process, and what it is charged to. +/// +/// The charge travels with the value rather than beside the stream, so a consumer cannot release a +/// chunk's reservation while it still holds the chunk, and cannot drop the chunk while keeping the +/// reservation either. A consumer that only reads the chunk and forgets it leaks nothing. +#[derive(Debug)] +pub struct HandedSeriesChunk { + chunk: SeriesChunk, + charge: Option, +} + +impl HandedSeriesChunk { + /// A chunk nothing is charged to. + /// + /// A producer that holds no reservation of its own - a decode of scan output, whose read is + /// charged where it happens - hands its values over like this. + pub fn uncharged(chunk: SeriesChunk) -> Self { + Self { + chunk, + charge: None, + } + } + + /// A chunk the producer reserved `charge` for, held until this value is dropped. + pub fn charged(chunk: SeriesChunk, charge: SeriesCharge) -> Self { + Self { + chunk, + charge: Some(charge), + } + } + + /// The chunk itself, borrowed for a check that keeps the charge in place. + pub fn chunk(&self) -> &SeriesChunk { + &self.chunk + } + + /// The chunk and the charge it carries, both to be held as long as the consumer reads it. + pub fn into_parts(self) -> (SeriesChunk, Option) { + (self.chunk, self.charge) + } +} + +/// One partition's output as internal series, not as an encoded frame. +/// +/// The error is the boxed error the internal series streams already report, so a chunk stream +/// composes with [`SendableRawSeriesStream`] and +/// [`SendableEvaluatedSeriesStream`](common_query::series_frame::SendableEvaluatedSeriesStream) +/// without translating it. +/// +/// [`SendableRawSeriesStream`]: store_api::region_engine::SendableRawSeriesStream +pub type SendableSeriesStream = + Pin> + Send>>; + +/// A native operator that can hand its output over in-process without encoding a frame. +/// +/// Implementing this is a statement about what the operator *is*: it runs in the same process as +/// its consumer, and what it produces is an internal value rather than a message. A node that reads +/// or writes a frame as its contract - a scan answering another process, an output boundary - must +/// not implement it, and [`series_execution_plan`] is the one place a consumer asks. +/// +/// [`ExecutionPlan::execute`] stays the whole answer for every consumer that is not native: an +/// implementor still publishes its frames, packed from what it hands over here, so a plan with a +/// foreign operator in the middle keeps working and is merely slower. +pub trait SeriesExecutionPlan: ExecutionPlan { + /// This plan as [`Any`], so a plan reached through this trait can still be asked which + /// concrete operator it is. + /// + /// The obvious spelling of that question - `downcast_ref::()` on a + /// `&dyn Any` - cannot be written, and not because of anything this trait does: + /// [`Any::downcast_ref`] requires `T: Sized` and compares the type id of a concrete type, so a + /// trait object is not a target it accepts. The standard answer is the one here: the trait + /// exposes its object as `dyn Any` and the caller names the concrete type it wants, which is + /// sized by construction. This is the same shape [`ExecutionPlan`] uses for its own downcasts, + /// and it is a method on the trait rather than a `where Self: Sized` helper because it has to + /// be callable on the trait object - the caller is a consumer holding + /// `&dyn SeriesExecutionPlan`, which is exactly the value that is not sized. + fn as_any(&self) -> &dyn Any; + + /// One partition's output as internal series, not as a `RecordBatch`. + /// + /// The stream carries each chunk with what it is charged to + /// ([`HandedSeriesChunk`]), so nothing a producer reserved is released behind the consumer's + /// back: a consumer holds the reservation exactly as long as it holds the chunk. + fn execute_series( + &self, + partition: usize, + ctx: Arc, + ) -> DataFusionResult; +} + +/// `plan` as a native series operator, when it is one. +/// +/// This is the guard a native consumer asks before it decides how to read its input, and it is +/// deliberately the list of operators this crate implements the trait on: a plan that is not in +/// the list is read as frames, so a consumer's fast path can never outrun the operators that +/// support it. It is the *only* place that decision is made - a consumer that asks this per input +/// has nothing to keep in step with it, and no plan is read in process because something else said +/// so. +/// +/// The obvious spelling - erasing the plan and asking it for `dyn SeriesExecutionPlan` - cannot be +/// written, and not because of the DataFusion this crate builds against: +/// [`Any::downcast_ref`] wants `T: Sized` and compares the type id of a concrete type, so a trait +/// object can never be its target and the call would not compile anywhere. The check therefore +/// names the concrete implementors it accepts, one `downcast_ref` per operator, which is why the +/// trait exposes [`SeriesExecutionPlan::as_any`] and why the question below starts from `dyn Any` +/// rather than from `dyn ExecutionPlan`: this DataFusion's [`ExecutionPlan`] declares no `as_any`, +/// but it is [`Any`], so the view is one upcast away. The decision stays in this one function: a +/// new implementor is added here, and until it is, a consumer reads that plan as frames. +pub fn series_execution_plan(plan: &dyn ExecutionPlan) -> Option<&dyn SeriesExecutionPlan> { + let plan: &dyn Any = plan; + if let Some(source) = plan.downcast_ref::() { + return Some(source as &dyn SeriesExecutionPlan); + } + // A router is asked for every content it publishes: an owner's merged raw identity, the series + // an owner settled on its grid, and the groups an owner exported are all values this crate + // holds, so all three are read in process and none of them is left on a frame path. + if let Some(router) = plan.downcast_ref::() { + return Some(router as &dyn SeriesExecutionPlan); + } + // A fused node answers with a frame - of values, or of the state a `Partial` folded - and that + // is a chunk another native operator reads. A node answering a row table is the query's answer + // instead, and only `execute` hands that out. + plan.downcast_ref::() + .filter(|fused| fused.hands_over_series()) + .map(|fused| fused as &dyn SeriesExecutionPlan) +} + +/// `chunks` with the sequence check the frame path runs, applied to each chunk as it arrives. +/// +/// A consumer that decodes a frame validates the sequence it receives - a chain that never closes, +/// a key that recurs after its final chunk, timestamps that go back across chunks, keys that go back +/// under key-then-time order - because the frame may have been written by another process. +/// [`pack_raw_series`](common_query::series_frame::pack_raw_series) and +/// [`unpack_raw_series`](common_query::series_frame::unpack_raw_series) run that check on both ends, +/// and the evaluated packer and unpacker run its evaluated counterpart. A consumer handed the +/// chunks themselves has no frame to decode and no other process to distrust, but the producer can +/// still be wrong: a router publishes what its owners merged, and a second publication of one +/// identity would be as wrong in process as it is across a frame. So the same validators run here, +/// over the same sequence, and the shortcut refuses what the frame would have refused. +/// +/// A state publication is the one content with no such check to run, on either path: the frame +/// consumer's state stream decodes each exported row and hands it on, so there is nothing it would +/// refuse that the handover must refuse too. What both paths do enforce is enforced where the row is +/// decoded - in the producer's handover stream - and this stream passes state rows through. +/// +/// `raw_ordering` is the ordering the producer declares for its raw frames - the one a decoding +/// consumer would read out of the frame schema. It is not inferred from the chunks. +pub fn checked_series_stream( + chunks: SendableSeriesStream, + raw_ordering: SeriesOrdering, +) -> SendableSeriesStream { + Box::pin(CheckedSeries { + chunks: Some(chunks), + raw: SequenceValidator::new(raw_ordering), + evaluated: EvaluatedSequenceValidator::new(), + }) +} + +/// The handover stream, with the frame path's sequence check in front of the consumer. +struct CheckedSeries { + /// The producer's stream, or `None` once this one ended. + chunks: Option, + /// The check a raw consumer of this input would run, at this input's declared ordering. + raw: SequenceValidator, + /// The check an evaluated consumer of this input would run. + evaluated: EvaluatedSequenceValidator, +} + +impl Stream for CheckedSeries { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + let Some(chunks) = this.chunks.as_mut() else { + return Poll::Ready(None); + }; + let handed = match chunks.as_mut().poll_next(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(Some(Err(error))) => { + this.chunks = None; + return Poll::Ready(Some(Err(error))); + } + // The producer ended, so the check that only an end can make is made here: a chain + // still open when the stream stopped is the failure the frame path reports as well. + Poll::Ready(None) => { + this.chunks = None; + let checked = this.raw.finish().and_then(|()| this.evaluated.finish()); + return Poll::Ready(checked.err().map(|error| Err(checked_error(error)))); + } + Poll::Ready(Some(Ok(handed))) => handed, + }; + let checked = match handed.chunk() { + SeriesChunk::Raw(chunk) => this.raw.validate(chunk), + SeriesChunk::Evaluated(chunk) => this.evaluated.validate(&chunk.series, chunk.is_last), + // A state publication has no chain of chunks to check, on either path: the frame + // consumer's state stream decodes each exported row and hands it on, running no + // cross-row validator at all, so there is nothing it would refuse that this would + // accept. What both paths do enforce - the declaration is this revision's, the batch + // carries the declared schema, and the declared ordering is contiguous - is enforced + // where the row is decoded, in the producer's handover stream. + SeriesChunk::State(_) => Ok(()), + }; + match checked { + Ok(()) => Poll::Ready(Some(Ok(handed))), + Err(error) => { + // Nothing more is read from a producer whose sequence is broken: the frame path + // drops its decoder at the same point. + this.chunks = None; + Poll::Ready(Some(Err(checked_error(error)))) + } + } + } +} + +/// The error a broken chunk sequence is reported as, in the handover's own error type. +fn checked_error(error: datafusion::error::DataFusionError) -> BoxedError { + BoxedError::new(common_query::error::Error::from(error)) +} + +#[cfg(test)] +mod tests; diff --git a/src/promql/src/extension_plan/series_execution/tests.rs b/src/promql/src/extension_plan/series_execution/tests.rs new file mode 100644 index 00000000000..6a92bae4cad --- /dev/null +++ b/src/promql/src/extension_plan/series_execution/tests.rs @@ -0,0 +1,211 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! What the guard has to answer: the operators that can hand chunks over, and nothing else. +//! +//! The consumer's fast path is only as safe as this answer, so the cases that keep it structural +//! are the ones that must say no: a region scan answering frames, a router over a content this +//! crate does not produce, and a wrapper that forwards whatever its input produces. Every content a +//! router does produce - raw, evaluated, aggregate state - is answered for, because every one of +//! them is a value this crate holds. + +use std::sync::Arc; + +use common_query::series_frame::frame_schema_with; +use datafusion::physical_plan::ExecutionPlan; +use datafusion::physical_plan::coop::CooperativeExec; +use datafusion::physical_plan::empty::EmptyExec; +use datatypes::series::SeriesOrdering; +use datatypes::series::aggregate_state::{ + AggregateStateKind, AggregateStateSchema, StateComponent, +}; +use datatypes::series::frame::{FrameLabelMode, aggregate_state_frame_schema}; +use datatypes::series::samples::{FieldSpec, SeriesSchema}; +use datatypes::series::time::{EvalGrid, GridSpec}; + +use super::series_execution_plan; +use crate::extension_plan::raw_series_source::tests::{per_series_scan, raw_source}; +use crate::extension_plan::{RawSeriesSourceExec, SeriesRepartitionExec}; + +#[test] +fn the_raw_source_hands_its_chunks_over() { + let source = raw_source(per_series_scan(1)); + assert!( + series_execution_plan(source.as_ref()).is_some(), + "the region's raw source decodes the scan's frames itself, so it answers series" + ); +} + +/// The answer is the operator itself, and `as_any` is how a caller says which one. +/// +/// A downcast to `dyn SeriesExecutionPlan` is not expressible - [`Any::downcast_ref`] wants a sized +/// target - so the trait exposes its object as `dyn Any` and a caller that wants the operator back +/// names it. That is what makes the guard useful beyond a yes or no: a consumer holding the answer +/// can still ask whether it was handed a source or a router. +#[test] +fn the_answer_is_the_operator_that_was_asked() { + let source = raw_source(per_series_scan(1)); + let answered = + series_execution_plan(source.as_ref()).expect("the raw source hands chunks over"); + assert!( + answered + .as_any() + .downcast_ref::() + .is_some(), + "the guard answered with the raw source it was asked about" + ); + + let router: Arc = Arc::new( + SeriesRepartitionExec::try_new(raw_source(per_series_scan(2)), 2) + .expect("the raw source publishes a routeable frame"), + ); + let answered = series_execution_plan(router.as_ref()).expect("a raw router hands chunks over"); + assert_eq!( + 2, + answered + .as_any() + .downcast_ref::() + .expect("the guard answered with the router it was asked about") + .outputs(), + "the operator the caller got back is the one it asked" + ); +} + +/// A router hands over the contents it publishes as chunks: the raw identity and the evaluated +/// series an owner merged, and neither of the two as a batch. +#[test] +fn a_router_hands_over_the_contents_it_publishes_as_chunks() { + // A raw router merges each stored identity on the owner it routed it to, and what it publishes + // is that owner's chunk: a value this crate holds, and the same value its frame encodes. + let raw: Arc = Arc::new( + SeriesRepartitionExec::try_new(raw_source(per_series_scan(2)), 2) + .expect("the raw source publishes a routeable frame"), + ); + assert!( + series_execution_plan(raw.as_ref()).is_some(), + "a router over raw frames publishes merged raw chunks, which a native consumer reads" + ); + + // The same for evaluated content: an owner publishes each label set once, already merged. + let evaluated: Arc = Arc::new( + SeriesRepartitionExec::try_new(evaluated_frames(), 2) + .expect("the child declares an evaluated frame"), + ); + assert!( + series_execution_plan(evaluated.as_ref()).is_some(), + "an owner's evaluated publication is a chunk, not a batch" + ); +} + +/// Every content a router publishes is handed over, aggregate state included. +/// +/// This is the shape the trait states: a state publication is the row of a group its producer +/// exported, and the router carries it exactly as it carries a raw identity or an evaluated series - +/// on the same queue, the same lease and the same charge. Nothing is left on a frame path of its own, +/// which is why the router answers for all three rather than holding one of them back. +#[test] +fn every_content_a_router_publishes_is_handed_over() { + let contents: [(&str, Arc); 3] = [ + ("raw", raw_source(per_series_scan(2))), + ("evaluated", evaluated_frames()), + ("aggregate state", state_frames()), + ]; + for (name, child) in contents { + let router: Arc = Arc::new( + SeriesRepartitionExec::try_new(child, 2) + .expect("the fixture publishes a routeable frame"), + ); + let answered = series_execution_plan(router.as_ref()) + .unwrap_or_else(|| panic!("a router over {name} hands its publication over")); + assert!( + answered + .as_any() + .downcast_ref::() + .is_some(), + "the answer over {name} is the router itself" + ); + } +} + +#[test] +fn a_plan_that_carries_frames_is_not_answered_for() { + // The region's raw-series leaf: it writes the frames this node reads, and what it produces is a + // stream of batches, so a consumer has nothing in-process to read. + let scan = per_series_scan(1); + assert!( + series_execution_plan(scan.as_ref()).is_none(), + "a scan answers frames, not chunks" + ); + + // A wrapper forwards whatever its input answers, and forwarding a chunk is not its contract: + // it is a frame-shaped operator above a native one. + let wrapped: Arc = + Arc::new(CooperativeExec::new(raw_source(per_series_scan(1)))); + assert!( + series_execution_plan(wrapped.as_ref()).is_none(), + "a wrapper around a native operator is not itself one" + ); + + // A plan that publishes batches is read from its batches, whatever its schema declares. + let frames: Arc = + Arc::new(EmptyExec::new(raw_source(per_series_scan(1)).schema())); + assert!( + series_execution_plan(frames.as_ref()).is_none(), + "a batch source answers batches" + ); +} + +/// The four-position grid every frame of these tests is declared on. +fn grid() -> Arc { + Arc::new( + EvalGrid::try_new(GridSpec::try_new(0, 60_000, 4).expect("the grid is legal")) + .expect("the grid is legal"), + ) +} + +/// The one-field series schema those frames declare. +fn series_schema() -> Arc { + Arc::new(SeriesSchema { + fields: Arc::from([FieldSpec { + name: Arc::from("value"), + }]), + eval_grid: Some(grid()), + }) +} + +/// A plan declaring an evaluated frame of one field. +fn evaluated_frames() -> Arc { + let schema = series_schema(); + let frame = frame_schema_with( + &schema, + FrameLabelMode::Explicit, + None, + SeriesOrdering::Contiguous, + ) + .expect("explicit labels are a frame"); + Arc::new(EmptyExec::new(frame)) +} + +/// A plan declaring an aggregate-state frame of one accumulator. +fn state_frames() -> Arc { + let schema = series_schema(); + let state = AggregateStateSchema::try_new( + AggregateStateKind::Sum, + vec![StateComponent::Value, StateComponent::Compensation], + ) + .expect("a sum carries a value and its compensation"); + let frame = aggregate_state_frame_schema(&state, &schema, FrameLabelMode::Explicit) + .expect("a state schema declares a state frame"); + Arc::new(EmptyExec::new(frame)) +} diff --git a/src/promql/src/extension_plan/series_repartition.rs b/src/promql/src/extension_plan/series_repartition.rs index 7b23e22aa2c..8d95bc9371d 100644 --- a/src/promql/src/extension_plan/series_repartition.rs +++ b/src/promql/src/extension_plan/series_repartition.rs @@ -114,6 +114,7 @@ //! partition can still claim its queue; the execution going away as a whole, which no later `execute` //! can reach, is the other point at which everything is released. +use std::any::Any; use std::collections::{BTreeMap, VecDeque}; use std::fmt::{self, Formatter}; use std::hash::{Hash, Hasher}; @@ -124,7 +125,8 @@ use std::task::{Context, Poll}; use common_error::ext::BoxedError; use common_query::series_frame::{ PendingBatching, SendableEvaluatedSeriesStream, pack_evaluated_series, pack_raw_series_with, - raw_series_frame_schema_with_ordering, unpack_evaluated_series, unpack_raw_series, + raw_series_frame_schema_with_ordering, series_frame_ordering, unpack_evaluated_series, + unpack_raw_series, }; use datafusion::arrow::datatypes::SchemaRef; use datafusion::arrow::record_batch::RecordBatch; @@ -146,12 +148,18 @@ use datatypes::series::raw::RawSeriesChunk; use datatypes::series::samples::{Series, SeriesSchema}; use datatypes::series::{SeriesLabels, SeriesOrdering}; use futures::{Stream, StreamExt}; -use store_api::region_engine::{RawSeriesStream, SendableRawSeriesStream}; +use store_api::region_engine::{RawLabelSource, RawSeriesStream, SendableRawSeriesStream}; use tokio::sync::mpsc; use twox_hash::XxHash64; +use crate::evaluated::EvaluatedChunk; +use crate::extension_plan::series_execution::{ + HandedSeriesChunk, SendableSeriesStream, SeriesCharge, SeriesChunk, SeriesExecutionPlan, + checked_series_stream, series_execution_plan, +}; use crate::grid_series::{label_set, merge_same_labelset}; -use crate::native::execute::{merge_workspace_bytes, operand_chunk_bytes}; +use crate::native::execute::{field_segments, merge_workspace_bytes, operand_chunk_bytes}; +use crate::native::state::{StateChunk, state_bytes, state_row_of}; use crate::source::merge_raw_identity_charging; use datatypes::series::samples::DenseSamplesRef; @@ -191,6 +199,234 @@ pub enum IdentityCompletion { CompleteDisjoint, } +/// How the claim of an output reads this node's child. +/// +/// The child is read once, for whichever of the two ways its consumer asked for first - the frames +/// this node publishes, or the chunks it hands over - and the second claim is refused, so the two +/// cannot disagree about it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum InputRead { + /// The consumer reads frames: the child is executed and its frames are decoded here. + Frames, + /// The consumer reads chunks: the child is asked for its chunks when it can hand them over, and + /// decoded here only when it cannot. + Chunks, +} + +impl InputRead { + /// What this way of reading is, for a refusal that has to name both. + fn as_str(&self) -> &'static str { + match self { + Self::Frames => "frames", + Self::Chunks => "chunks", + } + } +} + +/// One child partition, as this node reads it: its chunks when it hands them over, its frames when +/// it does not. +/// +/// `hand_over` is the child as a native operator, decided once for the whole read: with it, the +/// partition is read in process and wrapped in the form this node's chain assembly expects; without +/// it, the partition is executed and its frames decoded here. +#[allow(clippy::too_many_arguments)] +fn routed_input( + input: &Arc, + hand_over: Option<&dyn SeriesExecutionPlan>, + content: FrameContent, + series_schema: &Arc, + state: Option<&Arc>, + declared_ordering: SeriesOrdering, + partition: usize, + context: &Arc, +) -> DataFusionResult { + if let Some(plan) = hand_over { + // A handed-over stream is checked against the order its own plan declares, exactly as a + // decoded frame is: this node narrows what it publishes, but the child's promise is what its + // chunks were produced under, and a chain that breaks it has to be refused here too. + let chunks = checked_series_stream( + plan.execute_series(partition, Arc::clone(context))?, + declared_ordering, + ); + return Ok(match content { + FrameContent::Evaluated => { + RoutedInput::Evaluated(Box::pin(HeldSeriesCharges::evaluated(chunks))) + } + FrameContent::Raw => { + RoutedInput::Raw(HeldSeriesCharges::raw(chunks, Arc::clone(series_schema))) + } + FrameContent::AggregateState => { + // A chunk carries its own declaration, so the state this node declared is what the + // read is held to; without it there is nothing to hold the chunk to. + let state = state.ok_or_else(|| { + DataFusionError::Plan("aggregate state declaration is missing".into()) + })?; + RoutedInput::StateChunks(chunks, Arc::clone(state), Arc::clone(series_schema)) + } + }); + } + let frames = input.execute(partition, Arc::clone(context))?; + // The expected schema is a check and never an input: the decoder reads the frame's own + // declaration, and a partition declaring another frame is refused here rather than routed + // under labels it does not carry. + Ok(match content { + FrameContent::Evaluated => RoutedInput::Evaluated(unpack_evaluated_series( + frames, + Some(Arc::clone(series_schema)), + )?), + FrameContent::Raw => { + // The node publishes labels, so a child that names them by its key is decoded here, + // where the frames are already unpacked. An already-labelled stream passes through + // untouched. + let stream = unpack_raw_series(frames, Some(Arc::clone(series_schema)))?; + let stream = crate::source::materialize_raw_labels(stream) + .map_err(|error| DataFusionError::External(Box::new(error)))?; + RoutedInput::Raw(stream) + } + FrameContent::AggregateState => { + let state = state.ok_or_else(|| { + DataFusionError::Plan("aggregate state declaration is missing".into()) + })?; + RoutedInput::State(frames, Arc::clone(state), Arc::clone(series_schema)) + } + }) +} + +/// A child's chunks, read as the series this node's chain assembly expects. +/// +/// The producer's charge for a chunk is held until the next poll instead of being dropped with the +/// conversion: by then this node has grown its own reservation for what it queued, so there is no +/// moment at which the bytes are charged to nobody. That is the same hand-off the frame consumers +/// make when they keep a batch's charge through the next poll. +struct HeldSeriesCharges { + /// The child's chunks. + chunks: SendableSeriesStream, + /// What this stream is read as, so another content is refused rather than reinterpreted. + content: FrameContent, + /// The charge of the chunk handed out last, released when the next one is read. + held: Option, +} + +impl HeldSeriesCharges { + /// `chunks` read as evaluated series. + fn evaluated(chunks: SendableSeriesStream) -> SendableEvaluatedSeriesStream { + Box::pin(HeldEvaluated { + inner: HeldSeriesCharges { + chunks, + content: FrameContent::Evaluated, + held: None, + }, + }) + } + + /// `chunks` read as raw series declared on `schema`. + /// + /// The chunks already carry complete labels - that is what a raw producer hands over - so the + /// stream declares no decode description and no bound source, which is what a decoding consumer + /// reads to decide it has nothing to decode. + fn raw(chunks: SendableSeriesStream, schema: Arc) -> SendableRawSeriesStream { + Box::pin(HeldRaw { + inner: HeldSeriesCharges { + chunks, + content: FrameContent::Raw, + held: None, + }, + schema, + label_source: RawLabelSource::Explicit, + }) + } + + /// The next chunk, with the charge of the previous one released first. + fn next_chunk( + &mut self, + cx: &mut Context<'_>, + ) -> Poll>> { + self.held = None; + match self.chunks.as_mut().poll_next(cx) { + Poll::Ready(Some(Ok(handed))) => { + let (chunk, charge) = handed.into_parts(); + self.held = charge; + Poll::Ready(Some(Ok(chunk))) + } + Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))), + Poll::Ready(None) => Poll::Ready(None), + Poll::Pending => Poll::Pending, + } + } + + /// The error a child hands over a content this stream is not read as. + fn refused(&self, chunk: &SeriesChunk) -> BoxedError { + boxed(DataFusionError::Execution(format!( + "a {} input handed over {chunk:?}", + self.content.as_str() + ))) + } +} + +/// [`HeldSeriesCharges`] read as evaluated series. +struct HeldEvaluated { + inner: HeldSeriesCharges, +} + +impl Stream for HeldEvaluated { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + match this.inner.next_chunk(cx) { + Poll::Ready(Some(Ok(SeriesChunk::Evaluated(chunk)))) => { + Poll::Ready(Some(Ok((chunk.series, chunk.is_last)))) + } + Poll::Ready(Some(Ok(other))) => { + let error = this.inner.refused(&other); + Poll::Ready(Some(Err(error))) + } + Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))), + Poll::Ready(None) => Poll::Ready(None), + Poll::Pending => Poll::Pending, + } + } +} + +/// [`HeldSeriesCharges`] read as raw series. +struct HeldRaw { + inner: HeldSeriesCharges, + schema: Arc, + label_source: RawLabelSource, +} + +impl RawSeriesStream for HeldRaw { + fn schema(&self) -> &Arc { + &self.schema + } + + fn label_source(&self) -> &RawLabelSource { + &self.label_source + } + + fn ordering(&self) -> SeriesOrdering { + SeriesOrdering::Contiguous + } +} + +impl Stream for HeldRaw { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + match this.inner.next_chunk(cx) { + Poll::Ready(Some(Ok(SeriesChunk::Raw(chunk)))) => Poll::Ready(Some(Ok(chunk))), + Poll::Ready(Some(Ok(other))) => { + let error = this.inner.refused(&other); + Poll::Ready(Some(Err(error))) + } + Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))), + Poll::Ready(None) => Poll::Ready(None), + Poll::Pending => Poll::Pending, + } + } +} + /// The Repartition stage: one child's partitions, redistributed by canonical label set. /// /// The node holds one execution's shared state: its output partitions are separate `execute` calls @@ -426,6 +662,117 @@ impl SeriesRepartitionExec { pub fn outputs(&self) -> usize { self.properties.partitioning.partition_count() } + + /// The queue of `partition` and the lease on this read that reading it takes. + /// + /// Both public entry points take an output through here - the frames it publishes and the chunks + /// it hands over are the same publication, read two ways - so an output is claimed once no + /// matter which of them is asked for, and asking for both is the error it has always been. + fn claim_output( + &self, + partition: usize, + context: &Arc, + read: InputRead, + ) -> DataFusionResult<(mpsc::UnboundedReceiver, OutputLease)> { + if partition >= self.outputs() { + return Err(DataFusionError::Execution(format!( + "SeriesRepartition output partition {partition} is out of range" + ))); + } + let shared = { + let mut state = self + .shared + .lock() + .unwrap_or_else(|error| error.into_inner()); + if state.is_none() { + // The whole execution is started here, once: the output partitions are separate + // calls, and reading the child once for all of them is what keeps a chunk from being + // emitted twice or read by a scan that was never meant to run twice. + *state = Some(SharedExecution::start( + &self.input, + self.routing.clone(), + Arc::clone(&self.series_schema), + self.state.clone(), + context, + read, + )?); + } + let shared = Arc::clone(state.as_ref().expect("the execution was just started")); + // One read, one way of reading the child: an output that asks for the other form would + // be answered from a stream it did not ask for, so it is refused here rather than + // handed the wrong one. + if shared.read != read { + return Err(DataFusionError::Execution(format!( + "SeriesRepartition was already read as {} for an earlier output, so output \ + partition {partition} cannot read it as {}", + shared.read.as_str(), + read.as_str() + ))); + } + shared + }; + SharedExecution::claim(&shared, partition).ok_or_else(|| { + DataFusionError::Execution(format!( + "SeriesRepartition output partition {partition} was executed twice" + )) + }) + } + + /// One claimed output as the owner that merges it: the queue, its charge, and its lease. + fn partition_stream( + &self, + receiver: mpsc::UnboundedReceiver, + lease: OutputLease, + context: &Arc, + ) -> RepartitionStream { + RepartitionStream::new( + receiver, + lease, + Arc::clone(&self.series_schema), + &context.runtime_env().memory_pool, + self.input.properties().partitioning.partition_count(), + self.ordering, + self.identity_completion, + ) + } + + /// One claimed output's exported state, as the rows the queue carries. + /// + /// The decoder is built from the schema this node publishes, which is the schema a frame + /// consumer would parse, and it is run once on an empty batch before the read starts: a + /// declaration this revision cannot read is refused here rather than on the first row, which is + /// exactly what `unpack_aggregate_state` does for the frame path. + fn state_chunk_stream( + &self, + receiver: mpsc::UnboundedReceiver, + lease: OutputLease, + ) -> DataFusionResult { + let frame_schema = self.input.schema(); + let declaration = SeriesFrameDeclaration::parse(frame_schema.as_ref()) + .map_err(|error| DataFusionError::Execution(error.to_string()))?; + let state = declaration.aggregate_state().ok_or_else(|| { + DataFusionError::Execution( + "SeriesRepartition aggregate-state output declares no aggregate state".to_string(), + ) + })?; + let decoder = SeriesFrameDecoder::try_new_aggregate_state( + state, + &self.series_schema, + FrameLabelMode::Explicit, + ) + .map_err(|error| DataFusionError::Execution(error.to_string()))?; + decoder + .decode_aggregate_state(&RecordBatch::new_empty(Arc::clone(&frame_schema))) + .map_err(|error| DataFusionError::Execution(error.to_string()))?; + Ok(StateChunkOutputStream { + decoder, + frame_schema, + receiver, + lease, + pending: VecDeque::new(), + reported: false, + }) + } } impl fmt::Debug for SeriesRepartitionExec { @@ -511,36 +858,7 @@ impl ExecutionPlan for SeriesRepartitionExec { partition: usize, context: Arc, ) -> DataFusionResult { - if partition >= self.outputs() { - return Err(DataFusionError::Execution(format!( - "SeriesRepartition output partition {partition} is out of range" - ))); - } - let shared = { - let mut state = self - .shared - .lock() - .unwrap_or_else(|error| error.into_inner()); - if state.is_none() { - // The whole execution is started here, once: the output partitions are separate - // calls, and reading the child once for all of them is what keeps a chunk from being - // emitted twice or read by a scan that was never meant to run twice. - *state = Some(SharedExecution::start( - &self.input, - self.routing.clone(), - Arc::clone(&self.series_schema), - self.state.clone(), - &context, - )?); - } - Arc::clone(state.as_ref().expect("the execution was just started")) - }; - let (receiver, lease) = SharedExecution::claim(&shared, partition).ok_or_else(|| { - DataFusionError::Execution(format!( - "SeriesRepartition output partition {partition} was executed twice" - )) - })?; - // Take the queue and its claim on the read together. + let (receiver, lease) = self.claim_output(partition, &context, InputRead::Frames)?; if self.content == FrameContent::AggregateState { return Ok(Box::pin(StateBatchOutputStream { schema: self.input.schema(), @@ -550,15 +868,7 @@ impl ExecutionPlan for SeriesRepartitionExec { reported: false, })); } - let inner = RepartitionStream::new( - receiver, - lease, - Arc::clone(&self.series_schema), - &context.runtime_env().memory_pool, - self.input.properties().partitioning.partition_count(), - self.ordering, - self.identity_completion, - ); + let inner = self.partition_stream(receiver, lease, &context); let handoff = Arc::clone(&inner.handoff); let output: SendableRecordBatchStream = match self.content { FrameContent::Evaluated => pack_evaluated_series( @@ -594,6 +904,260 @@ impl ExecutionPlan for SeriesRepartitionExec { } } +impl SeriesExecutionPlan for SeriesRepartitionExec { + fn as_any(&self) -> &dyn Any { + self + } + + /// One owner's publications, as the chunks they are. + /// + /// This is [`ExecutionPlan::execute`] without the encode: the same claim of the same output of + /// the same read, the same owner merging the same identity, and the values that owner produced + /// handed over instead of packed into a frame. An evaluated publication leaves as one closed + /// chunk - the owner publishes an identity once, already merged, which is exactly the `is_last` + /// the packer's evaluated stream declares - and a raw one as the chunk whose finality + /// [`merge_raw_identity_charging`] recomputed for the whole identity. + /// + /// Everything the owner reserved for that publication rides along with the value + /// ([`SeriesCharge`]), because the consumer holds the bytes those reservations account for: the + /// frame path holds them in the packer's handoff until the batch is flushed, and there is no + /// packer here to hold them. + /// + /// A state publication is the one content this node does not merge: it forwards the exported row + /// of a group its child folded, on the same queue and the same lease as the frames it would have + /// published ([`StateChunkOutputStream`]), so the two entry points stay one read of one output. + fn execute_series( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + let (receiver, lease) = self.claim_output(partition, &context, InputRead::Chunks)?; + match self.content { + FrameContent::Raw | FrameContent::Evaluated => { + let inner = self.partition_stream(receiver, lease, &context); + Ok(Box::pin(ChunkOutputStream { + inner: Some(Box::pin(inner)), + content: self.content, + })) + } + FrameContent::AggregateState => Ok(Box::pin(self.state_chunk_stream(receiver, lease)?)), + } + } +} + +/// One owner's exported state, as the rows it is. +/// +/// The queue, the lease and the charge are [`StateBatchOutputStream`]'s: this node does not merge +/// state, it forwards the row a group was exported as. The only thing that changes is the form - +/// the batch the queue carries is decoded into the rows it holds, by the same +/// [`SeriesFrameDeclaration`] decoder a frame consumer would have used, and each row is handed over +/// with the charge of the batch it points into. So a consumer reads the same rows either way, and +/// the batch is never re-encoded. +struct StateChunkOutputStream { + /// The decoder the exported batches are read with, which is the frame path's decoder. + decoder: SeriesFrameDecoder, + /// The schema every exported batch carries, checked before it is decoded. + frame_schema: SchemaRef, + /// The owner's queue, shared with the frames this output would otherwise publish. + receiver: mpsc::UnboundedReceiver, + /// The claim on this read, released when this output ends. + lease: OutputLease, + /// Rows decoded from the batch last taken off the queue, in the order the frame carries them. + pending: VecDeque, + reported: bool, +} + +/// How many empty exported batches one poll reads before yielding, mirroring the frame consumer's +/// own guard so a producer of empty batches cannot hold the task. +const MAX_EMPTY_STATE_BATCHES_PER_POLL: usize = 32; + +impl StateChunkOutputStream { + /// Ends this output with a failure, draining the queue and releasing the rows it still held. + /// + /// The frame output ends exactly this way: the read fails once, every queued item is dropped + /// with its charge, and the output reports the first failure rather than a second one. + fn failed( + &mut self, + reason: impl Into, + ) -> Poll>> { + let reason = reason.into(); + self.lease + .fail(Arc::new(DataFusionError::Execution(reason.clone()))); + self.reported = true; + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + self.pending.clear(); + Poll::Ready(Some(Err(boxed(DataFusionError::Execution(reason))))) + } +} + +impl Stream for StateChunkOutputStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + if this.reported { + return Poll::Ready(None); + } + let mut empty_batches = 0; + loop { + if let Some(chunk) = this.pending.pop_front() { + return Poll::Ready(Some(Ok(chunk))); + } + if let Ending::Failed(error) = this.lease.shared.ending() { + this.reported = true; + this.receiver.close(); + while this.receiver.try_recv().is_ok() {} + return Poll::Ready(Some(Err(boxed(DataFusionError::from(&error))))); + } + match this.receiver.poll_recv(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(Some(Queued::StateBatch { + batch, + row, + _charge, + _metadata, + })) => { + // The queue publishes either the whole batch or the one row a multi-output + // routing selected, exactly as the frame output reads it. + let batch = match row { + Some(row) => batch.slice(row, 1), + None => batch.as_ref().clone(), + }; + if batch.schema().as_ref() != this.frame_schema.as_ref() { + return this.failed("aggregate state frame schema mismatch"); + } + let rows = match this.decoder.decode_aggregate_state(&batch) { + Ok(rows) => rows, + Err(error) => return this.failed(error.to_string()), + }; + if rows.is_empty() { + empty_batches += 1; + if empty_batches == MAX_EMPTY_STATE_BATCHES_PER_POLL { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + continue; + } + // One batch, one reservation, shared by every row cut from it: the bytes are + // live while any of those rows is, and released when the last one is dropped. + let metadata = Arc::new(_metadata); + for row in rows { + let row = match state_row_of(row) { + Ok(row) => row, + Err(error) => return this.failed(error.to_string()), + }; + this.pending.push_back(HandedSeriesChunk::charged( + SeriesChunk::State(StateChunk::Row(row)), + SeriesCharge::shared(vec![Arc::clone(&_charge), Arc::clone(&metadata)]), + )); + } + } + Poll::Ready(Some(Queued::StateChunk(queued))) => { + let QueuedStateChunk { + chunk, + _charge, + _metadata, + child, + } = *queued; + // A child that answered with its chunks has already done what this output's + // frame form would do, so the group is handed on as it is; only the charge this + // node queued it with moves onto the value, together with what the child charged + // for the publication the group was cut from. The group is a slice of that + // publication, so those bytes are still live while it is held. + let mut shared = child.map_or_else(Vec::new, |child| (*child).clone()); + shared.push(Arc::new(_charge)); + shared.push(Arc::new(_metadata)); + this.pending.push_back(HandedSeriesChunk::charged( + SeriesChunk::State(chunk), + SeriesCharge::shared(shared), + )); + } + Poll::Ready(Some(Queued::Eof { .. })) => { + // The shared ending and the queue's closure establish completion; this message + // is only a queue-order barrier. + } + Poll::Ready(Some(Queued::Chain { .. })) => { + return this.failed("series router received a non-state message"); + } + Poll::Ready(None) => { + this.reported = true; + this.pending.clear(); + return match this.lease.ending() { + Some(Err(error)) => Poll::Ready(Some(Err(boxed( + DataFusionError::External(Box::new(error)), + )))), + Some(Ok(_)) => unreachable!(), + None => Poll::Ready(None), + }; + } + } + } + } +} + +/// One owner's publications as handed-over chunks. +/// +/// The inner stream is [`RepartitionStream`], which decides what an owner publishes; this only +/// changes the form - a [`ReadyOutput`] becomes the [`SeriesChunk`] a native consumer reads - and +/// moves the charge of that publication out of the packer's handoff and onto the value. +struct ChunkOutputStream { + /// The owner's stream, or `None` once this one ended. + inner: Option>>, + /// What this node publishes, so a raw publication cannot be handed over as an evaluated one. + content: FrameContent, +} + +impl Stream for ChunkOutputStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + let Some(inner) = this.inner.as_mut() else { + return Poll::Ready(None); + }; + let ready = match inner.as_mut().poll_next(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(Some(Err(error))) => { + this.inner = None; + return Poll::Ready(Some(Err(error))); + } + Poll::Ready(None) => { + this.inner = None; + return Poll::Ready(None); + } + Poll::Ready(Some(Ok(ready))) => ready, + }; + // The owner charged this publication just before publishing it, and the charge is the whole + // of what the consumer's copy of the values keeps alive. + let charge = inner.take_charge(); + let chunk = match (this.content, ready) { + (FrameContent::Evaluated, ReadyOutput::Evaluated(series)) => { + SeriesChunk::Evaluated(EvaluatedChunk { + series, + // A merged identity is final: the owner publishes it once, already closed. + is_last: true, + }) + } + (FrameContent::Raw, ReadyOutput::Raw(chunk)) => SeriesChunk::Raw(chunk), + (content, ready) => { + this.inner = None; + return Poll::Ready(Some(Err(boxed(DataFusionError::Internal(format!( + "a {} repartition output carried {}", + content.as_str(), + ready.what() + )))))); + } + }; + match charge { + Some(charge) => Poll::Ready(Some(Ok(HandedSeriesChunk::charged(chunk, charge)))), + // The charge stays where the frame path keeps it, so it is released with the handoff + // rather than silently dropped here. + None => Poll::Ready(Some(Ok(HandedSeriesChunk::uncharged(chunk)))), + } + } +} + /// One execution's state: the child read once, and the outputs it is being distributed into. /// /// The plan that started it holds this, and so does every output stream it hands out. The read it @@ -604,6 +1168,8 @@ struct SharedExecution { running: Mutex, /// How the read ended, and the failure it owes its outputs if it failed. ending: Arc>, + /// The way this read's child is being read, fixed by the first output that claimed it. + read: InputRead, } /// What one execution's state holds that has to be stopped together. @@ -649,46 +1215,42 @@ impl SharedExecution { /// One task per child partition, started here: the child's computation happens inside its own /// `poll_next`, so a partition read on a task of another partition would run there, and the /// partition count the child declared would buy no parallelism at all. + #[allow(clippy::too_many_arguments)] fn start( input: &Arc, routing: Routing, series_schema: Arc, state: Option>, context: &Arc, + read: InputRead, ) -> DataFusionResult> { // What the child carries is what it declares, not what the policy suggests: a raw frame // can be routed by a match key too, so the policy no longer names the content. let content = SeriesFrameDeclaration::parse(input.schema().as_ref()) .map_err(|error| DataFusionError::Plan(error.to_string()))? .content(); + // What the child promises about the order of what it publishes, which is what a chunk read + // of it has to be held to. + let declared_ordering = series_frame_ordering(input.schema().as_ref())?; let partitions = input.properties().partitioning.partition_count(); + // The child is asked for its chunks only when a reader of them claimed this read: the other + // claim publishes frames, and a chunk read would have to be packed again. + let hand_over = match read { + InputRead::Chunks => series_execution_plan(input.as_ref()), + InputRead::Frames => None, + }; let mut streams = Vec::with_capacity(partitions); for child_partition in 0..partitions { - let frames = input.execute(child_partition, Arc::clone(context))?; - // The expected schema is a check and never an input: the decoder reads the frame's own - // declaration, and a partition declaring another frame is refused here rather than - // routed under labels it does not carry. - streams.push(match content { - FrameContent::Evaluated => RoutedInput::Evaluated(unpack_evaluated_series( - frames, - Some(Arc::clone(&series_schema)), - )?), - FrameContent::Raw => { - // The node publishes labels, so a child that names them by its key is decoded - // here, where the frames are already unpacked. An already-labelled stream - // passes through untouched. - let stream = unpack_raw_series(frames, Some(Arc::clone(&series_schema)))?; - let stream = crate::source::materialize_raw_labels(stream) - .map_err(|error| DataFusionError::External(Box::new(error)))?; - RoutedInput::Raw(stream) - } - FrameContent::AggregateState => { - let state = state.as_ref().ok_or_else(|| { - DataFusionError::Plan("aggregate state declaration is missing".into()) - })?; - RoutedInput::State(frames, Arc::clone(state), Arc::clone(&series_schema)) - } - }); + streams.push(routed_input( + input, + hand_over, + content, + &series_schema, + state.as_ref(), + declared_ordering, + child_partition, + context, + )?); } let mut senders = Vec::with_capacity(routing.outputs); let mut receivers = Vec::with_capacity(routing.outputs); @@ -699,6 +1261,7 @@ impl SharedExecution { } let ending = Arc::new(Mutex::new(Ending::default())); let shared = Arc::new_cyclic(|weak| SharedExecution { + read, running: Mutex::new(Running { receivers, inputs: Inputs::new(Arc::clone(&ending), partitions, weak.clone()), @@ -1273,6 +1836,153 @@ async fn read_state_batches( Stop::Ended } +/// Whether `chunk` is a publication of the state this node declared it routes. +/// +/// A state frame says what it is in its schema: the aggregate kind, the ordered component layout and +/// the series - fields and evaluation grid - it is of are all part of the frame `read_state_batches` +/// decodes, so a batch under any other schema is refused there before a row of it is routed. A chunk +/// says the same three things on the value: the layout in the [`StateChunk::Series`] it carries (or +/// in the row's fields), and the grid each group's axis is on. This is what holds a handed-over +/// publication to the standard the frame path holds a batch to; anything less would let a child hand +/// over state this node never declared and have it merged as that state. +fn declared_state_of( + declared: &AggregateStateSchema, + series: &SeriesSchema, + chunk: &StateChunk, +) -> bool { + let declared_grid = series.eval_grid.as_ref().map(|grid| grid.spec()); + let same_grid = |grid: Option<&Arc>| { + declared_grid.is_some_and(|declared| grid.is_some_and(|grid| grid.spec() == declared)) + }; + match chunk { + StateChunk::Series { + series: groups, + state_schema, + .. + } => { + state_schema.kind == declared.kind + && state_schema.components == declared.components + && declared_grid.is_some_and(|declared| state_schema.grid.spec() == declared) + && groups.iter().all(|group| { + group.states.len() == series.fields.len() && same_grid(group.time.grid()) + }) + } + StateChunk::Row(row) => { + row.kind == declared.kind + && row.fields.components() == declared.components.as_ref() + && row.fields.len() == series.fields.len() + && same_grid(row.time.grid()) + } + } +} + +/// Reads a child's handed-over state, routing each group to the owner that folds it. +/// +/// A state publication is not merged here: every group the child folded is one row of its export, and +/// which owner folds it is the hash of its labels, exactly as a state frame's row is routed. What +/// differs is only the form - the group arrives as the child's own chunk instead of as a batch - so +/// the charge this node queues it with is grown while the child's charge is still in hand, and the +/// child's own charge moves onto the groups rather than going with the publication it is for. +async fn read_state_chunks( + stream: &mut SendableSeriesStream, + // The queue item names the group, not the partition it came from: a state publication is routed + // by its labels, and nothing waits for one partition's group to complete another's. + _partition: usize, + routing: &Routing, + senders: &[mpsc::UnboundedSender], + read_ahead: &MemoryReservation, + declared: &Arc, + series: &Arc, +) -> Stop { + loop { + tokio::task::coop::consume_budget().await; + let next = stream.next().await; + match next { + Some(Ok(handed)) => { + let (chunk, child_charge) = handed.into_parts(); + let SeriesChunk::State(chunk) = chunk else { + return Stop::Failed(Arc::new(DataFusionError::Execution(format!( + "an aggregate-state input handed over {chunk:?}" + )))); + }; + // The check the frame path makes of a batch's schema, made of the declaration the + // chunk carries: a publication of another kind, layout or grid is refused here + // rather than routed under a state this node never declared. + if !declared_state_of(declared, series, &chunk) { + return Stop::Failed(Arc::new(DataFusionError::Execution( + "aggregate state chunk schema mismatch".into(), + ))); + } + // One publication may hold several groups; each is routed on its own labels, and + // the charge the child put on the whole of it rides on all of them - a group is a + // slice of that publication, so its bytes stay live until the last group is dropped. + let mut publication = child_charge.map_or_else(Vec::new, SeriesCharge::into_shared); + let groups = match chunk { + StateChunk::Series { + series, + state_schema, + reservation, + } => { + publication.extend(reservation.map(Arc::new)); + series + .into_iter() + .map(|series| StateChunk::Series { + series: vec![series], + state_schema: Arc::clone(&state_schema), + reservation: None, + }) + .collect::>() + } + StateChunk::Row(row) => vec![StateChunk::Row(row)], + }; + // One reference to the publication's charge, shared by every group cut from it. + let publication = (!publication.is_empty()).then(|| Arc::new(publication)); + for group in groups { + let metric = match &group { + StateChunk::Series { series, .. } => &series[0].metric, + StateChunk::Row(row) => &row.metric, + }; + let output = routing.output_labels(metric); + if senders[output].is_closed() { + continue; + } + // Charged as it is queued, so what this node holds is accounted for before the + // child's own charge goes. + let charge = read_ahead.new_empty(); + if let Err(error) = charge.try_grow(state_bytes(&group)) { + return Stop::Failed(Arc::new(error)); + } + // The message and the boxed group it points at, which is this content's own + // share of what a queue holds for one item. + let metadata = read_ahead.new_empty(); + if let Err(error) = metadata.try_grow( + std::mem::size_of::() + .saturating_add(std::mem::size_of::()), + ) { + return Stop::Failed(Arc::new(error)); + } + if let Err(error) = + senders[output].send(Queued::StateChunk(Box::new(QueuedStateChunk { + chunk: group, + _charge: charge, + _metadata: metadata, + // One reference per queued group, so none of them is this task's to + // hold: the publication's charge goes when its last group does. + child: publication.clone(), + }))) + { + drop(error.0); + } + } + } + Some(Err(error)) => { + return Stop::Failed(Arc::new(DataFusionError::External(Box::new(error)))); + } + None => return Stop::Ended, + } + } +} + /// One input partition's task: reads its own child, assembles chains, and sends each complete chain to /// its canonical owner. Output queues are unbounded, so sending does not wait for an owner to poll; /// queued chains remain charged to the pool until consumed or dropped. Each task records its outcome @@ -1294,6 +2004,18 @@ async fn route_partition( RoutedInput::Raw(stream) => { read_raw_chains(stream, partition, &routing, &senders, &read_ahead).await } + RoutedInput::StateChunks(stream, state, series) => { + read_state_chunks( + stream, + partition, + &routing, + &senders, + &read_ahead, + state, + series, + ) + .await + } RoutedInput::State(stream, state, series) => { read_state_batches( stream, @@ -1739,6 +2461,13 @@ enum Ending { enum RoutedInput { Evaluated(SendableEvaluatedSeriesStream), Raw(SendableRawSeriesStream), + /// Exported state a child handed over, one publication at a time, with the state and the series + /// this node declared those publications to be. + StateChunks( + SendableSeriesStream, + Arc, + Arc, + ), State( SendableRecordBatchStream, Arc, @@ -1769,6 +2498,29 @@ enum Queued { _charge: Arc, _metadata: MemoryReservation, }, + /// One group of exported state, as the child that folded it handed it over. + /// + /// Boxed because the queue message is charged for by its own size, and every chain and every row + /// of every other content pays that charge too: a state publication carries more than a chain + /// does, and it is the only content that does. + StateChunk(Box), +} + +/// What one queued state group holds: the group, and the charges it keeps alive. +struct QueuedStateChunk { + chunk: StateChunk, + /// What this node queued it with: the payload the group holds. + _charge: MemoryReservation, + _metadata: MemoryReservation, + /// What the child charged for the publication this group was cut from. + /// + /// A group is a slice of the publication it came from - a row's state columns still point into + /// the batch they were decoded out of - so the bytes the child reserved for that publication are + /// live for as long as any group cut from it is. They ride on the group for that reason: released + /// here they would be released while the group is still held, and the pool would hand the + /// parent's buffers to somebody else. The reference is taken once per publication and cloned per + /// group, so the publication's charge goes when its last group does. + child: Option>>>, } type ExactIdentity = (Option>, Vec<(Arc, Arc)>); @@ -1908,10 +2660,14 @@ fn raw_chunk_slice_bytes(chunk: &RawSeriesChunk) -> DataFusionResult { .saturating_add(tag.value.len()) })) }); - // A histogram field is an index array naming rows of a shared table; both are held per sample. + // A field is one or more dense segments - a merged chunk carries one per source piece - so this + // walks them and measures each. Asking the field for a single dense view instead answered `None` + // for a multi-segment field, which charged nothing for bytes the router then queued. A segment is + // measured here by the buffers a slice of it keeps alive, where the evaluated figure + // ([`sample_slice_bytes`]) bills its rows. let mut fields_bytes = 0usize; - for samples in chunk.fields.iter() { - let field_bytes = match samples.dense() { + for segment in field_segments(&chunk.fields) { + let field_bytes = match segment.dense() { Some(DenseSamplesRef::Float(values)) => values.to_data().get_slice_memory_size()?, Some(DenseSamplesRef::Histogram(histograms)) => histograms .indices() @@ -1930,6 +2686,8 @@ fn raw_chunk_slice_bytes(chunk: &RawSeriesChunk) -> DataFusionResult { .get_slice_memory_size()?, ) .saturating_add(histogram_table_slice_bytes(mixed.histograms().batch())?), + // `segments` hands out dense segments only, so this is unreachable; a zero here is + // what the whole-field view used to answer for a merged field. None => 0, }; fields_bytes = fields_bytes.saturating_add(field_bytes); @@ -1998,15 +2756,19 @@ enum ReadyOutput { Raw(RawSeriesChunk), } -struct ReadySeries { - series: ReadyOutput, - charges: ReadyCharges, +impl ReadyOutput { + /// What this publication is, for an error that has to name what arrived instead. + fn what(&self) -> &'static str { + match self { + Self::Evaluated(_) => "an evaluated series", + Self::Raw(_) => "a raw series", + } + } } -struct ReadyCharges { - _charges: Vec, - _metadata: MemoryReservation, - _workspace: Option, +struct ReadySeries { + series: ReadyOutput, + charge: SeriesCharge, } /// One owner processes identities as soon as every input has closed or contributed its final chain. @@ -2063,6 +2825,19 @@ impl Stream for StateBatchOutputStream { let _ = input; drop(_metadata); } + Poll::Ready(Some(Queued::StateChunk(_))) => { + let error = DataFusionError::Internal( + "a state frame output received a handed-over group".into(), + ); + self.lease.fail(Arc::new(DataFusionError::Internal( + "a state frame output received a handed-over group".into(), + ))); + self.reported = true; + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + self.retained = None; + return Poll::Ready(Some(Err(error))); + } Poll::Ready(Some(Queued::Chain { .. })) => { let error = DataFusionError::Internal( "series router received a non-state message".into(), @@ -2123,8 +2898,8 @@ struct RepartitionStream { /// releases completed cursors after the packer has flushed the frames they back. #[derive(Default)] struct Handoff { - current: Option, - completed: Vec, + current: Option, + completed: Vec, } struct PackedHandoffStream { @@ -2196,6 +2971,21 @@ impl RepartitionStream { } } + /// Takes what the owner charged for the publication it just returned. + /// + /// [`poll_next`](Stream::poll_next) installs the charge of the publication it returns in the + /// handoff, where [`PackedHandoffStream`] releases it once the batch it backs has been flushed. + /// A consumer that is handed the value itself takes it here instead, so the reservation rides + /// with the chunk and is released when the consumer drops it - neither before the bytes it + /// accounts for are gone, nor after. + fn take_charge(&mut self) -> Option { + self.handoff + .lock() + .unwrap_or_else(|error| error.into_inner()) + .current + .take() + } + fn finish_group(&mut self, key: &OwnerKey) -> DataFusionResult<()> { let Some(group) = self.groups.remove(key) else { return Ok(()); @@ -2231,11 +3021,7 @@ impl RepartitionStream { }; self.output.push_back(ReadySeries { series: ReadyOutput::Evaluated(series), - charges: ReadyCharges { - _charges: group.charges, - _metadata: group.metadata, - _workspace: workspace, - }, + charge: SeriesCharge::new(group.charges, group.metadata, workspace), }); Ok(()) } @@ -2270,11 +3056,7 @@ impl RepartitionStream { chunk.is_last = true; self.output.push_back(ReadySeries { series: ReadyOutput::Raw(chunk), - charges: ReadyCharges { - _charges: group.charges, - _metadata: group.metadata, - _workspace: None, - }, + charge: SeriesCharge::new(group.charges, group.metadata, None), }); return Ok(()); } @@ -2301,11 +3083,7 @@ impl RepartitionStream { )?; self.output.push_back(ReadySeries { series: ReadyOutput::Raw(chunk), - charges: ReadyCharges { - _charges: group.charges, - _metadata: group.metadata, - _workspace: Some(workspace), - }, + charge: SeriesCharge::new(group.charges, group.metadata, Some(workspace)), }); Ok(()) } @@ -2427,7 +3205,7 @@ impl Stream for RepartitionStream { this.handoff .lock() .unwrap_or_else(|e| e.into_inner()) - .current = Some(ready.charges); + .current = Some(ready.charge); return Poll::Ready(Some(Ok(ready.series))); } if this.reported { @@ -2438,9 +3216,10 @@ impl Stream for RepartitionStream { return Poll::Pending; } match this.receiver.poll_recv(cx) { - Poll::Ready(Some(Queued::StateBatch { .. })) => { + Poll::Ready(Some(Queued::StateBatch { .. })) + | Poll::Ready(Some(Queued::StateChunk(_))) => { this.lease.fail(Arc::new(DataFusionError::Internal( - "non-state output received an aggregate-state batch".into(), + "a series output received aggregate state".into(), ))); } Poll::Ready(Some(Queued::Chain { @@ -2597,7 +3376,7 @@ impl Stream for RepartitionStream { this.handoff .lock() .unwrap_or_else(|e| e.into_inner()) - .current = Some(ready.charges); + .current = Some(ready.charge); return Poll::Ready(Some(Ok(ready.series))); } return Poll::Ready(None); diff --git a/src/promql/src/extension_plan/series_repartition/tests.rs b/src/promql/src/extension_plan/series_repartition/tests.rs index 7e4e150931e..2bfb6084728 100644 --- a/src/promql/src/extension_plan/series_repartition/tests.rs +++ b/src/promql/src/extension_plan/series_repartition/tests.rs @@ -71,6 +71,7 @@ use futures::TryStreamExt; use store_api::region_engine::RawLabelSource; use super::*; +use crate::extension_plan::series_execution::series_execution_plan; use crate::extension_plan::test_util::prepare_test_data; use crate::grid_series::render_label_set; use crate::native::execute::merge_workspace_bytes; @@ -358,6 +359,92 @@ async fn public_frame_retains_large_series_charge_until_remainder_is_dropped() { ); } +/// The charge of a handed-over chunk is released with the chunk. +/// +/// The frame path keeps an owner's reservation in the packer's handoff until the batch it backs is +/// flushed; a chunk handed over in process has no packer, so the reservation travels with the value +/// instead. Both halves of that are asserted here: while a consumer holds the chunk the pool still +/// holds its bytes, so it cannot hand them out twice, and the moment the consumer drops the chunk +/// they are back. A release that ran early would let the pool over-commit; one that never ran would +/// leak the read - `drop` is the whole of what has to happen, so neither can hide behind a call. +#[tokio::test] +async fn a_handed_chunk_holds_its_charge_until_it_is_dropped() { + const FRAGMENTS: usize = 257; + let metric = labels("handed"); + let eval_grid = Arc::new( + EvalGrid::try_new(GridSpec::try_new(GRID_START, GRID_STEP, FRAGMENTS as u64).unwrap()) + .unwrap(), + ); + let series_schema = Arc::new(SeriesSchema { + fields: Arc::from([FieldSpec { + name: Arc::from("value"), + }]), + eval_grid: Some(eval_grid), + }); + let steps: Vec = (0..FRAGMENTS) + .map(|position| { + let time = TimeAxis::from_grid_spans( + series_schema.eval_grid.clone().unwrap(), + vec![GridSpan::new(position, 1)], + ) + .unwrap(); + let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![ + position as f64, + ]))); + let series = Series::try_new(&series_schema, metric.clone(), time, fields).unwrap(); + Step::Chunk(series, position + 1 == FRAGMENTS) + }) + .collect(); + let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); + let context = task_context(&pool); + let plan = node( + Scripted::plan_with_schema(vec![steps], Arc::clone(&series_schema)), + 1, + ); + let mut chunks = series_execution_plan(plan.as_ref()) + .expect("a router over evaluated frames hands its chunks over") + .execute_series(0, Arc::clone(&context)) + .expect("the output is claimed once"); + wait_until("the producer queues the completed series", || { + producer_stopped(&execution(&plan)) + }) + .await; + + // The owner publishes the one identity this read has once, merged, closed. + let handed = futures::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)) + .await + .expect("the owner publishes its merged series") + .expect("the publication arrives"); + let payload = FRAGMENTS * std::mem::size_of::(); + assert!( + pool.reserved() >= payload + merge_workspace_bytes(FRAGMENTS, 1, 1), + "a held chunk keeps its payload and its merge workspace: {} against at least {}", + pool.reserved(), + payload + merge_workspace_bytes(FRAGMENTS, 1, 1) + ); + + // Dropping the value is what releases it: the reservation rides with the chunk. + let held = pool.reserved(); + drop(handed); + let after = pool.reserved(); + assert!( + after + payload <= held, + "drop gives back at least the payload: {held} held, {after} still reserved, {payload} of values" + ); + assert!( + after < held, + "the reservation was released, not merely replaced" + ); + assert!( + futures::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)) + .await + .is_none(), + "the output ends after its one publication" + ); + drop(chunks); + assert_eq!(0, pool.reserved(), "the finished read holds nothing"); +} + /// One evaluated chunk: `len` rows from grid position `start`, and whether it closes its series. /// /// A chunk of no rows is the closing chunk a series sends when nothing is left of it, which is a @@ -1211,6 +1298,7 @@ async fn aggregate_state_slice_wrappers_remain_charged_until_terminal_cleanup() Arc::clone(&series), Some(Arc::clone(&wire)), &context, + InputRead::Frames, ) .unwrap(); let owner = Routing::new(2).output(&labels("many-slice-wrappers")); @@ -1624,6 +1712,359 @@ async fn aggregate_state_router_cancelled_consumer_releases_queued_charge() { assert_eq!(0, pool.reserved(), "cancelled consumer holds nothing"); } +/// A router that reads its child's chunks keeps the child's charge on the groups it hands over. +/// +/// A `StateChunk::Row` is a zero-copy slice of the batch it was decoded out of, and `state_bytes` +/// bills only the slice: the parent's buffers are charged to the child's publication, and they are +/// live for exactly as long as a group cut from it is. A router that released that charge once it had +/// charged its own figures would leave those buffers charged to nobody while a consumer still holds +/// them - which is what the frame path avoids by sharing one charge across every row of a batch. +/// +/// The figure is read at the moment only the group is left: the stream that produced it, the router +/// and the region under it are gone, so what the pool still counts is what the held group accounts +/// for. +#[tokio::test] +async fn a_chunk_fed_state_router_holds_the_parent_batch_until_its_row_is_dropped() { + const GROUPS: usize = 32; + const POINTS: usize = 4; + let series = schema(); + let wire = Arc::new( + AggregateStateSchema::try_new( + AggregateStateKind::Sum, + vec![StateComponent::Value, StateComponent::Compensation], + ) + .unwrap(), + ); + let rows = (0..GROUPS) + .map(|group| { + let states = (0..POINTS) + .map(|point| { + Some(StatePayload::Float(AggregateStateValues { + value: (group * POINTS + point) as f64, + compensation: 0.0, + ..Default::default() + })) + }) + .collect(); + Ok(( + StateSeries { + metric: labels(&format!("group-{group:03}")), + time: TimeAxis::from_grid_spans( + series.eval_grid.clone().unwrap(), + vec![GridSpan::new(0, POINTS)], + ) + .unwrap(), + states: vec![states], + }, + true, + )) + }) + .collect::>(); + let batch = common_query::series_frame::pack_aggregate_state( + Box::pin(futures::stream::iter(rows)), + Arc::clone(&wire), + Arc::clone(&series), + ) + .unwrap() + .try_collect::>() + .await + .unwrap() + .remove(0); + assert_eq!(GROUPS, batch.num_rows(), "all groups share one parent"); + let parent_payload = std::mem::size_of::() + + batch.num_columns() * std::mem::size_of::() + + batch.get_array_memory_size(); + let child_schema = batch.schema(); + let source: Arc = + MemorySourceConfig::try_new_exec(&[vec![batch]], child_schema, None).unwrap(); + // The region's exit forwards the packed frame, exactly as a region hands one over; the router + // above it reads that node's chunks instead of its frames. + let region: Arc = + Arc::new(SeriesRepartitionExec::try_new(source, 1).unwrap()); + let router = Arc::new(SeriesRepartitionExec::try_new(Arc::clone(®ion), 2).unwrap()); + let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); + let context = task_context(&pool); + let mut chunks = series_execution_plan(router.as_ref()) + .expect("a router hands its groups over") + .execute_series(0, Arc::clone(&context)) + .expect("the output is claimed"); + // The other owner is claimed too, so the read ends on its own instead of being stopped: what the + // pool counts afterwards is then what the streams released, not what an abort has yet to. + let mut sibling = series_execution_plan(router.as_ref()) + .expect("a router hands its groups over") + .execute_series(1, Arc::clone(&context)) + .expect("the second output is claimed once"); + let row = futures::future::poll_fn(|cx| chunks.as_mut().poll_next(cx)) + .await + .expect("the router routes a group") + .expect("a group arrives"); + assert!( + matches!(row.chunk(), SeriesChunk::State(StateChunk::Row(_))), + "a router reading another router's rows hands over rows: {:?}", + row.chunk() + ); + + // Read the export to its end while keeping the one group: every charge the read had is released + // as it finishes, except the one the group holds. + chunks + .by_ref() + .try_collect::>() + .await + .expect("the router's output ends instead of failing"); + sibling + .by_ref() + .try_collect::>() + .await + .expect("the sibling output ends instead of failing"); + drop(chunks); + drop(sibling); + drop(router); + drop(region); + assert!( + pool.reserved() >= parent_payload, + "the held group keeps the parent batch it was cut from charged: {} reserved, {parent_payload} of parent", + pool.reserved() + ); + + drop(row); + assert_eq!( + 0, + pool.reserved(), + "dropping the last group of a finished read releases everything" + ); +} + +/// Every contribution of a duplicated state input survives the chunk path as it does the frame path. +/// +/// `aggregate_state_router_slices_and_preserves_group_validity` states the rule for a frame: two +/// producers contributing one group at the same grid point are two rows the owner forwards, never a +/// duplicate collapsed into one. A chunk input is routed by the same rule - the form of the +/// publication is not the identity of a contribution - so the twin below is that fixture read as +/// chunks, through `execute_series`, and it has to count the same four rows with the overlapping +/// point counted twice. +#[tokio::test] +async fn a_duplicated_state_input_survives_the_chunk_path_as_it_does_the_frame_path() { + let series = schema(); + let wire = Arc::new( + AggregateStateSchema::try_new(AggregateStateKind::Group, Vec::new()) + .expect("Group has no components"), + ); + // Two producers both contribute to the same group, including the same grid point. + let mut batches = [vec![0, 1], vec![0, 2]] + .into_iter() + .map(|positions| { + let states = positions + .into_iter() + .map(|position| { + Ok(( + StateSeries { + metric: labels("same"), + time: TimeAxis::from_grid_spans( + series.eval_grid.clone().unwrap(), + vec![GridSpan::new(position, 1)], + ) + .unwrap(), + states: vec![vec![None]], + }, + true, + )) + }) + .collect::>(); + let frames = common_query::series_frame::pack_aggregate_state( + Box::pin(futures::stream::iter(states)), + Arc::clone(&wire), + Arc::clone(&series), + ) + .unwrap(); + let mut frames = frames; + futures::executor::block_on(futures::future::poll_fn(|cx| { + match frames.as_mut().poll_next(cx) { + Poll::Ready(batch) => Poll::Ready(batch.expect("state batch is emitted")), + Poll::Pending => Poll::Pending, + } + })) + .unwrap() + }) + .collect::>(); + let child_schema = batches[0].schema(); + let source: Arc = MemorySourceConfig::try_new_exec( + &[vec![batches.remove(0)], vec![batches.remove(0)]], + child_schema, + None, + ) + .unwrap(); + // The region's exit publishes the producers' rows as chunks; the router above routes them. + let region: Arc = + Arc::new(SeriesRepartitionExec::try_new(source, 1).unwrap()); + let plan = Arc::new(SeriesRepartitionExec::try_new(Arc::clone(®ion), 2).unwrap()); + let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); + let context = task_context(&pool); + let mut outputs = (0..2) + .map(|output| { + series_execution_plan(plan.as_ref()) + .expect("a router hands its groups over") + .execute_series(output, Arc::clone(&context)) + .expect("each output is claimed once") + }) + .collect::>(); + let mut carried = Vec::new(); + for output in &mut outputs { + for handed in output.by_ref().try_collect::>().await.unwrap() { + let (chunk, _charge) = handed.into_parts(); + let SeriesChunk::State(StateChunk::Row(row)) = chunk else { + panic!("a chunk-fed state router hands over rows"); + }; + carried.push( + row.time + .positions() + .map(|(point, _)| point) + .collect::>(), + ); + } + } + assert_eq!( + 4, + carried.len(), + "both producers' rows are forwarded, including their overlapping point: {carried:?}" + ); + assert_eq!( + 2, + carried.iter().filter(|points| points.contains(&0)).count(), + "the point both producers contribute is two contributions, not one: {carried:?}" + ); + assert!( + carried.iter().any(|points| points.contains(&1)) + && carried.iter().any(|points| points.contains(&2)), + "each producer's other point survives too: {carried:?}" + ); + drop(outputs); + drop(plan); + drop(region); + wait_until("the finished read releases everything", || { + pool.reserved() == 0 + }) + .await; +} + +/// A chunk of another state than the one this node declared is refused, as a batch of one is. +/// +/// A state frame says what it is in its schema, so `read_state_batches` refuses a batch under any +/// other schema before routing a row of it. A chunk says the same thing on the value, and the chunk +/// path has to make the same check: a publication of another kind, layout or grid names state this +/// node's owners would merge as theirs, which is not a merge any declaration allows. +/// +/// The reader is driven directly because no real producer can make that publication: every node in +/// the chain publishes the same declaration it hands over, which is what makes the check a guard +/// rather than a filter on ordinary input. +#[tokio::test] +async fn a_state_router_refuses_a_chunk_of_another_state() { + let series = schema(); + let declared = Arc::new( + AggregateStateSchema::try_new( + AggregateStateKind::Sum, + vec![StateComponent::Value, StateComponent::Compensation], + ) + .unwrap(), + ); + // The same publication, declaring another aggregate on another grid. + let other = Arc::new(crate::native::plan::AggregateStateSchema { + group: crate::native::plan::Grouping::By(Arc::from([])), + kind: AggregateStateKind::Count, + components: Arc::from([StateComponent::Count]), + accumulators: series.fields.clone(), + grid: Arc::new( + EvalGrid::try_new(GridSpec::try_new(GRID_START, GRID_STEP * 2, 2).unwrap()).unwrap(), + ), + }); + let declared_layout = Arc::new(crate::native::plan::AggregateStateSchema { + group: crate::native::plan::Grouping::By(Arc::from([])), + kind: AggregateStateKind::Sum, + components: Arc::from([StateComponent::Value, StateComponent::Compensation]), + accumulators: series.fields.clone(), + grid: grid(), + }); + let publication = |state: Arc, charted: usize| { + let grid = Arc::clone(&state.grid); + let time = TimeAxis::from_grid_spans(grid, vec![GridSpan::new(charted, 1)]).unwrap(); + let states = (0..series.fields.len()) + .map(|_| vec![Some(StatePayload::Float(AggregateStateValues::default()))]) + .collect(); + HandedSeriesChunk::uncharged(SeriesChunk::State(StateChunk::Series { + series: vec![StateSeries { + metric: labels("handed"), + time, + states, + }], + state_schema: state, + reservation: None, + })) + }; + let routing = Routing::new(2); + let mut senders = Vec::new(); + let mut receivers = Vec::new(); + for _ in 0..routing.outputs { + let (sender, receiver) = mpsc::unbounded_channel(); + senders.push(sender); + receivers.push(receiver); + } + let pool: Arc = Arc::new(GreedyMemoryPool::new(usize::MAX)); + let read_ahead = MemoryConsumer::new("SeriesRepartitionStateTest").register(&pool); + + let mut chunks: SendableSeriesStream = + Box::pin(futures::stream::iter(vec![Ok(publication(other, 0))])); + let stop = read_state_chunks( + &mut chunks, + 0, + &routing, + &senders, + &read_ahead, + &declared, + &series, + ) + .await; + let Stop::Failed(error) = stop else { + panic!("a publication of another state is refused"); + }; + assert!( + error + .to_string() + .contains("aggregate state chunk schema mismatch"), + "{error}" + ); + assert!( + receivers + .iter_mut() + .all(|receiver| receiver.try_recv().is_err()), + "nothing of another state is routed" + ); + + // The same publication declared as this node declared it is routed. + let mut chunks: SendableSeriesStream = Box::pin(futures::stream::iter(vec![Ok(publication( + declared_layout, + 1, + ))])); + let stop = read_state_chunks( + &mut chunks, + 0, + &routing, + &senders, + &read_ahead, + &declared, + &series, + ) + .await; + assert!(matches!(stop, Stop::Ended), "the declared state is routed"); + let queued = receivers + .iter_mut() + .filter_map(|receiver| receiver.try_recv().ok()) + .collect::>(); + assert_eq!(1, queued.len(), "the one group is queued once"); + assert!( + matches!(queued[0], Queued::StateChunk { .. }), + "a group reaches its owner as the group it is" + ); +} + /// The raw owner over `child` routing by an explicit policy. fn raw_node_with_routing( child: Arc, @@ -3383,6 +3824,7 @@ async fn eof_readies_two_groups_but_poll_merges_one_at_a_time() { Arc::clone(&schema()), None, &context, + InputRead::Frames, ) .unwrap(); let (receiver, lease) = SharedExecution::claim(&shared, 0).expect("claim output"); @@ -5416,6 +5858,7 @@ async fn a_recorded_failure_reaches_every_output_once() { Arc::clone(&schema()), None, &context, + InputRead::Frames, ) .unwrap(); let mut streams = Vec::new(); @@ -5743,6 +6186,7 @@ async fn dropping_unpolled_route_future_ends_outputs_and_cancels_peer() { receivers.push(Some(receiver)); } let shared = Arc::new(SharedExecution { + read: InputRead::Frames, running: Mutex::new(Running { receivers, inputs: Arc::clone(&inputs), @@ -5856,6 +6300,7 @@ async fn unpolled_route_drop_preserves_an_already_elected_failure() { receivers.push(Some(receiver)); } Arc::new(SharedExecution { + read: InputRead::Frames, running: Mutex::new(Running { receivers, inputs: Arc::clone(&inputs), @@ -6020,6 +6465,7 @@ async fn sibling_failure_aborts_budget_yielded_route_and_releases_prefix() { let inputs = Inputs::new(Arc::clone(&ending), 2, Weak::::new()); let (sender, receiver) = mpsc::unbounded_channel(); let shared = Arc::new(SharedExecution { + read: InputRead::Frames, running: Mutex::new(Running { receivers: vec![Some(receiver)], inputs: Arc::clone(&inputs), @@ -6608,6 +7054,7 @@ async fn internal_stream_releases_each_chunk_charge_only_when_polled() { Arc::clone(&schema()), None, &context, + InputRead::Frames, ) .unwrap(); let (receiver, lease) = SharedExecution::claim(&shared, 0).expect("claim output"); @@ -6914,6 +7361,7 @@ async fn histogram_chain_slices_fit_a_budget_below_the_full_table_charge() { Arc::clone(&schema()), None, &context, + InputRead::Frames, ) .unwrap(); let (receiver, lease) = SharedExecution::claim(&shared, 0).expect("claim output"); @@ -8085,3 +8533,213 @@ async fn histogram_state_router_dispatches_each_row_of_a_packed_batch() { } assert_eq!(seen, groups.len()); } + +/// The child is asked for its chunks when the consumer reads chunks, and for its frames when not. +/// +/// The two readings describe one publication, so nothing outside this node can tell them apart - but +/// the state content can, because a handed group and a decoded batch are different queue items. The +/// child here is a router over state frames, which is the one shape that answers both ways. +#[tokio::test] +async fn the_child_is_read_the_way_the_consumer_reads_this_node() { + let grid = Arc::new( + EvalGrid::try_new(GridSpec::try_new(GRID_START, GRID_STEP, GRID_LEN).unwrap()).unwrap(), + ); + let series = Arc::new(SeriesSchema { + fields: Arc::from([FieldSpec { + name: Arc::from("value"), + }]), + eval_grid: Some(grid), + }); + let wire = Arc::new( + datatypes::series::aggregate_state::AggregateStateSchema::try_new( + AggregateStateKind::Sum, + vec![StateComponent::Value, StateComponent::Compensation], + ) + .unwrap(), + ); + let rows = (0..2) + .map(|position| { + ( + StateSeries { + metric: labels("handed-state"), + time: TimeAxis::from_grid_spans( + Arc::clone(&series.eval_grid.clone().unwrap()), + vec![GridSpan::new(position, 1)], + ) + .unwrap(), + states: vec![vec![Some(StatePayload::Float(AggregateStateValues { + value: position as f64, + mean: position as f64, + compensation: 0.0, + count: 1.0, + incremental_mean: false, + }))]], + }, + true, + ) + }) + .collect::>(); + let mut frames = common_query::series_frame::pack_aggregate_state( + Box::pin(futures::stream::iter(rows.into_iter().map(Ok))), + Arc::clone(&wire), + Arc::clone(&series), + ) + .unwrap(); + let batch = frames + .next() + .await + .expect("a state batch is emitted") + .expect("the state batch packs"); + let child_schema = batch.schema(); + let leaf: Arc = + MemorySourceConfig::try_new_exec(&[vec![batch]], child_schema, None).unwrap(); + // A router over the frames answers both ways: chunks for a consumer that reads them, frames for + // one that does not. One claim per instance, so each reading gets its own child. + let child = || { + Arc::new( + SeriesRepartitionExec::try_new(Arc::clone(&leaf), 2).expect("a state frame routes"), + ) as Arc + }; + let context = task_context(&Arc::new(GreedyMemoryPool::new(usize::MAX))); + + let chunks = child(); + let handed = routed_input( + &chunks, + series_execution_plan(chunks.as_ref()), + FrameContent::AggregateState, + &series, + Some(&wire), + SeriesOrdering::Contiguous, + 0, + &context, + ) + .unwrap(); + assert!( + matches!(handed, RoutedInput::StateChunks(..)), + "a chunk read asks the child for its chunks" + ); + + let frames = child(); + let decoded = routed_input( + &frames, + None, + FrameContent::AggregateState, + &series, + Some(&wire), + SeriesOrdering::Contiguous, + 0, + &context, + ) + .unwrap(); + assert!( + matches!(decoded, RoutedInput::State(_, _, _)), + "a frame read executes the child and decodes it here" + ); +} + +/// A merged field is charged for every segment it is made of, not for one view of all of them. +/// +/// An inner router folds two pieces of one identity into a chunk whose field is two dense segments, +/// and asking such a field for a single dense view answers `None`. Charging that answer billed the +/// merged chunk as timestamps alone, so a router that queued it held live bytes nothing accounted +/// for - and the charge it was merged under was released as soon as the read that produced it ended. +/// +/// The figure is read at exactly that moment: the inner publication has been read to its end and +/// dropped, the outer queue has not been consumed, so what the pool still counts is the bytes the +/// queue is holding. Both are checked against the buffers themselves, so a field that costs +/// nothing cannot pass on the strength of the timestamps beside it. +#[tokio::test] +async fn a_merged_field_is_charged_what_the_queue_holds_once_the_merge_charge_is_gone() { + const SEGMENT: usize = 4096; + let fragment = |first: i64| { + let times: Vec = (0..SEGMENT as i64).map(|row| first + row).collect(); + raw_chunk( + "k", + Some(raw_metric("a")), + ×, + vec![Some(1.0); SEGMENT], + true, + ) + }; + // Two inputs, one closed piece of one identity each: what the inner router folds them into is one + // chunk whose field is the two segments it was merged from. + let inner = raw_node( + RawScripted::plan(vec![ + RawPartition { + chunks: vec![fragment(0)], + gate: None, + gate_chunks: false, + }, + RawPartition { + chunks: vec![fragment(SEGMENT as i64)], + gate: None, + gate_chunks: false, + }, + ]), + 1, + ); + let pool = Arc::new(GreedyMemoryPool::new(64 << 20)); + let context = task_context(&pool); + // The inner publication, read the way the outer node reads a child that hands its chunks over. + let inner: Arc = inner; + let hand_over = + series_execution_plan(inner.as_ref()).expect("a router hands its publication over"); + let RoutedInput::Raw(mut stream) = routed_input( + &inner, + Some(hand_over), + FrameContent::Raw, + &raw_schema(), + None, + SeriesOrdering::Contiguous, + 0, + &context, + ) + .expect("the child is read as raw series") else { + panic!("a raw child is read as a raw series stream"); + }; + // The outer node's own queue: filled by its read, and read by nobody. + let (sender, mut receiver) = mpsc::unbounded_channel(); + let read_ahead = MemoryConsumer::new("OuterQueue").register(&context.runtime_env().memory_pool); + let stop = read_raw_chains(&mut stream, 0, &Routing::new(1), &[sender], &read_ahead).await; + if let Stop::Failed(error) = stop { + panic!("the inner publication could not be read: {error}"); + } + // The read is the inner publication's end, so the charge it carried is gone with it; dropping the + // wrapper says so out loud rather than leaving it to when this function returns. + drop(stream); + let queued = pool.reserved(); + // Both fragments, both segments: the merged chunk is two of each. + let payload = 2 * SEGMENT * std::mem::size_of::(); + let timestamps = 2 * SEGMENT * std::mem::size_of::(); + assert!( + queued >= payload + timestamps, + "the queue holds {queued} bytes charged for a chunk of at least {} bytes: the merged field \ + is two segments of {payload} bytes and the timestamps beside them are {timestamps}", + payload + timestamps + ); + + // What was queued is the merged chunk this figure was about, and not one segment of it. + let Queued::Chain { + chain: RoutedChain::Raw(chain), + .. + } = receiver + .try_recv() + .expect("the queue holds the merged chain") + else { + panic!("a raw child's chain is queued as raw series"); + }; + assert_eq!(1, chain.len(), "one identity is one chain"); + let (chunk, _charge) = &chain[0]; + let field = chunk.fields.iter().next().expect("the chunk has its field"); + assert_eq!(2, field.segments().len(), "the field is two segments"); + assert!( + field.dense().is_none(), + "a field of two segments has no single dense view" + ); + + // And the figure is the queue's to hold: dropping what it queued gives all of it back. + drop(chain); + drop(receiver); + drop(inner); + assert_eq!(0, pool.reserved(), "the finished read holds nothing"); +} diff --git a/src/promql/src/native/aggregate.rs b/src/promql/src/native/aggregate.rs index 696354b1a8b..c99d5d0a02d 100644 --- a/src/promql/src/native/aggregate.rs +++ b/src/promql/src/native/aggregate.rs @@ -70,7 +70,9 @@ use crate::native::plan::{ AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, Grouping as BoundGrouping, aggregate_state_binding, }; -use crate::native::state::{StateChunk, state_bytes, state_chunk_from_partial}; +use crate::native::state::{ + StateChunk, state_bytes, state_chunk_from_partial, state_row_from_frame_row, +}; /// The output shape produced by an aggregate stage. pub(crate) enum AggregateOutput { @@ -491,6 +493,13 @@ impl AggregateRuntime { } /// Merges one state chunk into this final aggregate. + /// + /// State reaches a `Final` from exactly two places and is merged here, once: a producer in this + /// process hands over the groups it folded ([`StateChunk::Series`]), and a region's exported + /// frame is decoded into the row it carries ([`StateChunk::Row`], which a merge scan reads + /// across processes). Both are read as the rows the merge kernel takes, so there is one merge + /// and not one per source; the series form is turned into those rows here, inside the kernel, + /// instead of by a caller that would have to know what the kernel eats. pub(crate) fn accumulate_state( &mut self, chunk: StateChunk, @@ -500,36 +509,80 @@ impl AggregateRuntime { let expected = self.state_schema.as_ref().ok_or_else(|| { DataFusionError::NotImplemented("this runtime does not merge aggregate state".into()) })?; - let StateChunk::Row(row) = chunk else { - return Err(DataFusionError::Internal( - "Final aggregate received producer state series".into(), - )); + // The one conversion this edge performs, and it is here rather than at the API boundary: a + // producer hands over the groups it folded, and the kernel merges rows. Each source is + // validated once, where its rows are made: the series form by the row layout it is built + // against, a decoded row by the checks that layout makes of a group, so the merge below only + // merges and a group costs its own encoding. + let rows = match chunk { + StateChunk::Row(row) => { + if row.fields.kind() != expected.kind + || row.fields.components() != expected.components.as_ref() + { + return Err(DataFusionError::NotImplemented( + "this runtime does not merge that kind of state".into(), + )); + } + if row + .time + .grid() + .is_none_or(|grid| grid.spec() != expected.grid.spec()) + { + return Err(DataFusionError::Execution( + "aggregate state grid mismatch".into(), + )); + } + if row.fields.len() != self.schema.fields.len() { + return Err(DataFusionError::Execution( + "aggregate state field count mismatch".into(), + )); + } + vec![row] + } + StateChunk::Series { + series, + state_schema: _, + reservation: _reservation, + } => { + // The state layout and the Arrow shape a row is encoded against depend on the chunk, + // not on the group, so they are resolved once for all of its groups. The grid is + // checked here for the same reason: every row of this chunk lands on the series grid + // the layout encodes against, so comparing it once says what a comparison per row + // said before. + if self.schema.eval_grid.as_ref().map(|grid| grid.spec()) + != Some(expected.grid.spec()) + { + return Err(DataFusionError::Execution( + "aggregate state grid mismatch".into(), + )); + } + let declared = datatypes::series::aggregate_state::AggregateStateSchema::try_new( + expected.kind, + expected.components.to_vec(), + ) + .map_err(|error| DataFusionError::Execution(error.to_string()))?; + let layout = + datatypes::series::frame::StateRowLayout::try_new(&declared, &self.schema) + .map_err(|error| DataFusionError::Execution(error.to_string()))?; + let mut rows = Vec::with_capacity(series.len()); + for group in series { + // A group a `Partial` hands over is whole: it folded the group's contribution of + // its partition, and the merge above joins partitions rather than continuing a + // chain. + let row = layout + .row(group, true) + .map_err(|error| DataFusionError::Execution(error.to_string()))?; + rows.push(state_row_from_frame_row(row, expected)?); + } + rows + } }; - if row.fields.kind() != expected.kind - || row.fields.components() != expected.components.as_ref() - { - return Err(DataFusionError::NotImplemented( - "this runtime does not merge that kind of state".into(), - )); - } - if row - .time - .grid() - .is_none_or(|grid| grid.spec() != expected.grid.spec()) - { - return Err(DataFusionError::Execution( - "aggregate state grid mismatch".into(), - )); - } - if row.fields.len() != self.schema.fields.len() { - return Err(DataFusionError::Execution( - "aggregate state field count mismatch".into(), - )); - } let description = self.describe(); let merger = self.merger.as_mut().ok_or_else(|| no_fold(&description))?; - merger.merge_row(&row, |bytes| buffer.resize(pending.saturating_add(bytes)))?; - drop(row); + for row in &rows { + merger.merge_row(row, |bytes| buffer.resize(pending.saturating_add(bytes)))?; + } + drop(rows); buffer.resize(merger.state_bytes()) } diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 55c81d5c664..22023182916 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -199,14 +199,26 @@ pub(crate) fn operand_chunk_bytes(series: &Series) -> usize { .saturating_add(sample_slice_bytes(&series.fields)) } +/// The fields of one chunk, one dense segment at a time. +/// +/// A field is one or more dense segments - a merged chunk carries one per source piece it was folded +/// from - and asking such a field for a single dense view answers `None`. Every figure this crate +/// bills for a chunk's samples walks the segments through here, so the two of them cannot drift on +/// which parts of a field they count; only the yardstick differs, and each caller says why. +pub(crate) fn field_segments(fields: &SeriesFields) -> impl Iterator + '_ { + fields.iter().flat_map(|field| field.segments()) +} + /// The bytes the samples of one series' fields take as the slices they are. /// /// A dense segment is counted by its rows and a native-histogram field by its index column; a nested -/// segment is left to the chunks it is made of. +/// segment is left to the chunks it is made of. The walk over segments is the same one +/// [`raw_chunk_slice_bytes`](crate::extension_plan::series_repartition) makes for a raw chunk - a +/// field is one or more of them, and both walk them with [`field_segments`] - but the yardstick +/// differs on purpose: this figure bills rows and the allocations behind them are counted once by +/// `chunk_bytes_beside_samples`, while a router bills the buffers a slice keeps alive. fn sample_slice_bytes(fields: &SeriesFields) -> usize { - fields - .iter() - .flat_map(|field| field.segments()) + field_segments(fields) .map(|segment| match segment.dense() { Some(DenseSamplesRef::Float(values)) => { values.len().saturating_mul(std::mem::size_of::()) diff --git a/src/promql/src/native/state.rs b/src/promql/src/native/state.rs index fdd996b00c3..6ebb5c214dd 100644 --- a/src/promql/src/native/state.rs +++ b/src/promql/src/native/state.rs @@ -38,7 +38,7 @@ use crate::native::plan::{AggregateStateSchema, BoundAggregate, aggregate_state_ /// One partition's aggregate state, either in producer series form or as a decoded consumer row. #[derive(Debug)] -pub(crate) enum StateChunk { +pub enum StateChunk { Series { series: Vec, state_schema: Arc, @@ -101,6 +101,24 @@ pub(crate) fn state_chunk_from_partial( }) } +/// Builds the executor's state row for one exported row, as its producer declared it. +/// +/// A producer hands a row over without knowing which binding will fold it: the kind and the columns +/// it was written with travel in the row, and the consumer checks them against its own binding. So +/// this converts the row's columns and keeps the layout they were validated against. +pub(crate) fn state_row_of(row: StateFrameRow) -> Result { + let fields = row + .fields() + .map_err(|error| DataFusionError::Execution(error.to_string()))?; + let kind = fields.kind(); + Ok(crate::aggregate::state::StateRow { + metric: row.metric().clone(), + time: row.time().clone(), + fields, + kind, + }) +} + /// Builds the executor's Arrow-backed state row from one decoded frame row. pub(crate) fn state_row_from_frame_row( row: StateFrameRow,