promql/extension_plan/series_repartition.rs
1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Routes evaluated and raw series across DataFusion input partitions.
16//!
17//! Canonical routing hashes complete labels; matching routing hashes the evaluator's own PromQL
18//! matching key. Routing groups are not merge identities: evaluated series merge only by exact name
19//! and tags. Raw ownership is the complete primary key plus exact label agreement; each input's
20//! complete chain or EOF establishes its contribution to a raw identity for contiguous inputs.
21//! An interleaved raw frame here consists of concatenated, independently closed producer chains;
22//! identities can recur, but open chains cannot be multiplexed. The owner retains those raw
23//! identities until every input reaches normal EOF, then reconstructs contiguous output.
24//!
25//! Chains are transported intact to owners with their input-partition ID, followed by one charged
26//! normal-EOF message per live output from each completed input. Owners group exact identities and,
27//! except for interleaved raw input, may publish an identity as soon as every input has contributed
28//! its final chain or normal EOF. Evaluated chunks are decoded only to read routing labels.
29//!
30//! # Routing
31//!
32//! The key is [`label_set`] of the chunk's metric, hashed whole: coarsening it (a subset of the
33//! labels, a metric name alone) would send two label sets to one output for sharing a prefix, which
34//! is not the relation a downstream merge groups by. One [`Routing`] is built per execution and
35//! every chunk is reduced with it, so the destination of a label set cannot depend on which chunk of
36//! it was routed first.
37//!
38//! The node declares [`Partitioning::UnknownPartitioning`], never [`Partitioning::Hash`]: the key is
39//! decoded from the rows, and a hash declaration carries an Arrow expression DataFusion could use to
40//! prove two plans agree on a partitioning. There is no such expression here, so the claim would be
41//! one no optimizer could check and a hash exchange inserted on top of it could silently disagree
42//! with. No ordering is declared either: the node reorders, and it says so by claiming nothing.
43//!
44//! # Chain boundaries
45//!
46//! A consumer of these frames requires a series' identity not to change and its positions to increase
47//! strictly while open, with `is_last` closing it. An input task therefore assembles each child chain
48//! before routing it as one atomic unit. This prevents chains from interleaving during transport; it
49//! does not establish the output order or final series boundaries. For a full exact identity (metric
50//! name and every tag name/value), the input contract is that each identity closes at most once per
51//! input, except for the independently closed chains of an interleaved raw frame. Each owner waits
52//! for each distinct input's final chain or normal EOF before merging a contiguous identity, and
53//! for all input EOFs before merging an interleaved raw identity.
54//!
55//! What that costs is stated rather than hidden. Nothing of a chain is handed over before the chain
56//! closes, so the first chunk of a series reaches its output later than a chunk-at-a-time design would
57//! deliver it, and a long chain occupies memory for as long as it is being read. Those bytes are
58//! charged to a [`MemoryConsumer`] as the chain grows, so a pool under pressure ends the read with an
59//! error instead of letting a chain grow without bound: the node refuses, it does not spin and it does
60//! not buffer past the pool's limit.
61//!
62//! Queues carry whole chains rather than individual chunks, so two sources' partial chains cannot
63//! interleave on one shared output queue; each output needs only one queue.
64//!
65//! # Where the reads run
66//!
67//! One task per child partition, and no task above them: each input's task reads its own child,
68//! assembles that input's chains and sends them to their owners itself. No task makes a routing
69//! decision for another input, and nothing rotates over the inputs.
70//!
71//! That is not an optimisation of the routing: an evaluated partition is one stream whose computation
72//! happens inside its `poll_next`, so a task polling every partition in turn runs the child's native
73//! kernels for all of them itself, one chunk at a time, and the partition count the child declared
74//! buys no parallelism at all. It is also what keeps routing local, which is what this node needs
75//! when two of them are composed:
76//!
77//! - A partial chain never occupies a shared output queue, so no output waits for a continuation: a
78//! chain is either fully assembled in the input task that read it, or not sent at all.
79//! - A task never waits for another task's routing decision, and the tasks share no lock while
80//! routing, so where one input's chain goes is not something another input learns or needs.
81//!
82//! Producer queues are unbounded: unread owners do not stall routing, but their retained chains
83//! continue to consume pool-accounted memory. Owners publish each exact identity after its per-input
84//! close/EOF barrier, or all input EOFs for interleaved raw frames, with finality recomputed for
85//! that output series.
86//!
87//! # Memory, backpressure and end of stream
88//!
89//! Output queues are unbounded; each input task holds at most the one chain it is assembling. Every
90//! queued chain is admitted through the task context's pool and carries its charge. The public packed
91//! stream releases a completed cursor's charges after its batch is flushed, while retaining the
92//! current cursor's charges until the cursor is exhausted. The pool controls
93//! admission, but queue length is not a constant-byte bound. Owners retain each pending exact identity
94//! until its per-input close/EOF barrier is satisfied, then
95//! reserve merge workspace for that identity alone. This bounds merge workspace to one pending
96//! identity, while its inputs remain charged until handoff. No task waits for memory admission.
97//!
98//! An output ends only when every input partition finished and its queue was drained; a chain that
99//! closed locally is not the end of anything. Each input sends its own EOF to each live output before
100//! recording normal completion. With one task per input the tasks count themselves down: the last
101//! records the read outcome, then sender closure lets outputs detect missing EOF or report failure. If the child errors, the failing task records it before cancelling its peers; sender closure makes
102//! every output report that recorded error instead of a clean end.
103//!
104//! Shared execution records the read outcome before producer senders close, so queue closure together
105//! with that shared outcome distinguishes normal completion from a stopped or failed read. A stopped
106//! read is missing exactly what it did not route and is reported as an error rather than a clean end.
107//!
108//! An output stream owns the read, not the plan it was executed from: DataFusion's
109//! `execute_stream_partitioned` takes the plan by value and keeps only the streams, so a read tied to
110//! the plan would be stopped while its streams are still being consumed. The read therefore lives as
111//! long as any of its outputs does, and stops only when there is nothing left it could deliver to:
112//! every output was handed out and every one of them is gone. An output that ends - normally, or by
113//! being dropped - while another partition was never executed stops nothing by itself, because that
114//! partition can still claim its queue; the execution going away as a whole, which no later `execute`
115//! can reach, is the other point at which everything is released.
116
117use std::any::Any;
118use std::collections::{BTreeMap, VecDeque};
119use std::fmt::{self, Formatter};
120use std::hash::{Hash, Hasher};
121use std::pin::Pin;
122use std::sync::{Arc, Mutex, Weak};
123use std::task::{Context, Poll};
124
125use common_error::ext::BoxedError;
126use common_query::series_frame::{
127 PendingBatching, SendableEvaluatedSeriesStream, pack_evaluated_series, pack_raw_series_with,
128 raw_series_frame_schema_with_ordering, series_frame_ordering, unpack_evaluated_series,
129 unpack_raw_series,
130};
131use datafusion::arrow::datatypes::SchemaRef;
132use datafusion::arrow::record_batch::RecordBatch;
133use datafusion::common::tree_node::TreeNodeRecursion;
134use datafusion::error::{DataFusionError, Result as DataFusionResult};
135use datafusion::execution::context::TaskContext;
136use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
137use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
138use datafusion::physical_plan::execution_plan::{EmissionType, EvaluationType, SchedulingType};
139use datafusion::physical_plan::{
140 DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, InputDistributionRequirements,
141 Partitioning, PlanProperties, RecordBatchStream, SendableRecordBatchStream,
142};
143use datatypes::series::aggregate_state::AggregateStateSchema;
144use datatypes::series::frame::{
145 FrameContent, FrameLabelMode, LabelDecodeSpec, SeriesFrameDeclaration, SeriesFrameDecoder,
146};
147use datatypes::series::raw::RawSeriesChunk;
148use datatypes::series::samples::{Series, SeriesSchema};
149use datatypes::series::{SeriesLabels, SeriesOrdering};
150use futures::{Stream, StreamExt};
151use store_api::region_engine::{RawLabelSource, RawSeriesStream, SendableRawSeriesStream};
152use tokio::sync::mpsc;
153use twox_hash::XxHash64;
154
155use crate::evaluated::EvaluatedChunk;
156use crate::extension_plan::series_execution::{
157 HandedSeriesChunk, SendableSeriesStream, SeriesCharge, SeriesChunk, SeriesExecutionPlan,
158 checked_series_stream, series_execution_plan,
159};
160use crate::grid_series::{label_set, merge_same_labelset};
161use crate::native::execute::{field_segments, merge_workspace_bytes, operand_chunk_bytes};
162use crate::native::state::{StateChunk, state_bytes, state_row_of};
163use crate::source::merge_raw_identity_charging;
164use datatypes::series::samples::DenseSamplesRef;
165
166/// Selects the key used to route a series to an output partition.
167#[derive(Clone, Debug, PartialEq, Eq)]
168pub enum SeriesRouting {
169 /// Hash the canonical label set.
170 CanonicalLabels,
171 /// Hash the canonical label set without these labels, including an excluded metric name.
172 CanonicalLabelsExcept(Arc<[Arc<str>]>),
173 /// Hash the exact PromQL matching key, so both sides of a vector operation meet.
174 Matching(crate::vector_match::MatchingLabels),
175 /// Route raw frames by their complete stored primary key.
176 RawPrimaryKey,
177}
178
179/// The seed behind every routing decision.
180///
181/// Fixed rather than drawn per execution, so which output a label set belongs on is a function of
182/// the label set and the output count alone: an execution's own decisions have to agree with each
183/// other, and a seeded router can be reasoned about - and tested - without one.
184const ROUTING_SEED: u64 = 0x517c_c1b7_2722_0a95;
185
186/// Whether a series identity is complete on a single chain, or has to be merged across inputs.
187///
188/// A router can publish an identity as soon as its chain closes only when that chain is the whole
189/// identity for the execution. Whether that holds is a property of the producer, not of the router,
190/// so it is declared explicitly and defaults to the conservative merge.
191#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
192pub enum IdentityCompletion {
193 /// An identity may be split across inputs: every input has to contribute it or end first.
194 #[default]
195 MergeInputs,
196 /// The producer guarantees each identity appears as one complete chain on one input partition.
197 /// The router may publish a closed chain immediately and does not retain history to validate
198 /// that guarantee after publication.
199 CompleteDisjoint,
200}
201
202/// How the claim of an output reads this node's child.
203///
204/// The child is read once, for whichever of the two ways its consumer asked for first - the frames
205/// this node publishes, or the chunks it hands over - and the second claim is refused, so the two
206/// cannot disagree about it.
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208enum InputRead {
209 /// The consumer reads frames: the child is executed and its frames are decoded here.
210 Frames,
211 /// The consumer reads chunks: the child is asked for its chunks when it can hand them over, and
212 /// decoded here only when it cannot.
213 Chunks,
214}
215
216impl InputRead {
217 /// What this way of reading is, for a refusal that has to name both.
218 fn as_str(&self) -> &'static str {
219 match self {
220 Self::Frames => "frames",
221 Self::Chunks => "chunks",
222 }
223 }
224}
225
226/// One child partition, as this node reads it: its chunks when it hands them over, its frames when
227/// it does not.
228///
229/// `hand_over` is the child as a native operator, decided once for the whole read: with it, the
230/// partition is read in process and wrapped in the form this node's chain assembly expects; without
231/// it, the partition is executed and its frames decoded here.
232#[allow(clippy::too_many_arguments)]
233fn routed_input(
234 input: &Arc<dyn ExecutionPlan>,
235 hand_over: Option<&dyn SeriesExecutionPlan>,
236 content: FrameContent,
237 series_schema: &Arc<SeriesSchema>,
238 state: Option<&Arc<AggregateStateSchema>>,
239 declared_ordering: SeriesOrdering,
240 partition: usize,
241 context: &Arc<TaskContext>,
242) -> DataFusionResult<RoutedInput> {
243 if let Some(plan) = hand_over {
244 // A handed-over stream is checked against the order its own plan declares, exactly as a
245 // decoded frame is: this node narrows what it publishes, but the child's promise is what its
246 // chunks were produced under, and a chain that breaks it has to be refused here too.
247 let chunks = checked_series_stream(
248 plan.execute_series(partition, Arc::clone(context))?,
249 declared_ordering,
250 );
251 return Ok(match content {
252 FrameContent::Evaluated => {
253 RoutedInput::Evaluated(Box::pin(HeldSeriesCharges::evaluated(chunks)))
254 }
255 FrameContent::Raw => {
256 RoutedInput::Raw(HeldSeriesCharges::raw(chunks, Arc::clone(series_schema)))
257 }
258 FrameContent::AggregateState => {
259 // A chunk carries its own declaration, so the state this node declared is what the
260 // read is held to; without it there is nothing to hold the chunk to.
261 let state = state.ok_or_else(|| {
262 DataFusionError::Plan("aggregate state declaration is missing".into())
263 })?;
264 RoutedInput::StateChunks(chunks, Arc::clone(state), Arc::clone(series_schema))
265 }
266 });
267 }
268 let frames = input.execute(partition, Arc::clone(context))?;
269 // The expected schema is a check and never an input: the decoder reads the frame's own
270 // declaration, and a partition declaring another frame is refused here rather than routed
271 // under labels it does not carry.
272 Ok(match content {
273 FrameContent::Evaluated => RoutedInput::Evaluated(unpack_evaluated_series(
274 frames,
275 Some(Arc::clone(series_schema)),
276 )?),
277 FrameContent::Raw => {
278 // The node publishes labels, so a child that names them by its key is decoded here,
279 // where the frames are already unpacked. An already-labelled stream passes through
280 // untouched.
281 let stream = unpack_raw_series(frames, Some(Arc::clone(series_schema)))?;
282 let stream = crate::source::materialize_raw_labels(stream)
283 .map_err(|error| DataFusionError::External(Box::new(error)))?;
284 RoutedInput::Raw(stream)
285 }
286 FrameContent::AggregateState => {
287 let state = state.ok_or_else(|| {
288 DataFusionError::Plan("aggregate state declaration is missing".into())
289 })?;
290 RoutedInput::State(frames, Arc::clone(state), Arc::clone(series_schema))
291 }
292 })
293}
294
295/// A child's chunks, read as the series this node's chain assembly expects.
296///
297/// The producer's charge for a chunk is held until the next poll instead of being dropped with the
298/// conversion: by then this node has grown its own reservation for what it queued, so there is no
299/// moment at which the bytes are charged to nobody. That is the same hand-off the frame consumers
300/// make when they keep a batch's charge through the next poll.
301struct HeldSeriesCharges {
302 /// The child's chunks.
303 chunks: SendableSeriesStream,
304 /// What this stream is read as, so another content is refused rather than reinterpreted.
305 content: FrameContent,
306 /// The charge of the chunk handed out last, released when the next one is read.
307 held: Option<SeriesCharge>,
308}
309
310impl HeldSeriesCharges {
311 /// `chunks` read as evaluated series.
312 fn evaluated(chunks: SendableSeriesStream) -> SendableEvaluatedSeriesStream {
313 Box::pin(HeldEvaluated {
314 inner: HeldSeriesCharges {
315 chunks,
316 content: FrameContent::Evaluated,
317 held: None,
318 },
319 })
320 }
321
322 /// `chunks` read as raw series declared on `schema`.
323 ///
324 /// The chunks already carry complete labels - that is what a raw producer hands over - so the
325 /// stream declares no decode description and no bound source, which is what a decoding consumer
326 /// reads to decide it has nothing to decode.
327 fn raw(chunks: SendableSeriesStream, schema: Arc<SeriesSchema>) -> SendableRawSeriesStream {
328 Box::pin(HeldRaw {
329 inner: HeldSeriesCharges {
330 chunks,
331 content: FrameContent::Raw,
332 held: None,
333 },
334 schema,
335 label_source: RawLabelSource::Explicit,
336 })
337 }
338
339 /// The next chunk, with the charge of the previous one released first.
340 fn next_chunk(
341 &mut self,
342 cx: &mut Context<'_>,
343 ) -> Poll<Option<Result<SeriesChunk, BoxedError>>> {
344 self.held = None;
345 match self.chunks.as_mut().poll_next(cx) {
346 Poll::Ready(Some(Ok(handed))) => {
347 let (chunk, charge) = handed.into_parts();
348 self.held = charge;
349 Poll::Ready(Some(Ok(chunk)))
350 }
351 Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
352 Poll::Ready(None) => Poll::Ready(None),
353 Poll::Pending => Poll::Pending,
354 }
355 }
356
357 /// The error a child hands over a content this stream is not read as.
358 fn refused(&self, chunk: &SeriesChunk) -> BoxedError {
359 boxed(DataFusionError::Execution(format!(
360 "a {} input handed over {chunk:?}",
361 self.content.as_str()
362 )))
363 }
364}
365
366/// [`HeldSeriesCharges`] read as evaluated series.
367struct HeldEvaluated {
368 inner: HeldSeriesCharges,
369}
370
371impl Stream for HeldEvaluated {
372 type Item = Result<(Series, bool), BoxedError>;
373
374 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
375 let this = self.get_mut();
376 match this.inner.next_chunk(cx) {
377 Poll::Ready(Some(Ok(SeriesChunk::Evaluated(chunk)))) => {
378 Poll::Ready(Some(Ok((chunk.series, chunk.is_last))))
379 }
380 Poll::Ready(Some(Ok(other))) => {
381 let error = this.inner.refused(&other);
382 Poll::Ready(Some(Err(error)))
383 }
384 Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
385 Poll::Ready(None) => Poll::Ready(None),
386 Poll::Pending => Poll::Pending,
387 }
388 }
389}
390
391/// [`HeldSeriesCharges`] read as raw series.
392struct HeldRaw {
393 inner: HeldSeriesCharges,
394 schema: Arc<SeriesSchema>,
395 label_source: RawLabelSource,
396}
397
398impl RawSeriesStream for HeldRaw {
399 fn schema(&self) -> &Arc<SeriesSchema> {
400 &self.schema
401 }
402
403 fn label_source(&self) -> &RawLabelSource {
404 &self.label_source
405 }
406
407 fn ordering(&self) -> SeriesOrdering {
408 SeriesOrdering::Contiguous
409 }
410}
411
412impl Stream for HeldRaw {
413 type Item = Result<RawSeriesChunk, BoxedError>;
414
415 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
416 let this = self.get_mut();
417 match this.inner.next_chunk(cx) {
418 Poll::Ready(Some(Ok(SeriesChunk::Raw(chunk)))) => Poll::Ready(Some(Ok(chunk))),
419 Poll::Ready(Some(Ok(other))) => {
420 let error = this.inner.refused(&other);
421 Poll::Ready(Some(Err(error)))
422 }
423 Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
424 Poll::Ready(None) => Poll::Ready(None),
425 Poll::Pending => Poll::Pending,
426 }
427 }
428}
429
430/// The Repartition stage: one child's partitions, redistributed by canonical label set.
431///
432/// The node holds one execution's shared state: its output partitions are separate `execute` calls
433/// that must agree on one read of the child, so the first call starts the read and every call takes
434/// its own output from it.
435pub struct SeriesRepartitionExec {
436 input: Arc<dyn ExecutionPlan>,
437 /// The child frame's series schema, re-declared by every output batch.
438 series_schema: Arc<SeriesSchema>,
439 /// The one hash configuration of this node's execution.
440 routing: Routing,
441 routing_policy: SeriesRouting,
442 identity_completion: IdentityCompletion,
443 content: FrameContent,
444 state: Option<Arc<AggregateStateSchema>>,
445 ordering: SeriesOrdering,
446 /// Started by the first `execute` call, since the output partitions share one read of the child.
447 shared: Mutex<Option<Arc<SharedExecution>>>,
448 properties: Arc<PlanProperties>,
449}
450
451impl SeriesRepartitionExec {
452 /// The name this node is shown under.
453 pub const fn name() -> &'static str {
454 "SeriesRepartitionExec"
455 }
456
457 /// Creates the node over `input`, routing into `outputs` partitions.
458 ///
459 /// `outputs` is fixed here, by the planner, which knows the target partition count; the node
460 /// reads no session configuration of its own. A child that does not declare an evaluated frame
461 /// this node can re-declare is refused before the plan can run: the output schema is the child's,
462 /// and a frame whose declaration does not survive the round trip would be published under a
463 /// schema its batches do not match.
464 pub fn try_new(input: Arc<dyn ExecutionPlan>, outputs: usize) -> DataFusionResult<Self> {
465 let declaration =
466 SeriesFrameDeclaration::parse(input.schema().as_ref()).map_err(|error| {
467 DataFusionError::Plan(format!(
468 "SeriesRepartition input is not a series frame: {error}"
469 ))
470 })?;
471 let policy = match declaration.content() {
472 FrameContent::Evaluated => SeriesRouting::CanonicalLabels,
473 FrameContent::Raw => SeriesRouting::RawPrimaryKey,
474 FrameContent::AggregateState => SeriesRouting::CanonicalLabels,
475 };
476 Self::try_new_with_routing(input, outputs, policy)
477 }
478
479 /// Creates a node for an input whose producer guarantees each identity is one complete chain
480 /// on one input partition. Closed identities are published immediately; later duplicate chains
481 /// are not detected, so callers must uphold the producer guarantee.
482 pub fn try_new_complete_disjoint(
483 input: Arc<dyn ExecutionPlan>,
484 outputs: usize,
485 ) -> DataFusionResult<Self> {
486 let declaration =
487 SeriesFrameDeclaration::parse(input.schema().as_ref()).map_err(|error| {
488 DataFusionError::Plan(format!(
489 "SeriesRepartition input is not a series frame: {error}"
490 ))
491 })?;
492 let policy = match declaration.content() {
493 FrameContent::Evaluated => SeriesRouting::CanonicalLabels,
494 FrameContent::Raw => SeriesRouting::RawPrimaryKey,
495 FrameContent::AggregateState => {
496 return Err(DataFusionError::NotImplemented(
497 "a complete-disjoint router cannot prove aggregate state ownership; use the \
498 ordinary canonical-label routing for state frames"
499 .into(),
500 ));
501 }
502 };
503 Self::try_new_with_completion(input, outputs, policy, IdentityCompletion::CompleteDisjoint)
504 }
505
506 /// Creates the node with an explicit content-compatible routing policy.
507 pub fn try_new_with_routing(
508 input: Arc<dyn ExecutionPlan>,
509 outputs: usize,
510 routing_policy: SeriesRouting,
511 ) -> DataFusionResult<Self> {
512 Self::try_new_with_completion(
513 input,
514 outputs,
515 routing_policy,
516 IdentityCompletion::MergeInputs,
517 )
518 }
519
520 fn try_new_with_completion(
521 input: Arc<dyn ExecutionPlan>,
522 outputs: usize,
523 routing_policy: SeriesRouting,
524 identity_completion: IdentityCompletion,
525 ) -> DataFusionResult<Self> {
526 if outputs == 0 {
527 return Err(DataFusionError::Plan(
528 "SeriesRepartition requires at least one output partition".to_string(),
529 ));
530 }
531 if input.properties().boundedness.is_unbounded() {
532 return Err(DataFusionError::Plan(
533 "SeriesRepartition requires a finite input to finalize series identities".into(),
534 ));
535 }
536 let declaration =
537 SeriesFrameDeclaration::parse(input.schema().as_ref()).map_err(|error| {
538 DataFusionError::Plan(format!(
539 "SeriesRepartition input is not a series frame: {error}"
540 ))
541 })?;
542 let content = declaration.content();
543 match (content, &routing_policy) {
544 (FrameContent::Evaluated, SeriesRouting::RawPrimaryKey) => {
545 return Err(DataFusionError::Plan(
546 "SeriesRepartition evaluated frames cannot use RawPrimaryKey routing".into(),
547 ));
548 }
549 (
550 FrameContent::Raw,
551 SeriesRouting::CanonicalLabels | SeriesRouting::CanonicalLabelsExcept(_),
552 ) => {
553 return Err(DataFusionError::Plan(
554 "SeriesRepartition raw frames cannot use CanonicalLabels routing".into(),
555 ));
556 }
557 (
558 FrameContent::AggregateState,
559 SeriesRouting::RawPrimaryKey | SeriesRouting::Matching(_),
560 ) => {
561 return Err(DataFusionError::Plan(
562 "SeriesRepartition aggregate-state frames require canonical-label routing"
563 .into(),
564 ));
565 }
566 _ => {}
567 }
568 let series_schema = Arc::new(declaration.series().clone());
569 let ordering = if content == FrameContent::Raw {
570 common_query::series_frame::series_frame_ordering(input.schema().as_ref())?
571 } else {
572 SeriesOrdering::Contiguous
573 };
574 if content == FrameContent::Raw
575 && ordering == SeriesOrdering::Interleaved
576 && identity_completion == IdentityCompletion::CompleteDisjoint
577 {
578 return Err(DataFusionError::Plan(
579 "SeriesRepartition cannot use CompleteDisjoint with interleaved raw input".into(),
580 ));
581 }
582 let output_ordering = if ordering == SeriesOrdering::Interleaved {
583 SeriesOrdering::Contiguous
584 } else {
585 ordering
586 };
587 let declared = match content {
588 FrameContent::Evaluated => common_query::series_frame::frame_schema_with(
589 &series_schema,
590 FrameLabelMode::Explicit,
591 None,
592 SeriesOrdering::Contiguous,
593 )?,
594 FrameContent::Raw => raw_series_frame_schema_with_ordering(
595 &series_schema,
596 &store_api::region_engine::NO_BOUND_LABEL_SOURCE,
597 output_ordering,
598 )?,
599 FrameContent::AggregateState => input.schema(),
600 };
601 // The input is re-declared from what it says about itself, not from what this node
602 // publishes: the two differ whenever the child carries its labels in its keys.
603 let rebuilt_input = if content == FrameContent::AggregateState {
604 None
605 } else {
606 Some(
607 common_query::series_frame::frame_schema_with(
608 &series_schema,
609 declaration.labels(),
610 declaration.label_decode(),
611 ordering,
612 )
613 .map_err(|error| DataFusionError::Plan(error.to_string()))?,
614 )
615 };
616 if rebuilt_input.is_some_and(|rebuilt| rebuilt != input.schema()) {
617 return Err(DataFusionError::Plan(
618 "SeriesRepartition input frame carries a schema this node cannot re-declare"
619 .to_string(),
620 ));
621 }
622 let properties = PlanProperties::new(
623 EquivalenceProperties::new(declared),
624 Partitioning::UnknownPartitioning(outputs),
625 // Interleaved raw identities can recur until every input has ended.
626 if ordering == SeriesOrdering::Interleaved {
627 EmissionType::Final
628 } else {
629 EmissionType::Incremental
630 },
631 // The node ends when its child does, and spends its life waiting until then.
632 input.properties().boundedness,
633 )
634 .with_evaluation_type(EvaluationType::Eager)
635 .with_scheduling_type(SchedulingType::Cooperative);
636 let state = declaration.aggregate_state().cloned().map(Arc::new);
637 let properties = Arc::new(properties);
638 Ok(Self {
639 input,
640 series_schema,
641 routing: Routing::with_policy(outputs, routing_policy.clone()),
642 routing_policy,
643 identity_completion,
644 content,
645 state,
646 ordering,
647 shared: Mutex::new(None),
648 properties,
649 })
650 }
651
652 /// The routing policy used by this node.
653 pub fn routing_policy(&self) -> &SeriesRouting {
654 &self.routing_policy
655 }
656
657 pub fn identity_completion(&self) -> IdentityCompletion {
658 self.identity_completion
659 }
660
661 /// How many output partitions this node has.
662 pub fn outputs(&self) -> usize {
663 self.properties.partitioning.partition_count()
664 }
665
666 /// The queue of `partition` and the lease on this read that reading it takes.
667 ///
668 /// Both public entry points take an output through here - the frames it publishes and the chunks
669 /// it hands over are the same publication, read two ways - so an output is claimed once no
670 /// matter which of them is asked for, and asking for both is the error it has always been.
671 fn claim_output(
672 &self,
673 partition: usize,
674 context: &Arc<TaskContext>,
675 read: InputRead,
676 ) -> DataFusionResult<(mpsc::UnboundedReceiver<Queued>, OutputLease)> {
677 if partition >= self.outputs() {
678 return Err(DataFusionError::Execution(format!(
679 "SeriesRepartition output partition {partition} is out of range"
680 )));
681 }
682 let shared = {
683 let mut state = self
684 .shared
685 .lock()
686 .unwrap_or_else(|error| error.into_inner());
687 if state.is_none() {
688 // The whole execution is started here, once: the output partitions are separate
689 // calls, and reading the child once for all of them is what keeps a chunk from being
690 // emitted twice or read by a scan that was never meant to run twice.
691 *state = Some(SharedExecution::start(
692 &self.input,
693 self.routing.clone(),
694 Arc::clone(&self.series_schema),
695 self.state.clone(),
696 context,
697 read,
698 )?);
699 }
700 let shared = Arc::clone(state.as_ref().expect("the execution was just started"));
701 // One read, one way of reading the child: an output that asks for the other form would
702 // be answered from a stream it did not ask for, so it is refused here rather than
703 // handed the wrong one.
704 if shared.read != read {
705 return Err(DataFusionError::Execution(format!(
706 "SeriesRepartition was already read as {} for an earlier output, so output \
707 partition {partition} cannot read it as {}",
708 shared.read.as_str(),
709 read.as_str()
710 )));
711 }
712 shared
713 };
714 SharedExecution::claim(&shared, partition).ok_or_else(|| {
715 DataFusionError::Execution(format!(
716 "SeriesRepartition output partition {partition} was executed twice"
717 ))
718 })
719 }
720
721 /// One claimed output as the owner that merges it: the queue, its charge, and its lease.
722 fn partition_stream(
723 &self,
724 receiver: mpsc::UnboundedReceiver<Queued>,
725 lease: OutputLease,
726 context: &Arc<TaskContext>,
727 ) -> RepartitionStream {
728 RepartitionStream::new(
729 receiver,
730 lease,
731 Arc::clone(&self.series_schema),
732 &context.runtime_env().memory_pool,
733 self.input.properties().partitioning.partition_count(),
734 self.ordering,
735 self.identity_completion,
736 )
737 }
738
739 /// One claimed output's exported state, as the rows the queue carries.
740 ///
741 /// The decoder is built from the schema this node publishes, which is the schema a frame
742 /// consumer would parse, and it is run once on an empty batch before the read starts: a
743 /// declaration this revision cannot read is refused here rather than on the first row, which is
744 /// exactly what `unpack_aggregate_state` does for the frame path.
745 fn state_chunk_stream(
746 &self,
747 receiver: mpsc::UnboundedReceiver<Queued>,
748 lease: OutputLease,
749 ) -> DataFusionResult<StateChunkOutputStream> {
750 let frame_schema = self.input.schema();
751 let declaration = SeriesFrameDeclaration::parse(frame_schema.as_ref())
752 .map_err(|error| DataFusionError::Execution(error.to_string()))?;
753 let state = declaration.aggregate_state().ok_or_else(|| {
754 DataFusionError::Execution(
755 "SeriesRepartition aggregate-state output declares no aggregate state".to_string(),
756 )
757 })?;
758 let decoder = SeriesFrameDecoder::try_new_aggregate_state(
759 state,
760 &self.series_schema,
761 FrameLabelMode::Explicit,
762 )
763 .map_err(|error| DataFusionError::Execution(error.to_string()))?;
764 decoder
765 .decode_aggregate_state(&RecordBatch::new_empty(Arc::clone(&frame_schema)))
766 .map_err(|error| DataFusionError::Execution(error.to_string()))?;
767 Ok(StateChunkOutputStream {
768 decoder,
769 frame_schema,
770 receiver,
771 lease,
772 pending: VecDeque::new(),
773 reported: false,
774 })
775 }
776}
777
778impl fmt::Debug for SeriesRepartitionExec {
779 /// The node and what it routes: the child, the schema and the running execution are noise in a
780 /// plan's debug form.
781 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
782 f.debug_struct("SeriesRepartitionExec")
783 .field("outputs", &self.outputs())
784 .finish_non_exhaustive()
785 }
786}
787
788impl DisplayAs for SeriesRepartitionExec {
789 fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
790 write!(
791 f,
792 "SeriesRepartitionExec: outputs={}, input_partitions={}",
793 self.outputs(),
794 self.input.properties().partitioning.partition_count()
795 )
796 }
797}
798
799impl ExecutionPlan for SeriesRepartitionExec {
800 fn name(&self) -> &str {
801 Self::name()
802 }
803
804 fn properties(&self) -> &Arc<PlanProperties> {
805 &self.properties
806 }
807
808 /// Nothing is asked of the input's distribution, and nothing may be inserted above it.
809 ///
810 /// The child's own partitioning is what this node reads: it reads every partition as it is, and
811 /// an exchange inserted between the two would reorder chunks across the chain boundaries the node
812 /// relies on, which no requirement it states could survive. A hash requirement would be worse
813 /// still, since the routing key is decoded from the rows rather than computed by an expression.
814 fn input_distribution_requirements(&self) -> InputDistributionRequirements {
815 InputDistributionRequirements::new(vec![Distribution::UnspecifiedDistribution])
816 }
817
818 /// Splitting the child further would not help: this node reads every input partition itself, so
819 /// a repartition below it only adds a hop that reorders what it must read in order.
820 fn benefits_from_input_partitioning(&self) -> Vec<bool> {
821 vec![false]
822 }
823
824 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
825 vec![&self.input]
826 }
827
828 fn apply_expressions(
829 &self,
830 _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
831 ) -> DataFusionResult<TreeNodeRecursion> {
832 // The routing key is decoded from the rows, so this node binds no expression of its own.
833 Ok(TreeNodeRecursion::Continue)
834 }
835
836 fn with_new_children(
837 self: Arc<Self>,
838 mut children: Vec<Arc<dyn ExecutionPlan>>,
839 ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
840 if children.len() != 1 {
841 return Err(DataFusionError::Plan(format!(
842 "SeriesRepartitionExec requires one child, got {}",
843 children.len()
844 )));
845 }
846 // Rebuilt rather than patched, so a child whose schema changed is refused here instead of
847 // routed under a frame declaration the new child does not make.
848 Ok(Arc::new(Self::try_new_with_completion(
849 children.swap_remove(0),
850 self.outputs(),
851 self.routing_policy.clone(),
852 self.identity_completion,
853 )?))
854 }
855
856 fn execute(
857 &self,
858 partition: usize,
859 context: Arc<TaskContext>,
860 ) -> DataFusionResult<SendableRecordBatchStream> {
861 let (receiver, lease) = self.claim_output(partition, &context, InputRead::Frames)?;
862 if self.content == FrameContent::AggregateState {
863 return Ok(Box::pin(StateBatchOutputStream {
864 schema: self.input.schema(),
865 receiver,
866 lease,
867 retained: None,
868 reported: false,
869 }));
870 }
871 let inner = self.partition_stream(receiver, lease, &context);
872 let handoff = Arc::clone(&inner.handoff);
873 let output: SendableRecordBatchStream = match self.content {
874 FrameContent::Evaluated => pack_evaluated_series(
875 Box::pin(EvaluatedOutputStream {
876 inner: Some(Box::pin(inner)),
877 }),
878 Arc::clone(&self.series_schema),
879 )?,
880 FrameContent::Raw => {
881 let raw = RawOutputStream {
882 inner: Some(Box::pin(inner)),
883 schema: Arc::clone(&self.series_schema),
884 ordering: if self.ordering == SeriesOrdering::Interleaved {
885 SeriesOrdering::Contiguous
886 } else {
887 self.ordering
888 },
889 };
890 // Repartition runs inside the query engine's DataFusion execution, whose runtimes
891 // enable the time driver, so the packer may hold a partially filled batch across a
892 // pending period.
893 pack_raw_series_with(Box::pin(raw), PendingBatching::Deadline)?
894 }
895 FrameContent::AggregateState => unreachable!("aggregate state output handled above"),
896 };
897 let schema = output.schema();
898 let output = Box::pin(PackedHandoffStream {
899 inner: Some(output),
900 schema,
901 handoff,
902 });
903 Ok(datafusion::physical_plan::coop::make_cooperative(output))
904 }
905}
906
907impl SeriesExecutionPlan for SeriesRepartitionExec {
908 fn as_any(&self) -> &dyn Any {
909 self
910 }
911
912 /// One owner's publications, as the chunks they are.
913 ///
914 /// This is [`ExecutionPlan::execute`] without the encode: the same claim of the same output of
915 /// the same read, the same owner merging the same identity, and the values that owner produced
916 /// handed over instead of packed into a frame. An evaluated publication leaves as one closed
917 /// chunk - the owner publishes an identity once, already merged, which is exactly the `is_last`
918 /// the packer's evaluated stream declares - and a raw one as the chunk whose finality
919 /// [`merge_raw_identity_charging`] recomputed for the whole identity.
920 ///
921 /// Everything the owner reserved for that publication rides along with the value
922 /// ([`SeriesCharge`]), because the consumer holds the bytes those reservations account for: the
923 /// frame path holds them in the packer's handoff until the batch is flushed, and there is no
924 /// packer here to hold them.
925 ///
926 /// A state publication is the one content this node does not merge: it forwards the exported row
927 /// of a group its child folded, on the same queue and the same lease as the frames it would have
928 /// published ([`StateChunkOutputStream`]), so the two entry points stay one read of one output.
929 fn execute_series(
930 &self,
931 partition: usize,
932 context: Arc<TaskContext>,
933 ) -> DataFusionResult<SendableSeriesStream> {
934 let (receiver, lease) = self.claim_output(partition, &context, InputRead::Chunks)?;
935 match self.content {
936 FrameContent::Raw | FrameContent::Evaluated => {
937 let inner = self.partition_stream(receiver, lease, &context);
938 Ok(Box::pin(ChunkOutputStream {
939 inner: Some(Box::pin(inner)),
940 content: self.content,
941 }))
942 }
943 FrameContent::AggregateState => Ok(Box::pin(self.state_chunk_stream(receiver, lease)?)),
944 }
945 }
946}
947
948/// One owner's exported state, as the rows it is.
949///
950/// The queue, the lease and the charge are [`StateBatchOutputStream`]'s: this node does not merge
951/// state, it forwards the row a group was exported as. The only thing that changes is the form -
952/// the batch the queue carries is decoded into the rows it holds, by the same
953/// [`SeriesFrameDeclaration`] decoder a frame consumer would have used, and each row is handed over
954/// with the charge of the batch it points into. So a consumer reads the same rows either way, and
955/// the batch is never re-encoded.
956struct StateChunkOutputStream {
957 /// The decoder the exported batches are read with, which is the frame path's decoder.
958 decoder: SeriesFrameDecoder,
959 /// The schema every exported batch carries, checked before it is decoded.
960 frame_schema: SchemaRef,
961 /// The owner's queue, shared with the frames this output would otherwise publish.
962 receiver: mpsc::UnboundedReceiver<Queued>,
963 /// The claim on this read, released when this output ends.
964 lease: OutputLease,
965 /// Rows decoded from the batch last taken off the queue, in the order the frame carries them.
966 pending: VecDeque<HandedSeriesChunk>,
967 reported: bool,
968}
969
970/// How many empty exported batches one poll reads before yielding, mirroring the frame consumer's
971/// own guard so a producer of empty batches cannot hold the task.
972const MAX_EMPTY_STATE_BATCHES_PER_POLL: usize = 32;
973
974impl StateChunkOutputStream {
975 /// Ends this output with a failure, draining the queue and releasing the rows it still held.
976 ///
977 /// The frame output ends exactly this way: the read fails once, every queued item is dropped
978 /// with its charge, and the output reports the first failure rather than a second one.
979 fn failed(
980 &mut self,
981 reason: impl Into<String>,
982 ) -> Poll<Option<Result<HandedSeriesChunk, BoxedError>>> {
983 let reason = reason.into();
984 self.lease
985 .fail(Arc::new(DataFusionError::Execution(reason.clone())));
986 self.reported = true;
987 self.receiver.close();
988 while self.receiver.try_recv().is_ok() {}
989 self.pending.clear();
990 Poll::Ready(Some(Err(boxed(DataFusionError::Execution(reason)))))
991 }
992}
993
994impl Stream for StateChunkOutputStream {
995 type Item = Result<HandedSeriesChunk, BoxedError>;
996
997 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
998 let this = &mut *self;
999 if this.reported {
1000 return Poll::Ready(None);
1001 }
1002 let mut empty_batches = 0;
1003 loop {
1004 if let Some(chunk) = this.pending.pop_front() {
1005 return Poll::Ready(Some(Ok(chunk)));
1006 }
1007 if let Ending::Failed(error) = this.lease.shared.ending() {
1008 this.reported = true;
1009 this.receiver.close();
1010 while this.receiver.try_recv().is_ok() {}
1011 return Poll::Ready(Some(Err(boxed(DataFusionError::from(&error)))));
1012 }
1013 match this.receiver.poll_recv(cx) {
1014 Poll::Pending => return Poll::Pending,
1015 Poll::Ready(Some(Queued::StateBatch {
1016 batch,
1017 row,
1018 _charge,
1019 _metadata,
1020 })) => {
1021 // The queue publishes either the whole batch or the one row a multi-output
1022 // routing selected, exactly as the frame output reads it.
1023 let batch = match row {
1024 Some(row) => batch.slice(row, 1),
1025 None => batch.as_ref().clone(),
1026 };
1027 if batch.schema().as_ref() != this.frame_schema.as_ref() {
1028 return this.failed("aggregate state frame schema mismatch");
1029 }
1030 let rows = match this.decoder.decode_aggregate_state(&batch) {
1031 Ok(rows) => rows,
1032 Err(error) => return this.failed(error.to_string()),
1033 };
1034 if rows.is_empty() {
1035 empty_batches += 1;
1036 if empty_batches == MAX_EMPTY_STATE_BATCHES_PER_POLL {
1037 cx.waker().wake_by_ref();
1038 return Poll::Pending;
1039 }
1040 continue;
1041 }
1042 // One batch, one reservation, shared by every row cut from it: the bytes are
1043 // live while any of those rows is, and released when the last one is dropped.
1044 let metadata = Arc::new(_metadata);
1045 for row in rows {
1046 let row = match state_row_of(row) {
1047 Ok(row) => row,
1048 Err(error) => return this.failed(error.to_string()),
1049 };
1050 this.pending.push_back(HandedSeriesChunk::charged(
1051 SeriesChunk::State(StateChunk::Row(row)),
1052 SeriesCharge::shared(vec![Arc::clone(&_charge), Arc::clone(&metadata)]),
1053 ));
1054 }
1055 }
1056 Poll::Ready(Some(Queued::StateChunk(queued))) => {
1057 let QueuedStateChunk {
1058 chunk,
1059 _charge,
1060 _metadata,
1061 child,
1062 } = *queued;
1063 // A child that answered with its chunks has already done what this output's
1064 // frame form would do, so the group is handed on as it is; only the charge this
1065 // node queued it with moves onto the value, together with what the child charged
1066 // for the publication the group was cut from. The group is a slice of that
1067 // publication, so those bytes are still live while it is held.
1068 let mut shared = child.map_or_else(Vec::new, |child| (*child).clone());
1069 shared.push(Arc::new(_charge));
1070 shared.push(Arc::new(_metadata));
1071 this.pending.push_back(HandedSeriesChunk::charged(
1072 SeriesChunk::State(chunk),
1073 SeriesCharge::shared(shared),
1074 ));
1075 }
1076 Poll::Ready(Some(Queued::Eof { .. })) => {
1077 // The shared ending and the queue's closure establish completion; this message
1078 // is only a queue-order barrier.
1079 }
1080 Poll::Ready(Some(Queued::Chain { .. })) => {
1081 return this.failed("series router received a non-state message");
1082 }
1083 Poll::Ready(None) => {
1084 this.reported = true;
1085 this.pending.clear();
1086 return match this.lease.ending() {
1087 Some(Err(error)) => Poll::Ready(Some(Err(boxed(
1088 DataFusionError::External(Box::new(error)),
1089 )))),
1090 Some(Ok(_)) => unreachable!(),
1091 None => Poll::Ready(None),
1092 };
1093 }
1094 }
1095 }
1096 }
1097}
1098
1099/// One owner's publications as handed-over chunks.
1100///
1101/// The inner stream is [`RepartitionStream`], which decides what an owner publishes; this only
1102/// changes the form - a [`ReadyOutput`] becomes the [`SeriesChunk`] a native consumer reads - and
1103/// moves the charge of that publication out of the packer's handoff and onto the value.
1104struct ChunkOutputStream {
1105 /// The owner's stream, or `None` once this one ended.
1106 inner: Option<Pin<Box<RepartitionStream>>>,
1107 /// What this node publishes, so a raw publication cannot be handed over as an evaluated one.
1108 content: FrameContent,
1109}
1110
1111impl Stream for ChunkOutputStream {
1112 type Item = Result<HandedSeriesChunk, BoxedError>;
1113
1114 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1115 let this = &mut *self;
1116 let Some(inner) = this.inner.as_mut() else {
1117 return Poll::Ready(None);
1118 };
1119 let ready = match inner.as_mut().poll_next(cx) {
1120 Poll::Pending => return Poll::Pending,
1121 Poll::Ready(Some(Err(error))) => {
1122 this.inner = None;
1123 return Poll::Ready(Some(Err(error)));
1124 }
1125 Poll::Ready(None) => {
1126 this.inner = None;
1127 return Poll::Ready(None);
1128 }
1129 Poll::Ready(Some(Ok(ready))) => ready,
1130 };
1131 // The owner charged this publication just before publishing it, and the charge is the whole
1132 // of what the consumer's copy of the values keeps alive.
1133 let charge = inner.take_charge();
1134 let chunk = match (this.content, ready) {
1135 (FrameContent::Evaluated, ReadyOutput::Evaluated(series)) => {
1136 SeriesChunk::Evaluated(EvaluatedChunk {
1137 series,
1138 // A merged identity is final: the owner publishes it once, already closed.
1139 is_last: true,
1140 })
1141 }
1142 (FrameContent::Raw, ReadyOutput::Raw(chunk)) => SeriesChunk::Raw(chunk),
1143 (content, ready) => {
1144 this.inner = None;
1145 return Poll::Ready(Some(Err(boxed(DataFusionError::Internal(format!(
1146 "a {} repartition output carried {}",
1147 content.as_str(),
1148 ready.what()
1149 ))))));
1150 }
1151 };
1152 match charge {
1153 Some(charge) => Poll::Ready(Some(Ok(HandedSeriesChunk::charged(chunk, charge)))),
1154 // The charge stays where the frame path keeps it, so it is released with the handoff
1155 // rather than silently dropped here.
1156 None => Poll::Ready(Some(Ok(HandedSeriesChunk::uncharged(chunk)))),
1157 }
1158 }
1159}
1160
1161/// One execution's state: the child read once, and the outputs it is being distributed into.
1162///
1163/// The plan that started it holds this, and so does every output stream it hands out. The read it
1164/// owns lives while any of them does - which is what makes it survive the plan - and what stops it is
1165/// [`Running::claimed`] and [`Running::remaining`] both reaching zero, or the state itself going away.
1166struct SharedExecution {
1167 /// The queues, the tasks filling them, and how many of the execution's outputs the read still has.
1168 running: Mutex<Running>,
1169 /// How the read ended, and the failure it owes its outputs if it failed.
1170 ending: Arc<Mutex<Ending>>,
1171 /// The way this read's child is being read, fixed by the first output that claimed it.
1172 read: InputRead,
1173}
1174
1175/// What one execution's state holds that has to be stopped together.
1176struct Running {
1177 /// One receiver per output partition, taken by the `execute` call of that partition. A receiver
1178 /// that is never taken stays here with its pool-accounted queued chains.
1179 receivers: Vec<Option<mpsc::UnboundedReceiver<Queued>>>,
1180 /// The tasks reading the child's partitions into those queues, and how many of them are left.
1181 inputs: Arc<Inputs>,
1182 /// How many output streams were handed out and are not yet released.
1183 ///
1184 /// Counted rather than derived from a reference count, because the plan holds this state too and
1185 /// is not an output: what has to reach zero for the read to be over is the number of streams, not
1186 /// the number of owners.
1187 claimed: usize,
1188 /// How many outputs were never handed out, and can still be.
1189 ///
1190 /// Kept apart from [`claimed`](Self::claimed) because the two say different things: an output that
1191 /// is claimed is one somebody is reading, and one that is only `remaining` is one nobody has asked
1192 /// for yet. A claimed count that reaches zero with outputs left here has no active consumers
1193 /// yet, but those queues survive so a later `execute` can claim them.
1194 remaining: usize,
1195}
1196
1197impl Running {
1198 /// Stops the read: every queue nobody took is dropped and every input task is aborted.
1199 ///
1200 /// Idempotent - the queues are already gone on a second call, and aborting a finished or already
1201 /// aborted task is a no-op. Dropping the queues of outputs that were never handed out is part of
1202 /// it: what was queued for them is read-ahead nobody will take, and holding it until the process
1203 /// ends would keep both the memory and the child's scans alive for nothing.
1204 fn stop(&mut self) {
1205 self.receivers.clear();
1206 // Aborting a read that has not recorded an outcome is what the outputs still open have to
1207 // see: nothing was recorded, so the end they read is "the producer stopped unexpectedly".
1208 self.inputs.stop();
1209 }
1210}
1211
1212impl SharedExecution {
1213 /// Starts reading every partition of `input` into `routing`'s outputs on `context`'s pool.
1214 ///
1215 /// One task per child partition, started here: the child's computation happens inside its own
1216 /// `poll_next`, so a partition read on a task of another partition would run there, and the
1217 /// partition count the child declared would buy no parallelism at all.
1218 #[allow(clippy::too_many_arguments)]
1219 fn start(
1220 input: &Arc<dyn ExecutionPlan>,
1221 routing: Routing,
1222 series_schema: Arc<SeriesSchema>,
1223 state: Option<Arc<AggregateStateSchema>>,
1224 context: &Arc<TaskContext>,
1225 read: InputRead,
1226 ) -> DataFusionResult<Arc<Self>> {
1227 // What the child carries is what it declares, not what the policy suggests: a raw frame
1228 // can be routed by a match key too, so the policy no longer names the content.
1229 let content = SeriesFrameDeclaration::parse(input.schema().as_ref())
1230 .map_err(|error| DataFusionError::Plan(error.to_string()))?
1231 .content();
1232 // What the child promises about the order of what it publishes, which is what a chunk read
1233 // of it has to be held to.
1234 let declared_ordering = series_frame_ordering(input.schema().as_ref())?;
1235 let partitions = input.properties().partitioning.partition_count();
1236 // The child is asked for its chunks only when a reader of them claimed this read: the other
1237 // claim publishes frames, and a chunk read would have to be packed again.
1238 let hand_over = match read {
1239 InputRead::Chunks => series_execution_plan(input.as_ref()),
1240 InputRead::Frames => None,
1241 };
1242 let mut streams = Vec::with_capacity(partitions);
1243 for child_partition in 0..partitions {
1244 streams.push(routed_input(
1245 input,
1246 hand_over,
1247 content,
1248 &series_schema,
1249 state.as_ref(),
1250 declared_ordering,
1251 child_partition,
1252 context,
1253 )?);
1254 }
1255 let mut senders = Vec::with_capacity(routing.outputs);
1256 let mut receivers = Vec::with_capacity(routing.outputs);
1257 for _ in 0..routing.outputs {
1258 let (sender, receiver) = mpsc::unbounded_channel();
1259 senders.push(sender);
1260 receivers.push(Some(receiver));
1261 }
1262 let ending = Arc::new(Mutex::new(Ending::default()));
1263 let shared = Arc::new_cyclic(|weak| SharedExecution {
1264 read,
1265 running: Mutex::new(Running {
1266 receivers,
1267 inputs: Inputs::new(Arc::clone(&ending), partitions, weak.clone()),
1268 claimed: 0,
1269 remaining: routing.outputs,
1270 }),
1271 ending: Arc::clone(&ending),
1272 });
1273 let inputs = {
1274 let running = shared
1275 .running
1276 .lock()
1277 .unwrap_or_else(|error| error.into_inner());
1278 Arc::clone(&running.inputs)
1279 };
1280 // A child with no partitions has nothing to read, so the read finished before it started: the
1281 // count that the last input task would bring to zero is already there.
1282 if partitions == 0 {
1283 inputs.record(Ending::Finished);
1284 }
1285 let pool = Arc::clone(&context.runtime_env().memory_pool);
1286 for (partition, stream) in streams.into_iter().enumerate() {
1287 // Each task is handed its own copy of the senders rather than a lock over one copy: a
1288 // send is then a send of its own, and the queues close when the last task returns instead
1289 // of when some shared lock says so.
1290 let report = ReportIfUnreported {
1291 inputs: Arc::clone(&inputs),
1292 partition,
1293 reported: false,
1294 };
1295 let task = common_runtime::spawn_query(route_partition(
1296 stream,
1297 partition,
1298 routing.clone(),
1299 senders.clone(),
1300 // What this partition reads ahead is charged to its own consumer, so the read-ahead
1301 // of one partition is attributable to the task that did it.
1302 MemoryConsumer::new("SeriesRepartitionInput").register(&pool),
1303 Arc::clone(&inputs),
1304 report,
1305 ));
1306 inputs.attach(partition, task);
1307 }
1308 // This copy is dropped before any output exists, so it is no part of when the queues close.
1309 drop(senders);
1310 Ok(shared)
1311 }
1312
1313 /// The queue of `partition` and the lease on this read that reading it takes.
1314 ///
1315 /// The queue and the claim are taken under one lock, and that is what keeps the counts honest: an
1316 /// output stops being one nobody asked for and becomes one the read is running for in the same
1317 /// step, so a release on another task cannot see "nothing left" in between and stop a read that
1318 /// is being handed out. `None` means that output was claimed before - its queue is gone and this
1319 /// call does not count as one the read is running for.
1320 fn claim(
1321 shared: &Arc<Self>,
1322 partition: usize,
1323 ) -> Option<(mpsc::UnboundedReceiver<Queued>, OutputLease)> {
1324 let mut running = shared
1325 .running
1326 .lock()
1327 .unwrap_or_else(|error| error.into_inner());
1328 let receiver = running
1329 .receivers
1330 .get_mut(partition)
1331 .and_then(Option::take)?;
1332 running.remaining -= 1;
1333 running.claimed += 1;
1334 Some((
1335 receiver,
1336 OutputLease {
1337 shared: Arc::clone(shared),
1338 },
1339 ))
1340 }
1341
1342 /// Gives up one claim, and stops the read once there is nothing left it could deliver to.
1343 ///
1344 /// An output that is released is one that finished being read; outputs nobody has claimed yet can
1345 /// still be claimed later. Stop only when no output is being read and none remains to hand out.
1346 fn release_output(&self) {
1347 let mut running = self
1348 .running
1349 .lock()
1350 .unwrap_or_else(|error| error.into_inner());
1351 running.claimed -= 1;
1352 if running.claimed == 0 && running.remaining == 0 {
1353 running.stop();
1354 }
1355 }
1356
1357 /// How the read ended, and the failure it owes its outputs if it failed.
1358 ///
1359 /// Both are read under the one lock that records them, so an output never sees a failure without
1360 /// the error that belongs to it.
1361 fn ending(&self) -> Ending {
1362 self.ending
1363 .lock()
1364 .unwrap_or_else(|error| error.into_inner())
1365 .clone()
1366 }
1367
1368 /// Stops the read and releases everything it holds.
1369 ///
1370 /// Called when the execution itself goes away - the plan and every output are gone, so no later
1371 /// `execute` can claim an output that was never handed out - and by
1372 /// [`release_output`](Self::release_output) when the last claim is given up on an execution that
1373 /// has nothing left to hand out. Idempotent, because both can happen and because the state's own
1374 /// drop runs it once more.
1375 fn stop(&self) {
1376 let mut running = self
1377 .running
1378 .lock()
1379 .unwrap_or_else(|error| error.into_inner());
1380 running.stop();
1381 }
1382}
1383
1384impl Drop for SharedExecution {
1385 fn drop(&mut self) {
1386 // Nothing holds the read any more: every output is gone and so is the plan. No input task
1387 // may outlive both of them.
1388 self.stop();
1389 }
1390}
1391
1392/// The input tasks of one read: what is left of them, and what the last of them records.
1393///
1394/// One task reads each child partition. The tasks count themselves down; the last records completion
1395/// before returning and dropping its senders, so outputs read the recorded outcome when queues close.
1396struct Inputs {
1397 /// The tasks themselves, and the count of those that have not stopped.
1398 state: Mutex<InputState>,
1399 /// How the read ended, and the failure it owes its outputs if it failed.
1400 ending: Arc<Mutex<Ending>>,
1401 shared: Weak<SharedExecution>,
1402}
1403
1404/// What [`Inputs`] guards.
1405struct InputState {
1406 /// The task of each input partition, by partition, `None` once it stopped.
1407 ///
1408 /// Kept rather than dropped so that the read can be stopped as a whole, and so that the one task
1409 /// that records a failure can abort the rest: a partition whose peer already failed has
1410 /// nothing left to route that an output would still take.
1411 tasks: Vec<Option<common_runtime::JoinHandle<()>>>,
1412 /// How many of those tasks have not stopped yet.
1413 ///
1414 /// The last task to stop brings this to zero and records that the read finished. Cancelled peers
1415 /// are aborted and their report guards count them out; a task attached after cancellation is
1416 /// aborted by [`Inputs::attach`] and its guard does the same.
1417 live: usize,
1418 /// Whether the read has been cancelled: a failure was elected, or [`Inputs::stop`] was called.
1419 ///
1420 /// Recorded under the same lock that guards [`tasks`](Self::tasks), so a task attached after the
1421 /// cancellation is aborted by [`Inputs::attach`] rather than stored. The sweep that cancels the
1422 /// read can only abort the handles that exist when it runs, and a task spawned afterwards would
1423 /// otherwise continue polling a child for a read that is over while holding a sender to every
1424 /// output, keeping its queues open.
1425 cancelled: bool,
1426}
1427
1428impl Inputs {
1429 /// The bookkeeping of a read over `partitions` input partitions.
1430 fn new(
1431 ending: Arc<Mutex<Ending>>,
1432 partitions: usize,
1433 shared: Weak<SharedExecution>,
1434 ) -> Arc<Self> {
1435 Arc::new(Self {
1436 state: Mutex::new(InputState {
1437 tasks: (0..partitions).map(|_| None).collect(),
1438 live: partitions,
1439 cancelled: false,
1440 }),
1441 ending,
1442 shared,
1443 })
1444 }
1445
1446 /// Gives `task` the slot of `partition`, so that the read can still abort it.
1447 ///
1448 /// Stored even if the task has already stopped - a partition that answers at once can return
1449 /// before its handle is stored - because the slot is only consulted to stop what is still running,
1450 /// and aborting a finished task is a no-op.
1451 ///
1452 /// A task attached after cancellation is aborted rather than stored, so it cannot keep output
1453 /// queues open after the read is over. Its report guard counts it out if it is polled.
1454 fn attach(&self, partition: usize, task: common_runtime::JoinHandle<()>) {
1455 let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
1456 if state.cancelled {
1457 state.tasks[partition] = None;
1458 task.abort();
1459 return;
1460 }
1461 state.tasks[partition] = Some(task);
1462 }
1463
1464 /// Records that `partition` ended, and that the read finished if it was the last one running.
1465 ///
1466 /// A stopped or cancelled read cannot be reported as finished.
1467 fn ended(&self, partition: usize) {
1468 if self.count_out(partition) {
1469 self.record(Ending::Finished);
1470 }
1471 }
1472
1473 /// Records that `partition`'s task stopped without reporting an outcome, and stops the read with
1474 /// it.
1475 ///
1476 /// This runs where no arm of [`route_partition`]'s match can: in a `Drop`. A panic inside
1477 /// [`read_chains`] unwinds the task and drops the future that was polling it, and an abort drops
1478 /// that same future where it stands, so both land here - which is the point, because neither
1479 /// records anything otherwise. What that costs when nothing stops it is the whole read: the peers
1480 /// go on reading a child that may never answer, their sender clones stay alive, no queue closes,
1481 /// and every output waits for an ending that is not coming. So a task that died is a failure of
1482 /// the read, and it is recorded before peer tasks are aborted.
1483 ///
1484 /// A read that is already cancelled - stopped from outside or by a failure - only counts this task out. The outcome that cancelled it is the one
1485 /// the outputs report, and the aborts it performs are what killed this task: a task dying there is
1486 /// a consequence of that outcome, not a second one for the outputs to choose between.
1487 ///
1488 /// Nothing is sent to the outputs: a `Drop` cannot send asynchronously, and closing the senders
1489 /// lets every output observe the recorded failure.
1490 /// Delivery here is structural: a queue closes when the last of its senders is dropped, every input
1491 /// task holds a clone of every sender, and the peers cancelled here drop theirs as their futures
1492 /// are dropped - so the queues close with nobody sending anything. What an output whose queue has
1493 /// closed reads is [`RepartitionStream::poll_next`] at `Ready(None)`, which consults
1494 /// [`OutputLease::ending`] before calling the read over, and that turns the [`Ending::Failed`]
1495 /// recorded here into the error built from its terminal error. Every output therefore reports this
1496 /// failure out of the read's own record after all input senders close.
1497 fn task_died(&self, partition: usize) {
1498 if self.is_cancelled() {
1499 // The read has an outcome already, or another task's failure is the one being handed
1500 // over. Counting out only keeps the bookkeeping honest: the read is cancelled, so this
1501 // cannot make it look finished.
1502 self.count_out(partition);
1503 return;
1504 }
1505 // Record the error before cancellation drops this task's senders.
1506 self.fail(Arc::new(DataFusionError::Execution(format!(
1507 "series repartition input partition {partition} stopped without reporting an outcome"
1508 ))));
1509 self.cancel(partition);
1510 self.count_out(partition);
1511 }
1512
1513 /// Records the first failure before cancelling peers. Outputs read it after sender closure.
1514 fn failed(&self, partition: usize, error: &Arc<DataFusionError>) {
1515 self.fail(Arc::clone(error));
1516 self.cancel(partition);
1517 self.count_out(partition);
1518 }
1519
1520 fn is_cancelled(&self) -> bool {
1521 self.state
1522 .lock()
1523 .unwrap_or_else(|error| error.into_inner())
1524 .cancelled
1525 }
1526
1527 /// Marks the read cancelled under the task lock, then aborts its peer tasks.
1528 ///
1529 /// Cancellation keeps peers from recording a successful completion after this read has failed.
1530 fn cancel(&self, partition: usize) {
1531 {
1532 let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
1533 state.cancelled = true;
1534 }
1535 self.abort_others(partition);
1536 }
1537
1538 /// Counts `partition` off the read, and says whether it was the last task still running.
1539 fn count_out(&self, partition: usize) -> bool {
1540 let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
1541 // Taken and dropped: this task is the one stopping, and holding its own handle would leave the
1542 // read waiting for a task that has already finished.
1543 state.tasks[partition] = None;
1544 state.live -= 1;
1545 // A cancelled read never records that it finished: a failure is the outcome its outputs
1546 // report, and a stop is not an end.
1547 state.live == 0 && !state.cancelled
1548 }
1549
1550 /// Aborts every input task but `partition`'s own.
1551 ///
1552 /// Stops peer tasks after a failure or an unexpected task death. `partition`'s own task is spared
1553 /// so it can finish its bookkeeping, or because it has already died.
1554 fn abort_others(&self, partition: usize) {
1555 let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
1556 for (index, task) in state.tasks.iter().enumerate() {
1557 // Aborting a task that already stopped is a no-op, so the finished ones cost nothing
1558 // here.
1559 if index != partition
1560 && let Some(task) = task
1561 {
1562 task.abort();
1563 }
1564 }
1565 }
1566
1567 /// Stops every input task that has not stopped yet and marks the read cancelled, so a task
1568 /// attached after this sweep is aborted by [`attach`](Self::attach) rather than keeping queues
1569 /// open after the read is over.
1570 fn stop(&self) {
1571 let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
1572 state.cancelled = true;
1573 for task in state.tasks.iter_mut() {
1574 if let Some(task) = task.take() {
1575 task.abort();
1576 }
1577 }
1578 }
1579
1580 /// Records `outcome` as how the read ended, unless an ending is already recorded.
1581 ///
1582 /// A normal ending is recorded once. A failure is recorded by [`fail`](Self::fail), which stores
1583 /// its error in the same write.
1584 fn record(&self, outcome: Ending) {
1585 debug_assert!(
1586 !matches!(outcome, Ending::Failed(_)),
1587 "a failure is recorded by `fail`, with its error"
1588 );
1589 let mut ending = self
1590 .ending
1591 .lock()
1592 .unwrap_or_else(|error| error.into_inner());
1593 if matches!(*ending, Ending::Pending) {
1594 *ending = outcome;
1595 }
1596 }
1597
1598 /// Records that the read failed with `error`, keeping the error where its outputs can read it.
1599 ///
1600 /// The first failure and its error are recorded together so outputs all report the same error.
1601 fn fail(&self, error: Arc<DataFusionError>) {
1602 let mut ending = self
1603 .ending
1604 .lock()
1605 .unwrap_or_else(|error| error.into_inner());
1606 let first_failure = !matches!(*ending, Ending::Failed(_));
1607 if first_failure {
1608 *ending = Ending::Failed(error);
1609 }
1610 drop(ending);
1611 if first_failure && let Some(shared) = self.shared.upgrade() {
1612 let mut running = shared
1613 .running
1614 .lock()
1615 .unwrap_or_else(|error| error.into_inner());
1616 for receiver in running.receivers.iter_mut().flatten() {
1617 receiver.close();
1618 while receiver.try_recv().is_ok() {}
1619 }
1620 }
1621 }
1622
1623 /// How many input tasks have not stopped, which is what a test sees the read stop by.
1624 #[cfg(test)]
1625 fn live(&self) -> usize {
1626 self.state
1627 .lock()
1628 .unwrap_or_else(|error| error.into_inner())
1629 .live
1630 }
1631
1632 /// Aborts the task of one input partition, for a test that has to make exactly one producer stop.
1633 ///
1634 /// [`stop`](Self::stop) cannot state that: it stops every task and records the read as stopped,
1635 /// so what an output reports afterwards is the stop rather than one producer dying.
1636 #[cfg(test)]
1637 fn abort(&self, partition: usize) {
1638 let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
1639 if let Some(task) = &state.tasks[partition] {
1640 task.abort();
1641 }
1642 }
1643}
1644
1645/// Upper bound for transient arrays allocated by slicing one aggregate-state row. It counts each
1646/// schema node's concrete array object, two `usize` wrapper words, and one reference per child.
1647fn state_slice_wrapper_bytes(
1648 schema: &datafusion::arrow::datatypes::Schema,
1649) -> DataFusionResult<usize> {
1650 use datafusion::arrow::array::{
1651 ArrayRef, BinaryArray, BooleanArray, ListArray, PrimitiveArray, StringArray, StructArray,
1652 };
1653 use datafusion::arrow::datatypes::{DataType, Float64Type, UInt64Type};
1654 fn node(data_type: &DataType) -> DataFusionResult<usize> {
1655 let children = match data_type {
1656 DataType::Struct(fields) => fields
1657 .iter()
1658 .map(|field| node(field.data_type()))
1659 .collect::<DataFusionResult<Vec<_>>>()?,
1660 DataType::List(_) => Vec::new(),
1661 _ => Vec::new(),
1662 };
1663 let object = match data_type {
1664 DataType::Struct(_) => std::mem::size_of::<StructArray>(),
1665 DataType::List(_) => std::mem::size_of::<ListArray>(),
1666 DataType::Utf8 | DataType::LargeUtf8 => std::mem::size_of::<StringArray>(),
1667 DataType::Binary | DataType::LargeBinary => std::mem::size_of::<BinaryArray>(),
1668 DataType::Boolean => std::mem::size_of::<BooleanArray>(),
1669 DataType::Float64 => std::mem::size_of::<PrimitiveArray<Float64Type>>(),
1670 DataType::UInt64 => std::mem::size_of::<PrimitiveArray<UInt64Type>>(),
1671 // Frame schema types outside this list are bounded by the largest enumerated object.
1672 _ => [
1673 std::mem::size_of::<StructArray>(),
1674 std::mem::size_of::<ListArray>(),
1675 std::mem::size_of::<StringArray>(),
1676 std::mem::size_of::<BinaryArray>(),
1677 std::mem::size_of::<BooleanArray>(),
1678 std::mem::size_of::<PrimitiveArray<Float64Type>>(),
1679 std::mem::size_of::<PrimitiveArray<UInt64Type>>(),
1680 ]
1681 .into_iter()
1682 .max()
1683 .unwrap(),
1684 };
1685 object
1686 .checked_add(2 * std::mem::size_of::<usize>())
1687 .and_then(|bytes| bytes.checked_add(children.len() * std::mem::size_of::<ArrayRef>()))
1688 .and_then(|bytes| children.into_iter().try_fold(bytes, usize::checked_add))
1689 .ok_or_else(|| {
1690 DataFusionError::Execution("aggregate-state slice wrapper size overflow".into())
1691 })
1692 }
1693 let arrays = schema.fields().iter().try_fold(0usize, |bytes, field| {
1694 bytes.checked_add(node(field.data_type())?).ok_or_else(|| {
1695 DataFusionError::Execution("aggregate-state slice wrapper size overflow".into())
1696 })
1697 })?;
1698 // `RecordBatch::slice` also allocates the vector it collects the sliced columns into.
1699 arrays
1700 .checked_add(
1701 schema
1702 .fields()
1703 .len()
1704 .checked_mul(std::mem::size_of::<ArrayRef>())
1705 .ok_or_else(|| {
1706 DataFusionError::Execution("aggregate-state slice wrapper size overflow".into())
1707 })?,
1708 )
1709 .ok_or_else(|| {
1710 DataFusionError::Execution("aggregate-state slice wrapper size overflow".into())
1711 })
1712}
1713
1714/// Routes state rows without materializing Rust accumulator objects or rebuilding Arrow columns.
1715async fn read_state_batches(
1716 stream: &mut SendableRecordBatchStream,
1717 _partition: usize,
1718 routing: &Routing,
1719 senders: &[mpsc::UnboundedSender<Queued>],
1720 read_ahead: &MemoryReservation,
1721 state: &AggregateStateSchema,
1722 series: &SeriesSchema,
1723) -> Stop {
1724 use datatypes::series::frame::FrameLabelMode;
1725 let decoder = match SeriesFrameDecoder::try_new_aggregate_state(
1726 state,
1727 series,
1728 FrameLabelMode::Explicit,
1729 ) {
1730 Ok(decoder) => decoder,
1731 Err(error) => return Stop::Failed(Arc::new(DataFusionError::Execution(error.to_string()))),
1732 };
1733 let expected_schema = match datatypes::series::frame::aggregate_state_frame_schema(
1734 state,
1735 series,
1736 FrameLabelMode::Explicit,
1737 ) {
1738 Ok(schema) => schema,
1739 Err(error) => return Stop::Failed(Arc::new(DataFusionError::Execution(error.to_string()))),
1740 };
1741 while let Some(next) = stream.next().await {
1742 let batch = match next {
1743 Ok(batch) => batch,
1744 Err(error) => {
1745 return Stop::Failed(Arc::new(DataFusionError::External(Box::new(error))));
1746 }
1747 };
1748 if batch.schema().as_ref() != expected_schema.as_ref() {
1749 return Stop::Failed(Arc::new(DataFusionError::Execution(
1750 "aggregate state frame schema mismatch".into(),
1751 )));
1752 }
1753 let charge = read_ahead.new_empty();
1754 // Charge the input batch's retained buffers once. List slices still reference their entire
1755 // values array, so a slice-size estimate cannot safely charge each queued row instead.
1756 let batch_bytes = std::mem::size_of::<RecordBatch>()
1757 .saturating_add(
1758 batch
1759 .num_columns()
1760 .saturating_mul(std::mem::size_of::<datafusion::arrow::array::ArrayRef>()),
1761 )
1762 .saturating_add(batch.get_array_memory_size());
1763 if let Err(error) = charge.try_grow(batch_bytes) {
1764 return Stop::Failed(Arc::new(error));
1765 }
1766 let labels = match decoder.decode_aggregate_state_labels(&batch) {
1767 Ok(labels) => labels,
1768 Err(error) => {
1769 return Stop::Failed(Arc::new(DataFusionError::Execution(error.to_string())));
1770 }
1771 };
1772 let charge = Arc::new(charge);
1773 let batch = Arc::new(batch);
1774 if routing.outputs == 1 {
1775 // Every row has the same owner. Keep the frame packed so a downstream router reads
1776 // its shared payload once rather than receiving one parent-retaining slice per row.
1777 if !labels.is_empty() && !senders[0].is_closed() {
1778 let metadata = read_ahead.new_empty();
1779 // Cloning the batch for the output allocates a new column-reference vector.
1780 let wrapper_bytes = std::mem::size_of::<Queued>()
1781 .saturating_add(std::mem::size_of::<RecordBatch>())
1782 .saturating_add(
1783 batch.num_columns().saturating_mul(std::mem::size_of::<
1784 datafusion::arrow::array::ArrayRef,
1785 >()),
1786 );
1787 if let Err(error) = metadata.try_grow(wrapper_bytes) {
1788 return Stop::Failed(Arc::new(error));
1789 }
1790 if let Err(error) = senders[0].send(Queued::StateBatch {
1791 batch,
1792 row: None,
1793 _charge: charge,
1794 _metadata: metadata,
1795 }) {
1796 drop(error.0);
1797 }
1798 }
1799 tokio::task::coop::consume_budget().await;
1800 continue;
1801 }
1802 // Each queued row receives a reservation for the schema-based slice-wrapper upper bound.
1803 let slice_charge = match state_slice_wrapper_bytes(batch.schema().as_ref()) {
1804 Ok(bytes) => bytes,
1805 Err(error) => return Stop::Failed(Arc::new(error)),
1806 };
1807 let slice_metadata_bytes = match std::mem::size_of::<Queued>().checked_add(slice_charge) {
1808 Some(bytes) => bytes,
1809 None => {
1810 return Stop::Failed(Arc::new(DataFusionError::Execution(
1811 "aggregate-state slice wrapper size overflow".into(),
1812 )));
1813 }
1814 };
1815 for (index, metric) in labels.iter().enumerate() {
1816 let output = routing.output_labels(metric);
1817 if senders[output].is_closed() {
1818 continue;
1819 }
1820 // All slices retain the same parent buffers; a shared reservation charges them once.
1821 let metadata = read_ahead.new_empty();
1822 if let Err(error) = metadata.try_grow(slice_metadata_bytes) {
1823 return Stop::Failed(Arc::new(error));
1824 }
1825 if let Err(error) = senders[output].send(Queued::StateBatch {
1826 batch: Arc::clone(&batch),
1827 row: Some(index),
1828 _charge: Arc::clone(&charge),
1829 _metadata: metadata,
1830 }) {
1831 drop(error.0);
1832 }
1833 }
1834 tokio::task::coop::consume_budget().await;
1835 }
1836 Stop::Ended
1837}
1838
1839/// Whether `chunk` is a publication of the state this node declared it routes.
1840///
1841/// A state frame says what it is in its schema: the aggregate kind, the ordered component layout and
1842/// the series - fields and evaluation grid - it is of are all part of the frame `read_state_batches`
1843/// decodes, so a batch under any other schema is refused there before a row of it is routed. A chunk
1844/// says the same three things on the value: the layout in the [`StateChunk::Series`] it carries (or
1845/// in the row's fields), and the grid each group's axis is on. This is what holds a handed-over
1846/// publication to the standard the frame path holds a batch to; anything less would let a child hand
1847/// over state this node never declared and have it merged as that state.
1848fn declared_state_of(
1849 declared: &AggregateStateSchema,
1850 series: &SeriesSchema,
1851 chunk: &StateChunk,
1852) -> bool {
1853 let declared_grid = series.eval_grid.as_ref().map(|grid| grid.spec());
1854 let same_grid = |grid: Option<&Arc<datatypes::series::time::EvalGrid>>| {
1855 declared_grid.is_some_and(|declared| grid.is_some_and(|grid| grid.spec() == declared))
1856 };
1857 match chunk {
1858 StateChunk::Series {
1859 series: groups,
1860 state_schema,
1861 ..
1862 } => {
1863 state_schema.kind == declared.kind
1864 && state_schema.components == declared.components
1865 && declared_grid.is_some_and(|declared| state_schema.grid.spec() == declared)
1866 && groups.iter().all(|group| {
1867 group.states.len() == series.fields.len() && same_grid(group.time.grid())
1868 })
1869 }
1870 StateChunk::Row(row) => {
1871 row.kind == declared.kind
1872 && row.fields.components() == declared.components.as_ref()
1873 && row.fields.len() == series.fields.len()
1874 && same_grid(row.time.grid())
1875 }
1876 }
1877}
1878
1879/// Reads a child's handed-over state, routing each group to the owner that folds it.
1880///
1881/// A state publication is not merged here: every group the child folded is one row of its export, and
1882/// which owner folds it is the hash of its labels, exactly as a state frame's row is routed. What
1883/// differs is only the form - the group arrives as the child's own chunk instead of as a batch - so
1884/// the charge this node queues it with is grown while the child's charge is still in hand, and the
1885/// child's own charge moves onto the groups rather than going with the publication it is for.
1886async fn read_state_chunks(
1887 stream: &mut SendableSeriesStream,
1888 // The queue item names the group, not the partition it came from: a state publication is routed
1889 // by its labels, and nothing waits for one partition's group to complete another's.
1890 _partition: usize,
1891 routing: &Routing,
1892 senders: &[mpsc::UnboundedSender<Queued>],
1893 read_ahead: &MemoryReservation,
1894 declared: &Arc<AggregateStateSchema>,
1895 series: &Arc<SeriesSchema>,
1896) -> Stop {
1897 loop {
1898 tokio::task::coop::consume_budget().await;
1899 let next = stream.next().await;
1900 match next {
1901 Some(Ok(handed)) => {
1902 let (chunk, child_charge) = handed.into_parts();
1903 let SeriesChunk::State(chunk) = chunk else {
1904 return Stop::Failed(Arc::new(DataFusionError::Execution(format!(
1905 "an aggregate-state input handed over {chunk:?}"
1906 ))));
1907 };
1908 // The check the frame path makes of a batch's schema, made of the declaration the
1909 // chunk carries: a publication of another kind, layout or grid is refused here
1910 // rather than routed under a state this node never declared.
1911 if !declared_state_of(declared, series, &chunk) {
1912 return Stop::Failed(Arc::new(DataFusionError::Execution(
1913 "aggregate state chunk schema mismatch".into(),
1914 )));
1915 }
1916 // One publication may hold several groups; each is routed on its own labels, and
1917 // the charge the child put on the whole of it rides on all of them - a group is a
1918 // slice of that publication, so its bytes stay live until the last group is dropped.
1919 let mut publication = child_charge.map_or_else(Vec::new, SeriesCharge::into_shared);
1920 let groups = match chunk {
1921 StateChunk::Series {
1922 series,
1923 state_schema,
1924 reservation,
1925 } => {
1926 publication.extend(reservation.map(Arc::new));
1927 series
1928 .into_iter()
1929 .map(|series| StateChunk::Series {
1930 series: vec![series],
1931 state_schema: Arc::clone(&state_schema),
1932 reservation: None,
1933 })
1934 .collect::<Vec<_>>()
1935 }
1936 StateChunk::Row(row) => vec![StateChunk::Row(row)],
1937 };
1938 // One reference to the publication's charge, shared by every group cut from it.
1939 let publication = (!publication.is_empty()).then(|| Arc::new(publication));
1940 for group in groups {
1941 let metric = match &group {
1942 StateChunk::Series { series, .. } => &series[0].metric,
1943 StateChunk::Row(row) => &row.metric,
1944 };
1945 let output = routing.output_labels(metric);
1946 if senders[output].is_closed() {
1947 continue;
1948 }
1949 // Charged as it is queued, so what this node holds is accounted for before the
1950 // child's own charge goes.
1951 let charge = read_ahead.new_empty();
1952 if let Err(error) = charge.try_grow(state_bytes(&group)) {
1953 return Stop::Failed(Arc::new(error));
1954 }
1955 // The message and the boxed group it points at, which is this content's own
1956 // share of what a queue holds for one item.
1957 let metadata = read_ahead.new_empty();
1958 if let Err(error) = metadata.try_grow(
1959 std::mem::size_of::<Queued>()
1960 .saturating_add(std::mem::size_of::<QueuedStateChunk>()),
1961 ) {
1962 return Stop::Failed(Arc::new(error));
1963 }
1964 if let Err(error) =
1965 senders[output].send(Queued::StateChunk(Box::new(QueuedStateChunk {
1966 chunk: group,
1967 _charge: charge,
1968 _metadata: metadata,
1969 // One reference per queued group, so none of them is this task's to
1970 // hold: the publication's charge goes when its last group does.
1971 child: publication.clone(),
1972 })))
1973 {
1974 drop(error.0);
1975 }
1976 }
1977 }
1978 Some(Err(error)) => {
1979 return Stop::Failed(Arc::new(DataFusionError::External(Box::new(error))));
1980 }
1981 None => return Stop::Ended,
1982 }
1983 }
1984}
1985
1986/// One input partition's task: reads its own child, assembles chains, and sends each complete chain to
1987/// its canonical owner. Output queues are unbounded, so sending does not wait for an owner to poll;
1988/// queued chains remain charged to the pool until consumed or dropped. Each task records its outcome
1989/// before returning and dropping its senders, so output streams observe the final read outcome.
1990async fn route_partition(
1991 mut stream: RoutedInput,
1992 partition: usize,
1993 routing: Routing,
1994 senders: Vec<mpsc::UnboundedSender<Queued>>,
1995 read_ahead: MemoryReservation,
1996 inputs: Arc<Inputs>,
1997 mut report: ReportIfUnreported,
1998) {
1999 // The variant is the content: decoding the input's declared frame is what produced it.
2000 let stop = match &mut stream {
2001 RoutedInput::Evaluated(stream) => {
2002 read_evaluated_chains(stream, partition, &routing, &senders, &read_ahead).await
2003 }
2004 RoutedInput::Raw(stream) => {
2005 read_raw_chains(stream, partition, &routing, &senders, &read_ahead).await
2006 }
2007 RoutedInput::StateChunks(stream, state, series) => {
2008 read_state_chunks(
2009 stream,
2010 partition,
2011 &routing,
2012 &senders,
2013 &read_ahead,
2014 state,
2015 series,
2016 )
2017 .await
2018 }
2019 RoutedInput::State(stream, state, series) => {
2020 read_state_batches(
2021 stream,
2022 partition,
2023 &routing,
2024 &senders,
2025 &read_ahead,
2026 state,
2027 series,
2028 )
2029 .await
2030 }
2031 };
2032 if matches!(&stop, Stop::Ended) {
2033 for sender in &senders {
2034 if sender.is_closed() {
2035 continue;
2036 }
2037 let metadata = read_ahead.new_empty();
2038 if let Err(error) = metadata.try_grow(std::mem::size_of::<Queued>()) {
2039 inputs.failed(partition, &Arc::new(error));
2040 report.reported = true;
2041 return;
2042 }
2043 if let Err(error) = sender.send(Queued::Eof {
2044 input: partition,
2045 _metadata: metadata,
2046 }) {
2047 drop(error.0);
2048 }
2049 }
2050 }
2051 match &stop {
2052 Stop::Ended => inputs.ended(partition),
2053 Stop::Failed(error) => inputs.failed(partition, error),
2054 }
2055 // This task said what became of its partition, so the guard has nothing left to report.
2056 report.reported = true;
2057 drop(report);
2058}
2059
2060/// Reports an input task that stopped without recording an outcome, on the paths that would
2061/// otherwise report nothing.
2062///
2063/// [`route_partition`] records ordinary input completion and errors; this guard records when a task
2064/// stops without returning. A panic unwinds the task and takes the future polling it with it, and the task
2065/// being aborted drops that future where it stands; neither reaches an arm of that match, so nothing
2066/// is recorded, the count is untouched and the peers go on reading. A peer parked on a child that
2067/// never answers then holds a sender to every output for good, no queue ever closes, and every output
2068/// waits for an ending that is not coming - the `Pending` fallback is no help there, since it is
2069/// only read once a queue has closed.
2070///
2071/// A guard is what covers both without [`std::panic::catch_unwind`], which covers neither an abort nor
2072/// a panic the runtime catches elsewhere: unwinding and cancellation both drop this, so both report.
2073struct ReportIfUnreported {
2074 /// The bookkeeping of the read this task belongs to.
2075 inputs: Arc<Inputs>,
2076 /// The input partition whose task holds this guard.
2077 partition: usize,
2078 /// Whether that task recorded its own outcome, which is what makes this a no-op.
2079 reported: bool,
2080}
2081
2082impl Drop for ReportIfUnreported {
2083 fn drop(&mut self) {
2084 // Also runs on the way out of a normal return, which is what the flag is for: a task that
2085 // reached its own ending reported it there and has nothing to add here.
2086 if !self.reported {
2087 self.inputs.task_died(self.partition);
2088 }
2089 }
2090}
2091
2092/// Why one input task stopped reading its partition.
2093enum Stop {
2094 /// The partition ended: every chunk it had was read and handed to the output it belongs on.
2095 Ended,
2096 /// The partition failed, or a chain could not be buffered: every output has to learn that.
2097 Failed(Arc<DataFusionError>),
2098}
2099
2100/// Accounts for the portion of a decoded histogram table retained by one series slice.
2101pub(crate) fn histogram_table_slice_bytes(
2102 batch: &datatypes::series::histogram::HistogramBatch,
2103) -> DataFusionResult<usize> {
2104 use datafusion::arrow::array::{Array, ListArray};
2105
2106 let array = batch.as_arrow();
2107 let mut bytes = std::mem::size_of_val(batch);
2108 if array.nulls().is_some() {
2109 bytes = bytes.saturating_add(array.len().div_ceil(8));
2110 }
2111 for (index, column) in array.columns().iter().enumerate() {
2112 if (7..=13).contains(&index) {
2113 let list = column.as_any().downcast_ref::<ListArray>().ok_or_else(|| {
2114 DataFusionError::Execution(format!(
2115 "histogram list column {index} has invalid type"
2116 ))
2117 })?;
2118 let offsets = list.value_offsets();
2119 let first = *offsets
2120 .first()
2121 .ok_or_else(|| DataFusionError::Execution("empty histogram offsets".into()))?
2122 as usize;
2123 let last = *offsets
2124 .last()
2125 .ok_or_else(|| DataFusionError::Execution("empty histogram offsets".into()))?
2126 as usize;
2127 let values = list.values().slice(first, last.saturating_sub(first));
2128 bytes =
2129 bytes.saturating_add((list.len() + 1).saturating_mul(std::mem::size_of::<i32>()));
2130 bytes = bytes.saturating_add(values.to_data().get_slice_memory_size()?);
2131 if list.nulls().is_some() {
2132 bytes = bytes.saturating_add(list.len().div_ceil(8));
2133 }
2134 } else {
2135 bytes = bytes.saturating_add(column.to_data().get_slice_memory_size()?);
2136 }
2137 }
2138 Ok(bytes)
2139}
2140
2141/// Reads one input partition to its end, one whole chain at a time, routing each chain as it closes.
2142///
2143/// A chain is assembled here and handed over atomically after it closes; its growing memory is charged
2144/// to the pool. Output queues are unbounded, so routing does not wait for output polling. Each queued
2145/// chain retains its pool charge until the owner consumes it or the queue is dropped. This function
2146/// otherwise waits only on its own child.
2147async fn read_evaluated_chains(
2148 stream: &mut SendableEvaluatedSeriesStream,
2149 partition: usize,
2150 routing: &Routing,
2151 senders: &[mpsc::UnboundedSender<Queued>],
2152 read_ahead: &MemoryReservation,
2153) -> Stop {
2154 loop {
2155 // One whole chain, assembled here: the chunk that closes the series ends it, and so does a
2156 // stream that ends between two chains.
2157 let mut chain: Vec<(Series, bool, MemoryReservation)> = Vec::new();
2158 let mut chain_output: Option<usize> = None;
2159 let mut discarding = false;
2160 let mut ended = false;
2161 loop {
2162 // Input streams may return a long run of ready chunks without yielding to Tokio. Consume
2163 // the normal task budget per chunk so sibling producers can run and report failures.
2164 tokio::task::coop::consume_budget().await;
2165 let next = match (chain_output, discarding) {
2166 (Some(output), false) if !chain.is_empty() => {
2167 tokio::select! {
2168 biased;
2169 _ = senders[output].closed() => {
2170 chain.clear();
2171 discarding = true;
2172 continue;
2173 }
2174 next = stream.next() => next,
2175 }
2176 }
2177 _ => stream.next().await,
2178 };
2179 match next {
2180 Some(Ok((series, is_last))) => {
2181 let output = match chain_output {
2182 Some(output) => output,
2183 None => {
2184 let output = routing.output_labels(&series.metric);
2185 chain_output = Some(output);
2186 output
2187 }
2188 };
2189 // A dropped output is no longer a destination. Still read and validate its
2190 // entire chain, but do not retain or reserve its chunks.
2191 if senders[output].is_closed() {
2192 chain.clear();
2193 discarding = true;
2194 if is_last {
2195 break;
2196 }
2197 continue;
2198 }
2199 // Charged as the chain grows, so a chain that does not fit the pool is refused
2200 // here rather than after it has been held.
2201 if discarding {
2202 if is_last {
2203 break;
2204 }
2205 continue;
2206 }
2207 let charge = read_ahead.new_empty();
2208 let mut tables = 0usize;
2209 for segment in series.fields.iter().flat_map(|field| field.segments()) {
2210 let batch = match segment.dense() {
2211 Some(DenseSamplesRef::Histogram(histograms)) => {
2212 Some(histograms.batch())
2213 }
2214 Some(DenseSamplesRef::Mixed(mixed)) => Some(mixed.histograms().batch()),
2215 _ => None,
2216 };
2217 if let Some(batch) = batch {
2218 match histogram_table_slice_bytes(batch) {
2219 Ok(bytes) => tables = tables.saturating_add(bytes),
2220 Err(error) => return Stop::Failed(Arc::new(error)),
2221 }
2222 }
2223 }
2224 let bytes = operand_chunk_bytes(&series).saturating_add(tables);
2225 if let Err(error) = charge.try_grow(bytes) {
2226 if senders[output].is_closed() {
2227 chain.clear();
2228 discarding = true;
2229 if is_last {
2230 break;
2231 }
2232 continue;
2233 }
2234 return Stop::Failed(Arc::new(error));
2235 }
2236 chain.push((series, is_last, charge));
2237 if is_last {
2238 break;
2239 }
2240 }
2241 Some(Err(error)) => {
2242 // The error is the last thing this partition says: it is handed to every output
2243 // rather than ending this one task quietly.
2244 return Stop::Failed(Arc::new(DataFusionError::External(Box::new(error))));
2245 }
2246 None => {
2247 ended = true;
2248 break;
2249 }
2250 }
2251 }
2252 if ended {
2253 // A partition that ends is a partition with nothing left to route - unless it ended
2254 // inside a chain, which no later chunk can close. The decoders refuse that, so this is a
2255 // producer that bypassed them, and its output would hold a series no chunk can close.
2256 return if chain_output.is_none() {
2257 Stop::Ended
2258 } else {
2259 Stop::Failed(Arc::new(DataFusionError::Execution(
2260 "series repartition input ended with its series open".to_string(),
2261 )))
2262 };
2263 }
2264 // One hash per chain, over the labels of its first chunk: the chunks of a chain are one
2265 // series, so the first of them names the output for all of them.
2266 let Some(output) = chain_output else {
2267 return Stop::Failed(Arc::new(DataFusionError::Internal(
2268 "series repartition completed a chain without a routing destination".into(),
2269 )));
2270 };
2271 if !discarding && {
2272 let metadata = read_ahead.new_empty();
2273 if let Err(error) = metadata.try_grow(std::mem::size_of::<Queued>()) {
2274 return Stop::Failed(Arc::new(error));
2275 }
2276 senders[output]
2277 .send(Queued::Chain {
2278 input: partition,
2279 chain: RoutedChain::Evaluated(chain),
2280 _metadata: metadata,
2281 })
2282 .is_err()
2283 } {
2284 // A closed output is no longer a destination. Drop this chain and keep consuming.
2285 continue;
2286 }
2287 }
2288}
2289
2290async fn read_raw_chains(
2291 stream: &mut SendableRawSeriesStream,
2292 partition: usize,
2293 routing: &Routing,
2294 senders: &[mpsc::UnboundedSender<Queued>],
2295 read_ahead: &MemoryReservation,
2296) -> Stop {
2297 loop {
2298 let mut chain: Vec<(RawSeriesChunk, MemoryReservation)> = Vec::new();
2299 let mut destination: Option<usize> = None;
2300 let mut discarding = false;
2301 loop {
2302 tokio::task::coop::consume_budget().await;
2303 let next = match (destination, discarding) {
2304 (Some(output), false) if !chain.is_empty() => tokio::select! {
2305 biased;
2306 _ = senders[output].closed() => { chain.clear(); discarding = true; continue; }
2307 item = stream.next() => item,
2308 },
2309 _ => stream.next().await,
2310 };
2311 match next {
2312 Some(Ok(chunk)) => {
2313 let output = match destination {
2314 Some(output) => output,
2315 None => {
2316 let output = match &routing.policy {
2317 SeriesRouting::Matching(_) => {
2318 let Some(labels) = chunk.metric.as_ref() else {
2319 return Stop::Failed(Arc::new(DataFusionError::Execution(
2320 "a matching-routed raw chain carries no labels".into(),
2321 )));
2322 };
2323 routing.output_labels(labels)
2324 }
2325 _ => routing.output_key(chunk.primary_key.as_slice()),
2326 };
2327 *destination.insert(output)
2328 }
2329 };
2330 let final_chunk = chunk.is_last;
2331 if senders[output].is_closed() {
2332 chain.clear();
2333 discarding = true;
2334 if final_chunk {
2335 break;
2336 }
2337 continue;
2338 }
2339 if discarding {
2340 if final_chunk {
2341 break;
2342 }
2343 continue;
2344 }
2345 let charge = read_ahead.new_empty();
2346 let bytes = match raw_chunk_slice_bytes(&chunk) {
2347 Ok(bytes) => bytes,
2348 Err(error) => return Stop::Failed(Arc::new(error)),
2349 };
2350 if let Err(error) = charge.try_grow(bytes) {
2351 return Stop::Failed(Arc::new(error));
2352 }
2353 chain.push((chunk, charge));
2354 if final_chunk {
2355 break;
2356 }
2357 }
2358 Some(Err(error)) => {
2359 return Stop::Failed(Arc::new(DataFusionError::External(Box::new(error))));
2360 }
2361 None => {
2362 return if destination.is_none() {
2363 Stop::Ended
2364 } else {
2365 Stop::Failed(Arc::new(DataFusionError::Execution(
2366 "raw series ended without is_last".into(),
2367 )))
2368 };
2369 }
2370 }
2371 }
2372 let Some(output) = destination else {
2373 return Stop::Failed(Arc::new(DataFusionError::Internal(
2374 "raw chain has no destination".into(),
2375 )));
2376 };
2377 if !discarding {
2378 let metadata = read_ahead.new_empty();
2379 if let Err(error) = metadata.try_grow(std::mem::size_of::<Queued>()) {
2380 return Stop::Failed(Arc::new(error));
2381 }
2382 if senders[output]
2383 .send(Queued::Chain {
2384 input: partition,
2385 chain: RoutedChain::Raw(chain),
2386 _metadata: metadata,
2387 })
2388 .is_err()
2389 {
2390 continue;
2391 }
2392 }
2393 }
2394}
2395
2396/// What one output stream holds so that the read belongs to the streams rather than to the plan.
2397///
2398/// DataFusion's `execute_stream_partitioned` takes the plan by value and keeps only the streams, so
2399/// the state that started the read is dropped before the first chunk is read: a read stopped there
2400/// would end every output early, and an end is not something a consumer can tell from a complete
2401/// answer. The lease is what keeps it running instead; and because only streams hold one, a lease
2402/// going away is the point at which that one output can no longer take a chunk - which
2403/// [`SharedExecution::release_output`] turns into the end of the read only when no output is left that
2404/// could.
2405struct OutputLease {
2406 shared: Arc<SharedExecution>,
2407}
2408
2409impl OutputLease {
2410 /// Records an owner-side failure and cancels producer tasks without replacing an earlier error.
2411 fn fail(&self, error: Arc<DataFusionError>) {
2412 let inputs = {
2413 let running = self
2414 .shared
2415 .running
2416 .lock()
2417 .unwrap_or_else(|error| error.into_inner());
2418 Arc::clone(&running.inputs)
2419 };
2420 inputs.fail(Arc::clone(&error));
2421 inputs.stop();
2422 }
2423
2424 /// Reports successful EOF only when every producer ended successfully.
2425 fn ending(&self) -> Option<Result<(Series, bool), BoxedError>> {
2426 match self.shared.ending() {
2427 Ending::Finished => None,
2428 Ending::Failed(error) => Some(Err(boxed(DataFusionError::from(&error)))),
2429 Ending::Pending => Some(Err(boxed(DataFusionError::Execution(
2430 "series repartition producer stopped unexpectedly before the read finished"
2431 .to_string(),
2432 )))),
2433 }
2434 }
2435}
2436
2437impl Drop for OutputLease {
2438 fn drop(&mut self) {
2439 // An output that is done is not by itself the end of the read: the outputs that were never
2440 // claimed are still to come, and what is queued for them is what they will read. Giving up
2441 // the claim therefore only says that this one output will take nothing more - whether the
2442 // read can go on is decided from every output, claimed and unclaimed alike.
2443 self.shared.release_output();
2444 }
2445}
2446
2447/// How a read ended, as an output whose queue has closed has to report it.
2448#[derive(Clone, Debug, Default)]
2449enum Ending {
2450 #[default]
2451 Pending,
2452 Finished,
2453 Failed(Arc<DataFusionError>),
2454}
2455
2456/// One whole chain of one series: its chunks from the one that opened it to the one that closed it,
2457/// each with the bytes it is charged.
2458///
2459/// The transport unit is a chain so queued source contributions remain intact. Owners collect all
2460/// chains before locally merging exact identities and producing their final output.
2461enum RoutedInput {
2462 Evaluated(SendableEvaluatedSeriesStream),
2463 Raw(SendableRawSeriesStream),
2464 /// Exported state a child handed over, one publication at a time, with the state and the series
2465 /// this node declared those publications to be.
2466 StateChunks(
2467 SendableSeriesStream,
2468 Arc<AggregateStateSchema>,
2469 Arc<SeriesSchema>,
2470 ),
2471 State(
2472 SendableRecordBatchStream,
2473 Arc<AggregateStateSchema>,
2474 Arc<SeriesSchema>,
2475 ),
2476}
2477
2478enum RoutedChain {
2479 Evaluated(Vec<(Series, bool, MemoryReservation)>),
2480 Raw(Vec<(RawSeriesChunk, MemoryReservation)>),
2481}
2482
2483/// What one output queue carries: a whole chain and its memory charge.
2484enum Queued {
2485 Chain {
2486 input: usize,
2487 chain: RoutedChain,
2488 _metadata: MemoryReservation,
2489 },
2490 Eof {
2491 input: usize,
2492 _metadata: MemoryReservation,
2493 },
2494 StateBatch {
2495 batch: Arc<RecordBatch>,
2496 // None forwards the entire parent; Some selects one row for multi-output routing.
2497 row: Option<usize>,
2498 _charge: Arc<MemoryReservation>,
2499 _metadata: MemoryReservation,
2500 },
2501 /// One group of exported state, as the child that folded it handed it over.
2502 ///
2503 /// Boxed because the queue message is charged for by its own size, and every chain and every row
2504 /// of every other content pays that charge too: a state publication carries more than a chain
2505 /// does, and it is the only content that does.
2506 StateChunk(Box<QueuedStateChunk>),
2507}
2508
2509/// What one queued state group holds: the group, and the charges it keeps alive.
2510struct QueuedStateChunk {
2511 chunk: StateChunk,
2512 /// What this node queued it with: the payload the group holds.
2513 _charge: MemoryReservation,
2514 _metadata: MemoryReservation,
2515 /// What the child charged for the publication this group was cut from.
2516 ///
2517 /// A group is a slice of the publication it came from - a row's state columns still point into
2518 /// the batch they were decoded out of - so the bytes the child reserved for that publication are
2519 /// live for as long as any group cut from it is. They ride on the group for that reason: released
2520 /// here they would be released while the group is still held, and the pool would hand the
2521 /// parent's buffers to somebody else. The reference is taken once per publication and cloned per
2522 /// group, so the publication's charge goes when its last group does.
2523 child: Option<Arc<Vec<Arc<MemoryReservation>>>>,
2524}
2525
2526type ExactIdentity = (Option<Arc<str>>, Vec<(Arc<str>, Arc<str>)>);
2527
2528fn exact_identity(series: &Series) -> ExactIdentity {
2529 (
2530 series.metric.name().map(Arc::<str>::from),
2531 series
2532 .metric
2533 .tags()
2534 .iter()
2535 .map(|tag| (Arc::clone(&tag.name), Arc::clone(&tag.value)))
2536 .collect(),
2537 )
2538}
2539
2540/// Turns an owner's evaluated publications into the evaluated stream the packer consumes.
2541struct EvaluatedOutputStream {
2542 inner: Option<Pin<Box<RepartitionStream>>>,
2543}
2544
2545impl Stream for EvaluatedOutputStream {
2546 type Item = Result<(Series, bool), BoxedError>;
2547
2548 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2549 let this = self.get_mut();
2550 let Some(inner) = this.inner.as_mut() else {
2551 return Poll::Ready(None);
2552 };
2553 match inner.as_mut().poll_next(cx) {
2554 Poll::Pending => Poll::Pending,
2555 Poll::Ready(None) => {
2556 this.inner = None;
2557 Poll::Ready(None)
2558 }
2559 Poll::Ready(Some(Err(error))) => {
2560 this.inner = None;
2561 Poll::Ready(Some(Err(error)))
2562 }
2563 // A merged identity is final: the owner publishes it once, already closed.
2564 Poll::Ready(Some(Ok(ReadyOutput::Evaluated(series)))) => {
2565 Poll::Ready(Some(Ok((series, true))))
2566 }
2567 Poll::Ready(Some(Ok(ReadyOutput::Raw(_)))) => {
2568 this.inner = None;
2569 Poll::Ready(Some(Err(boxed(DataFusionError::Internal(
2570 "an evaluated repartition output carried a raw series".into(),
2571 )))))
2572 }
2573 }
2574 }
2575}
2576
2577/// Turns an owner's raw publications into the raw frame stream the packer consumes.
2578struct RawOutputStream {
2579 inner: Option<Pin<Box<RepartitionStream>>>,
2580 schema: Arc<SeriesSchema>,
2581 ordering: SeriesOrdering,
2582}
2583
2584impl Stream for RawOutputStream {
2585 type Item = Result<RawSeriesChunk, BoxedError>;
2586
2587 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2588 let this = self.get_mut();
2589 let Some(inner) = this.inner.as_mut() else {
2590 return Poll::Ready(None);
2591 };
2592 match inner.as_mut().poll_next(cx) {
2593 Poll::Pending => Poll::Pending,
2594 Poll::Ready(None) => {
2595 this.inner = None;
2596 Poll::Ready(None)
2597 }
2598 Poll::Ready(Some(Err(error))) => {
2599 this.inner = None;
2600 Poll::Ready(Some(Err(error)))
2601 }
2602 Poll::Ready(Some(Ok(ReadyOutput::Raw(chunk)))) => Poll::Ready(Some(Ok(chunk))),
2603 Poll::Ready(Some(Ok(ReadyOutput::Evaluated(_)))) => {
2604 this.inner = None;
2605 Poll::Ready(Some(Err(boxed(DataFusionError::Internal(
2606 "a raw repartition output carried an evaluated series".into(),
2607 )))))
2608 }
2609 }
2610 }
2611}
2612
2613impl RawSeriesStream for RawOutputStream {
2614 fn schema(&self) -> &Arc<SeriesSchema> {
2615 &self.schema
2616 }
2617
2618 fn label_source(&self) -> &store_api::region_engine::RawLabelSource {
2619 &store_api::region_engine::NO_BOUND_LABEL_SOURCE
2620 }
2621
2622 fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> {
2623 None
2624 }
2625
2626 fn ordering(&self) -> SeriesOrdering {
2627 self.ordering
2628 }
2629}
2630
2631/// What one owner groups by: an evaluated exact identity, or a complete raw primary key.
2632///
2633/// The two are separate variants rather than one tuple, so a raw key can never be confused with an
2634/// evaluated identity that happens to look similar.
2635#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
2636enum OwnerKey {
2637 Evaluated(ExactIdentity),
2638 Raw(Vec<u8>),
2639}
2640
2641fn raw_identity(chunk: &RawSeriesChunk) -> OwnerKey {
2642 OwnerKey::Raw(chunk.primary_key.as_slice().to_vec())
2643}
2644
2645/// The raw identity of one chunk: its complete stored primary key and nothing else.
2646///
2647/// Labels are deliberately not part of the key. Two pieces of one physical key must always meet in
2648/// the same owner so a label disagreement can be rejected there, instead of being split across
2649/// owners that would each look consistent on its own.
2650fn raw_chunk_slice_bytes(chunk: &RawSeriesChunk) -> DataFusionResult<usize> {
2651 use datafusion::arrow::array::Array;
2652
2653 let metric_bytes = chunk.metric.as_ref().map_or(0, |metric| {
2654 metric
2655 .name()
2656 .map_or(0, |name| name.len())
2657 .saturating_add(metric.tags().iter().fold(0usize, |bytes, tag| {
2658 bytes
2659 .saturating_add(tag.name.len())
2660 .saturating_add(tag.value.len())
2661 }))
2662 });
2663 // A field is one or more dense segments - a merged chunk carries one per source piece - so this
2664 // walks them and measures each. Asking the field for a single dense view instead answered `None`
2665 // for a multi-segment field, which charged nothing for bytes the router then queued. A segment is
2666 // measured here by the buffers a slice of it keeps alive, where the evaluated figure
2667 // ([`sample_slice_bytes`]) bills its rows.
2668 let mut fields_bytes = 0usize;
2669 for segment in field_segments(&chunk.fields) {
2670 let field_bytes = match segment.dense() {
2671 Some(DenseSamplesRef::Float(values)) => values.to_data().get_slice_memory_size()?,
2672 Some(DenseSamplesRef::Histogram(histograms)) => histograms
2673 .indices()
2674 .to_data()
2675 .get_slice_memory_size()?
2676 .saturating_add(histogram_table_slice_bytes(histograms.batch())?),
2677 Some(DenseSamplesRef::Mixed(mixed)) => mixed
2678 .floats()
2679 .to_data()
2680 .get_slice_memory_size()?
2681 .saturating_add(
2682 mixed
2683 .histograms()
2684 .indices()
2685 .to_data()
2686 .get_slice_memory_size()?,
2687 )
2688 .saturating_add(histogram_table_slice_bytes(mixed.histograms().batch())?),
2689 // `segments` hands out dense segments only, so this is unreachable; a zero here is
2690 // what the whole-field view used to answer for a merged field.
2691 None => 0,
2692 };
2693 fields_bytes = fields_bytes.saturating_add(field_bytes);
2694 }
2695 Ok(std::mem::size_of::<RawSeriesChunk>()
2696 .saturating_add(chunk.primary_key.len())
2697 .saturating_add(metric_bytes)
2698 .saturating_add(
2699 chunk
2700 .time
2701 .as_buffer()
2702 .len()
2703 .saturating_mul(std::mem::size_of::<i64>()),
2704 )
2705 .saturating_add(fields_bytes))
2706}
2707
2708struct PendingGroup {
2709 fragments: Vec<Series>,
2710 raw_chunks: Vec<RawSeriesChunk>,
2711 charges: Vec<MemoryReservation>,
2712 received: Vec<bool>,
2713 metadata: MemoryReservation,
2714}
2715
2716/// Whether this owner may publish `group` now.
2717///
2718/// A key-then-time raw frame promises its keys arrive in order, and this owner publishes in key
2719/// order only when it publishes them together: an identity that is complete while a smaller one is
2720/// still waiting would go out first and break that promise. Watermarks let it publish once every
2721/// input has advanced past the identity, without waiting for every input to end. An interleaved
2722/// raw identity can recur even after an input contributed, so only all normal EOFs complete it.
2723fn group_ready(
2724 group: &PendingGroup,
2725 eof: &[bool],
2726 last_key_from: &[Option<Vec<u8>>],
2727 ordering: SeriesOrdering,
2728 completion: IdentityCompletion,
2729 key: &OwnerKey,
2730) -> bool {
2731 if ordering == SeriesOrdering::Interleaved && matches!(key, OwnerKey::Raw(_)) {
2732 return eof.iter().all(|eof| *eof);
2733 }
2734 if ordering == SeriesOrdering::KeyThenTime {
2735 let OwnerKey::Raw(key) = key else {
2736 return false;
2737 };
2738 return group.received.iter().zip(eof).zip(last_key_from).all(
2739 |((received, eof), last_key)| {
2740 *received || *eof || last_key.as_ref().is_some_and(|last| last > key)
2741 },
2742 );
2743 }
2744 if completion == IdentityCompletion::CompleteDisjoint {
2745 return true;
2746 }
2747 group
2748 .received
2749 .iter()
2750 .zip(eof)
2751 .all(|(received, eof)| *received || *eof)
2752}
2753
2754enum ReadyOutput {
2755 Evaluated(Series),
2756 Raw(RawSeriesChunk),
2757}
2758
2759impl ReadyOutput {
2760 /// What this publication is, for an error that has to name what arrived instead.
2761 fn what(&self) -> &'static str {
2762 match self {
2763 Self::Evaluated(_) => "an evaluated series",
2764 Self::Raw(_) => "a raw series",
2765 }
2766 }
2767}
2768
2769struct ReadySeries {
2770 series: ReadyOutput,
2771 charge: SeriesCharge,
2772}
2773
2774/// One owner processes identities as soon as every input has closed or contributed its final chain.
2775struct StateBatchOutputStream {
2776 schema: SchemaRef,
2777 receiver: mpsc::UnboundedReceiver<Queued>,
2778 lease: OutputLease,
2779 retained: Option<(Arc<MemoryReservation>, MemoryReservation)>,
2780 reported: bool,
2781}
2782
2783impl RecordBatchStream for StateBatchOutputStream {
2784 fn schema(&self) -> SchemaRef {
2785 Arc::clone(&self.schema)
2786 }
2787}
2788
2789impl Stream for StateBatchOutputStream {
2790 type Item = DataFusionResult<RecordBatch>;
2791
2792 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2793 if self.reported {
2794 return Poll::Ready(None);
2795 }
2796 self.retained = None;
2797 loop {
2798 if let Ending::Failed(error) = self.lease.shared.ending() {
2799 self.reported = true;
2800 self.receiver.close();
2801 while self.receiver.try_recv().is_ok() {}
2802 self.retained = None;
2803 return Poll::Ready(Some(Err(DataFusionError::from(&error))));
2804 }
2805 match self.receiver.poll_recv(cx) {
2806 Poll::Pending => return Poll::Pending,
2807 Poll::Ready(Some(Queued::StateBatch {
2808 batch,
2809 row,
2810 _charge,
2811 _metadata,
2812 })) => {
2813 // Keep the router reservation through the next poll so Final can admit the
2814 // returned batch's retained component arrays before releasing router charge.
2815 self.retained = Some((_charge, _metadata));
2816 let batch = match row {
2817 Some(row) => batch.slice(row, 1),
2818 None => batch.as_ref().clone(),
2819 };
2820 return Poll::Ready(Some(Ok(batch)));
2821 }
2822 Poll::Ready(Some(Queued::Eof { input, _metadata })) => {
2823 // The shared Ending state and channel closure establish stream completion;
2824 // this message is only a queue-order barrier for the routed state stream.
2825 let _ = input;
2826 drop(_metadata);
2827 }
2828 Poll::Ready(Some(Queued::StateChunk(_))) => {
2829 let error = DataFusionError::Internal(
2830 "a state frame output received a handed-over group".into(),
2831 );
2832 self.lease.fail(Arc::new(DataFusionError::Internal(
2833 "a state frame output received a handed-over group".into(),
2834 )));
2835 self.reported = true;
2836 self.receiver.close();
2837 while self.receiver.try_recv().is_ok() {}
2838 self.retained = None;
2839 return Poll::Ready(Some(Err(error)));
2840 }
2841 Poll::Ready(Some(Queued::Chain { .. })) => {
2842 let error = DataFusionError::Internal(
2843 "series router received a non-state message".into(),
2844 );
2845 self.lease.fail(Arc::new(DataFusionError::Internal(
2846 "series router received a non-state message".into(),
2847 )));
2848 self.reported = true;
2849 self.receiver.close();
2850 while self.receiver.try_recv().is_ok() {}
2851 self.retained = None;
2852 return Poll::Ready(Some(Err(error)));
2853 }
2854 Poll::Ready(None) => {
2855 self.reported = true;
2856 self.retained = None;
2857 return match self.lease.ending() {
2858 Some(Err(error)) => {
2859 Poll::Ready(Some(Err(DataFusionError::External(Box::new(error)))))
2860 }
2861 Some(Ok(_)) => unreachable!(),
2862 None => Poll::Ready(None),
2863 };
2864 }
2865 }
2866 }
2867 }
2868}
2869
2870struct RepartitionStream {
2871 receiver: mpsc::UnboundedReceiver<Queued>,
2872 lease: OutputLease,
2873 schema: Arc<SeriesSchema>,
2874 pool: Arc<dyn MemoryPool>,
2875 /// The input's ordering and identity completion guarantee.
2876 ordering: SeriesOrdering,
2877 identity_completion: IdentityCompletion,
2878 groups: BTreeMap<OwnerKey, PendingGroup>,
2879 eof: Vec<bool>,
2880 last_key_from: Vec<Option<Vec<u8>>>,
2881 eof_metadata: Option<MemoryReservation>,
2882 inputs: usize,
2883 output: VecDeque<ReadySeries>,
2884 handoff: Arc<Mutex<Handoff>>,
2885 /// Whether a new pass over the pending identities is owed after an input EOF.
2886 ///
2887 /// A chain can only complete the identity it carries, so the chain arm checks that group
2888 /// directly. An EOF can complete any waiting identity, so it opens a pass instead; the pass
2889 /// resumes after [`resume_after`](Self::resume_after) so the same prefix is not rescanned for
2890 /// every identity it releases.
2891 rescan: bool,
2892 /// The last identity a pass examined, exclusive. Retains at most one identity descriptor.
2893 resume_after: Option<OwnerKey>,
2894 reported: bool,
2895}
2896
2897/// Charges move out of the current cursor only after it is exhausted; the public batch stream
2898/// releases completed cursors after the packer has flushed the frames they back.
2899#[derive(Default)]
2900struct Handoff {
2901 current: Option<SeriesCharge>,
2902 completed: Vec<SeriesCharge>,
2903}
2904
2905struct PackedHandoffStream {
2906 inner: Option<SendableRecordBatchStream>,
2907 schema: SchemaRef,
2908 handoff: Arc<Mutex<Handoff>>,
2909}
2910
2911impl RecordBatchStream for PackedHandoffStream {
2912 fn schema(&self) -> SchemaRef {
2913 Arc::clone(&self.schema)
2914 }
2915}
2916
2917impl Stream for PackedHandoffStream {
2918 type Item = DataFusionResult<RecordBatch>;
2919
2920 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2921 let result = match self.inner.as_mut() {
2922 Some(inner) => inner.as_mut().poll_next(cx),
2923 None => return Poll::Ready(None),
2924 };
2925 match &result {
2926 Poll::Ready(Some(Ok(_))) | Poll::Pending => {
2927 let mut handoff = self.handoff.lock().unwrap_or_else(|e| e.into_inner());
2928 // A pending packer has exhausted its cursor and its frame builder is empty, so
2929 // completed charges no longer retain any payload; `current` may still own the
2930 // whole merged series behind a live cursor.
2931 handoff.completed.clear();
2932 }
2933 Poll::Ready(None) | Poll::Ready(Some(Err(_))) => {
2934 drop(self.inner.take());
2935 let mut handoff = self.handoff.lock().unwrap_or_else(|e| e.into_inner());
2936 handoff.current = None;
2937 handoff.completed.clear();
2938 }
2939 }
2940 result
2941 }
2942}
2943
2944impl RepartitionStream {
2945 fn new(
2946 receiver: mpsc::UnboundedReceiver<Queued>,
2947 lease: OutputLease,
2948 schema: Arc<SeriesSchema>,
2949 pool: &Arc<dyn MemoryPool>,
2950 inputs: usize,
2951 ordering: SeriesOrdering,
2952 identity_completion: IdentityCompletion,
2953 ) -> Self {
2954 Self {
2955 receiver,
2956 lease,
2957 schema,
2958 ordering,
2959 identity_completion,
2960 pool: Arc::clone(pool),
2961 groups: BTreeMap::new(),
2962 eof: Vec::new(),
2963 last_key_from: vec![None; inputs],
2964 eof_metadata: None,
2965 inputs,
2966 output: VecDeque::new(),
2967 handoff: Arc::new(Mutex::new(Handoff::default())),
2968 rescan: false,
2969 resume_after: None,
2970 reported: false,
2971 }
2972 }
2973
2974 /// Takes what the owner charged for the publication it just returned.
2975 ///
2976 /// [`poll_next`](Stream::poll_next) installs the charge of the publication it returns in the
2977 /// handoff, where [`PackedHandoffStream`] releases it once the batch it backs has been flushed.
2978 /// A consumer that is handed the value itself takes it here instead, so the reservation rides
2979 /// with the chunk and is released when the consumer drops it - neither before the bytes it
2980 /// accounts for are gone, nor after.
2981 fn take_charge(&mut self) -> Option<SeriesCharge> {
2982 self.handoff
2983 .lock()
2984 .unwrap_or_else(|error| error.into_inner())
2985 .current
2986 .take()
2987 }
2988
2989 fn finish_group(&mut self, key: &OwnerKey) -> DataFusionResult<()> {
2990 let Some(group) = self.groups.remove(key) else {
2991 return Ok(());
2992 };
2993 if matches!(key, OwnerKey::Raw(_)) {
2994 return self.finish_raw_group(group);
2995 }
2996 let workspace = if group.fragments.len() > 1 {
2997 let rows = group.fragments.iter().fold(0usize, |rows, series| {
2998 rows.saturating_add(series.time.len())
2999 });
3000 let reservation = MemoryConsumer::new("SeriesRepartitionOwner").register(&self.pool);
3001 reservation.try_grow(merge_workspace_bytes(
3002 rows,
3003 group.fragments.len(),
3004 self.schema.fields.len(),
3005 ))?;
3006 Some(reservation)
3007 } else {
3008 None
3009 };
3010 let merged = merge_same_labelset(&self.schema, group.fragments)
3011 .map_err(|error| DataFusionError::External(Box::new(error)))?;
3012 if merged.len() != 1 {
3013 return Err(DataFusionError::Internal(
3014 "exact identity produced multiple merged series".into(),
3015 ));
3016 }
3017 let Some(series) = merged.into_iter().next() else {
3018 return Err(DataFusionError::Internal(
3019 "exact identity produced no merged series".into(),
3020 ));
3021 };
3022 self.output.push_back(ReadySeries {
3023 series: ReadyOutput::Evaluated(series),
3024 charge: SeriesCharge::new(group.charges, group.metadata, workspace),
3025 });
3026 Ok(())
3027 }
3028}
3029
3030impl RepartitionStream {
3031 /// Publishes one complete raw identity.
3032 ///
3033 /// A piece's `is_last` closes that producer's chain, not the reconstructed series. For
3034 /// interleaved input, pieces are retained until every input reaches normal EOF. The workspace
3035 /// reconstruction needs is charged as it runs and rides with the output until the packer
3036 /// hands the batch off, like any other owner output.
3037 fn finish_raw_group(&mut self, group: PendingGroup) -> DataFusionResult<()> {
3038 let labels = group
3039 .raw_chunks
3040 .first()
3041 .and_then(|chunk| chunk.metric.clone())
3042 .ok_or_else(|| {
3043 DataFusionError::Execution("raw identity has no explicit labels".to_string())
3044 })?;
3045 if group
3046 .raw_chunks
3047 .iter()
3048 .any(|chunk| chunk.metric.as_ref() != Some(&labels))
3049 {
3050 return Err(DataFusionError::Execution(
3051 "raw identity pieces disagree on their explicit labels".to_string(),
3052 ));
3053 }
3054 if group.raw_chunks.len() == 1 {
3055 let mut chunk = group.raw_chunks.into_iter().next().expect("one raw chunk");
3056 chunk.is_last = true;
3057 self.output.push_back(ReadySeries {
3058 series: ReadyOutput::Raw(chunk),
3059 charge: SeriesCharge::new(group.charges, group.metadata, None),
3060 });
3061 return Ok(());
3062 }
3063 // Reconstruction's working set depends on how the pieces interleave, which is only known
3064 // while it runs: charge each allocation as it is made rather than reserving a worst case
3065 // that a well-ordered identity never approaches.
3066 let workspace = MemoryConsumer::new("SeriesRepartitionRawOwner").register(&self.pool);
3067 let mut reserve = |bytes: usize| workspace.try_grow(bytes);
3068 let mut shrink = |bytes: usize| {
3069 let result = workspace.try_shrink(bytes);
3070 debug_assert!(
3071 result.is_ok(),
3072 "raw merge workspace shrink failed: {result:?}"
3073 );
3074 // The merged data is already correct; tolerate accounting inconsistency rather than
3075 // turning a valid query result into an error.
3076 let _ = result;
3077 };
3078 let chunk = merge_raw_identity_charging(
3079 &self.schema,
3080 &group.raw_chunks,
3081 &mut reserve,
3082 &mut shrink,
3083 )?;
3084 self.output.push_back(ReadySeries {
3085 series: ReadyOutput::Raw(chunk),
3086 charge: SeriesCharge::new(group.charges, group.metadata, Some(workspace)),
3087 });
3088 Ok(())
3089 }
3090}
3091
3092impl Stream for RepartitionStream {
3093 type Item = Result<ReadyOutput, BoxedError>;
3094
3095 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3096 let this = self.get_mut();
3097 {
3098 let mut handoff = this.handoff.lock().unwrap_or_else(|e| e.into_inner());
3099 if let Some(current) = handoff.current.take() {
3100 handoff.completed.push(current);
3101 }
3102 }
3103 let mut drained = 0;
3104 loop {
3105 if let Ending::Failed(error) = this.lease.shared.ending() {
3106 if this.reported {
3107 return Poll::Ready(None);
3108 }
3109 this.reported = true;
3110 this.receiver.close();
3111 while this.receiver.try_recv().is_ok() {}
3112 this.groups.clear();
3113 this.output.clear();
3114 this.eof.clear();
3115 this.eof_metadata = None;
3116 return Poll::Ready(Some(Err(boxed(DataFusionError::from(&error)))));
3117 }
3118 if this.eof_metadata.is_none() {
3119 let metadata = MemoryConsumer::new("SeriesRepartitionEof").register(&this.pool);
3120 let bytes = this.inputs.saturating_mul(std::mem::size_of::<bool>());
3121 if let Err(error) = metadata.try_grow(bytes) {
3122 this.lease.fail(Arc::new(error));
3123 continue;
3124 }
3125 this.eof = vec![false; this.inputs];
3126 this.eof_metadata = Some(metadata);
3127 }
3128 if let Ending::Failed(error) = this.lease.shared.ending() {
3129 if this.reported {
3130 return Poll::Ready(None);
3131 }
3132 this.reported = true;
3133 this.receiver.close();
3134 while this.receiver.try_recv().is_ok() {}
3135 this.groups.clear();
3136 this.output.clear();
3137 this.eof.clear();
3138 this.eof_metadata = None;
3139 return Poll::Ready(Some(Err(boxed(DataFusionError::from(&error)))));
3140 }
3141 if this.rescan {
3142 let next = if this.ordering == SeriesOrdering::KeyThenTime {
3143 this.groups.first_key_value().and_then(|(key, group)| {
3144 group_ready(
3145 group,
3146 &this.eof,
3147 &this.last_key_from,
3148 this.ordering,
3149 this.identity_completion,
3150 key,
3151 )
3152 .then(|| key.clone())
3153 })
3154 } else {
3155 match &this.resume_after {
3156 Some(after) => this
3157 .groups
3158 .range((
3159 std::ops::Bound::Excluded(after.clone()),
3160 std::ops::Bound::Unbounded,
3161 ))
3162 .find_map(|(key, group)| {
3163 group_ready(
3164 group,
3165 &this.eof,
3166 &this.last_key_from,
3167 this.ordering,
3168 this.identity_completion,
3169 key,
3170 )
3171 .then(|| key.clone())
3172 }),
3173 None => this.groups.iter().find_map(|(key, group)| {
3174 group_ready(
3175 group,
3176 &this.eof,
3177 &this.last_key_from,
3178 this.ordering,
3179 this.identity_completion,
3180 key,
3181 )
3182 .then(|| key.clone())
3183 }),
3184 }
3185 };
3186 match next {
3187 Some(key) => {
3188 this.resume_after = Some(key.clone());
3189 if let Err(error) = this.finish_group(&key) {
3190 this.rescan = false;
3191 this.resume_after = None;
3192 this.lease.fail(Arc::new(error));
3193 continue;
3194 }
3195 }
3196 None => {
3197 // Every pending identity after the resume point was examined and none is
3198 // ready; only a new chain or EOF can change that.
3199 this.rescan = false;
3200 this.resume_after = None;
3201 }
3202 }
3203 }
3204 if let Some(ready) = this.output.pop_front() {
3205 this.handoff
3206 .lock()
3207 .unwrap_or_else(|e| e.into_inner())
3208 .current = Some(ready.charge);
3209 return Poll::Ready(Some(Ok(ready.series)));
3210 }
3211 if this.reported {
3212 return Poll::Ready(None);
3213 }
3214 if drained == 128 {
3215 cx.waker().wake_by_ref();
3216 return Poll::Pending;
3217 }
3218 match this.receiver.poll_recv(cx) {
3219 Poll::Ready(Some(Queued::StateBatch { .. }))
3220 | Poll::Ready(Some(Queued::StateChunk(_))) => {
3221 this.lease.fail(Arc::new(DataFusionError::Internal(
3222 "a series output received aggregate state".into(),
3223 )));
3224 }
3225 Poll::Ready(Some(Queued::Chain {
3226 input,
3227 chain,
3228 _metadata,
3229 })) => {
3230 drained += 1;
3231 if input >= this.eof.len() {
3232 this.lease.fail(Arc::new(DataFusionError::Execution(
3233 "series repartition input index is out of range".into(),
3234 )));
3235 continue;
3236 }
3237 let (key, pieces) = match chain {
3238 RoutedChain::Evaluated(chain) => {
3239 let Some(first) = chain.first() else {
3240 continue;
3241 };
3242 let key = exact_identity(&first.0);
3243 (OwnerKey::Evaluated(key), RoutedChain::Evaluated(chain))
3244 }
3245 RoutedChain::Raw(chain) => {
3246 let Some(first) = chain.first() else {
3247 continue;
3248 };
3249 let key = raw_identity(&first.0);
3250 if let OwnerKey::Raw(raw_key) = &key
3251 && this.ordering == SeriesOrdering::KeyThenTime
3252 {
3253 let last = &mut this.last_key_from[input];
3254 if last.as_ref().is_none_or(|last| raw_key > last) {
3255 *last = Some(raw_key.clone());
3256 }
3257 }
3258 (key, RoutedChain::Raw(chain))
3259 }
3260 };
3261 if !this.groups.contains_key(&key) {
3262 let metadata =
3263 MemoryConsumer::new("SeriesRepartitionIdentity").register(&this.pool);
3264 let key_bytes =
3265 match &key {
3266 OwnerKey::Evaluated((name, tags)) => {
3267 std::mem::size_of::<ExactIdentity>()
3268 .saturating_add(name.as_ref().map_or(0, |name| name.len()))
3269 .saturating_add(tags.capacity().saturating_mul(
3270 std::mem::size_of::<(Arc<str>, Arc<str>)>(),
3271 ))
3272 .saturating_add(
3273 tags.iter()
3274 .map(|(n, v)| n.len().saturating_add(v.len()))
3275 .sum::<usize>(),
3276 )
3277 }
3278 OwnerKey::Raw(key) => key.capacity(),
3279 };
3280 let bytes = std::mem::size_of::<PendingGroup>()
3281 .saturating_add(std::mem::size_of::<OwnerKey>())
3282 .saturating_add(key_bytes)
3283 .saturating_add(this.eof.len().saturating_mul(2));
3284 if let Err(error) = metadata.try_grow(bytes) {
3285 this.lease.fail(Arc::new(error));
3286 continue;
3287 }
3288 this.groups.insert(
3289 key.clone(),
3290 PendingGroup {
3291 fragments: Vec::new(),
3292 raw_chunks: Vec::new(),
3293 charges: Vec::new(),
3294 received: vec![false; this.eof.len()],
3295 metadata,
3296 },
3297 );
3298 }
3299 let Some(group) = this.groups.get_mut(&key) else {
3300 this.lease.fail(Arc::new(DataFusionError::Internal(
3301 "series identity group was not retained".into(),
3302 )));
3303 continue;
3304 };
3305 if input >= group.received.len()
3306 || (group.received[input]
3307 && !(this.ordering == SeriesOrdering::Interleaved
3308 && matches!(&key, OwnerKey::Raw(_))))
3309 {
3310 this.lease.fail(Arc::new(DataFusionError::Execution(
3311 "input repeated an exact series identity".into(),
3312 )));
3313 continue;
3314 }
3315 group.received[input] = true;
3316 match pieces {
3317 RoutedChain::Evaluated(chain) => {
3318 for (series, _, charge) in chain {
3319 group.fragments.push(series);
3320 group.charges.push(charge);
3321 }
3322 }
3323 RoutedChain::Raw(chain) => {
3324 for (chunk, charge) in chain {
3325 group.raw_chunks.push(chunk);
3326 group.charges.push(charge);
3327 }
3328 }
3329 }
3330 if this.ordering == SeriesOrdering::KeyThenTime {
3331 this.rescan = true;
3332 this.resume_after = None;
3333 } else if group_ready(
3334 group,
3335 &this.eof,
3336 &this.last_key_from,
3337 this.ordering,
3338 this.identity_completion,
3339 &key,
3340 ) && let Err(error) = this.finish_group(&key)
3341 {
3342 this.lease.fail(Arc::new(error));
3343 }
3344 }
3345 Poll::Ready(Some(Queued::Eof { input, _metadata })) => {
3346 drained += 1;
3347 if input >= this.eof.len() || this.eof[input] {
3348 this.lease.fail(Arc::new(DataFusionError::Execution(
3349 "duplicate series repartition input EOF".into(),
3350 )));
3351 continue;
3352 }
3353 this.eof[input] = true;
3354 // An EOF can complete any identity waiting only for this input.
3355 this.rescan = true;
3356 this.resume_after = None;
3357 }
3358 Poll::Ready(None) => {
3359 this.reported = true;
3360 if let Some(Err(error)) = this.lease.ending() {
3361 this.groups.clear();
3362 this.output.clear();
3363 return Poll::Ready(Some(Err(error)));
3364 }
3365 if this.eof.iter().any(|seen| !seen) || !this.groups.is_empty() {
3366 let error = boxed(DataFusionError::Execution(
3367 "series repartition queue closed before every input EOF".into(),
3368 ));
3369 this.lease.fail(Arc::new(DataFusionError::Execution(
3370 "series repartition queue closed before every input EOF".into(),
3371 )));
3372 this.groups.clear();
3373 return Poll::Ready(Some(Err(error)));
3374 }
3375 if let Some(ready) = this.output.pop_front() {
3376 this.handoff
3377 .lock()
3378 .unwrap_or_else(|e| e.into_inner())
3379 .current = Some(ready.charge);
3380 return Poll::Ready(Some(Ok(ready.series)));
3381 }
3382 return Poll::Ready(None);
3383 }
3384 Poll::Pending => return Poll::Pending,
3385 }
3386 }
3387 }
3388}
3389
3390/// The boxed error a frame stream reports.
3391fn boxed(error: DataFusionError) -> BoxedError {
3392 BoxedError::new(common_query::error::Error::from(error))
3393}
3394
3395/// The hash configuration one execution routes with.
3396///
3397/// The seed is what an execution builds once; a [`XxHash64`] accumulates, so a fresh hasher starts
3398/// from this configuration for each chunk, and that is the only thing each chunk builds.
3399#[derive(Clone, Debug)]
3400struct Routing {
3401 outputs: usize,
3402 seed: u64,
3403 policy: SeriesRouting,
3404}
3405
3406impl Routing {
3407 /// The canonical routing of an execution with `outputs` output partitions.
3408 #[cfg(test)]
3409 fn new(outputs: usize) -> Self {
3410 Self::with_policy(outputs, SeriesRouting::CanonicalLabels)
3411 }
3412
3413 /// The routing of an execution with `outputs` output partitions and an explicit policy.
3414 fn with_policy(outputs: usize, policy: SeriesRouting) -> Self {
3415 Self {
3416 outputs,
3417 seed: ROUTING_SEED,
3418 policy,
3419 }
3420 }
3421
3422 /// The output a label-carrying chunk belongs on.
3423 #[cfg(test)]
3424 fn output(&self, metric: &SeriesLabels) -> usize {
3425 self.output_labels(metric)
3426 }
3427
3428 fn output_labels(&self, metric: &SeriesLabels) -> usize {
3429 let mut hasher = XxHash64::with_seed(self.seed);
3430 match &self.policy {
3431 SeriesRouting::CanonicalLabels => label_set(metric).hash(&mut hasher),
3432 SeriesRouting::CanonicalLabelsExcept(excluded) => {
3433 let mut labels = label_set(metric);
3434 labels.retain(|(name, _)| !excluded.contains(name));
3435 labels.hash(&mut hasher);
3436 }
3437 SeriesRouting::Matching(policy) => {
3438 crate::vector_match::group_key(metric, policy).hash(&mut hasher)
3439 }
3440 SeriesRouting::RawPrimaryKey => {
3441 debug_assert!(
3442 false,
3443 "RawPrimaryKey routing hashes stored keys, not labels"
3444 );
3445 }
3446 }
3447 (hasher.finish() % self.outputs as u64) as usize
3448 }
3449
3450 fn output_key(&self, key: &[u8]) -> usize {
3451 let mut hasher = XxHash64::with_seed(self.seed);
3452 key.hash(&mut hasher);
3453 (hasher.finish() % self.outputs as u64) as usize
3454 }
3455}
3456
3457#[cfg(test)]
3458mod tests;