refactor(promql): read evaluated and raw repartition chains with one loop (#10841)

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
dennis zhuang
2026-12-02 15:20:21 +00:00
committed by GitHub
parent 42e96e5bd9
commit cd3406a0db
2 changed files with 166 additions and 272 deletions
@@ -121,7 +121,7 @@ use std::fmt::{self, Formatter};
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::{Arc, Mutex, Weak};
use std::task::{Context, Poll};
use std::task::{Context, Poll, ready};
use common_error::ext::BoxedError;
use common_query::series_frame::{
@@ -345,30 +345,27 @@ impl HeldSeriesCharges {
})
}
/// The next chunk, with the charge of the previous one released first.
fn next_chunk(
/// The next chunk as `T`, with the charge of the previous one released first. A chunk `pick`
/// hands back is another content than this stream is read as, and is refused.
fn next_as<T>(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Option<Result<SeriesChunk, BoxedError>>> {
pick: impl FnOnce(SeriesChunk) -> Result<T, SeriesChunk>,
) -> Poll<Option<Result<T, BoxedError>>> {
self.held = None;
match self.chunks.as_mut().poll_next(cx) {
Poll::Ready(Some(Ok(handed))) => {
let (chunk, charge) = handed.into_parts();
self.held = charge;
Poll::Ready(Some(Ok(chunk)))
}
Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
/// The error a child hands over a content this stream is not read as.
fn refused(&self, chunk: &SeriesChunk) -> BoxedError {
boxed(DataFusionError::Execution(format!(
"a {} input handed over {chunk:?}",
self.content.as_str()
)))
let Some(handed) = ready!(self.chunks.as_mut().poll_next(cx)) else {
return Poll::Ready(None);
};
Poll::Ready(Some(handed.and_then(|handed| {
let (chunk, charge) = handed.into_parts();
self.held = charge;
pick(chunk).map_err(|other| {
boxed(DataFusionError::Execution(format!(
"a {} input handed over {other:?}",
self.content.as_str()
)))
})
})))
}
}
@@ -381,19 +378,10 @@ impl Stream for HeldEvaluated {
type Item = Result<(Series, bool), BoxedError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
match this.inner.next_chunk(cx) {
Poll::Ready(Some(Ok(SeriesChunk::Evaluated(chunk)))) => {
Poll::Ready(Some(Ok((chunk.series, chunk.is_last))))
}
Poll::Ready(Some(Ok(other))) => {
let error = this.inner.refused(&other);
Poll::Ready(Some(Err(error)))
}
Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
self.get_mut().inner.next_as(cx, |chunk| match chunk {
SeriesChunk::Evaluated(chunk) => Ok((chunk.series, chunk.is_last)),
other => Err(other),
})
}
}
@@ -422,17 +410,10 @@ impl Stream for HeldRaw {
type Item = Result<RawSeriesChunk, BoxedError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
match this.inner.next_chunk(cx) {
Poll::Ready(Some(Ok(SeriesChunk::Raw(chunk)))) => Poll::Ready(Some(Ok(chunk))),
Poll::Ready(Some(Ok(other))) => {
let error = this.inner.refused(&other);
Poll::Ready(Some(Err(error)))
}
Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
self.get_mut().inner.next_as(cx, |chunk| match chunk {
SeriesChunk::Raw(chunk) => Ok(chunk),
other => Err(other),
})
}
}
@@ -2028,10 +2009,10 @@ async fn route_partition(
// The variant is the content: decoding the input's declared frame is what produced it.
let stop = match &mut stream {
RoutedInput::Evaluated(stream) => {
read_evaluated_chains(stream, partition, &routing, &senders, &read_ahead).await
read_chains(stream, partition, &routing, &senders, &read_ahead).await
}
RoutedInput::Raw(stream) => {
read_raw_chains(stream, partition, &routing, &senders, &read_ahead).await
read_chains(stream, partition, &routing, &senders, &read_ahead).await
}
RoutedInput::StateChunks(stream, state, series) => {
read_state_chunks(
@@ -2167,258 +2148,172 @@ pub(crate) fn histogram_table_slice_bytes(
Ok(bytes)
}
/// A chunk the chain reader routes: where its chain goes and what holding it costs.
trait ChainChunk: Sized {
fn is_last(&self) -> bool;
/// The output the chain this chunk opens belongs on.
fn output(&self, routing: &Routing) -> DataFusionResult<usize>;
/// The bytes a queued chunk keeps alive.
fn retained_bytes(&self) -> DataFusionResult<usize>;
fn into_routed(chain: Vec<(Self, MemoryReservation)>) -> RoutedChain;
}
impl ChainChunk for (Series, bool) {
fn is_last(&self) -> bool {
self.1
}
fn output(&self, routing: &Routing) -> DataFusionResult<usize> {
Ok(routing.output_labels(&self.0.metric))
}
fn retained_bytes(&self) -> DataFusionResult<usize> {
let mut tables = 0usize;
for segment in self.0.fields.iter().flat_map(|field| field.segments()) {
let batch = match segment.dense() {
Some(DenseSamplesRef::Histogram(histograms)) => Some(histograms.batch()),
Some(DenseSamplesRef::Mixed(mixed)) => Some(mixed.histograms().batch()),
_ => None,
};
if let Some(batch) = batch {
tables = tables.saturating_add(histogram_table_slice_bytes(batch)?);
}
}
Ok(operand_chunk_bytes(&self.0).saturating_add(tables))
}
fn into_routed(chain: Vec<(Self, MemoryReservation)>) -> RoutedChain {
RoutedChain::Evaluated(chain)
}
}
impl ChainChunk for RawSeriesChunk {
fn is_last(&self) -> bool {
self.is_last
}
fn output(&self, routing: &Routing) -> DataFusionResult<usize> {
match &routing.policy {
SeriesRouting::Matching(_) | SeriesRouting::RawLabelSet => {
let labels = self.metric.as_ref().ok_or_else(|| {
DataFusionError::Execution("a label-routed raw chain carries no labels".into())
})?;
Ok(routing.output_labels(labels))
}
_ => Ok(routing.output_key(self.primary_key.as_slice())),
}
}
fn retained_bytes(&self) -> DataFusionResult<usize> {
raw_chunk_slice_bytes(self)
}
fn into_routed(chain: Vec<(Self, MemoryReservation)>) -> RoutedChain {
RoutedChain::Raw(chain)
}
}
/// Reads one input partition to its end, one whole chain at a time, routing each chain as it closes.
///
/// A chain is assembled here and handed over atomically after it closes; its growing memory is charged
/// to the pool. Output queues are unbounded, so routing does not wait for output polling. Each queued
/// chain retains its pool charge until the owner consumes it or the queue is dropped. This function
/// otherwise waits only on its own child.
async fn read_evaluated_chains(
stream: &mut SendableEvaluatedSeriesStream,
async fn read_chains<C, S>(
stream: &mut S,
partition: usize,
routing: &Routing,
senders: &[mpsc::UnboundedSender<Queued>],
read_ahead: &MemoryReservation,
) -> Stop {
) -> Stop
where
C: ChainChunk,
S: Stream<Item = Result<C, BoxedError>> + Unpin,
{
loop {
// One whole chain, assembled here: the chunk that closes the series ends it, and so does a
// stream that ends between two chains.
let mut chain: Vec<(Series, bool, MemoryReservation)> = Vec::new();
let mut chain_output: Option<usize> = None;
let mut chain: Vec<(C, MemoryReservation)> = Vec::new();
let mut destination: Option<usize> = None;
// Set once the destination closed: the rest of the chain is still read and validated, but
// neither retained nor charged.
let mut discarding = false;
let mut ended = false;
loop {
let output = loop {
// Input streams may return a long run of ready chunks without yielding to Tokio. Consume
// the normal task budget per chunk so sibling producers can run and report failures.
tokio::task::coop::consume_budget().await;
let next = match (chain_output, discarding) {
(Some(output), false) if !chain.is_empty() => {
tokio::select! {
biased;
_ = senders[output].closed() => {
chain.clear();
discarding = true;
continue;
}
next = stream.next() => next,
}
}
_ => stream.next().await,
};
match next {
Some(Ok((series, is_last))) => {
let output = match chain_output {
Some(output) => output,
None => {
let output = routing.output_labels(&series.metric);
chain_output = Some(output);
output
}
};
// A dropped output is no longer a destination. Still read and validate its
// entire chain, but do not retain or reserve its chunks.
if senders[output].is_closed() {
let next = match (destination, discarding) {
(Some(output), false) if !chain.is_empty() => tokio::select! {
biased;
_ = senders[output].closed() => {
chain.clear();
discarding = true;
if is_last {
break;
}
continue;
}
// Charged as the chain grows, so a chain that does not fit the pool is refused
// here rather than after it has been held.
if discarding {
if is_last {
break;
}
continue;
}
let charge = read_ahead.new_empty();
let mut tables = 0usize;
for segment in series.fields.iter().flat_map(|field| field.segments()) {
let batch = match segment.dense() {
Some(DenseSamplesRef::Histogram(histograms)) => {
Some(histograms.batch())
}
Some(DenseSamplesRef::Mixed(mixed)) => Some(mixed.histograms().batch()),
_ => None,
};
if let Some(batch) = batch {
match histogram_table_slice_bytes(batch) {
Ok(bytes) => tables = tables.saturating_add(bytes),
Err(error) => return Stop::Failed(Arc::new(error)),
}
}
}
let bytes = operand_chunk_bytes(&series).saturating_add(tables);
if let Err(error) = charge.try_grow(bytes) {
if senders[output].is_closed() {
chain.clear();
discarding = true;
if is_last {
break;
}
continue;
}
return Stop::Failed(Arc::new(error));
}
chain.push((series, is_last, charge));
if is_last {
break;
}
}
next = stream.next() => next,
},
_ => stream.next().await,
};
let chunk = match next {
Some(Ok(chunk)) => chunk,
Some(Err(error)) => {
// The error is the last thing this partition says: it is handed to every output
// rather than ending this one task quietly.
return Stop::Failed(Arc::new(DataFusionError::External(Box::new(error))));
}
None => {
ended = true;
break;
}
}
}
if ended {
// A partition that ends is a partition with nothing left to route - unless it ended
// inside a chain, which no later chunk can close. The decoders refuse that, so this is a
// producer that bypassed them, and its output would hold a series no chunk can close.
return if chain_output.is_none() {
Stop::Ended
} else {
Stop::Failed(Arc::new(DataFusionError::Execution(
"series repartition input ended with its series open".to_string(),
)))
};
}
// One hash per chain, over the labels of its first chunk: the chunks of a chain are one
// series, so the first of them names the output for all of them.
let Some(output) = chain_output else {
return Stop::Failed(Arc::new(DataFusionError::Internal(
"series repartition completed a chain without a routing destination".into(),
)));
};
if !discarding && {
let metadata = read_ahead.new_empty();
if let Err(error) = metadata.try_grow(std::mem::size_of::<Queued>()) {
return Stop::Failed(Arc::new(error));
}
senders[output]
.send(Queued::Chain {
input: partition,
chain: RoutedChain::Evaluated(chain),
_metadata: metadata,
})
.is_err()
} {
// A closed output is no longer a destination. Drop this chain and keep consuming.
continue;
}
}
}
async fn read_raw_chains(
stream: &mut SendableRawSeriesStream,
partition: usize,
routing: &Routing,
senders: &[mpsc::UnboundedSender<Queued>],
read_ahead: &MemoryReservation,
) -> Stop {
loop {
let mut chain: Vec<(RawSeriesChunk, MemoryReservation)> = Vec::new();
let mut destination: Option<usize> = None;
let mut discarding = false;
loop {
tokio::task::coop::consume_budget().await;
let next = match (destination, discarding) {
(Some(output), false) if !chain.is_empty() => tokio::select! {
biased;
_ = senders[output].closed() => { chain.clear(); discarding = true; continue; }
item = stream.next() => item,
},
_ => stream.next().await,
};
match next {
Some(Ok(chunk)) => {
let output = match destination {
Some(output) => output,
None => {
let output = match &routing.policy {
SeriesRouting::Matching(_) | SeriesRouting::RawLabelSet => {
let Some(labels) = chunk.metric.as_ref() else {
return Stop::Failed(Arc::new(DataFusionError::Execution(
"a label-routed raw chain carries no labels".into(),
)));
};
routing.output_labels(labels)
}
_ => routing.output_key(chunk.primary_key.as_slice()),
};
*destination.insert(output)
}
};
let final_chunk = chunk.is_last;
if senders[output].is_closed() {
chain.clear();
discarding = true;
if final_chunk {
break;
}
continue;
}
if discarding {
if final_chunk {
break;
}
continue;
}
let charge = read_ahead.new_empty();
let bytes = match raw_chunk_slice_bytes(&chunk) {
Ok(bytes) => bytes,
Err(error) => return Stop::Failed(Arc::new(error)),
};
if let Err(error) = charge.try_grow(bytes) {
return Stop::Failed(Arc::new(error));
}
chain.push((chunk, charge));
if final_chunk {
break;
}
}
Some(Err(error)) => {
return Stop::Failed(Arc::new(DataFusionError::External(Box::new(error))));
}
None => {
// Ending inside a chain leaves a series no later chunk can close. The decoders
// refuse that, so this is a producer that bypassed them.
return if destination.is_none() {
Stop::Ended
} else {
Stop::Failed(Arc::new(DataFusionError::Execution(
"raw series ended without is_last".into(),
"series repartition input ended with its series open".to_string(),
)))
};
}
};
// One hash per chain, over its first chunk: the chunks of a chain are one series.
let output = match destination {
Some(output) => output,
None => match chunk.output(routing) {
Ok(output) => *destination.insert(output),
Err(error) => return Stop::Failed(Arc::new(error)),
},
};
let is_last = chunk.is_last();
if senders[output].is_closed() {
chain.clear();
discarding = true;
}
if !discarding {
let charge = read_ahead.new_empty();
let bytes = match chunk.retained_bytes() {
Ok(bytes) => bytes,
Err(error) => return Stop::Failed(Arc::new(error)),
};
// Charged as the chain grows, so a chain that does not fit the pool is refused here
// rather than after it has been held.
if let Err(error) = charge.try_grow(bytes) {
return Stop::Failed(Arc::new(error));
}
chain.push((chunk, charge));
}
if is_last {
break output;
}
}
let Some(output) = destination else {
return Stop::Failed(Arc::new(DataFusionError::Internal(
"raw chain has no destination".into(),
)));
};
if !discarding {
let metadata = read_ahead.new_empty();
if let Err(error) = metadata.try_grow(std::mem::size_of::<Queued>()) {
return Stop::Failed(Arc::new(error));
}
if senders[output]
.send(Queued::Chain {
input: partition,
chain: RoutedChain::Raw(chain),
_metadata: metadata,
})
.is_err()
{
continue;
}
if discarding {
continue;
}
let metadata = read_ahead.new_empty();
if let Err(error) = metadata.try_grow(std::mem::size_of::<Queued>()) {
return Stop::Failed(Arc::new(error));
}
// A send to an output closed since is dropped; the next chain is read either way.
let _ = senders[output].send(Queued::Chain {
input: partition,
chain: C::into_routed(chain),
_metadata: metadata,
});
}
}
@@ -2505,7 +2400,7 @@ enum RoutedInput {
}
enum RoutedChain {
Evaluated(Vec<(Series, bool, MemoryReservation)>),
Evaluated(Vec<((Series, bool), MemoryReservation)>),
Raw(Vec<(RawSeriesChunk, MemoryReservation)>),
}
@@ -3320,7 +3215,7 @@ impl Stream for RepartitionStream {
let Some(first) = chain.first() else {
continue;
};
let key = exact_identity(&first.0);
let key = exact_identity(&first.0.0);
(OwnerKey::Evaluated(key), RoutedChain::Evaluated(chain))
}
RoutedChain::Raw(chain) => {
@@ -3423,7 +3318,7 @@ impl Stream for RepartitionStream {
group.received[input] = true;
match pieces {
RoutedChain::Evaluated(chain) => {
for (series, _, charge) in chain {
for ((series, _), charge) in chain {
group.fragments.push(series);
group.charges.push(charge);
}
@@ -5621,7 +5621,7 @@ async fn ready_chain_yields_after_a_charged_prefix_and_drop_releases_it() {
let (sender, receiver) = mpsc::unbounded_channel();
let routing = Routing::new(1);
let senders = [sender];
let mut read = Box::pin(read_evaluated_chains(
let mut read = Box::pin(read_chains(
&mut source,
0,
&routing,
@@ -6012,8 +6012,7 @@ async fn discarded_open_chain_eof_is_still_an_error() {
Box::pin(futures::stream::iter(vec![Ok((series, false))]));
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
let reservation = MemoryConsumer::new("discarded-open-eof-test").register(&pool);
let result =
read_evaluated_chains(&mut input, 0, &Routing::new(1), &[sender], &reservation).await;
let result = read_chains(&mut input, 0, &Routing::new(1), &[sender], &reservation).await;
assert!(
matches!(result, Stop::Failed(_)),
"open discarded chain EOF is not clean"
@@ -7766,7 +7765,7 @@ async fn a_merged_field_is_charged_what_the_queue_holds_once_the_merge_charge_is
// 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;
let stop = read_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}");
}