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 <discord9@163.com>

* feat(promql): hand aggregate state between native operators as chunks too

Signed-off-by: discord9 <discord9@163.com>

* feat(promql): read children as chunks and hand fused outputs over in process

Signed-off-by: discord9 <discord9@163.com>

* fix(promql): keep the chunk handover's checks and accounting honest

Signed-off-by: discord9 <discord9@163.com>

* 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 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-11-23 08:26:22 +00:00
committed by GitHub
parent 0ab8dcb866
commit 82ed828ded
15 changed files with 4733 additions and 385 deletions
+29 -8
View File
@@ -640,7 +640,13 @@ fn invalid(reason: impl Into<String>) -> 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<Vec<u8>>,
previous_timestamp: Option<i64>,
@@ -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
+306 -153
View File
@@ -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<StructArray> {
// 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<ArrayRef> = 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<ArrayRef> = 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::<Result<Vec<_>>>()?;
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<ArrayRef> = 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<ArrayRef> = 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::<Result<Vec<_>>>()?;
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<ArrayRef> = 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<EvalGrid>,
/// 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<Self> {
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<StateFrameRow> {
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::<Vec<_>>();
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<Self> {
StateRowLayout::try_new(state, schema)?.row(series, is_last)
}
/// Complete group identity for this row.
pub fn metric(&self) -> &SeriesLabels {
&self.metric
+162
View File
@@ -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::<Vec<_>>(),
framed.time().positions().collect::<Vec<_>>(),
"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<Option<Values>> {
(0..n)
.map(|i| {
+1 -1
View File
@@ -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,
+5
View File
@@ -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};
+418 -62
View File
@@ -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<TaskContext>,
) -> DataFusionResult<SendableRecordBatchStream> {
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<TaskContext>,
) -> DataFusionResult<SendableSeriesStream> {
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<TaskContext>,
) -> DataFusionResult<FusedExecution> {
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<futures::stream::BoxStream<'static, Result<FusedFeed, BoxedError>>> =
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<FusedStateOutput>,
}
/// 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<datatypes::series::aggregate_state::AggregateStateSchema>,
/// The same layout as the tree's binding, which is what a handed-over chunk names.
binding: Arc<AggregateStateSchema>,
/// The series schema the export is of.
series: Arc<SeriesSchema>,
}
/// 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<SeriesCharge>,
}
/// 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<SeriesSchema>,
state: Option<&Arc<AggregateStateSchema>>,
handed: HandedSeriesChunk,
) -> Result<FusedFeed, BoxedError> {
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<Arc<AggregateStateSchema>> {
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<HandedSeriesChunk, BoxedError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
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<AggregateStateSchema>,
/// 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<Arc<MemoryReservation>>,
)>,
}
impl Stream for FusedStateChunks {
type Item = Result<HandedSeriesChunk, BoxedError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
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::<Vec<_>>()
.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,
}
File diff suppressed because it is too large Load Diff
@@ -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<SeriesSchema>,
}
impl Stream for DeclaredOrdering {
impl Stream for DeclaredSeries {
type Item = Result<RawSeriesChunk, BoxedError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
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<SeriesSchema> {
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<dyn ExecutionPlan>,
@@ -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<TaskContext>,
) -> DataFusionResult<SendableRecordBatchStream> {
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<TaskContext>,
) -> DataFusionResult<SendableRecordBatchStream> {
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<TaskContext>,
) -> DataFusionResult<SendableSeriesStream> {
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;
@@ -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<MemoryReservation>,
/// The reservations it shares with the other chunks cut from the same publication.
_shared: Vec<Arc<MemoryReservation>>,
}
impl SeriesCharge {
/// The charge of one owner publication.
pub(crate) fn new(
fragments: Vec<MemoryReservation>,
descriptor: MemoryReservation,
workspace: Option<MemoryReservation>,
) -> 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<Arc<MemoryReservation>>) -> 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<Arc<MemoryReservation>> {
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<SeriesCharge>,
}
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<SeriesCharge>) {
(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<Box<dyn Stream<Item = Result<HandedSeriesChunk, BoxedError>> + 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::<dyn SeriesExecutionPlan>()` 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<TaskContext>,
) -> DataFusionResult<SendableSeriesStream>;
}
/// `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::<RawSeriesSourceExec>() {
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::<SeriesRepartitionExec>() {
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::<FusedSeriesExec>()
.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<SendableSeriesStream>,
/// 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<HandedSeriesChunk, BoxedError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
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;
@@ -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::<RawSeriesSourceExec>()
.is_some(),
"the guard answered with the raw source it was asked about"
);
let router: Arc<dyn ExecutionPlan> = 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::<SeriesRepartitionExec>()
.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<dyn ExecutionPlan> = 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<dyn ExecutionPlan> = 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<dyn ExecutionPlan>); 3] = [
("raw", raw_source(per_series_scan(2))),
("evaluated", evaluated_frames()),
("aggregate state", state_frames()),
];
for (name, child) in contents {
let router: Arc<dyn ExecutionPlan> = 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::<SeriesRepartitionExec>()
.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<dyn ExecutionPlan> =
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<dyn ExecutionPlan> =
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<EvalGrid> {
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<SeriesSchema> {
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<dyn ExecutionPlan> {
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<dyn ExecutionPlan> {
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))
}
File diff suppressed because it is too large Load Diff
@@ -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<Step> = (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::<f64>();
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::<Vec<_>>();
let batch = common_query::series_frame::pack_aggregate_state(
Box::pin(futures::stream::iter(rows)),
Arc::clone(&wire),
Arc::clone(&series),
)
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap()
.remove(0);
assert_eq!(GROUPS, batch.num_rows(), "all groups share one parent");
let parent_payload = std::mem::size_of::<RecordBatch>()
+ batch.num_columns() * std::mem::size_of::<datafusion::arrow::array::ArrayRef>()
+ batch.get_array_memory_size();
let child_schema = batch.schema();
let source: Arc<dyn ExecutionPlan> =
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<dyn ExecutionPlan> =
Arc::new(SeriesRepartitionExec::try_new(source, 1).unwrap());
let router = Arc::new(SeriesRepartitionExec::try_new(Arc::clone(&region), 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::<Vec<_>>()
.await
.expect("the router's output ends instead of failing");
sibling
.by_ref()
.try_collect::<Vec<_>>()
.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::<Vec<_>>();
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::<Vec<_>>();
let child_schema = batches[0].schema();
let source: Arc<dyn ExecutionPlan> = 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<dyn ExecutionPlan> =
Arc::new(SeriesRepartitionExec::try_new(source, 1).unwrap());
let plan = Arc::new(SeriesRepartitionExec::try_new(Arc::clone(&region), 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::<Vec<_>>();
let mut carried = Vec::new();
for output in &mut outputs {
for handed in output.by_ref().try_collect::<Vec<_>>().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::<Vec<_>>(),
);
}
}
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<crate::native::plan::AggregateStateSchema>, 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<dyn MemoryPool> = 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::<Vec<_>>();
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<dyn ExecutionPlan>,
@@ -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::<SharedExecution>::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::<Vec<_>>();
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<dyn ExecutionPlan> =
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<dyn ExecutionPlan>
};
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<i64> = (0..SEGMENT as i64).map(|row| first + row).collect();
raw_chunk(
"k",
Some(raw_metric("a")),
&times,
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<dyn ExecutionPlan> = 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::<f64>();
let timestamps = 2 * SEGMENT * std::mem::size_of::<i64>();
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");
}
+81 -28
View File
@@ -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())
}
+16 -4
View File
@@ -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<Item = &Samples> + '_ {
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::<f64>())
+19 -1
View File
@@ -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<StateSeries>,
state_schema: Arc<AggregateStateSchema>,
@@ -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<crate::aggregate::state::StateRow> {
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,