mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-01 07:04:09 +00:00
feat(promql): prove, and read, a match that two routed sources co-locate
A match pairs two sides by a key its modifiers name, while canonical-key
routing places a series by its canonical label set, and the two keys are
the same only when neither side carries a metric name. `m1 / m2` is the
case that shows it: `m1{ns="a"}` and `m2{ns="a"}` are one match group and
two canonical label sets, so routing by canonical key hands the partners
to different executions and the match answers nothing where a whole match
answers a row. `sum by(ns)(m1) / sum by(ns)(m2)` is the case that works:
after the fold each side holds only `{ns}`, so the keys coincide and the
routing genuinely puts partners together.
This adds the two facts that tell those cases apart.
`output_has_metric_name` derives, per node kind, whether every series the
node hands over carries `__name__` - three-valued and deliberately
conservative: a shape whose answer is not a function of the node kind
answers `None`, and `None` never proves anything. It exists because the
question is answerable and nothing else answered it, not as a general
"labels" property.
`match_is_co_partitioned` is the joint proof, and it is joint on purpose.
A per-side predicate cannot express what a match needs, because the fact
that makes the keys coincide is about *both* sides at once. Its conjuncts
are the routed operands, the co-partitioned pair, the default one-to-one
modifiers, and the pair's `name_free`. That last one is supplied by the
layer that built the producers: an `Input` over evaluated samples answers
`None` to `output_has_metric_name`, since whether its label sets still
carry a name was decided by a node outside the consuming tree. So the
pair's `name_free` is the producer half of the proof and this function is
the tree half, and neither can be derived from the other.
`needs_single_execution_in_co` carries that proof; the existing
`needs_single_execution_in` delegates with no pairs, so every current
caller and test keeps its exact meaning, and `matching_co_located` is not
loosened - a canonical-key boundary still proves nothing about a match
group.
The executor learns to read several evaluated sources without mixing
them. It kept one and silently dropped the rest: every later source's
streams were filed under the first index, so a second source's frames were
read as though they were the first's, and construction refused the
configuration rather than let it be seen. Streams are now filed per
source, each gathered and charged separately, and one `EvaluatedSources`
hands a chunk over under the index of the gather that read it. The node
ends only when every source ended, the first error drops the others rather
than reading them out, and neither source can starve the other.
Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -1158,6 +1158,7 @@ impl FusedSeriesExec {
|
||||
input.properties().partitioning.partition_count()
|
||||
});
|
||||
let mut evaluated_sources = 0usize;
|
||||
let mut raw_sources = 0usize;
|
||||
for (index, (input, label_source, ordering)) in inputs.iter().enumerate() {
|
||||
let count = input.properties().partitioning.partition_count();
|
||||
if count == 0 {
|
||||
@@ -1195,18 +1196,26 @@ impl FusedSeriesExec {
|
||||
evaluated_sources += 1;
|
||||
let _ = unpack_evaluated_series(empty(), Some(Arc::clone(&raw_schemas[index])))?;
|
||||
} else {
|
||||
raw_sources += 1;
|
||||
unpack_raw_series(empty(), Some(Arc::clone(&raw_schemas[index])))?;
|
||||
}
|
||||
}
|
||||
// One evaluated source at a time is what this node reads: a raw source is gathered across
|
||||
// its partitions by series, because one of its series may span them, and an evaluated one
|
||||
// the same way, because each frame is contiguous within a partition and not across them.
|
||||
// Combining the two, or evaluating more than one source, would need a routing this node does
|
||||
// not have - which label set of one source belongs beside which of another - so it is
|
||||
// refused instead of run with one side read wrongly.
|
||||
if evaluated_sources > 1 || (evaluated_sources == 1 && inputs.len() > 1) {
|
||||
// Several evaluated sources are read, each gathered from its own child: every source's
|
||||
// partitions are read at once and kept apart, because a frame is contiguous within a
|
||||
// partition and not across them, and because the runtime routes a chunk by the source index
|
||||
// its gather hands it over with. What carries them out is the plain-row conversion, one
|
||||
// evaluated chunk at a time; a frame output over more than one source is refused above,
|
||||
// since packing several sources into one frame would have to say which label set of one
|
||||
// source belongs beside which of another.
|
||||
//
|
||||
// An evaluated source beside a raw one is still refused. A raw source is gathered across its
|
||||
// partitions by series with [`SeriesGather`], whose chunks and label materialization differ
|
||||
// from an evaluated gather's, so reading both at once would need a third merge over the two
|
||||
// kinds of gather; this node has none, and running one side through the other would read it
|
||||
// wrongly. Nothing above this node asks for that combination, so it declines instead.
|
||||
if evaluated_sources > 0 && raw_sources > 0 {
|
||||
return Err(DataFusionError::Plan(
|
||||
"FusedSeries reads one evaluated source alone, not beside another source".into(),
|
||||
"FusedSeries reads evaluated sources on their own, not beside a raw source".into(),
|
||||
));
|
||||
}
|
||||
// One execution over every input partition, rather than one execution per partition: a tree
|
||||
@@ -1379,7 +1388,12 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
// of them here; a per-partition execution does, and must name one the input has.
|
||||
let single_execution = Self::requires_single_execution(&self.inputs, &self.tree);
|
||||
let mut streams = Vec::new();
|
||||
let mut evaluated: Option<(usize, Vec<SendableEvaluatedSeriesStream>)> = None;
|
||||
// One list of streams per evaluated source, indexed by source index: the index is what
|
||||
// routes a chunk into that source's own input slots, so the sources are kept apart here
|
||||
// rather than collected into one list. Every source is dense ([`Self::build`] refused
|
||||
// anything else), so the list's own index is the source index.
|
||||
let mut evaluated: Vec<Vec<SendableEvaluatedSeriesStream>> =
|
||||
(0..self.series_schemas.len()).map(|_| Vec::new()).collect();
|
||||
for (source, (input, _, _)) in self.inputs.iter().enumerate() {
|
||||
let count = input.properties().partitioning.partition_count();
|
||||
if !single_execution && partition >= count {
|
||||
@@ -1401,15 +1415,14 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
if decoded_input {
|
||||
// An evaluated frame carries values its producer already decided on the grid,
|
||||
// so its chunks are queued at the input node as they are: there are no scan
|
||||
// labels to materialize and no series to hold back.
|
||||
// labels to materialize and no series to hold back. The stream is filed under
|
||||
// the source it was read from, and every later chunk of it is handed over with
|
||||
// that same index.
|
||||
let stream = unpack_evaluated_series(
|
||||
frames,
|
||||
Some(Arc::clone(&self.series_schemas[source])),
|
||||
)?;
|
||||
evaluated
|
||||
.get_or_insert_with(|| (source, Vec::new()))
|
||||
.1
|
||||
.push(stream);
|
||||
evaluated[source].push(stream);
|
||||
} else {
|
||||
let raw =
|
||||
unpack_raw_series(frames, Some(Arc::clone(&self.series_schemas[source])))?;
|
||||
@@ -1444,17 +1457,24 @@ impl ExecutionPlan for FusedSeriesExec {
|
||||
})
|
||||
.transpose()?;
|
||||
let mut executor = NativeExecutor::new(state);
|
||||
let inputs = if let Some((source, partitions)) = evaluated {
|
||||
// One evaluated source, its partitions read through one gather: its frames are
|
||||
// contiguous per partition by declaration, and the gather is what keeps a chain whole
|
||||
// while none of the partitions waits on another.
|
||||
let reservation = MemoryConsumer::new(format!("FusedSeriesEvaluated[{partition}]"))
|
||||
.register(&context.runtime_env().memory_pool);
|
||||
Some(FusedInputs::Evaluated(EvaluatedGather::new(
|
||||
source,
|
||||
partitions,
|
||||
reservation,
|
||||
)))
|
||||
let inputs = if evaluated.iter().any(|partitions| !partitions.is_empty()) {
|
||||
// Every evaluated source, each read through its own gather: its frames are contiguous
|
||||
// per partition by declaration, and the gather is what keeps a chain whole within that
|
||||
// source while none of its partitions waits on another. The gathers are charged
|
||||
// separately - the consumer's name carries the source *and* the output partition - so
|
||||
// one source's pressure is paid by its own reservation and never by another's.
|
||||
let gathers = evaluated
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, partitions)| !partitions.is_empty())
|
||||
.map(|(source, partitions)| {
|
||||
let reservation =
|
||||
MemoryConsumer::new(format!("FusedSeriesEvaluated[{source}][{partition}]"))
|
||||
.register(&context.runtime_env().memory_pool);
|
||||
EvaluatedGather::new(source, partitions, reservation)
|
||||
})
|
||||
.collect();
|
||||
Some(FusedInputs::Evaluated(EvaluatedSources::new(gathers)))
|
||||
} else if streams.is_empty() {
|
||||
executor.end_of_input()?;
|
||||
None
|
||||
@@ -1602,18 +1622,20 @@ struct FusedFeed {
|
||||
chunk: FusedChunk,
|
||||
}
|
||||
|
||||
/// The input of one execution: its raw partitions gathered together, or one evaluated source's
|
||||
/// The input of one execution: its raw partitions gathered together, or its evaluated sources'
|
||||
/// partitions read at once.
|
||||
///
|
||||
/// [`SeriesGather`] interleaves the partitions of one raw source while keeping every series
|
||||
/// [`SeriesGather`] interleaves the partitions of every raw source while keeping every series
|
||||
/// contiguous, because a series read from storage may span them. An evaluated source is gathered
|
||||
/// the same way and for the same reason: its frames are contiguous within a partition by
|
||||
/// declaration, and reading one partition to its end before the next would stall against an upstream
|
||||
/// that routes by series into bounded queues, since the partition being read cannot end while the
|
||||
/// read feeding it waits on a partition nobody reads.
|
||||
/// read feeding it waits on a partition nobody reads. Each evaluated source gets a gather of its own
|
||||
/// ([`EvaluatedSources`]), because what one source's chain holds back is only its own: the runtime
|
||||
/// routes a chunk by the source index it is handed over with.
|
||||
enum FusedInputs {
|
||||
Raw(SeriesGather),
|
||||
Evaluated(EvaluatedGather),
|
||||
Evaluated(EvaluatedSources),
|
||||
}
|
||||
|
||||
impl Stream for FusedInputs {
|
||||
@@ -1630,7 +1652,78 @@ impl Stream for FusedInputs {
|
||||
chunk: FusedChunk::Raw(chunk),
|
||||
}))),
|
||||
},
|
||||
Self::Evaluated(gather) => Pin::new(gather).poll_next(cx),
|
||||
Self::Evaluated(sources) => Pin::new(sources).poll_next(cx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every evaluated source of one execution, read at once, one gather per source.
|
||||
///
|
||||
/// Each [`EvaluatedGather`] keeps one chain whole *within its own source*: a series' chunks arrive
|
||||
/// contiguously, and a chunk of another series of that source is held back until its chain closes.
|
||||
/// Sources do not constrain each other, and that is a fact about the runtime rather than a hope:
|
||||
/// every chunk is queued at the input slots bound to its source index
|
||||
/// ([`NativeExecutionState::input_ids`]), each slot belongs to exactly one source, and a slot's
|
||||
/// chain rule is about the chunks queued at *it*. A chunk of source 1 handed over between two chunks
|
||||
/// of source 0 therefore reaches a different slot and cannot break the chain the other slot holds,
|
||||
/// so the two sources' chains may interleave.
|
||||
///
|
||||
/// What this type adds is the order the gathers are polled in. Every sweep starts at the source
|
||||
/// after the one that last handed a chunk over, so a source that always has a chunk ready cannot
|
||||
/// keep another from being polled - the same rotation [`EvaluatedGather`] keeps across one source's
|
||||
/// partitions, extended across sources. The node ends only when every source ended: a source ending
|
||||
/// while another still has frames is not the end, because the other's frames are still its answer.
|
||||
struct EvaluatedSources {
|
||||
/// One gather per evaluated source, in source-index order.
|
||||
gathers: Vec<EvaluatedGather>,
|
||||
/// The gather polled first on the next sweep, so every source is reached even while one of them
|
||||
/// stays ready.
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl EvaluatedSources {
|
||||
fn new(gathers: Vec<EvaluatedGather>) -> Self {
|
||||
Self { gathers, next: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for EvaluatedSources {
|
||||
type Item = Result<FusedFeed, BoxedError>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let this = self.get_mut();
|
||||
let count = this.gathers.len();
|
||||
let mut ended = 0;
|
||||
for offset in 0..count {
|
||||
let index = (this.next + offset) % count;
|
||||
match Pin::new(&mut this.gathers[index]).poll_next(cx) {
|
||||
// Handed over under the index of the gather that read it: a chunk never leaves the
|
||||
// source it was read from, so nothing re-stamps it here.
|
||||
Poll::Ready(Some(Ok(feed))) => {
|
||||
this.next = (index + 1) % count;
|
||||
return Poll::Ready(Some(Ok(feed)));
|
||||
}
|
||||
// The first error ends the node, and every other source's streams are dropped with
|
||||
// it - and so are the reservations they hold - rather than read to their ends.
|
||||
Poll::Ready(Some(Err(error))) => {
|
||||
this.gathers.clear();
|
||||
this.next = 0;
|
||||
return Poll::Ready(Some(Err(error)));
|
||||
}
|
||||
Poll::Ready(None) => ended += 1,
|
||||
// A source still waiting has registered this task's waker, so one of them holding a
|
||||
// read is the node still running.
|
||||
Poll::Pending => {}
|
||||
}
|
||||
}
|
||||
// A sweep that ends here either handed a chunk over (returned above) or found every source
|
||||
// ended or waiting, so the node ends exactly when every source ended. A source that ended
|
||||
// earlier is polled again and answers `None` again; that is what keeps a single source's
|
||||
// end from being read as the node's.
|
||||
if ended == count {
|
||||
Poll::Ready(None)
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1649,8 +1742,9 @@ impl Stream for FusedInputs {
|
||||
/// whose held chain ended stops being polled until that chain is handed over. Every held chunk is
|
||||
/// charged to `reservation` until it leaves the gather.
|
||||
struct EvaluatedGather {
|
||||
/// The source every partition of this gather belongs to: [`FusedSeriesExec::build`] refuses a
|
||||
/// second evaluated source and an evaluated source beside a raw one.
|
||||
/// The source every partition of this gather belongs to: one gather is built per evaluated
|
||||
/// source ([`EvaluatedSources`]), so every chunk this gather hands over belongs to this source
|
||||
/// and to no other. [`FusedSeriesExec::build`] refuses an evaluated source beside a raw one.
|
||||
source: usize,
|
||||
partitions: Vec<EvaluatedPartition>,
|
||||
/// The partition whose open chain is being handed over, if any. Until it closes, what the other
|
||||
|
||||
@@ -52,7 +52,9 @@ use datafusion::datasource::memory::MemorySourceConfig;
|
||||
use datafusion::datasource::source::DataSourceExec;
|
||||
use datafusion::error::{DataFusionError, Result as DataFusionResult};
|
||||
use datafusion::execution::context::TaskContext;
|
||||
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, UnboundedMemoryPool};
|
||||
use datafusion::execution::memory_pool::{
|
||||
GreedyMemoryPool, MemoryConsumer, MemoryPool, UnboundedMemoryPool,
|
||||
};
|
||||
use datafusion::execution::runtime_env::RuntimeEnvBuilder;
|
||||
use datafusion::logical_expr::{EmptyRelation, Expr, LogicalPlan, UserDefinedLogicalNodeCore};
|
||||
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
|
||||
@@ -86,8 +88,8 @@ use store_api::region_engine::RawLabelSource;
|
||||
mod frame_output;
|
||||
|
||||
use super::{
|
||||
FusedOutputFormat, FusedSeries, FusedSeriesBinding, OutputColumn, POLL_BUDGET,
|
||||
series_to_record_batch,
|
||||
EvaluatedGather, EvaluatedSources, FusedChunk, FusedOutputFormat, FusedSeries,
|
||||
FusedSeriesBinding, OutputColumn, POLL_BUDGET, series_to_record_batch,
|
||||
};
|
||||
use crate::evaluated::EvaluatedChunk;
|
||||
use crate::extension_plan::aggregate_exchange::state_schema;
|
||||
@@ -97,11 +99,13 @@ use crate::map_label::LabelRewrite;
|
||||
use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor};
|
||||
use crate::native::plan::{
|
||||
AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar,
|
||||
BoundVectorOp, BoundWindow, Grouping, InstantValue, MapOp, NativeExpr, NativeNode, NativeTree,
|
||||
NativeType,
|
||||
BoundSetOp, BoundVectorOp, BoundWindow, Grouping, InstantValue, MapOp, NativeExpr, NativeNode,
|
||||
NativeTree, NativeType,
|
||||
};
|
||||
use crate::range_eval::{RangeFunction, RangeWindow};
|
||||
use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels};
|
||||
use crate::vector_match::{
|
||||
BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp,
|
||||
};
|
||||
use common_query::series_frame::series_frame_ordering;
|
||||
|
||||
/// The query every tree here is compiled from.
|
||||
@@ -5278,6 +5282,14 @@ fn evaluated_schema() -> Arc<SeriesSchema> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The frame schema a child hands over when its series are already evaluated on [`grid`]: what
|
||||
/// [`ScriptedEvaluated`] executes and what a logical child of this node declares.
|
||||
fn evaluated_frame_schema() -> SchemaRef {
|
||||
pack_evaluated_series(Box::pin(futures::stream::empty()), evaluated_schema())
|
||||
.expect("an evaluated schema declares a frame")
|
||||
.schema()
|
||||
}
|
||||
|
||||
/// One evaluated chunk of `metric`: `len` rows from grid position `start`, each holding its own
|
||||
/// position as its value, and whether it closes the series.
|
||||
///
|
||||
@@ -5288,17 +5300,33 @@ fn evaluated_chunk(
|
||||
start: usize,
|
||||
len: usize,
|
||||
is_last: bool,
|
||||
) -> (Series, bool) {
|
||||
let values = (0..len)
|
||||
.map(|index| Some((start + index) as f64))
|
||||
.collect::<Vec<_>>();
|
||||
evaluated_chunk_with(metric, start, values, is_last)
|
||||
}
|
||||
|
||||
/// One evaluated chunk of `metric` holding `values` from grid position `start` on, and whether it
|
||||
/// closes the series.
|
||||
///
|
||||
/// The values are the caller's, which is what a test of several sources needs: two sources carrying
|
||||
/// the same label set have to carry *different* values, or a chunk read as the wrong source's would
|
||||
/// answer the same thing and prove nothing.
|
||||
fn evaluated_chunk_with(
|
||||
metric: &SeriesLabels,
|
||||
start: usize,
|
||||
values: Vec<Option<f64>>,
|
||||
is_last: bool,
|
||||
) -> (Series, bool) {
|
||||
let schema = evaluated_schema();
|
||||
let len = values.len();
|
||||
let spans = if len == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![GridSpan::new(start, len)]
|
||||
};
|
||||
let time = TimeAxis::from_grid_spans(grid(), spans).expect("one run on the grid");
|
||||
let values = (0..len)
|
||||
.map(|index| Some((start + index) as f64))
|
||||
.collect::<Vec<_>>();
|
||||
(
|
||||
Series::try_new(
|
||||
&schema,
|
||||
@@ -5327,12 +5355,7 @@ impl ScriptedEvaluated {
|
||||
/// The child plan over `partitions`, one partition per list of chunks.
|
||||
fn plan(partitions: Vec<Vec<(Series, bool)>>) -> Arc<dyn ExecutionPlan> {
|
||||
let series_schema = evaluated_schema();
|
||||
let frame = pack_evaluated_series(
|
||||
Box::pin(futures::stream::empty()),
|
||||
Arc::clone(&series_schema),
|
||||
)
|
||||
.expect("an evaluated schema declares a frame")
|
||||
.schema();
|
||||
let frame = evaluated_frame_schema();
|
||||
Arc::new(Self {
|
||||
series_schema,
|
||||
properties: Arc::new(PlanProperties::new(
|
||||
@@ -5405,10 +5428,16 @@ impl ExecutionPlan for ScriptedEvaluated {
|
||||
/// The tree's input node, bound to the grid: what a Fused reads when its child already decided the
|
||||
/// values.
|
||||
fn evaluated_input() -> NativeNode {
|
||||
evaluated_input_of(0)
|
||||
}
|
||||
|
||||
/// The grid-bound input node reading source `source_index`: the leaf a Fused decodes an evaluated
|
||||
/// frame into, for a tree whose child already decided the values.
|
||||
fn evaluated_input_of(source_index: usize) -> NativeNode {
|
||||
let evaluated = evaluated_of(&raw_schema(), &grid());
|
||||
NativeNode {
|
||||
expr: NativeExpr::Input(BoundInput {
|
||||
source_index: 0,
|
||||
source_index,
|
||||
output: evaluated.clone(),
|
||||
ordering: SeriesOrdering::Contiguous,
|
||||
}),
|
||||
@@ -7035,3 +7064,469 @@ async fn a_match_over_two_canonical_owners_is_refused_instead_of_answered_locall
|
||||
.await
|
||||
.expect("the match is refused instead of waiting for a partition nobody reads");
|
||||
}
|
||||
|
||||
/// `left - right` between two evaluated sources: both operands are grid-bound input leaves, so the
|
||||
/// node decodes an evaluated frame from each child and has to keep the two apart.
|
||||
///
|
||||
/// The subtraction makes the answer depend on which side is which - the same operands read the other
|
||||
/// way round answer the negation of every value - and the values themselves are the caller's, so a
|
||||
/// chunk read as the other source's data shows up as a wrong value instead of a plausible one.
|
||||
fn evaluated_binary_tree(op: BinaryOp, left_source: usize, right_source: usize) -> NativeTree {
|
||||
let left = evaluated_input_of(left_source);
|
||||
let right = evaluated_input_of(right_source);
|
||||
let output = crate::vector_match::binary_output_schema(
|
||||
left.output.samples().expect("an input produces samples"),
|
||||
right.output.samples().expect("an input produces samples"),
|
||||
)
|
||||
.expect("both operands are evaluated on one grid");
|
||||
NativeTree::try_new(NativeNode {
|
||||
expr: NativeExpr::Binary {
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
matching: BinaryMatching {
|
||||
op,
|
||||
return_bool: false,
|
||||
labels: MatchingLabels::On(vec![Arc::from(HOST)]),
|
||||
cardinality: Cardinality::OneToOne,
|
||||
fill: FillValues::default(),
|
||||
},
|
||||
},
|
||||
output: NativeType::Samples(output),
|
||||
})
|
||||
.expect("a match over two evaluated sources is a legal tree")
|
||||
}
|
||||
|
||||
/// `left or right` between two evaluated sources: every series of the left, then the right's series
|
||||
/// that no left series matches.
|
||||
///
|
||||
/// `or` hands the right side's series on under their own label sets, so the right side's data is
|
||||
/// observable even when the left has no series at all - which is what an empty source beside a
|
||||
/// non-empty one needs, since a subtraction of nothing from nothing answers nothing either way.
|
||||
fn evaluated_or_tree(left_source: usize, right_source: usize) -> NativeTree {
|
||||
let left = evaluated_input_of(left_source);
|
||||
let right = evaluated_input_of(right_source);
|
||||
let output = left.output.clone();
|
||||
NativeTree::try_new(NativeNode {
|
||||
expr: NativeExpr::Set {
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
op: BoundSetOp {
|
||||
op: SetOp::Or,
|
||||
labels: MatchingLabels::On(vec![Arc::from(HOST)]),
|
||||
},
|
||||
},
|
||||
output,
|
||||
})
|
||||
.expect("a set operation over two evaluated sources is a legal tree")
|
||||
}
|
||||
|
||||
/// The physical node of `tree` over its two evaluated sources, `left` and `right`.
|
||||
fn evaluated_two_source_plan(
|
||||
tree: &NativeTree,
|
||||
output_schema: SchemaRef,
|
||||
left: Arc<dyn ExecutionPlan>,
|
||||
right: Arc<dyn ExecutionPlan>,
|
||||
) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
|
||||
let node = FusedSeries::try_new(
|
||||
Arc::from(PROMQL),
|
||||
tree.clone(),
|
||||
binding(tree),
|
||||
vec![
|
||||
input_plan(evaluated_frame_schema()),
|
||||
input_plan(evaluated_frame_schema()),
|
||||
],
|
||||
output_schema.to_dfschema_ref()?,
|
||||
)?;
|
||||
node.to_execution_plan(vec![
|
||||
(left, RawLabelSource::Explicit, SeriesOrdering::Contiguous),
|
||||
(right, RawLabelSource::Explicit, SeriesOrdering::Contiguous),
|
||||
])
|
||||
}
|
||||
|
||||
/// [`GRID_LEN`] values starting at `first`, one per grid position: `first + position`.
|
||||
fn climb(first: f64) -> Vec<Option<f64>> {
|
||||
(0..GRID_LEN as usize)
|
||||
.map(|position| Some(first + position as f64))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `(time, value, host)` rows of a match's answer, ordered by timestamp.
|
||||
///
|
||||
/// A match's output has no metric-name column ([`binary_output_schema`]), so this reads the three
|
||||
/// columns it does have rather than going through [`rows`], which requires a name column.
|
||||
fn binary_rows(batches: &[RecordBatch]) -> Vec<(i64, Option<f64>, Option<String>)> {
|
||||
let mut rows = Vec::new();
|
||||
for batch in batches {
|
||||
let time = batch
|
||||
.column_by_name(TIME)
|
||||
.expect("a binary batch has a time column")
|
||||
.as_any()
|
||||
.downcast_ref::<TimestampMillisecondArray>()
|
||||
.expect("the time column is a millisecond timestamp");
|
||||
let value = batch
|
||||
.column_by_name(VALUE)
|
||||
.expect("a binary batch has the field column")
|
||||
.as_any()
|
||||
.downcast_ref::<Float64Array>()
|
||||
.expect("the field column is Float64");
|
||||
let host = batch
|
||||
.column_by_name(HOST)
|
||||
.expect("a binary batch has the tag column")
|
||||
.as_any()
|
||||
.downcast_ref::<StringArray>()
|
||||
.expect("the tag column is Utf8");
|
||||
for row in 0..batch.num_rows() {
|
||||
rows.push((
|
||||
time.value(row),
|
||||
value.is_valid(row).then(|| value.value(row)),
|
||||
host.is_valid(row).then(|| host.value(row).to_string()),
|
||||
));
|
||||
}
|
||||
}
|
||||
rows.sort_by_key(|row| row.0);
|
||||
rows
|
||||
}
|
||||
|
||||
/// A staged child that hands over `chunks` and then fails: an evaluated producer whose stream ends
|
||||
/// in an error rather than in EOF.
|
||||
fn staged_evaluated_with_error(
|
||||
chunks: Vec<(Series, bool)>,
|
||||
message: &'static str,
|
||||
) -> Arc<dyn ExecutionPlan> {
|
||||
let schema = evaluated_frame_schema();
|
||||
staged(schema, move || {
|
||||
let items = chunks
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(Ok)
|
||||
.chain(std::iter::once(Err(BoxedError::new(
|
||||
common_query::error::Error::from(DataFusionError::Execution(message.to_string())),
|
||||
))))
|
||||
.collect::<Vec<Result<(Series, bool), BoxedError>>>();
|
||||
let source: SendableEvaluatedSeriesStream = Box::pin(futures::stream::iter(items));
|
||||
pack_evaluated_series(source, evaluated_schema())
|
||||
.expect("an evaluated schema declares a frame")
|
||||
})
|
||||
}
|
||||
|
||||
/// One evaluated source's gather, reading `chunks` from a single partition, charged to `pool`.
|
||||
fn evaluated_gather_of(
|
||||
source: usize,
|
||||
chunks: Vec<(Series, bool)>,
|
||||
pool: &Arc<dyn MemoryPool>,
|
||||
) -> EvaluatedGather {
|
||||
let stream: SendableEvaluatedSeriesStream = Box::pin(futures::stream::iter(
|
||||
chunks.into_iter().map(Ok::<_, BoxedError>),
|
||||
));
|
||||
let reservation = MemoryConsumer::new(format!("test.evaluated[{source}]")).register(pool);
|
||||
EvaluatedGather::new(source, vec![stream], reservation)
|
||||
}
|
||||
|
||||
/// Two evaluated sources are read side by side, and neither side's frames answer as the other's.
|
||||
///
|
||||
/// The two children carry different label sets *and* different values: `{host=web-1, zone=west}` on
|
||||
/// the left and `{host=web-1, zone=east}` on the right, so the `on(host)` match pairs them and the
|
||||
/// answer is `left - right` under `{host=web-1}`. This is the case the node used to refuse and then
|
||||
/// mishandle: reading source 1's frames as source 0's puts both series in the left operand - two
|
||||
/// series under one label set, which the runtime refuses - and leaves the right operand empty. A
|
||||
/// swap of the two sides answers `right - left`, so the sign and the offset below are both part of
|
||||
/// what this pins.
|
||||
#[tokio::test]
|
||||
async fn two_evaluated_sources_answer_each_sides_data_under_its_own_identity() {
|
||||
let tree = evaluated_binary_tree(BinaryOp::Sub, 0, 1);
|
||||
let left = ScriptedEvaluated::plan(vec![vec![evaluated_chunk_with(
|
||||
&metric(&[(HOST, "web-1"), (ZONE, "west")], Some(METRIC)),
|
||||
0,
|
||||
climb(100.0),
|
||||
true,
|
||||
)]]);
|
||||
let right = ScriptedEvaluated::plan(vec![vec![evaluated_chunk_with(
|
||||
&metric(&[(HOST, "web-1"), (ZONE, "east")], Some(METRIC)),
|
||||
0,
|
||||
vec![Some(7.0); GRID_LEN as usize],
|
||||
true,
|
||||
)]]);
|
||||
|
||||
let exec = evaluated_two_source_plan(&tree, binary_output_schema(), left, right)
|
||||
.expect("the node accepts two evaluated sources");
|
||||
assert_eq!(
|
||||
1,
|
||||
exec.properties().partitioning.partition_count(),
|
||||
"more than one source is one execution, which is the path this test reads"
|
||||
);
|
||||
let batches = collect(exec, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("the two-source tree runs");
|
||||
let answered = binary_rows(&batches);
|
||||
|
||||
assert_eq!(
|
||||
grid_timestamps(),
|
||||
answered.iter().map(|row| row.0).collect::<Vec<_>>(),
|
||||
"one row per grid position: {answered:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
(0..GRID_LEN as usize)
|
||||
.map(|position| Some(100.0 + position as f64 - 7.0))
|
||||
.collect::<Vec<_>>(),
|
||||
answered.iter().map(|row| row.1).collect::<Vec<_>>(),
|
||||
"`left - right`, so the left side's offset is positive and the right side's is subtracted"
|
||||
);
|
||||
assert!(
|
||||
answered.iter().all(|row| row.2.as_deref() == Some("web-1")),
|
||||
"the match is filed under the label set it matched on: {answered:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Two evaluated sources may carry one label set, and the answer still comes from the right sides.
|
||||
///
|
||||
/// Both children carry `{host=web-1, zone=west}` - the same label set - with *different* values, so a
|
||||
/// chunk re-stamped with the other source's index collides inside one operand (two series under one
|
||||
/// label set, which the runtime refuses) or pairs a side with itself (which answers the difference of
|
||||
/// two different values, not zero). Either way the assertion below is about which source a chunk was
|
||||
/// read from, and nothing else.
|
||||
#[tokio::test]
|
||||
async fn two_evaluated_sources_with_one_label_set_do_not_cross_their_indices() {
|
||||
let tree = evaluated_binary_tree(BinaryOp::Sub, 0, 1);
|
||||
let shared = metric(&[(HOST, "web-1"), (ZONE, "west")], Some(METRIC));
|
||||
let left = ScriptedEvaluated::plan(vec![vec![evaluated_chunk_with(
|
||||
&shared,
|
||||
0,
|
||||
climb(100.0),
|
||||
true,
|
||||
)]]);
|
||||
let right = ScriptedEvaluated::plan(vec![vec![evaluated_chunk_with(
|
||||
&shared,
|
||||
0,
|
||||
climb(7.0),
|
||||
true,
|
||||
)]]);
|
||||
|
||||
let exec = evaluated_two_source_plan(&tree, binary_output_schema(), left, right)
|
||||
.expect("the node accepts two evaluated sources");
|
||||
let batches = collect(exec, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("the two-source tree runs");
|
||||
let answered = binary_rows(&batches);
|
||||
|
||||
assert_eq!(
|
||||
grid_timestamps(),
|
||||
answered.iter().map(|row| row.0).collect::<Vec<_>>(),
|
||||
"the one label set is answered at every grid position: {answered:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
vec![Some(93.0); GRID_LEN as usize],
|
||||
answered.iter().map(|row| row.1).collect::<Vec<_>>(),
|
||||
"each position answers `(100 + p) - (7 + p)`: the two sources' chunks paired by position, \
|
||||
not one side paired with itself"
|
||||
);
|
||||
assert!(
|
||||
answered.iter().all(|row| row.2.as_deref() == Some("web-1")),
|
||||
"one series, not two under the same label set: {answered:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The node ends when *every* evaluated source ended, not when the first one does.
|
||||
///
|
||||
/// The left source answers its whole series in one chunk and ends immediately, while the right one
|
||||
/// answers the same positions in [`GRID_LEN`] chunks and closes last. Ending the node on the left
|
||||
/// source's end would end the runtime's input while the right operand is still open, which the
|
||||
/// runtime reports as a truncated input instead of answering - so the row count and the values below
|
||||
/// are what tell a correct end from a premature one.
|
||||
#[tokio::test]
|
||||
async fn one_source_ending_first_does_not_end_the_other_sources_frames() {
|
||||
let tree = evaluated_binary_tree(BinaryOp::Sub, 0, 1);
|
||||
let shared = metric(&[(HOST, "web-1")], Some(METRIC));
|
||||
let left = ScriptedEvaluated::plan(vec![vec![evaluated_chunk_with(
|
||||
&shared,
|
||||
0,
|
||||
climb(100.0),
|
||||
true,
|
||||
)]]);
|
||||
let right = ScriptedEvaluated::plan(vec![
|
||||
(0..GRID_LEN as usize)
|
||||
.map(|position| {
|
||||
evaluated_chunk_with(
|
||||
&shared,
|
||||
position,
|
||||
vec![Some(7.0 + position as f64)],
|
||||
position == GRID_LEN as usize - 1,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
]);
|
||||
|
||||
let exec = evaluated_two_source_plan(&tree, binary_output_schema(), left, right)
|
||||
.expect("the node accepts two evaluated sources");
|
||||
let batches = collect(exec, SessionContext::default().task_ctx())
|
||||
.await
|
||||
.expect("the right source is read to its end after the left one ended");
|
||||
let answered = binary_rows(&batches);
|
||||
|
||||
assert_eq!(
|
||||
GRID_LEN as usize,
|
||||
answered.len(),
|
||||
"every position the longer source carries is answered: {answered:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
grid_timestamps(),
|
||||
answered.iter().map(|row| row.0).collect::<Vec<_>>(),
|
||||
"the positions of the source that ended later are all there"
|
||||
);
|
||||
assert_eq!(
|
||||
vec![Some(93.0); GRID_LEN as usize],
|
||||
answered.iter().map(|row| row.1).collect::<Vec<_>>(),
|
||||
"the answer covers the whole grid rather than the first chunk"
|
||||
);
|
||||
}
|
||||
|
||||
/// A source that fails mid-stream surfaces its error instead of ending the node quietly.
|
||||
///
|
||||
/// The failing child hands over one chunk and then an error, and the other source is still open when
|
||||
/// it does. A merge that dropped the error for the source's EOF would answer `None` here, and one
|
||||
/// that never polled the failing source again would hang; the timeout tells those apart from a run
|
||||
/// that reports the error it was given.
|
||||
#[tokio::test]
|
||||
async fn an_evaluated_sources_error_ends_the_two_source_node() {
|
||||
let tree = evaluated_binary_tree(BinaryOp::Sub, 0, 1);
|
||||
let shared = metric(&[(HOST, "web-1")], Some(METRIC));
|
||||
let left = ScriptedEvaluated::plan(vec![vec![evaluated_chunk_with(
|
||||
&shared,
|
||||
0,
|
||||
climb(100.0),
|
||||
true,
|
||||
)]]);
|
||||
let right = staged_evaluated_with_error(
|
||||
vec![evaluated_chunk_with(&shared, 0, climb(7.0), true)],
|
||||
"evaluated source failed",
|
||||
);
|
||||
|
||||
let exec = evaluated_two_source_plan(&tree, binary_output_schema(), left, right)
|
||||
.expect("the node accepts two evaluated sources");
|
||||
let error = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
collect(exec, SessionContext::default().task_ctx()),
|
||||
)
|
||||
.await
|
||||
.expect("the node waited on a source that had already failed")
|
||||
.expect_err("the failing source's error is the node's answer");
|
||||
let message = error_chain(&error);
|
||||
assert!(
|
||||
message.contains("evaluated source failed"),
|
||||
"reported for another reason: {message}"
|
||||
);
|
||||
}
|
||||
|
||||
/// An empty evaluated source beside a non-empty one still terminates and answers the other's data.
|
||||
///
|
||||
/// Two sources of different shapes meet here: the left one holds no chunk in either of its two
|
||||
/// partitions, the right one holds a series. `or` hands the right side's series on unchanged where no
|
||||
/// left series matches it, so the right side's data is exactly what the node has to produce - a node
|
||||
/// that ended on the empty source's EOF, or that mixed the two sources' streams, answers nothing.
|
||||
#[tokio::test]
|
||||
async fn an_empty_evaluated_source_beside_a_non_empty_one_answers_the_non_empty_side() {
|
||||
let tree = evaluated_or_tree(0, 1);
|
||||
let empty = ScriptedEvaluated::plan(vec![Vec::new(), Vec::new()]);
|
||||
let right = ScriptedEvaluated::plan(vec![vec![evaluated_chunk_with(
|
||||
&metric(&[(HOST, "web-1")], Some(METRIC)),
|
||||
0,
|
||||
climb(500.0),
|
||||
true,
|
||||
)]]);
|
||||
|
||||
let exec = evaluated_two_source_plan(&tree, output_schema(), empty, right)
|
||||
.expect("the node accepts two evaluated sources");
|
||||
let batches = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
collect(exec, SessionContext::default().task_ctx()),
|
||||
)
|
||||
.await
|
||||
.expect("the node hung on the empty source")
|
||||
.expect("the node answers the non-empty source");
|
||||
let answered = rows(&batches);
|
||||
|
||||
assert_eq!(
|
||||
(0..GRID_LEN as usize)
|
||||
.map(|position| Some(500.0 + position as f64))
|
||||
.collect::<Vec<_>>(),
|
||||
answered.iter().map(|row| row.1).collect::<Vec<_>>(),
|
||||
"the non-empty side's values come out unchanged: {answered:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
grid_timestamps(),
|
||||
answered.iter().map(|row| row.0).collect::<Vec<_>>(),
|
||||
"the whole grid of the non-empty side is answered: {answered:?}"
|
||||
);
|
||||
assert!(
|
||||
answered.iter().all(|row| row.2.as_deref() == Some("web-1")),
|
||||
"the answer keeps the non-empty side's own label set: {answered:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A source that always has a chunk ready does not starve a second source.
|
||||
///
|
||||
/// Both gathers here answer on every poll - nothing is pending to force a rotation - so this reads
|
||||
/// the merge's own order: every sweep starts at the source after the one that last handed a chunk
|
||||
/// over, which makes two always-ready sources alternate. A merge that drained one source before
|
||||
/// polling the other would hand over all eight of `busy`'s chunks before either of `quiet`'s, and
|
||||
/// the assertion below would fail on the second feed. The chunks carry their source's own hosts, so
|
||||
/// the order also says which source each chunk was read from.
|
||||
#[tokio::test]
|
||||
async fn an_always_ready_evaluated_source_does_not_starve_a_second_source() {
|
||||
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
|
||||
let busy = (0..8)
|
||||
.map(|index| {
|
||||
evaluated_chunk_with(
|
||||
&metric(&[(HOST, &format!("busy-{index}"))], Some(METRIC)),
|
||||
0,
|
||||
vec![Some(100.0 + index as f64)],
|
||||
true,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let quiet = (0..2)
|
||||
.map(|index| {
|
||||
evaluated_chunk_with(
|
||||
&metric(&[(HOST, &format!("quiet-{index}"))], Some(METRIC)),
|
||||
0,
|
||||
vec![Some(900.0 + index as f64)],
|
||||
true,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut sources = EvaluatedSources::new(vec![
|
||||
evaluated_gather_of(0, busy, &pool),
|
||||
evaluated_gather_of(1, quiet, &pool),
|
||||
]);
|
||||
|
||||
let mut order = Vec::new();
|
||||
let mut hosts = Vec::new();
|
||||
while let Some(feed) = sources.next().await {
|
||||
let feed = feed.expect("a scripted gather does not fail");
|
||||
let FusedChunk::Evaluated(chunk) = feed.chunk else {
|
||||
panic!("an evaluated gather hands over evaluated chunks");
|
||||
};
|
||||
order.push(feed.source);
|
||||
hosts.push(
|
||||
chunk
|
||||
.series
|
||||
.metric
|
||||
.get(HOST)
|
||||
.expect("every scripted series names its host")
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
vec![0, 1, 0, 1, 0, 0, 0, 0, 0, 0],
|
||||
order,
|
||||
"the two always-ready sources alternate instead of one being drained first"
|
||||
);
|
||||
assert_eq!(
|
||||
vec![
|
||||
"busy-0", "quiet-0", "busy-1", "quiet-1", "busy-2", "busy-3", "busy-4", "busy-5",
|
||||
"busy-6", "busy-7"
|
||||
],
|
||||
hosts,
|
||||
"each chunk is handed over under the source it was read from"
|
||||
);
|
||||
}
|
||||
|
||||
+391
-21
@@ -40,7 +40,7 @@ use crate::map::MathOp;
|
||||
use crate::map_label::LabelRewrite;
|
||||
use crate::range_eval::{RangeFunction, RangeWindow};
|
||||
use crate::select::SortOrder;
|
||||
use crate::vector_match::{BinaryMatching, BinaryOp, MatchingLabels, SetOp};
|
||||
use crate::vector_match::{BinaryMatching, BinaryOp, Cardinality, MatchingLabels, SetOp};
|
||||
|
||||
/// What one node produces.
|
||||
///
|
||||
@@ -857,11 +857,43 @@ pub fn needs_single_execution(node: &NativeNode) -> bool {
|
||||
needs_single_execution_in(node, &[])
|
||||
}
|
||||
|
||||
/// Two fused sources whose producers this execution reads in step: the routing placed them
|
||||
/// identically, and their outputs name no series.
|
||||
///
|
||||
/// This is a *joint* fact about a pair and cannot be derived inside the tree that consumes them.
|
||||
/// An [`NativeExpr::Input`] over evaluated samples answers `None` to [`output_has_metric_name`],
|
||||
/// because whether its label sets still carry a metric name was decided by the node that built
|
||||
/// them, which is not in this tree. So the layer that builds those producers asks each producer's
|
||||
/// own root and states the answer here.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct CoPartitionedPair {
|
||||
/// The left fused source index.
|
||||
pub left: usize,
|
||||
/// The right fused source index.
|
||||
pub right: usize,
|
||||
/// Both producers' outputs carry no metric name, proved where those producers were built.
|
||||
pub name_free: bool,
|
||||
}
|
||||
|
||||
impl CoPartitionedPair {
|
||||
/// Whether this pair names the two sources `left` and `right`, in either orientation.
|
||||
///
|
||||
/// The two orientations are one pair: a routing that sends source `i`'s partners to source `j`'s
|
||||
/// execution sends `j`'s to `i`'s too, and which side of the match a source sits on is the
|
||||
/// query's choice rather than the routing's.
|
||||
fn joins(&self, left: usize, right: usize) -> bool {
|
||||
(self.left == left && self.right == right) || (self.left == right && self.right == left)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `node` answers a value for the whole vector, given what the caller knows about where the
|
||||
/// sources below it sit.
|
||||
/// sources below it sit and which of them route identically.
|
||||
///
|
||||
/// `boundary` is the same slice [`NativeNode::properties`] takes: the facts of the fused inputs the
|
||||
/// tree was compiled over, indexed by `source_index`.
|
||||
/// tree was compiled over, indexed by `source_index`. `co_partitioned` is what the caller proved
|
||||
/// about pairs of those sources ([`CoPartitionedPair`]): that the routing placed the two identically,
|
||||
/// and that both producers' outputs name no series. It is the fact a match needs and a merge does not
|
||||
/// ([`match_is_co_partitioned`]), and it is read by no other node.
|
||||
///
|
||||
/// A `Merge` needs every piece of ONE canonical label set, and one execution is one way of having
|
||||
/// them - but which way applies is not this predicate's question. A merge's own need is therefore
|
||||
@@ -877,49 +909,78 @@ pub fn needs_single_execution(node: &NativeNode) -> bool {
|
||||
/// is the caller's. Two series that agree on `on(host)` can differ in every other label and sit
|
||||
/// under two canonical keys, so two owner partitions can each hold one series of that match group,
|
||||
/// pair them locally, and never run the duplicate-series check over the real group: the error a
|
||||
/// whole match reports is silently not reported. A match therefore needs one execution unless both
|
||||
/// sides are proven to sit in it ([`matching_co_located`]). A broadcast is not a match, so a
|
||||
/// constant's side is not asked for that proof.
|
||||
pub fn needs_single_execution_in(node: &NativeNode, boundary: &[NativeProperties]) -> bool {
|
||||
/// whole match reports is silently not reported. A match therefore needs one execution unless one
|
||||
/// of two proofs says otherwise. A broadcast is not a match, so a constant's side is not asked for
|
||||
/// either.
|
||||
///
|
||||
/// The first proof is the per-side one ([`matching_co_located`]): each side's series are all in this
|
||||
/// execution, so every pair of them is here too. The second is two-sided
|
||||
/// ([`match_is_co_partitioned`]): each side's series are *not* all here, but the sources the two
|
||||
/// sides read route identically and the match pairs by exactly the key that routing used, so a pair
|
||||
/// built from this partition is the pair the whole match would have built. The two answer different
|
||||
/// questions - "is everything here?" and "is the partner of what is here also here?" - and neither
|
||||
/// implies the other: a per-key placement proves each canonical label set whole without proving a
|
||||
/// match group whole, and a co-partitioned pair proves a match group whole without proving either
|
||||
/// side whole.
|
||||
pub fn needs_single_execution_in_co(
|
||||
node: &NativeNode,
|
||||
boundary: &[NativeProperties],
|
||||
co_partitioned: &[CoPartitionedPair],
|
||||
) -> bool {
|
||||
match &node.expr {
|
||||
NativeExpr::Input(_) | NativeExpr::Scalar(_) => false,
|
||||
NativeExpr::Instant { input, .. }
|
||||
| NativeExpr::Window { input, .. }
|
||||
| NativeExpr::Map { input, .. }
|
||||
| NativeExpr::Timestamp { input } => needs_single_execution_in(input, boundary),
|
||||
| NativeExpr::Timestamp { input } => {
|
||||
needs_single_execution_in_co(input, boundary, co_partitioned)
|
||||
}
|
||||
// `info` pairs each base series with the info series that share its identifying labels,
|
||||
// which is a match by a label set of the caller's choosing rather than by a canonical key -
|
||||
// the same reason a two-vector `Binary` needs one execution unless both sides are proven to
|
||||
// sit in it.
|
||||
NativeExpr::Info { base, info, .. } => {
|
||||
needs_single_execution_in(base, boundary)
|
||||
|| needs_single_execution_in(info, boundary)
|
||||
needs_single_execution_in_co(base, boundary, co_partitioned)
|
||||
|| needs_single_execution_in_co(info, boundary, co_partitioned)
|
||||
|| !(matching_co_located(base, boundary) && matching_co_located(info, boundary))
|
||||
}
|
||||
NativeExpr::Aggregate { input, op } => {
|
||||
op.stage == AggregateStage::Complete || needs_single_execution_in(input, boundary)
|
||||
op.stage == AggregateStage::Complete
|
||||
|| needs_single_execution_in_co(input, boundary, co_partitioned)
|
||||
}
|
||||
// A match pairs the series of both sides by the label set its modifiers name, which is not
|
||||
// the canonical key a placement proves whole ([`matching_co_located`]), so it needs one
|
||||
// execution unless both sides are already in it. A broadcast is not a match: it pairs a
|
||||
// vector with one value, so the constant's side holds no series to pair and proves nothing it
|
||||
// was asked for - `x > 0` and `x * 2` stay as parallel as the vector side.
|
||||
NativeExpr::Binary { left, right, .. } => {
|
||||
// execution unless both sides are already in it - or unless the two-sided proof says the
|
||||
// match pairs by the key the sides' sources were routed by ([`match_is_co_partitioned`]).
|
||||
// A broadcast is not a match: it pairs a vector with one value, so the constant's side holds
|
||||
// no series to pair and proves nothing it was asked for - `x > 0` and `x * 2` stay as
|
||||
// parallel as the vector side.
|
||||
NativeExpr::Binary {
|
||||
left,
|
||||
right,
|
||||
matching,
|
||||
} => {
|
||||
let both_vectors = matches!(
|
||||
(&left.output, &right.output),
|
||||
(NativeType::Samples(_), NativeType::Samples(_))
|
||||
);
|
||||
needs_single_execution_in(left, boundary)
|
||||
|| needs_single_execution_in(right, boundary)
|
||||
needs_single_execution_in_co(left, boundary, co_partitioned)
|
||||
|| needs_single_execution_in_co(right, boundary, co_partitioned)
|
||||
|| (both_vectors
|
||||
&& !(matching_co_located(left, boundary)
|
||||
&& matching_co_located(right, boundary)))
|
||||
&& matching_co_located(right, boundary))
|
||||
&& !match_is_co_partitioned(left, right, matching, co_partitioned))
|
||||
}
|
||||
// A set operation keeps samples of two evaluated vectors, so both sides are always matched:
|
||||
// `validate` refuses a scalar on either side and there is no broadcast form of it.
|
||||
//
|
||||
// It gains no two-sided proof this round. A set operation keeps each side's samples under the
|
||||
// labels they arrived with, so what it compares is the two sides' own identities, and a
|
||||
// per-partition answer would have to show that those identities - not the match's modifiers,
|
||||
// which a set operation does not have - are the ones the routing used.
|
||||
NativeExpr::Set { left, right, .. } => {
|
||||
needs_single_execution_in(left, boundary)
|
||||
|| needs_single_execution_in(right, boundary)
|
||||
needs_single_execution_in_co(left, boundary, co_partitioned)
|
||||
|| needs_single_execution_in_co(right, boundary, co_partitioned)
|
||||
|| !(matching_co_located(left, boundary) && matching_co_located(right, boundary))
|
||||
}
|
||||
NativeExpr::Vector { .. } => true,
|
||||
@@ -930,10 +991,103 @@ pub fn needs_single_execution_in(node: &NativeNode, boundary: &[NativeProperties
|
||||
// tree needs from an execution, and a merge's own need is its input's. Whether the merge can
|
||||
// be *placed* here is `merges_are_placeable_in`, asked by the caller that knows the
|
||||
// placement.
|
||||
NativeExpr::Merge { input } => needs_single_execution_in(input, boundary),
|
||||
NativeExpr::Merge { input } => {
|
||||
needs_single_execution_in_co(input, boundary, co_partitioned)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `node` answers a value for the whole vector, given what the caller knows about where the
|
||||
/// sources below it sit but nothing about how they route.
|
||||
///
|
||||
/// This is [`needs_single_execution_in_co`] with no co-partitioned pair: a caller that has not proved
|
||||
/// two sources route identically has not proved a match between them can run per partition, so the
|
||||
/// two-sided proof is never given a pair to fire on and the answer is the per-side one it always was.
|
||||
pub fn needs_single_execution_in(node: &NativeNode, boundary: &[NativeProperties]) -> bool {
|
||||
needs_single_execution_in_co(node, boundary, &[])
|
||||
}
|
||||
|
||||
/// Whether a match between two routed inputs pairs its series by the key their sources were routed
|
||||
/// by, so one execution per partition answers it.
|
||||
///
|
||||
/// This is a *two-sided* proof, and the question it asks is neither the per-side one
|
||||
/// ([`matching_co_located`]: are both sides' series all in this execution?) nor a merge's
|
||||
/// ([`pieces_co_located`]: are the pieces of every canonical label set here?). It asks: does the key
|
||||
/// this match pairs by name the same groups the placement grouped the two sources by?
|
||||
///
|
||||
/// That question has two halves, and they are answered by two different parties.
|
||||
///
|
||||
/// The *tree* half is answered here. A placement by canonical key partitions by the canonical label
|
||||
/// set, which is `__name__` plus the ordinary labels - the key a [`NativeExpr::Merge`] groups by -
|
||||
/// while a match pairs by the label set its modifiers name: the default
|
||||
/// [`MatchingLabels::Ignoring`] with no label is every label *except* `__name__`. So
|
||||
/// `m1{ns="a"} / m2{ns="a"}` is two canonical label sets and one match group: routing by canonical
|
||||
/// key sends the two partners to different partitions, each partition finds no partner, and the
|
||||
/// match answers nothing where the whole match would answer a value. The two keys coincide exactly
|
||||
/// when neither side's series carries a metric name, because then the canonical key *is* the set of
|
||||
/// ordinary labels. Which operands and which modifiers make the keys coincide is the tree's question,
|
||||
/// and it is the one this function settles.
|
||||
///
|
||||
/// The *producer* half is [`CoPartitionedPair::name_free`], and it is supplied by whoever could
|
||||
/// observe it. It cannot be derived here: both operands of the shape this proof exists to serve are
|
||||
/// an [`NativeExpr::Input`] over evaluated samples, whose label sets another execution built, so
|
||||
/// [`output_has_metric_name`] answers `None` for them - it has no node to read the name off. The layer
|
||||
/// that builds those producers asks each producer's own root, where the answer is a function of the
|
||||
/// tree in front of it, and states it on the pair. Reading `None` as "no name" instead would be the
|
||||
/// guess that makes a named match look name-free, which is exactly the silent-empty-answer bug: the
|
||||
/// match would be run per partition, find no partner, and answer nothing.
|
||||
///
|
||||
/// `co_partitioned` is therefore what the caller proved about the pair, and both halves are required.
|
||||
/// Co-partitioned sources whose series carry a name still pair by a key no partition holds whole, and
|
||||
/// name-free sides whose sources are not co-partitioned can still have their partners in two
|
||||
/// executions.
|
||||
///
|
||||
/// The operands are read strictly: this round proves nothing about a node between the routed input
|
||||
/// and the match. A per-series node above the input hands the label set it read on unchanged, so the
|
||||
/// identity the router used would still be the identity the match sees through it, but a fold, a
|
||||
/// name-dropping window or a label rewrite does not: it invents an identity the routing never saw, and
|
||||
/// a proof about the routed key would then be about a key the match no longer reads. Looking through
|
||||
/// those nodes - only the ones that provably keep the identity the router used - is a later round's
|
||||
/// work, and answering it by assuming they all keep it is the silent-empty-answer bug this proof
|
||||
/// exists to prevent.
|
||||
///
|
||||
/// Every conjunct below is required:
|
||||
///
|
||||
/// 1. each operand is the routed input itself ([`NativeExpr::Input`]);
|
||||
/// 2. the caller proved those two sources co-partitioned, either way round;
|
||||
/// 3. the match is the default one - [`MatchingLabels::Ignoring`] with no label, whose key is every
|
||||
/// label but `__name__` - so its key is the canonical key of a name-free series;
|
||||
/// 4. it is one-to-one: `group_left`/`group_right` copy the one side's labels into each result, so a
|
||||
/// result's identity is not the many side's and the routed key does not name it;
|
||||
/// 5. that pair says both producers are name-free, which is what makes the canonical key and the
|
||||
/// match key one key. It is per pair, and one named side is enough to break it - which is why the
|
||||
/// pair states the joint fact rather than each side stating its own.
|
||||
pub fn match_is_co_partitioned(
|
||||
left: &NativeNode,
|
||||
right: &NativeNode,
|
||||
matching: &BinaryMatching,
|
||||
co_partitioned: &[CoPartitionedPair],
|
||||
) -> bool {
|
||||
let (NativeExpr::Input(left_input), NativeExpr::Input(right_input)) = (&left.expr, &right.expr)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let (left_source, right_source) = (left_input.source_index, right_input.source_index);
|
||||
let Some(pair) = co_partitioned
|
||||
.iter()
|
||||
.find(|pair| pair.joins(left_source, right_source))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(&matching.labels, MatchingLabels::Ignoring(names) if names.is_empty()) {
|
||||
return false;
|
||||
}
|
||||
if matching.cardinality != Cardinality::OneToOne {
|
||||
return false;
|
||||
}
|
||||
pair.name_free
|
||||
}
|
||||
|
||||
/// Whether every merge in `node` can be answered by an execution placed as `co_located` says.
|
||||
///
|
||||
/// `co_located` is what the caller already decided about the execution this tree will run in:
|
||||
@@ -1492,6 +1646,222 @@ fn broadcast_drops_labels(matching: &BinaryMatching) -> bool {
|
||||
) || matching.return_bool
|
||||
}
|
||||
|
||||
/// Whether every series `node` hands over carries a metric name (`__name__`).
|
||||
///
|
||||
/// This is the fact the two-sided match proof asks of each side ([`match_is_co_partitioned`]): a
|
||||
/// placement routes by the canonical label set, which holds `__name__` when a series has one, while a
|
||||
/// match pairs by the label set its modifiers name. The two keys are the same key only on series
|
||||
/// without a name, so one named side is already enough to make them differ.
|
||||
///
|
||||
/// - `Some(true)`: every series the output holds carries a name.
|
||||
/// - `Some(false)`: no series the output holds carries a name.
|
||||
/// - `None`: this walk cannot decide, which is not a claim in either direction: a consumer that
|
||||
/// needs the fact must read it as "not proved here" rather than as an answer.
|
||||
///
|
||||
/// The answer is derived from the node and the kernels it is bound to, never from a boundary, so a
|
||||
/// shape whose output labels are decided outside the tree answers `None`. The shapes decided in every
|
||||
/// case are the ones whose kernel writes the name away for whatever it read: `timestamp`, a window
|
||||
/// running any function but `last_over_time`/`first_over_time`, a map of the two dropping operations,
|
||||
/// an aggregate or `count_values` whose grouping does not list `__name__`, `absent`, the histogram
|
||||
/// functions, and a two-vector arithmetic or `bool` comparison. The shapes that follow their input
|
||||
/// are the ones that only carry labels through. Four answers are deliberately not given: a
|
||||
/// `label_replace`/`label_join` may write `__name__` or clear it, an input of evaluated samples hands
|
||||
/// on a value another execution built, a one-side-name-free `or`/`and`/`unless` keeps both sides'
|
||||
/// samples, and a `group_left`/`group_right` may copy a name from its one side. Each of those is a
|
||||
/// later fact's question, not this walk's.
|
||||
pub fn output_has_metric_name(node: &NativeNode) -> Option<bool> {
|
||||
match &node.expr {
|
||||
// A scan of raw samples reads one metric: the selector it was bound from names the metric, so
|
||||
// every series it hands over carries that name, and raw samples are the only thing a scan
|
||||
// hands over. The name itself is not in the tree - `BoundInput` holds the source index, the
|
||||
// output type and the ordering, and the compiler keeps the name beside them - so this is the
|
||||
// one input shape the tree can answer for: which type an input is decides whether anything
|
||||
// above it can name a series at all.
|
||||
//
|
||||
// Evaluated samples at an input are another execution's answer: whether its label sets still
|
||||
// carry a name was decided by the node that built them, which is not in this tree. Aggregate
|
||||
// state is not a series at all, and no consumer of this fact has an operand of that type.
|
||||
NativeExpr::Input(binding) => match binding.output.samples() {
|
||||
Some(schema) if schema.eval_grid.is_none() => Some(true),
|
||||
_ => None,
|
||||
},
|
||||
// A constant is one value per grid point and holds no label set, so it carries no name.
|
||||
NativeExpr::Scalar(_) => Some(false),
|
||||
// A selection answers the label set it read, except `timestamp(x)`: `output_metric` in
|
||||
// [`execute`](crate::native::execute) rewrites the labels through `map::drop_metric_name` for
|
||||
// `InstantValue::Timestamp` and clones them for `Sample` and `InfoTimestamp`, which is the
|
||||
// selection `info` reads.
|
||||
NativeExpr::Instant { input, op } => match op.value {
|
||||
InstantValue::Sample | InstantValue::InfoTimestamp => output_has_metric_name(input),
|
||||
InstantValue::Timestamp => Some(false),
|
||||
},
|
||||
// A merge groups the fragments it read by canonical label set and hands each set on as it
|
||||
// arrived, so it writes no label of its own and what it emits carries the name the fragments
|
||||
// carried.
|
||||
NativeExpr::Merge { input } => output_has_metric_name(input),
|
||||
// A window folds values and keeps the label set of the series it read, unless the function
|
||||
// drops the metric name: `RangeFunction::drops_metric_name` holds for every function but
|
||||
// `last_over_time` and `first_over_time`, and `RangeEvaluator::emit` applies it by removing
|
||||
// `METADATA_LABELS` from the label set it hands over.
|
||||
NativeExpr::Window { input, op } => {
|
||||
if op.function.drops_metric_name() {
|
||||
Some(false)
|
||||
} else {
|
||||
output_has_metric_name(input)
|
||||
}
|
||||
}
|
||||
// A map rewrites the label set of every series it is handed. `map_math` and
|
||||
// `map_native_histogram` both end with `drop_metric_name` (see
|
||||
// [`preserves_canonical_identity`]), so their output carries no name whatever it read, while
|
||||
// `label_replace`/`label_join` write a label of the caller's choosing - `__name__` included -
|
||||
// and can empty it, so what a series ends under is not this node's to answer.
|
||||
NativeExpr::Map { input, op } => {
|
||||
if op.ops.is_empty() {
|
||||
// A map with no operation rewrites nothing; `validate` refuses the shape, and
|
||||
// following the input keeps the answer exact rather than reporting a rewrite that is
|
||||
// not there.
|
||||
output_has_metric_name(input)
|
||||
} else if op
|
||||
.ops
|
||||
.iter()
|
||||
.all(|op| matches!(op, MapOp::Math(_) | MapOp::Histogram(_)))
|
||||
{
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
// A timestamp reports each sample's position, and `NativeNode::timestamp` rebuilds the labels
|
||||
// through `map::drop_metric_name` on the way: its output carries no name.
|
||||
NativeExpr::Timestamp { .. } => Some(false),
|
||||
// An aggregate answers its group key, which is `GroupingLabels::apply` in
|
||||
// [`aggregate`](crate::aggregate): `by(names)` keeps the name only when `names` lists it
|
||||
// (`SeriesLabels::keep_only` clears a name the list does not hold) and `without(_)` removes it
|
||||
// whatever `names` says. Partial state is not a series at all, so it carries none.
|
||||
NativeExpr::Aggregate { input, op } => match &node.output {
|
||||
NativeType::Samples(_) => {
|
||||
grouping_keeps_metric_name(&op.group, output_has_metric_name(input))
|
||||
}
|
||||
NativeType::Scalar(_) | NativeType::AggregateState(_) => Some(false),
|
||||
},
|
||||
// A vector operation is decided one operator at a time.
|
||||
//
|
||||
// `topk`, `bottomk`, `limitk`, `limit_ratio` and `sort` hand back series they read under the
|
||||
// labels those series arrived with - `select.rs` rewrites no label - so the input's answer is
|
||||
// theirs. `absent` builds its labels from the argument's matchers and skips `__name__`
|
||||
// (`absent_labels`), `histogram_quantile`/`histogram_fraction` remove `METADATA_LABELS` from
|
||||
// each group they read (`histogram_eval`), and `count_values` answers a grouping's label sets
|
||||
// as an aggregate does.
|
||||
NativeExpr::Vector { input, op } => match op {
|
||||
BoundVectorOp::TopK { .. }
|
||||
| BoundVectorOp::LimitK { .. }
|
||||
| BoundVectorOp::LimitRatio { .. }
|
||||
| BoundVectorOp::Sort(_) => output_has_metric_name(input),
|
||||
BoundVectorOp::Absent { .. } | BoundVectorOp::Histogram(_) => Some(false),
|
||||
BoundVectorOp::CountValues { group, .. } => {
|
||||
grouping_keeps_metric_name(group, output_has_metric_name(input))
|
||||
}
|
||||
},
|
||||
// A binary operation answers under the label set `result_metric` builds in
|
||||
// [`vector_match`](crate::vector_match), which is the many side's labels and the modifiers'
|
||||
// rewrite of them.
|
||||
NativeExpr::Binary {
|
||||
left,
|
||||
right,
|
||||
matching,
|
||||
} => match (&left.output, &right.output) {
|
||||
// Two constants make a constant, which holds no label set.
|
||||
(NativeType::Scalar(_), NativeType::Scalar(_)) => Some(false),
|
||||
// A broadcast reaches each series of its vector side as it is, unless the operation drops
|
||||
// the metric name on the way: arithmetic and a `bool` comparison do, a filtering
|
||||
// comparison keeps the label set it read (`BroadcastRuntime::drops_labels`, which
|
||||
// [`broadcast_drops_labels`] restates).
|
||||
(NativeType::Scalar(_), _) | (_, NativeType::Scalar(_)) => {
|
||||
let vector = if left.output.samples().is_some() {
|
||||
left
|
||||
} else {
|
||||
right
|
||||
};
|
||||
if broadcast_drops_labels(matching) {
|
||||
Some(false)
|
||||
} else {
|
||||
output_has_metric_name(vector)
|
||||
}
|
||||
}
|
||||
// Two vectors are matched by the kernel, which files each pairing under the many side's
|
||||
// labels with the name removed unless the operation is a filtering comparison: `drop_name`
|
||||
// in `vector_match` is `!op.is_comparison() || return_bool`, the same rule the broadcast
|
||||
// applies. One-to-one then rewrites that label set by the modifiers - `on(names)` keeps
|
||||
// only `names`, `ignoring(names)` drops them - and `group_left`/`group_right` keep it as
|
||||
// it is and copy the `include` labels of the one side instead.
|
||||
(_, _) => {
|
||||
if broadcast_drops_labels(matching) {
|
||||
return Some(false);
|
||||
}
|
||||
match &matching.cardinality {
|
||||
Cardinality::OneToOne => {
|
||||
let keeps_name = match &matching.labels {
|
||||
MatchingLabels::On(names) => {
|
||||
names.iter().any(|name| &**name == "__name__")
|
||||
}
|
||||
MatchingLabels::Ignoring(names) => {
|
||||
!names.iter().any(|name| &**name == "__name__")
|
||||
}
|
||||
};
|
||||
if keeps_name {
|
||||
output_has_metric_name(left)
|
||||
} else {
|
||||
Some(false)
|
||||
}
|
||||
}
|
||||
Cardinality::ManyToOne(include) => {
|
||||
if include.iter().any(|name| &**name == "__name__") {
|
||||
// The included name of the one side replaces the many side's.
|
||||
None
|
||||
} else {
|
||||
output_has_metric_name(left)
|
||||
}
|
||||
}
|
||||
Cardinality::OneToMany(include) => {
|
||||
if include.iter().any(|name| &**name == "__name__") {
|
||||
None
|
||||
} else {
|
||||
output_has_metric_name(right)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// A set operation keeps each side's samples under the label set they arrived with
|
||||
// (`set_vectors` rewrites no label), so a name survives it only if both sides carry one and a
|
||||
// name is absent only if both sides lack it. Sides that disagree settle nothing: `or` keeps
|
||||
// both sides' samples and `and`/`unless` keep the left side's, so the answer would be a claim
|
||||
// about one operator rather than about the shape.
|
||||
NativeExpr::Set { left, right, .. } => {
|
||||
match (output_has_metric_name(left), output_has_metric_name(right)) {
|
||||
(Some(left), Some(right)) if left == right => Some(left),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
// `info` enriches each base series with the data labels of the info series that share its
|
||||
// identifying labels: `add_data_labels` copies the info series' ordinary tags only, never the
|
||||
// name, so each result keeps the name its base series had.
|
||||
NativeExpr::Info { base, .. } => output_has_metric_name(base),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a grouping does to the metric name of the series it is handed.
|
||||
///
|
||||
/// `by(names)` keeps the name only when `names` lists it and `without(_)` removes it, which is
|
||||
/// `GroupingLabels::apply` in [`aggregate`](crate::aggregate): `keep_only` clears a name the list does
|
||||
/// not hold, and the `without` arm removes `__name__` after removing its own labels.
|
||||
fn grouping_keeps_metric_name(group: &Grouping, input: Option<bool>) -> Option<bool> {
|
||||
match group {
|
||||
Grouping::By(names) if names.iter().any(|name| &**name == "__name__") => input,
|
||||
Grouping::By(_) | Grouping::Without(_) => Some(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `node` hands over one logical series per canonical label set, or several.
|
||||
///
|
||||
/// This is the rule the runtime applies when it decides whether a consumer above `node` has to
|
||||
|
||||
@@ -14,16 +14,12 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::common::DFSchema;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridSpec};
|
||||
|
||||
use super::{
|
||||
AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap, BoundScalar,
|
||||
BoundSetOp, BoundVectorOp, BoundWindow, CanonicalGrouping, CanonicalOwner, Grouping,
|
||||
InstantValue, MapOp, NativeExpr, NativeNode, NativeProperties, NativeTree, NativeType,
|
||||
merges_are_placeable_in, needs_single_execution, needs_single_execution_in, no_label_sets,
|
||||
BoundSetOp, BoundVectorOp, BoundWindow, CanonicalGrouping, CanonicalOwner, CoPartitionedPair,
|
||||
Grouping, InstantValue, MapOp, NativeExpr, NativeNode, NativeProperties, NativeTree,
|
||||
NativeType, match_is_co_partitioned, merges_are_placeable_in, needs_single_execution,
|
||||
needs_single_execution_in, needs_single_execution_in_co, no_label_sets, output_has_metric_name,
|
||||
preserves_canonical_identity, reads_across_series,
|
||||
};
|
||||
use crate::extension_plan::{FusedSeries, FusedSeriesBinding};
|
||||
@@ -36,6 +32,11 @@ use crate::select::SortOrder;
|
||||
use crate::vector_match::{
|
||||
BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp,
|
||||
};
|
||||
use datafusion::common::DFSchema;
|
||||
use datatypes::series::SeriesLabels;
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use datatypes::series::time::{EvalGrid, GridSpec};
|
||||
|
||||
// The tree builders below are `pub(crate)` because the rewrite in [`canonicalize`] is proved with
|
||||
// the trees they build, rather than with a second set of fixtures that could drift from these.
|
||||
@@ -362,6 +363,52 @@ fn on_host() -> BinaryMatching {
|
||||
}
|
||||
}
|
||||
|
||||
/// `by(names)`: the grouping `sum by(names)` folds with, which keeps only the labels it lists.
|
||||
fn by(names: &[&str]) -> Grouping {
|
||||
Grouping::By(
|
||||
names
|
||||
.iter()
|
||||
.map(|name| Arc::from(*name))
|
||||
.collect::<Vec<_>>()
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
/// `without(names)`: the grouping `sum without(names)` folds with, which drops the labels it lists and
|
||||
/// `__name__` with them.
|
||||
fn without(names: &[&str]) -> Grouping {
|
||||
Grouping::Without(
|
||||
names
|
||||
.iter()
|
||||
.map(|name| Arc::from(*name))
|
||||
.collect::<Vec<_>>()
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
/// `sum` over `inner` folded into a query value, grouped as `group` says.
|
||||
///
|
||||
/// A `Complete` fold answers a group key of its own: `by(ns)` drops the metric name, `by("__name__")`
|
||||
/// keeps whatever the input had, and the same group is what a split plan's `Final` stage answers.
|
||||
fn sum_by(inner: NativeNode, group: Grouping) -> NativeNode {
|
||||
let out = inner
|
||||
.output
|
||||
.grid()
|
||||
.expect("an aggregate needs a grid")
|
||||
.clone();
|
||||
NativeNode {
|
||||
expr: NativeExpr::Aggregate {
|
||||
input: Box::new(inner),
|
||||
op: BoundAggregate {
|
||||
kind: AggregateKind::Sum,
|
||||
group,
|
||||
stage: AggregateStage::Complete,
|
||||
},
|
||||
},
|
||||
output: evaluated(Arc::new([]), out),
|
||||
}
|
||||
}
|
||||
|
||||
/// A `sum by (job)` folded into `inner` within this execution, which is an aggregate whose output is
|
||||
/// a query value rather than state.
|
||||
pub(crate) fn complete_aggregate(inner: NativeNode) -> NativeNode {
|
||||
@@ -2812,3 +2859,459 @@ fn info_reads_the_sample_times_of_a_merged_selection_and_nothing_else() {
|
||||
"a selection of samples was read as sample times: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The metric-name fact each shape answers, and the kernel each answer rests on.
|
||||
///
|
||||
/// The shapes whose output carries no name are the ones that write it away whatever they read, the
|
||||
/// shapes that only carry a label set through follow their input, and the shapes whose output labels
|
||||
/// are decided elsewhere answer `None`, which is not an answer in either direction.
|
||||
#[test]
|
||||
fn the_metric_name_fact_follows_what_each_shape_does_to_a_label_set() {
|
||||
let shared = grid(0, 60_000, 4);
|
||||
let selected = || instant_over(raw_input_at(0), InstantValue::Sample, Arc::clone(&shared));
|
||||
|
||||
// A scan of one metric hands its series over under that metric's name. A value another execution
|
||||
// produced carries whatever that execution left on it, and this tree does not hold that
|
||||
// execution, so the answer is `None` rather than a guess in either direction: reading it as "no
|
||||
// name" is what would make a named match look name-free and run it per partition. That is why the
|
||||
// match proof takes the fact on [`CoPartitionedPair::name_free`], from the layer that built the
|
||||
// producers, instead of deriving it here.
|
||||
assert_eq!(output_has_metric_name(&raw_input_at(0)), Some(true));
|
||||
assert_eq!(
|
||||
output_has_metric_name(&input_on_at(0, Arc::clone(&shared))),
|
||||
None
|
||||
);
|
||||
|
||||
// A selection answers the label set it read, except `timestamp(x)`, which rebuilds the labels
|
||||
// through `drop_metric_name`. Over an evaluated input the same selection follows it into `None`.
|
||||
assert_eq!(output_has_metric_name(&selected()), Some(true));
|
||||
assert_eq!(
|
||||
output_has_metric_name(&instant_over(
|
||||
raw_input_at(0),
|
||||
InstantValue::InfoTimestamp,
|
||||
Arc::clone(&shared)
|
||||
)),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&instant_over(
|
||||
raw_input_at(0),
|
||||
InstantValue::Timestamp,
|
||||
Arc::clone(&shared)
|
||||
)),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&instant_over(
|
||||
input_on_at(0, Arc::clone(&shared)),
|
||||
InstantValue::Sample,
|
||||
Arc::clone(&shared)
|
||||
)),
|
||||
None
|
||||
);
|
||||
|
||||
// A window drops the name with every function but the two that hand the sample they read on.
|
||||
assert_eq!(
|
||||
output_has_metric_name(&window_with(
|
||||
raw_input_at(0),
|
||||
RangeFunction::Rate,
|
||||
None,
|
||||
Arc::clone(&shared)
|
||||
)),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&window_with(
|
||||
raw_input_at(0),
|
||||
RangeFunction::LastOverTime,
|
||||
None,
|
||||
Arc::clone(&shared)
|
||||
)),
|
||||
Some(true)
|
||||
);
|
||||
|
||||
// An aggregate answers its group key: `by(ns)` and `without(...)` drop `__name__`, and
|
||||
// `by("__name__")` keeps the name the input had.
|
||||
assert_eq!(
|
||||
output_has_metric_name(&sum_by(selected(), by(&["ns"]))),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&sum_by(selected(), by(&["__name__"]))),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&sum_by(selected(), without(&["ns"]))),
|
||||
Some(false)
|
||||
);
|
||||
|
||||
// A timestamp reports a position under the name dropped, and a merge writes no label of its own.
|
||||
assert_eq!(
|
||||
output_has_metric_name(×tamp_of(selected())),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(output_has_metric_name(&merge_over(selected())), Some(true));
|
||||
|
||||
// A map of `map_math`/`map_native_histogram` drops the name, while a label rewrite writes a label
|
||||
// of its own choosing - `__name__` included - and can clear it.
|
||||
let mapped = map_over(selected());
|
||||
assert_eq!(output_has_metric_name(&mapped), Some(false));
|
||||
assert_eq!(
|
||||
output_has_metric_name(&map_rewriting_labels(selected())),
|
||||
None
|
||||
);
|
||||
|
||||
// `absent` builds its labels from the argument's matchers and binds no name; `sort` hands back the
|
||||
// series it read.
|
||||
let absent = NativeNode {
|
||||
expr: NativeExpr::Vector {
|
||||
input: Box::new(selected()),
|
||||
op: BoundVectorOp::Absent {
|
||||
labels: SeriesLabels::try_new(None, Vec::new()).expect("an empty label set"),
|
||||
},
|
||||
},
|
||||
output: evaluated(Arc::new([]), Arc::clone(&shared)),
|
||||
};
|
||||
assert_eq!(output_has_metric_name(&absent), Some(false));
|
||||
assert_eq!(output_has_metric_name(&sorted(selected())), Some(true));
|
||||
|
||||
// A two-vector match drops the name for arithmetic and for a `bool` comparison, keeps the many
|
||||
// side's labels for a filtering comparison under the default modifiers, and drops them under
|
||||
// `on(host)`, which keeps only the labels it names.
|
||||
let two_vectors = |modifiers: BinaryMatching| binary_with(selected(), selected(), modifiers);
|
||||
assert_eq!(output_has_metric_name(&two_vectors(add())), Some(false));
|
||||
assert_eq!(
|
||||
output_has_metric_name(&two_vectors(matching(BinaryOp::Gt, false))),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&two_vectors(matching(BinaryOp::Gt, true))),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(output_has_metric_name(&two_vectors(on_host())), Some(false));
|
||||
|
||||
// A broadcast answers the vector side's series, and the operation decides whether the labels
|
||||
// survive it.
|
||||
let constant = || scalar_on(2.0, Arc::clone(&shared));
|
||||
assert_eq!(
|
||||
output_has_metric_name(&binary_with(
|
||||
selected(),
|
||||
constant(),
|
||||
matching(BinaryOp::Mul, false)
|
||||
)),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&binary_with(
|
||||
selected(),
|
||||
constant(),
|
||||
matching(BinaryOp::Gt, false)
|
||||
)),
|
||||
Some(true)
|
||||
);
|
||||
|
||||
// A set operation keeps each side's samples, so it answers only when both sides agree.
|
||||
let set = |left: NativeNode, right: NativeNode| NativeNode {
|
||||
expr: NativeExpr::Set {
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
op: BoundSetOp {
|
||||
op: SetOp::Or,
|
||||
labels: MatchingLabels::Ignoring(Vec::new()),
|
||||
},
|
||||
},
|
||||
output: evaluated(Arc::new([]), Arc::clone(&shared)),
|
||||
};
|
||||
assert_eq!(
|
||||
output_has_metric_name(&set(selected(), selected())),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&set(selected(), sum_by(selected(), by(&["ns"])))),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
/// The `m1{ns="a"} / m2{ns="a"}` match: two canonical label sets and one match group.
|
||||
///
|
||||
/// Both sides are selections over raw scans, so every series carries its metric's name, and the
|
||||
/// canonical key a placement routes by holds `__name__` while the default match key does not. A
|
||||
/// co-partitioned pair of sources therefore proves nothing about this match: routing by canonical key
|
||||
/// sends `m1{ns="a"}` and `m2{ns="a"}` to different partitions, each partition finds no partner, and
|
||||
/// the match answers nothing where the whole match answers a value. That is the silent-empty-answer
|
||||
/// case, and the two-sided proof must not touch it.
|
||||
///
|
||||
/// The pair below states the producer half as `false` because both scans hand over named series, which
|
||||
/// is what a caller that could observe the producers would state. The pairing itself is real, so what
|
||||
/// refuses the shape is the naming fact and nothing else.
|
||||
#[test]
|
||||
fn a_match_of_two_named_sides_needs_one_execution_whatever_the_routing_proved() {
|
||||
let shared = grid(0, 60_000, 4);
|
||||
let matched = || {
|
||||
binary_with(
|
||||
instant_over(raw_input_at(0), InstantValue::Sample, Arc::clone(&shared)),
|
||||
instant_over(raw_input_at(1), InstantValue::Sample, Arc::clone(&shared)),
|
||||
add(),
|
||||
)
|
||||
};
|
||||
let named_pair = CoPartitionedPair {
|
||||
left: 0,
|
||||
right: 1,
|
||||
name_free: false,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
output_has_metric_name(&instant_over(
|
||||
raw_input_at(0),
|
||||
InstantValue::Sample,
|
||||
Arc::clone(&shared)
|
||||
)),
|
||||
Some(true),
|
||||
"a scan of one metric hands its series over under that metric's name"
|
||||
);
|
||||
assert_eq!(
|
||||
output_has_metric_name(&instant_over(
|
||||
raw_input_at(1),
|
||||
InstantValue::Sample,
|
||||
Arc::clone(&shared)
|
||||
)),
|
||||
Some(true)
|
||||
);
|
||||
assert!(
|
||||
needs_single_execution_in_co(
|
||||
&matched(),
|
||||
&[proven_by_key(), proven_by_key()],
|
||||
&[named_pair]
|
||||
),
|
||||
"the canonical key of `m1{{ns=\"a\"}}` is not the key `m1{{ns=\"a\"}} / m2{{ns=\"a\"}}` pairs by"
|
||||
);
|
||||
// The same tree in one execution is both sides here at once, which is the per-side proof and stays
|
||||
// the answer it was.
|
||||
assert!(!needs_single_execution_in_co(
|
||||
&matched(),
|
||||
&[proven_in_one_execution(), proven_in_one_execution()],
|
||||
&[named_pair]
|
||||
));
|
||||
// The naming conjunct on its own, asked of the operands the shape actually has: two routed inputs
|
||||
// over named series, a pair that says so, and the answer is still no.
|
||||
assert!(
|
||||
!match_is_co_partitioned(
|
||||
&instant_over(raw_input_at(0), InstantValue::Sample, Arc::clone(&shared)),
|
||||
&instant_over(raw_input_at(1), InstantValue::Sample, Arc::clone(&shared)),
|
||||
&add(),
|
||||
&[named_pair]
|
||||
),
|
||||
"both sides hand over named series, so the match key is not the canonical key"
|
||||
);
|
||||
}
|
||||
|
||||
/// The shape the feature exists to serve: `B = FusedSeries { tree: Binary { left: Input(0), right:
|
||||
/// Input(1) } }` over two routed producers, each of which answers a name-free vector.
|
||||
///
|
||||
/// Both operands are an [`NativeExpr::Input`] over *evaluated* samples, so [`output_has_metric_name`]
|
||||
/// answers `None` for them: the node that built those label sets sits in the producers, not in this
|
||||
/// tree, and guessing `Some(false)` there would be exactly the silent-empty-answer bug. The producer
|
||||
/// half therefore travels on the pair ([`CoPartitionedPair::name_free`]), stated by the layer that
|
||||
/// built the producers, and this is the case that must engage: with the joint fact stated, the match
|
||||
/// runs once per partition.
|
||||
#[test]
|
||||
fn a_co_partitioned_name_free_pair_lets_the_match_run_per_partition() {
|
||||
let shared = grid(0, 60_000, 4);
|
||||
let matched = || {
|
||||
binary_with(
|
||||
input_on_at(0, Arc::clone(&shared)),
|
||||
input_on_at(1, Arc::clone(&shared)),
|
||||
add(),
|
||||
)
|
||||
};
|
||||
let by_key = [proven_by_key(), proven_by_key()];
|
||||
let name_free = CoPartitionedPair {
|
||||
left: 0,
|
||||
right: 1,
|
||||
name_free: true,
|
||||
};
|
||||
|
||||
// What the tree cannot see, and the reason the fact has to travel beside it.
|
||||
assert_eq!(
|
||||
output_has_metric_name(&input_on_at(0, Arc::clone(&shared))),
|
||||
None,
|
||||
"an input over evaluated samples is another execution's answer"
|
||||
);
|
||||
// Conjuncts 1-5 all hold, so the match needs no execution of its own: `sum by(ns)(m1)` and
|
||||
// `sum by(ns)(m2)` pair by the very key the routing used.
|
||||
assert!(
|
||||
!needs_single_execution_in_co(&matched(), &by_key, &[name_free]),
|
||||
"a name-free co-partitioned pair is the case the two-sided proof exists for"
|
||||
);
|
||||
assert!(match_is_co_partitioned(
|
||||
&input_on_at(0, Arc::clone(&shared)),
|
||||
&input_on_at(1, Arc::clone(&shared)),
|
||||
&add(),
|
||||
&[name_free]
|
||||
));
|
||||
|
||||
// The producer half is required: the same pair stated as naming its series refuses the proof, and
|
||||
// the match needs one execution again.
|
||||
let named = CoPartitionedPair {
|
||||
name_free: false,
|
||||
..name_free
|
||||
};
|
||||
assert!(!match_is_co_partitioned(
|
||||
&input_on_at(0, Arc::clone(&shared)),
|
||||
&input_on_at(1, Arc::clone(&shared)),
|
||||
&add(),
|
||||
&[named]
|
||||
));
|
||||
assert!(
|
||||
needs_single_execution_in_co(&matched(), &by_key, &[named]),
|
||||
"a pair that names its series proves nothing about the match key"
|
||||
);
|
||||
|
||||
// No pair at all proves nothing either: the routing fact is also required.
|
||||
assert!(needs_single_execution_in_co(&matched(), &by_key, &[]));
|
||||
|
||||
// The two orientations are one pair. A match writes one source on its left and the other on its
|
||||
// right because of how the query was written, not because of how the routing placed them, so a
|
||||
// pair listed the other way round proves the same thing.
|
||||
let reversed = CoPartitionedPair {
|
||||
left: 1,
|
||||
right: 0,
|
||||
name_free: true,
|
||||
};
|
||||
assert!(match_is_co_partitioned(
|
||||
&input_on_at(0, Arc::clone(&shared)),
|
||||
&input_on_at(1, Arc::clone(&shared)),
|
||||
&add(),
|
||||
&[reversed]
|
||||
));
|
||||
assert!(
|
||||
!needs_single_execution_in_co(&matched(), &by_key, &[reversed]),
|
||||
"the reversed orientation is the same pair"
|
||||
);
|
||||
}
|
||||
|
||||
/// A match with modifiers pairs by a key of the caller's own choosing, so co-partitioned sources say
|
||||
/// nothing about it: `on(host)` pairs two series whose canonical keys differ, and `group_left` answers
|
||||
/// a label set copied out of its one side.
|
||||
///
|
||||
/// The operands are the routed inputs over evaluated samples, and the pair states a name-free
|
||||
/// production, so conjuncts 1, 2 and 5 all hold: what refuses the shape is the modifier alone.
|
||||
#[test]
|
||||
fn a_match_with_modifiers_needs_one_execution_whatever_the_routing_proved() {
|
||||
let shared = grid(0, 60_000, 4);
|
||||
let matched = |modifiers: BinaryMatching| {
|
||||
binary_with(
|
||||
input_on_at(0, Arc::clone(&shared)),
|
||||
input_on_at(1, Arc::clone(&shared)),
|
||||
modifiers,
|
||||
)
|
||||
};
|
||||
let by_key = [proven_by_key(), proven_by_key()];
|
||||
let name_free = CoPartitionedPair {
|
||||
left: 0,
|
||||
right: 1,
|
||||
name_free: true,
|
||||
};
|
||||
let group_left = BinaryMatching {
|
||||
cardinality: Cardinality::ManyToOne(Vec::new()),
|
||||
..add()
|
||||
};
|
||||
// Every match modifier a caller could write that is not the default `Ignoring([])` one: `on(host)`
|
||||
// names its own key, and `ignoring(host)` still names a key of its own.
|
||||
let ignoring_host = BinaryMatching {
|
||||
labels: MatchingLabels::Ignoring(vec!["host".into()]),
|
||||
..add()
|
||||
};
|
||||
|
||||
for modifiers in [on_host(), ignoring_host, group_left] {
|
||||
let tree = matched(modifiers);
|
||||
assert!(
|
||||
needs_single_execution_in_co(&tree, &by_key, &[name_free]),
|
||||
"a modified match pairs by its own key, not by the one the routing used: {tree:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The naming fact is joint, and it is the half the tree cannot see: with conjuncts 1-4 all satisfied
|
||||
/// and the operands being the routed inputs themselves, the pair's [`CoPartitionedPair::name_free`]
|
||||
/// alone decides.
|
||||
///
|
||||
/// The shape is `sum by(ns)(m1) / m2`, whose two producers disagree: one hands over a folded, name-free
|
||||
/// vector and the other a named series. One named side is enough, so the pair that knows both
|
||||
/// producers states `name_free: false`. Reading that bit as `true` is what would run the match per
|
||||
/// partition, pair the two sides under a key one of them does not answer under, and emit nothing.
|
||||
#[test]
|
||||
fn one_named_side_is_enough_to_refuse_the_name_free_proof() {
|
||||
let shared = grid(0, 60_000, 4);
|
||||
// The two operands are both routed inputs, so this pins the naming bit and nothing else: the tree
|
||||
// half of the proof is satisfied either way.
|
||||
let left = || input_on_at(0, Arc::clone(&shared));
|
||||
let right = || input_on_at(1, Arc::clone(&shared));
|
||||
let one_named = CoPartitionedPair {
|
||||
left: 0,
|
||||
right: 1,
|
||||
name_free: false,
|
||||
};
|
||||
|
||||
assert!(!match_is_co_partitioned(
|
||||
&left(),
|
||||
&right(),
|
||||
&add(),
|
||||
&[one_named]
|
||||
));
|
||||
assert!(needs_single_execution_in_co(
|
||||
&binary_with(left(), right(), add()),
|
||||
&[proven_by_key(), proven_by_key()],
|
||||
&[one_named]
|
||||
));
|
||||
// The very same operands and pair with the joint bit flipped are parallel, so the bit is the whole
|
||||
// of the producer half here rather than decoration.
|
||||
let both_name_free = CoPartitionedPair {
|
||||
name_free: true,
|
||||
..one_named
|
||||
};
|
||||
assert!(match_is_co_partitioned(
|
||||
&left(),
|
||||
&right(),
|
||||
&add(),
|
||||
&[both_name_free]
|
||||
));
|
||||
}
|
||||
|
||||
/// A pair the caller did not prove co-partitioned proves nothing: source 0 and source 2 route as the
|
||||
/// caller said, and the caller said nothing about 0 and 2. The pair is read by the sources it names,
|
||||
/// never by the position the two sides happen to sit in.
|
||||
#[test]
|
||||
fn a_pair_missing_from_the_co_partitioned_list_needs_one_execution() {
|
||||
let shared = grid(0, 60_000, 4);
|
||||
let matched = || {
|
||||
binary_with(
|
||||
input_on_at(0, Arc::clone(&shared)),
|
||||
input_on_at(2, Arc::clone(&shared)),
|
||||
add(),
|
||||
)
|
||||
};
|
||||
let three_sources = [proven_by_key(), proven_by_key(), proven_by_key()];
|
||||
let names_free_but_other_pair = CoPartitionedPair {
|
||||
left: 0,
|
||||
right: 1,
|
||||
name_free: true,
|
||||
};
|
||||
|
||||
assert!(
|
||||
needs_single_execution_in_co(&matched(), &three_sources, &[names_free_but_other_pair]),
|
||||
"sources 0 and 2 were never proved to route together"
|
||||
);
|
||||
// A pair that does name these two sources engages, which is what makes the assertion above about
|
||||
// the pair list and not about the operands: the shape is otherwise the one that runs per partition,
|
||||
// and the orientation is the reverse of the one the match writes.
|
||||
assert!(!needs_single_execution_in_co(
|
||||
&matched(),
|
||||
&three_sources,
|
||||
&[CoPartitionedPair {
|
||||
left: 2,
|
||||
right: 0,
|
||||
name_free: true,
|
||||
}]
|
||||
));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user