diff --git a/src/promql/src/extension_plan.rs b/src/promql/src/extension_plan.rs index 102dd918c9e..ba4cf65e0d5 100644 --- a/src/promql/src/extension_plan.rs +++ b/src/promql/src/extension_plan.rs @@ -26,6 +26,7 @@ mod raw_series_source; mod scalar_calculate; mod series_divide; mod series_gather; +mod series_repartition; #[cfg(test)] mod test_util; mod union_distinct_on; @@ -56,6 +57,7 @@ pub use range_manipulate::{RangeManipulate, RangeManipulateExec, RangeManipulate pub use raw_series_source::{RawSeriesSource, RawSeriesSourceExec}; pub use scalar_calculate::ScalarCalculate; pub use series_divide::{SeriesDivide, SeriesDivideExec, SeriesDivideStream}; +pub use series_repartition::SeriesRepartitionExec; pub use union_distinct_on::{UnionDistinctOn, UnionDistinctOnExec, UnionDistinctOnStream}; pub type Millisecond = ::Native; diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index 19dda710801..5a0f9fb25c4 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -84,6 +84,7 @@ use store_api::region_engine::RawLabelSource; use crate::evaluated::EvaluatedChunk; use crate::extension_plan::aggregate_exchange::{PartialFold, aggregate_op, state_schema}; use crate::extension_plan::series_gather::{SeriesGather, spawn_partitions}; +use crate::extension_plan::series_repartition::SeriesRepartitionExec; use crate::grid_series::series_bytes; use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor}; use crate::native::plan::{ @@ -775,14 +776,28 @@ fn validate_physical_tree(tree: &NativeTree) -> DataFusionResult, RawLabelSource, SeriesOrdering)], ) -> Vec { - // What a fused input proves on its own: the pieces of a metric one scan partition holds. - // Nothing here places those pieces by canonical key, so nothing is claimed about ownership - a - // merge over what this boundary describes is therefore not placeable in a per-partition - // execution, which is what [`merges_are_placeable_in`] is asked and what a single execution - // provides without needing a proof. + // What a fused input proves about the pieces it hands over. + // + // A `SeriesRepartitionExec` routes every chunk by the canonical label set it carries and is + // recognised **by node identity**, not by its declared partitioning: it publishes + // `UnknownPartitioning(M)`, which says "this node promises nothing about where a key lives" and + // is deliberately not upgraded to a proof. Every other child places pieces by the storage + // `read_key`, so pieces of one canonical label set can sit in different partitions and nothing + // is claimed about their ownership. + // + // What that means for a merge is [`merges_are_placeable_in`]'s question, not this function's: + // over an unproven input a merge is not placeable in a per-partition execution, so the route + // that would need one declines rather than collapsing the node to a single execution. inputs .iter() - .map(|_| NativeProperties::source_pieces()) + .map(|(input, _, _)| NativeProperties { + owner: if input.downcast_ref::().is_some() { + CanonicalOwner::ByCanonicalKey + } else { + CanonicalOwner::Unknown + }, + ..NativeProperties::source_pieces() + }) .collect() } diff --git a/src/promql/src/extension_plan/series_repartition.rs b/src/promql/src/extension_plan/series_repartition.rs new file mode 100644 index 00000000000..0b808de6ba2 --- /dev/null +++ b/src/promql/src/extension_plan/series_repartition.rs @@ -0,0 +1,1376 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Routes evaluated series chunks by canonical label set, so that every piece of one label set +//! reaches one output partition. +//! +//! A per-partition execution cannot see another partition's pieces of a label set, so a merge there +//! would answer with a partial result and present it as a canonical one. This node removes that +//! premise: it reads every partition of its one child and hands each chunk to the output the +//! canonical label set of its series hashes to, so one merge sees all pieces of a label set. It is +//! the Repartition stage between two merges; nothing inserts it yet. +//! +//! The frame is the child's own: an evaluated chunk is decoded only to read the labels that route +//! it, and every output publishes the layout its input declared. +//! +//! # Routing +//! +//! The key is [`label_set`] of the chunk's metric, hashed whole: coarsening it (a subset of the +//! labels, a metric name alone) would send two label sets to one output for sharing a prefix, which +//! is not the relation a downstream merge groups by. One [`Routing`] is built per execution and +//! every chunk is reduced with it, so the destination of a label set cannot depend on which chunk of +//! it was routed first. +//! +//! The node declares [`Partitioning::UnknownPartitioning`], never [`Partitioning::Hash`]: the key is +//! decoded from the rows, and a hash declaration carries an Arrow expression DataFusion could use to +//! prove two plans agree on a partitioning. There is no such expression here, so the claim would be +//! one no optimizer could check and a hash exchange inserted on top of it could silently disagree +//! with. No ordering is declared either: the node reorders, and it says so by claiming nothing. +//! +//! # Chain boundaries +//! +//! A consumer of these frames - the native merge - requires that a series' identity does not change +//! and its positions strictly increase while it is open, and that `is_last` closes it. Two chains of +//! one label set, each valid on its own, violate that if their chunks interleave on one output: the +//! merge would refuse the stream, or a coarser reader would sort two series into a plausible answer. +//! +//! So a chain is the unit of routing, not a chunk: an input task reads its child until the chunk that +//! closes the chain it is assembling - or until its stream ends - and hands the whole chain to the one +//! output its label set hashes to, in one step. Two sources' chains may reach one output in either +//! order, but never inside one another, so an output is still a run of whole chains. That is what the +//! node handed downstream when one routing task served every input and only switched input at a chain +//! boundary, and it is what a downstream merge relies on. +//! +//! What that costs is stated rather than hidden. Nothing of a chain is handed over before the chain +//! closes, so the first chunk of a series reaches its output later than a chunk-at-a-time design would +//! deliver it, and a long chain occupies memory for as long as it is being read. Those bytes are +//! charged to a [`MemoryConsumer`] as the chain grows, so a pool under pressure ends the read with an +//! error instead of letting a chain grow without bound: the node refuses, it does not spin and it does +//! not buffer past the pool's limit. +//! +//! The alternative - routing one chunk at a time - would need a channel per (input, output) pair to +//! keep two sources' partial chains from interleaving on one shared output queue, which is N x M +//! channels plus a reader for each of them. That complexity is deliberately not taken here: a whole +//! chain per handover gets every output the same order with one queue per output. +//! +//! # Where the reads run +//! +//! One task per child partition, and no task above them: each input's task reads its own child, +//! assembles that input's chains and sends them to their owners itself. No task makes a routing +//! decision for another input, and nothing rotates over the inputs. +//! +//! That is not an optimisation of the routing: an evaluated partition is one stream whose computation +//! happens inside its `poll_next`, so a task polling every partition in turn runs the child's native +//! kernels for all of them itself, one chunk at a time, and the partition count the child declared +//! buys no parallelism at all. It is also what keeps routing local, which is what this node needs +//! when two of them are composed: +//! +//! - A partial chain never occupies a shared output queue, so no output waits for a continuation: a +//! chain is either fully assembled in the input task that read it, or not sent at all. +//! - A task never waits for another task's routing decision, and the tasks share no lock while +//! routing, so where one input's chain goes is not something another input learns or needs. +//! +//! Local routing is not independence, and the difference is what the rest of this section states. The +//! one sender set is cloned per task in `start`, so every input task holds a sender to **every** +//! output, and an input parked on a full queue is parked on a queue its siblings route into: +//! +//! - **An empty output closes late.** A queue closes when the last of its senders is dropped, and each +//! task drops its copy only by returning - so an output that no chain ever reached still ends when +//! the last input finished, not when the routing is known to have skipped it. A child that is itself +//! a repartition therefore depends on sibling progress for its EOF, and every output above it +//! inherits that. +//! - **A starved output stalls the others.** An input task with a chain for a full queue is parked +//! there, so what that input owed the other outputs waits behind it. Sustained starvation of one +//! output delays chains destined for the rest: it is not only the starved output that a consumer +//! loses. See the caller requirements below - they ask for steady drainage of every output, not one +//! poll of each. +//! +//! A single task routing every input was worse in both of those directions: it parked on the queue of +//! one output while holding the reads of every input, so an input that could have answered was not +//! read until that queue moved, and a composed node whose first input's stream only closes when the +//! reader finishes stalled outright. +//! +//! # Caller requirements +//! +//! **Every output partition MUST be polled, and must keep being polled until it ends.** +//! +//! Each input task suspends on a full output queue rather than dropping what belongs there, so an +//! output nobody polls keeps the input tasks whose chains hash to it parked. Concretely: +//! +//! - **Poll every partition, and keep polling it.** Once an unread output's queue fills, every input +//! task with a chain for it stops there, and what those inputs owe the other outputs stops with +//! them: this node does not spill and does not drop to make progress. What relieves a full queue is +//! a consumer that comes back to it, so one poll of each output is not the contract - an output has +//! to keep being read until it ends, all of them at once rather than one to completion. Polling the +//! partitions in turn, which is what a DataFusion executor does, is the shape that does this +//! because it returns to all of them; they need not be on separate tasks. Starvation of one output +//! is therefore not confined to it: the inputs parked on it never return, so the chains they would +//! have routed elsewhere stop arriving however steadily those other outputs are read. +//! - **Do not drain one partition to its end before polling the rest, unless what is routed to the +//! others fits their queues.** A consumer that finishes partition 0 before it looks at partition 1 +//! stalls as soon as partition 1's queue fills: the input tasks holding chains for partition 1 are +//! parked on it, and partition 0's remaining chunks are behind them. What an output ends with +//! before that point ends nothing else - an output nobody has claimed yet stays claimable and the +//! read keeps running for it, since it has not been handed out yet. +//! - **An unread output also holds the other outputs' end.** Every input task holds a sender to every +//! output, so an output's queue closes only once the last input task returned; an input parked on +//! an output nobody reads never returns. A consumer waiting for one output to end while neglecting +//! another is waiting on progress that only its own drainage of the neglected one can release. +//! - **Dropping an output is not the same as leaving it unread.** An input task stops routing to a +//! dropped output instead of suspending on it, because a queue nobody will drain is not worth +//! waiting for, and a plan that dropped one of its own outputs is being torn down. If chains read +//! for it were never delivered, the outputs that are still being read end with an error saying so +//! rather than with an end: the read did not finish. +//! +//! # Memory, backpressure and end of stream +//! +//! Each output has a bounded channel of [`OUTPUT_CAPACITY`] **chains** - a bound on how far the read +//! may run ahead of a consumer, not a bound on bytes - and each input task holds at most the one chain +//! it is assembling. Every queued chain is charged to a [`MemoryConsumer`] on the task context's pool, +//! the charge travels with the chain and is released when a consumer takes it or drops it, so bytes +//! are bounded by the pool refusing to grow rather than by the queue length. A pool that refuses a +//! chain ends the read with that error, because waiting for memory that will not come is not progress. +//! +//! An output ends only when every input partition finished and every chain routed to it was handed +//! over; a chain that closed locally is not the end of anything. With one task per input there is no +//! longer a single place that sees every input finish, so the tasks count themselves down: the one +//! that counts the last of the others off records that the read finished, and returning is what drops +//! the last sender and closes the queues - so an output woken by the close reads the outcome instead +//! of finding nothing there. If the child errors, every output receives that error as its terminal +//! item rather than a clean end, because an end would report the series that never arrived as series +//! that do not exist; the failing task records the failure before it hands the error over, and the +//! remaining input tasks are aborted rather than read to an end nobody asked for. +//! +//! A queue closing is not by itself that end: it also closes when the read is stopped - aborted, or +//! panicked - and a stopped read is missing exactly what it did not route. The read therefore records +//! how it ended, and an output whose queue has closed reads that record, so only a read that ended on +//! its own terms ends an output and anything else is an error saying the producer stopped +//! unexpectedly. +//! +//! An output stream owns the read, not the plan it was executed from: DataFusion's +//! `execute_stream_partitioned` takes the plan by value and keeps only the streams, so a read tied to +//! the plan would be stopped while its streams are still being consumed. The read therefore lives as +//! long as any of its outputs does, and stops only when there is nothing left it could deliver to: +//! every output was handed out and every one of them is gone. An output that ends - normally, or by +//! being dropped - while another partition was never executed stops nothing by itself, because that +//! partition can still claim its queue; the execution going away as a whole, which no later `execute` +//! can reach, is the other point at which everything is released. + +use std::fmt::{self, Formatter}; +use std::hash::{Hash, Hasher}; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; + +use common_error::ext::BoxedError; +use common_query::series_frame::{ + SendableEvaluatedSeriesStream, pack_evaluated_series, unpack_evaluated_series, +}; +use datafusion::common::tree_node::TreeNodeRecursion; +use datafusion::error::{DataFusionError, Result as DataFusionResult}; +use datafusion::execution::context::TaskContext; +use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation}; +use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr}; +use datafusion::physical_plan::execution_plan::EmissionType; +use datafusion::physical_plan::{ + DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, InputDistributionRequirements, + Partitioning, PlanProperties, SendableRecordBatchStream, +}; +use datatypes::series::SeriesLabels; +use datatypes::series::frame::{FrameContent, SeriesFrameDeclaration}; +use datatypes::series::samples::{Series, SeriesSchema}; +use futures::{Stream, StreamExt}; +use tokio::sync::mpsc; +use twox_hash::XxHash64; + +use crate::grid_series::{label_set, series_bytes}; + +/// How many whole chains one output partition queues before an input task suspends on it. +/// +/// This bounds read-ahead, NOT memory: the chains are already-decoded evaluated slices, so four of +/// them can still be large, and what actually bounds the bytes is the [`MemoryConsumer`] on the +/// task context's pool refusing to grow. Small and fixed because queue depth buys little here and +/// the sooner a slow consumer stops the read, the sooner the memory it would have taken is not +/// taken. +const OUTPUT_CAPACITY: usize = 4; + +/// The seed behind every routing decision. +/// +/// Fixed rather than drawn per execution, so which output a label set belongs on is a function of +/// the label set and the output count alone: an execution's own decisions have to agree with each +/// other, and a seeded router can be reasoned about - and tested - without one. +const ROUTING_SEED: u64 = 0x517c_c1b7_2722_0a95; + +/// The Repartition stage: one child's partitions, redistributed by canonical label set. +/// +/// The node holds one execution's shared state: its output partitions are separate `execute` calls +/// that must agree on one read of the child, so the first call starts the read and every call takes +/// its own output from it. +pub struct SeriesRepartitionExec { + input: Arc, + /// The frame the child declares, re-declared by every output batch. + series_schema: Arc, + /// The one hash configuration of this node's execution. + routing: Routing, + /// Started by the first `execute` call, since the output partitions share one read of the child. + shared: Mutex>>, + properties: Arc, +} + +impl SeriesRepartitionExec { + /// The name this node is shown under. + pub const fn name() -> &'static str { + "SeriesRepartitionExec" + } + + /// Creates the node over `input`, routing into `outputs` partitions. + /// + /// `outputs` is fixed here, by the planner, which knows the target partition count; the node + /// reads no session configuration of its own. A child that does not declare an evaluated frame + /// this node can re-declare is refused before the plan can run: the output schema is the child's, + /// and a frame whose declaration does not survive the round trip would be published under a + /// schema its batches do not match. + pub fn try_new(input: Arc, outputs: usize) -> DataFusionResult { + if outputs == 0 { + return Err(DataFusionError::Plan( + "SeriesRepartition requires at least one output partition".to_string(), + )); + } + let declaration = + SeriesFrameDeclaration::parse(input.schema().as_ref()).map_err(|error| { + DataFusionError::Plan(format!( + "SeriesRepartition input is not a series frame: {error}" + )) + })?; + if declaration.content() != FrameContent::Evaluated { + return Err(DataFusionError::Plan( + "SeriesRepartition routes evaluated series fragments, not raw samples".to_string(), + )); + } + let series_schema = Arc::new(declaration.series().clone()); + let declared = pack_evaluated_series( + Box::pin(futures::stream::empty()), + Arc::clone(&series_schema), + )? + .schema(); + if declared != input.schema() { + return Err(DataFusionError::Plan( + "SeriesRepartition input frame carries a schema this node cannot re-declare" + .to_string(), + )); + } + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(input.schema()), + Partitioning::UnknownPartitioning(outputs), + // Every chunk is handed on as it is read, so an output is written more than once - and + // an input that only answers at its end is still answered as it arrives. + EmissionType::Incremental, + // The node ends when its child does, and spends its life waiting until then. + input.properties().boundedness, + )); + Ok(Self { + input, + series_schema, + routing: Routing::new(outputs), + shared: Mutex::new(None), + properties, + }) + } + + /// How many output partitions this node has. + fn outputs(&self) -> usize { + self.properties.partitioning.partition_count() + } +} + +impl fmt::Debug for SeriesRepartitionExec { + /// The node and what it routes: the child, the schema and the running execution are noise in a + /// plan's debug form. + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("SeriesRepartitionExec") + .field("outputs", &self.outputs()) + .finish_non_exhaustive() + } +} + +impl DisplayAs for SeriesRepartitionExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!( + f, + "SeriesRepartitionExec: outputs={}, input_partitions={}", + self.outputs(), + self.input.properties().partitioning.partition_count() + ) + } +} + +impl ExecutionPlan for SeriesRepartitionExec { + fn name(&self) -> &str { + Self::name() + } + + fn properties(&self) -> &Arc { + &self.properties + } + + /// Nothing is asked of the input's distribution, and nothing may be inserted above it. + /// + /// The child's own partitioning is what this node reads: it reads every partition as it is, and + /// an exchange inserted between the two would reorder chunks across the chain boundaries the node + /// relies on, which no requirement it states could survive. A hash requirement would be worse + /// still, since the routing key is decoded from the rows rather than computed by an expression. + fn input_distribution_requirements(&self) -> InputDistributionRequirements { + InputDistributionRequirements::new(vec![Distribution::UnspecifiedDistribution]) + } + + /// Splitting the child further would not help: this node reads every input partition itself, so + /// a repartition below it only adds a hop that reorders what it must read in order. + fn benefits_from_input_partitioning(&self) -> Vec { + vec![false] + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + // The routing key is decoded from the rows, so this node binds no expression of its own. + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + mut children: Vec>, + ) -> DataFusionResult> { + if children.len() != 1 { + return Err(DataFusionError::Plan(format!( + "SeriesRepartitionExec requires one child, got {}", + children.len() + ))); + } + // Rebuilt rather than patched, so a child whose schema changed is refused here instead of + // routed under a frame declaration the new child does not make. + Ok(Arc::new(Self::try_new( + children.swap_remove(0), + self.outputs(), + )?)) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + if partition >= self.outputs() { + return Err(DataFusionError::Execution(format!( + "SeriesRepartition output partition {partition} is out of range" + ))); + } + let shared = { + let mut state = self + .shared + .lock() + .unwrap_or_else(|error| error.into_inner()); + if state.is_none() { + // The whole execution is started here, once: the output partitions are separate + // calls, and reading the child once for all of them is what keeps a chunk from being + // emitted twice or read by a scan that was never meant to run twice. + *state = Some(SharedExecution::start( + &self.input, + self.routing, + Arc::clone(&self.series_schema), + &context, + )?); + } + Arc::clone(state.as_ref().expect("the execution was just started")) + }; + let (receiver, lease) = SharedExecution::claim(&shared, partition).ok_or_else(|| { + DataFusionError::Execution(format!( + "SeriesRepartition output partition {partition} was executed twice" + )) + })?; + // The queue and the claim on the read are taken in one step, so an output that is refused - + // or one that is handed out after every other output already finished - is counted for + // exactly what it is. + pack_evaluated_series( + Box::pin(RepartitionStream { + receiver, + // Nothing of a chain is read from the queue yet. + chain: Vec::new().into_iter(), + lease, + reported: false, + }), + Arc::clone(&self.series_schema), + ) + } +} + +/// One execution's state: the child read once, and the outputs it is being distributed into. +/// +/// The plan that started it holds this, and so does every output stream it hands out. The read it +/// owns lives while any of them does - which is what makes it survive the plan - and what stops it is +/// [`Running::claimed`] and [`Running::remaining`] both reaching zero, or the state itself going away. +struct SharedExecution { + /// The queues, the tasks filling them, and how many of the execution's outputs the read still has. + running: Mutex, + /// How the read ended, and the failure it owes its outputs if it failed. + ending: Arc>, +} + +/// What one execution's state holds that has to be stopped together. +struct Running { + /// One receiver per output partition, taken by the `execute` call of that partition. A receiver + /// that is never taken stays here, which is what makes its queue fill and the input tasks whose + /// chains belong there suspend. + receivers: Vec>>, + /// The tasks reading the child's partitions into those queues, and how many of them are left. + inputs: Arc, + /// How many output streams were handed out and are not yet released. + /// + /// Counted rather than derived from a reference count, because the plan holds this state too and + /// is not an output: what has to reach zero for the read to be over is the number of streams, not + /// the number of owners. + claimed: usize, + /// How many outputs were never handed out, and can still be. + /// + /// Kept apart from [`claimed`](Self::claimed) because the two say different things: an output that + /// is claimed is one somebody is reading, and one that is only `remaining` is one nobody has asked + /// for yet. A claimed count that reaches zero with outputs left in this count has not lost its + /// consumers - it is waiting for them - and the queues of those outputs are exactly what a later + /// `execute` comes for, so they must outlive the read of every output that was claimed. + remaining: usize, +} + +impl Running { + /// Stops the read: every queue nobody took is dropped and every input task is aborted. + /// + /// Idempotent - the queues are already gone on a second call, and aborting a finished or already + /// aborted task is a no-op. Dropping the queues of outputs that were never handed out is part of + /// it: what was queued for them is read-ahead nobody will take, and holding it until the process + /// ends would keep both the memory and the child's scans alive for nothing. + fn stop(&mut self) { + self.receivers.clear(); + // Aborting a read that has not recorded an outcome is what the outputs still open have to + // see: nothing was recorded, so the end they read is "the producer stopped unexpectedly". + self.inputs.stop(); + } +} + +impl SharedExecution { + /// Starts reading every partition of `input` into `routing`'s outputs on `context`'s pool. + /// + /// One task per child partition, started here: the child's computation happens inside its own + /// `poll_next`, so a partition read on a task of another partition would run there, and the + /// partition count the child declared would buy no parallelism at all. + fn start( + input: &Arc, + routing: Routing, + series_schema: Arc, + context: &Arc, + ) -> DataFusionResult> { + let partitions = input.properties().partitioning.partition_count(); + let mut streams = Vec::with_capacity(partitions); + for child_partition in 0..partitions { + let frames = input.execute(child_partition, Arc::clone(context))?; + // The expected schema is a check and never an input: the decoder reads the frame's own + // declaration, and a partition declaring another frame is refused here rather than + // routed under labels it does not carry. + streams.push(unpack_evaluated_series( + frames, + Some(Arc::clone(&series_schema)), + )?); + } + let mut senders = Vec::with_capacity(routing.outputs); + let mut receivers = Vec::with_capacity(routing.outputs); + for _ in 0..routing.outputs { + let (sender, receiver) = mpsc::channel(OUTPUT_CAPACITY); + senders.push(sender); + receivers.push(Some(receiver)); + } + let ending = Arc::new(Mutex::new(EndingRecord::default())); + let inputs = Inputs::new(Arc::clone(&ending), partitions); + // A child with no partitions has nothing to read, so the read finished before it started: the + // count that the last input task would bring to zero is already there. + if partitions == 0 { + inputs.record(Ending::Finished); + } + let pool = Arc::clone(&context.runtime_env().memory_pool); + for (partition, stream) in streams.into_iter().enumerate() { + // Each task is handed its own copy of the senders rather than a lock over one copy: a + // send is then a send of its own, and the queues close when the last task returns instead + // of when some shared lock says so. + let task = common_runtime::spawn_query(route_partition( + stream, + partition, + routing, + senders.clone(), + // What this partition reads ahead is charged to its own consumer, so the read-ahead + // of one partition is attributable to the task that did it. + MemoryConsumer::new("SeriesRepartitionInput").register(&pool), + Arc::clone(&inputs), + )); + inputs.attach(partition, task); + } + // This copy is dropped before any output exists, so it is no part of when the queues close. + drop(senders); + Ok(Arc::new(Self { + running: Mutex::new(Running { + receivers, + inputs, + // No output is handed out yet: every one of them is still to be claimed. + claimed: 0, + remaining: routing.outputs, + }), + ending, + })) + } + + /// The queue of `partition` and the lease on this read that reading it takes. + /// + /// The queue and the claim are taken under one lock, and that is what keeps the counts honest: an + /// output stops being one nobody asked for and becomes one the read is running for in the same + /// step, so a release on another task cannot see "nothing left" in between and stop a read that + /// is being handed out. `None` means that output was claimed before - its queue is gone and this + /// call does not count as one the read is running for. + fn claim( + shared: &Arc, + partition: usize, + ) -> Option<(mpsc::Receiver, OutputLease)> { + let mut running = shared + .running + .lock() + .unwrap_or_else(|error| error.into_inner()); + let receiver = running + .receivers + .get_mut(partition) + .and_then(Option::take)?; + running.remaining -= 1; + running.claimed += 1; + Some(( + receiver, + OutputLease { + shared: Arc::clone(shared), + }, + )) + } + + /// Gives up one claim, and stops the read once there is nothing left it could deliver to. + /// + /// This is the one decision the lifecycle turns on, and it is not "the last output went away": an + /// output that is released is one that finished being read, and the outputs nobody has claimed + /// yet are ones a later `execute` will still claim. The read may stop only when both are + /// impossible - no output is being read ([`claimed`](Running::claimed) is zero) and none is left + /// to hand out ([`remaining`](Running::remaining) is zero) - so an input task parked on the queue + /// of an output that has not been claimed yet keeps waiting: that is backpressure on a consumer + /// that is still coming, not a read with nowhere to go. + fn release_output(&self) { + let mut running = self + .running + .lock() + .unwrap_or_else(|error| error.into_inner()); + running.claimed -= 1; + if running.claimed == 0 && running.remaining == 0 { + running.stop(); + } + } + + /// How the read ended, and the failure it owes its outputs if it failed. + /// + /// Both are read under the one lock that records them, so an output never sees a failure without + /// the error that belongs to it. + fn ending(&self) -> (Ending, Option>) { + let record = self + .ending + .lock() + .unwrap_or_else(|error| error.into_inner()); + (record.ending, record.terminal.clone()) + } + + /// Stops the read and releases everything it holds. + /// + /// Called when the execution itself goes away - the plan and every output are gone, so no later + /// `execute` can claim an output that was never handed out - and by + /// [`release_output`](Self::release_output) when the last claim is given up on an execution that + /// has nothing left to hand out. Idempotent, because both can happen and because the state's own + /// drop runs it once more. + fn stop(&self) { + let mut running = self + .running + .lock() + .unwrap_or_else(|error| error.into_inner()); + running.stop(); + } +} + +impl Drop for SharedExecution { + fn drop(&mut self) { + // Nothing holds the read any more: every output is gone and so is the plan. A task parked on + // a queue nobody will drain, or on a scan, must not outlive both of them. + self.stop(); + } +} + +/// The input tasks of one read: what is left of them, and what the last of them records. +/// +/// There is one task per child partition and no task above them, so there is no longer one place that +/// sees every input finish and no producer whose return closes the queues. This is that place +/// instead: the tasks count themselves down, and the task that counts the last of the others off +/// records that the read finished and then returns - returning is what drops its senders, so the +/// record is made before the queues close, and an output woken by their closing reads the outcome +/// instead of finding nothing there. +struct Inputs { + /// The tasks themselves, and the count of those that have not stopped. + state: Mutex, + /// How the read ended, and the failure it owes its outputs if it failed. + ending: Arc>, +} + +/// What [`Inputs`] guards. +struct InputState { + /// The task of each input partition, by partition, `None` once it stopped. + /// + /// Kept rather than dropped so that the read can be stopped as a whole, and so that the one task + /// that broadcasts a failure can abort the rest: a partition whose peer already failed has + /// nothing left to route that an output would still take. + tasks: Vec>>, + /// How many of those tasks have not stopped yet. + /// + /// The last task to stop brings this to zero, and reaching zero on a read nobody cancelled is + /// what records that the read finished. A cancellation sets it to zero itself, because a + /// cancelled read has no task left that will do its own bookkeeping: the failure's broadcaster + /// counts itself out at the end of its broadcast, and every other task is aborted, which drops + /// its future without it ever reaching [`Inputs::count_out`]. A task spawned and attached after + /// the cancellation is aborted by [`Inputs::attach`] and never runs, so it cannot raise this + /// back above zero and keep a finished read open. + live: usize, + /// Whether the read was stopped from outside - every output is gone, or the plan's state went + /// away. It is the one thing that keeps the last task from recording that the read finished: a + /// stopped read never finished, and the outputs that wake on the close of their queues must say + /// so rather than report a complete answer. + stopped: bool, + /// The partition whose task is broadcasting the read's failure, once one was elected. + /// + /// Exactly one task claims this, under this lock, and the claim is what makes the failure path + /// single-threaded: the task that finds it unclaimed is the only one that records the failure, + /// aborts the other tasks and hands the error to the outputs, and every other failing task finds + /// it taken and stops without touching a peer. That is what keeps a second failure from aborting + /// the broadcaster that is still handing the error over - the interleaving that used to leave an + /// output with a failed read recorded and no error item, which it then reported as a clean end. + failed_by: Option, + /// Whether the read has been cancelled: a failure was elected, or [`Inputs::stop`] was called. + /// + /// Recorded under the same lock that guards [`tasks`](Self::tasks), so a task attached after the + /// cancellation is aborted by [`Inputs::attach`] rather than stored. The sweep that cancels the + /// read can only abort the handles that exist when it runs, and a task spawned afterwards would + /// otherwise wait on a child for a read that is over while holding a sender to every output - + /// which keeps every queue open and every reader of it waiting. + cancelled: bool, +} + +impl Inputs { + /// The bookkeeping of a read over `partitions` input partitions. + fn new(ending: Arc>, partitions: usize) -> Arc { + Arc::new(Self { + state: Mutex::new(InputState { + tasks: (0..partitions).map(|_| None).collect(), + live: partitions, + stopped: false, + failed_by: None, + cancelled: false, + }), + ending, + }) + } + + /// Gives `task` the slot of `partition`, so that the read can still abort it. + /// + /// Stored even if the task has already stopped - a partition that answers at once can return + /// before its handle is stored - because the slot is only consulted to stop what is still running, + /// and aborting a finished task is a no-op. + /// + /// A task attached to an already cancelled read is aborted here instead of stored. The + /// cancellation swept the tasks that existed when it ran - a partition that fails before its + /// peers are even spawned is exactly the case the sweep misses - so this is where those tasks + /// stop: storing one would leave it waiting on its child for a read that is over, holding a + /// sender to every output, so no queue would ever close. It is not counted either: + /// [`live`](InputState::live) is already zero and a task that never runs cannot add to it. + fn attach(&self, partition: usize, task: common_runtime::JoinHandle<()>) { + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + if state.cancelled { + state.tasks[partition] = None; + task.abort(); + return; + } + state.tasks[partition] = Some(task); + } + + /// Records that `partition` ended, and that the read finished if it was the last one running. + /// + /// Nothing is recorded when the read was stopped from outside: its tasks do not reach this point, + /// and one that gets here anyway must not turn a stopped read into a finished one. + fn ended(&self, partition: usize) { + if self.count_out(partition) { + self.record(Ending::Finished); + } + } + + /// Records that the chain this partition was routing had no output left to be delivered to, and + /// stops the read with it. + /// + /// Nothing is recorded as finished here, whatever the other partitions go on to do: the read lost + /// the chains that output would have carried, so it did not finish. Nothing is recorded as a + /// failure either - nothing failed, an output went away - so what the outputs report is + /// [`Ending::Abandoned`], which wins over [`Ending::Finished`] because the cancellation below takes + /// the count to zero: a peer that reads its child to its end after this finds the read cancelled + /// and records nothing. + /// + /// Stopping the peers is part of it, and is what an abandoned read was missing. An output that is + /// gone cannot come back, so the read cannot complete for anyone - and a peer parked on a child + /// that never answers keeps its sender to every output alive, which keeps every queue open, which + /// is every other output waiting for an end that can no longer be complete. Cancel them instead: + /// their senders drop, the queues close, and each output reads the `Abandoned` recorded here. + fn abandoned(&self, partition: usize) { + self.record(Ending::Abandoned); + self.cancel(partition); + self.count_out(partition); + } + + /// Records that `partition`'s task stopped without reporting an outcome, and stops the read with + /// it. + /// + /// This runs where no arm of [`route_partition`]'s match can: in a `Drop`. A panic inside + /// [`read_chains`] unwinds the task and drops the future that was polling it, and an abort drops + /// that same future where it stands, so both land here - which is the point, because neither + /// records anything otherwise. What that costs when nothing stops it is the whole read: the peers + /// go on reading a child that may never answer, their sender clones stay alive, no queue closes, + /// and every output waits for an ending that is not coming. So a task that died is a failure of + /// the read, and it is recorded and acted on as one. + /// + /// A read that is already cancelled - stopped from outside, abandoned by an output, or already + /// broadcasting a failure - only counts this task out. The outcome that cancelled it is the one + /// the outputs report, and the aborts it performs are what killed this task: a task dying there is + /// a consequence of that outcome, not a second one for the outputs to choose between. + /// + /// Nothing is sent to the outputs, and nothing could be: a `Drop` has nowhere to await a full + /// queue. It is not needed either, and that is read off what an output does rather than assumed. + /// Delivery here is structural: a queue closes when the last of its senders is dropped, every input + /// task holds a clone of every sender, and the peers cancelled here drop theirs as their futures + /// are dropped - so the queues close with nobody sending anything. What an output whose queue has + /// closed reads is [`RepartitionStream::poll_next`] at `Ready(None)`, which consults + /// [`OutputLease::ending`] before calling the read over, and that turns the [`Ending::Failed`] + /// recorded here into the error built from its terminal error. Every output therefore reports this + /// failure out of the read's own record, exactly as it reports a failure whose broadcast was cut + /// short. + fn task_died(&self, partition: usize) { + if !self.claim_death(partition) { + // The read has an outcome already, or another task's failure is the one being handed + // over. Counting out only keeps the bookkeeping honest: the read is cancelled, so this + // cannot make it look finished. + self.count_out(partition); + return; + } + // Recorded with its error in one write, and before this task's sender clones are dropped: an + // output woken by its queue closing reads the failure and the error that belongs to it. + self.fail(Arc::new(DataFusionError::Execution(format!( + "series repartition input partition {partition} stopped without reporting an outcome" + )))); + self.abort_others(partition); + self.count_out(partition); + } + + /// Records that `partition` failed, hands the failure to every output, and stops the rest. + /// + /// Only one task does that, and it is the one that wins the election below. The claim, the + /// cancellation and the count going to zero are one step under the lock that also guards the + /// task handles, so two failing tasks cannot both decide they are the broadcaster, and cannot + /// disagree about whether the read is over either. + /// + /// The failure and its error are recorded before anything is aborted and before anything is sent: + /// the queues close when the last task returns, and an output woken by that has to read that the + /// read failed rather than read nothing. Every output then receives the error as a terminal item, + /// so an output that is still being read cannot mistake the failure for an end - and the other + /// input tasks are aborted, because what they would still route belongs to a read that has + /// already failed. + /// + /// A task that loses the election records nothing, aborts nobody and returns: the failure is + /// being broadcast by another task, and sweeping the peers from here would abort it - a task + /// suspended on a full output queue dies at that point, so the outputs it had not reached yet + /// would be left with a failed read recorded and no error item, which an output reports as a + /// clean end. + async fn failed( + &self, + partition: usize, + error: &Arc, + senders: &[mpsc::Sender], + ) { + if !self.claim_failure(partition) { + // Another partition's task is the read's one broadcaster. It is already stopping this + // task, so this one records nothing and stops nobody - counting itself out only keeps + // the bookkeeping tidy, since the read is cancelled and this cannot make it look + // finished. + self.count_out(partition); + return; + } + self.fail(Arc::clone(error)); + self.abort_others(partition); + for sender in senders { + // Ignored: an output that is gone has nobody left to tell, and one whose queue is full + // is drained by the consumer that owns it. + let _ = sender.send(Err(Arc::clone(error))).await; + } + self.count_out(partition); + } + + /// Claims the read's one failure broadcast for `partition`, and cancels the read if it got it. + /// + /// `true` means this task is the broadcaster and the read is now cancelled; `false` means another + /// task claimed the broadcast first, and this one must not touch the read any more. Everything + /// that makes the claim atomic happens here, under the task lock: the loser's read of + /// [`failed_by`](InputState::failed_by) and the winner's write of it, the cancellation that + /// [`attach`](Self::attach) honours, and the count the read's end was read from. + fn claim_failure(&self, partition: usize) -> bool { + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + if state.failed_by.is_some() { + return false; + } + state.failed_by = Some(partition); + Self::cancel_locked(&mut state); + true + } + + /// Claims the read's one failure broadcast for a task that has already stopped, if there is + /// anything left to claim. + /// + /// The same claim [`claim_failure`](Self::claim_failure) makes, refused when the read is already + /// cancelled, and that difference is what keeps a dying task from rewriting an outcome that + /// exists. A stopped read records nothing and is reported as a stop; an abandoned one records + /// [`Ending::Abandoned`]; a failed one is broadcasting its own error. The aborts those paths + /// perform are what stopped this task in the first place, so its death is the consequence of the + /// outcome already recorded rather than a second one the outputs would have to choose between. A + /// task that fails on its own is not that case: a failure outranks every other ending, so the + /// failure path claims whatever else was recorded. + fn claim_death(&self, partition: usize) -> bool { + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + if state.cancelled || state.failed_by.is_some() { + return false; + } + state.failed_by = Some(partition); + Self::cancel_locked(&mut state); + true + } + + /// Cancels the read and aborts every input task but `partition`'s own. + /// + /// The one primitive for ending a read its remaining tasks cannot serve: a failure is on its way + /// to the outputs, a task died, or an output the read would have delivered into is gone. What it + /// does is what each of those needs from the others - see [`cancel_locked`](Self::cancel_locked) + /// for the cancellation itself, and [`abort_others`](Self::abort_others) for the sweep. + fn cancel(&self, partition: usize) { + { + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + Self::cancel_locked(&mut state); + } + self.abort_others(partition); + } + + /// Cancels the read, under the task lock the caller already holds. + /// + /// Cancelled is what keeps a peer from recording that the read finished: a task that reaches + /// [`count_out`](Self::count_out) after this records nothing, so [`Ending::Finished`] - which an + /// output reports as a complete answer - cannot be recorded for a read that stopped under its + /// outputs. The count is taken to zero in the same step for the same reason from the count's side: + /// the read is over as of here, every other task is about to be aborted and so never counts itself + /// out, and the task doing the cancelling has no more of the read to run either. + fn cancel_locked(state: &mut InputState) { + state.cancelled = true; + state.live = 0; + } + + /// Counts `partition` off the read, and says whether it was the last task still running. + fn count_out(&self, partition: usize) -> bool { + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + // Taken and dropped: this task is the one stopping, and holding its own handle would leave the + // read waiting for a task that has already finished. Saturating because a task that was + // stopped from outside may still reach this after [`stop`](Self::stop) counted it off. + state.tasks[partition] = None; + state.live = state.live.saturating_sub(1); + // A cancelled read never records that it finished: a failure is the outcome its outputs + // report, and a stop is not an end. + state.live == 0 && !state.stopped && !state.cancelled + } + + /// Aborts every input task but `partition`'s own. + /// + /// Called by whatever ended the read: the one failure broadcaster, a task that died without + /// reporting (through [`cancel`](Self::cancel)), and a partition that lost a chain to a dropped + /// output. `partition`'s own task is spared because it still has bookkeeping to do - it is the one + /// handing the error over, or the one already gone - and aborting it from here would cut that + /// short: a broadcaster aborted while suspended on a full output queue leaves the outputs it had + /// not reached with a failed read recorded and no error item, which an output reports as a clean + /// end. + fn abort_others(&self, partition: usize) { + let state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + for (index, task) in state.tasks.iter().enumerate() { + // Aborting a task that already stopped is a no-op, so the finished ones cost nothing + // here. + if index != partition + && let Some(task) = task + { + task.abort(); + } + } + } + + /// Stops every input task that has not stopped yet, and counts the read as stopped. + /// + /// The count is set rather than left to the tasks: an aborted task does not run its own + /// bookkeeping, and a read whose tasks were aborted never reached an end of its own. The read is + /// cancelled as well as stopped, so that a task attached after this call - one the sweep here + /// could not see - is aborted by [`attach`](Self::attach) instead of waiting on a child for a + /// read that is over. + fn stop(&self) { + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + state.stopped = true; + state.cancelled = true; + state.live = 0; + for task in state.tasks.iter_mut() { + if let Some(task) = task.take() { + task.abort(); + } + } + } + + /// Records `outcome` as how the read ended, unless an ending is already recorded. + /// + /// Nothing outranks a recorded ending, so the first task to record `Abandoned` or `Finished` is + /// the one reported - a read that lost chains to a dropped output did not finish, whatever the + /// other partitions went on to do. A failure is recorded by [`fail`](Self::fail), which stores + /// its error in the same write: recording one here would be a failure no output could report. + fn record(&self, outcome: Ending) { + debug_assert!( + !matches!(outcome, Ending::Failed), + "a failure is recorded by `fail`, with its error" + ); + let mut record = self + .ending + .lock() + .unwrap_or_else(|error| error.into_inner()); + if matches!(record.ending, Ending::Unrecorded) { + record.ending = outcome; + } + } + + /// Records that the read failed with `error`, keeping the error where its outputs can read it. + /// + /// A failure outranks every other ending, so it is recorded whatever is there already - and it is + /// recorded together with its error, in one write, so that an output reading [`Ending::Failed`] + /// always reads the error that goes with it. Only the broadcast's elected task calls this. + fn fail(&self, error: Arc) { + let mut record = self + .ending + .lock() + .unwrap_or_else(|error| error.into_inner()); + record.ending = Ending::Failed; + if record.terminal.is_none() { + record.terminal = Some(error); + } + } + + /// How many input tasks have not stopped, which is what a test sees the read stop by. + #[cfg(test)] + fn live(&self) -> usize { + self.state + .lock() + .unwrap_or_else(|error| error.into_inner()) + .live + } + + /// Aborts the task of one input partition, for a test that has to make exactly one producer stop. + /// + /// [`stop`](Self::stop) cannot state that: it stops every task and records the read as stopped, + /// so what an output reports afterwards is the stop rather than one producer dying. + #[cfg(test)] + fn abort(&self, partition: usize) { + let state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + if let Some(task) = &state.tasks[partition] { + task.abort(); + } + } +} + +/// One input partition's task: reads its own child, one whole chain at a time, and hands each chain +/// to the output its canonical label set hashes to. +/// +/// This is the whole of that input's routing. Nothing here reads another partition, waits for another +/// task's decision, or holds a lock another task takes, so the two things it can be parked on are its +/// own child and a full output queue. Neither is another task's routing decision - but a queue is +/// shared with the siblings that route into it, so what they filled it with can delay a chain of this +/// input, and this task's return is one of the senders every output's close waits for. +/// +/// What it saw is recorded before it returns, and returning is what drops its senders: the queues +/// close only once every task has done that, so the outcome is in place before anything can be woken +/// by a close. +async fn route_partition( + mut stream: SendableEvaluatedSeriesStream, + partition: usize, + routing: Routing, + senders: Vec>, + read_ahead: MemoryReservation, + inputs: Arc, +) { + // Held across the whole read, and built before it starts, so that every way of leaving this + // function reports what happened - including the two that never reach the match below. + let mut report = ReportIfUnreported { + inputs: Arc::clone(&inputs), + partition, + reported: false, + }; + let stop = read_chains(&mut stream, &routing, &senders, &read_ahead).await; + match &stop { + Stop::Ended => inputs.ended(partition), + Stop::Abandoned => inputs.abandoned(partition), + Stop::Failed(error) => inputs.failed(partition, error, &senders).await, + } + // This task said what became of its partition, so the guard has nothing left to report. + report.reported = true; +} + +/// Reports an input task that stopped without recording an outcome, on the paths that would +/// otherwise report nothing. +/// +/// The match in [`route_partition`] covers the ways a read ends on its own terms: the partition ended, +/// a chain had no output to go to, the child failed. What it does not cover is a task that never +/// returns at all. A panic unwinds the task and takes the future polling it with it, and the task +/// being aborted drops that future where it stands; neither reaches an arm of that match, so nothing +/// is recorded, the count is untouched and the peers go on reading. A peer parked on a child that +/// never answers then holds a sender to every output for good, no queue ever closes, and every output +/// waits for an ending that is not coming - the `Unrecorded` fallback is no help there, since it is +/// only read once a queue has closed. +/// +/// A guard is what covers both without [`std::panic::catch_unwind`], which covers neither an abort nor +/// a panic the runtime catches elsewhere: unwinding and cancellation both drop this, so both report. +struct ReportIfUnreported { + /// The bookkeeping of the read this task belongs to. + inputs: Arc, + /// The input partition whose task holds this guard. + partition: usize, + /// Whether that task recorded its own outcome, which is what makes this a no-op. + reported: bool, +} + +impl Drop for ReportIfUnreported { + fn drop(&mut self) { + // Also runs on the way out of a normal return, which is what the flag is for: a task that + // reached its own ending reported it there and has nothing to add here. + if !self.reported { + self.inputs.task_died(self.partition); + } + } +} + +/// Why one input task stopped reading its partition. +enum Stop { + /// The partition ended: every chunk it had was read and handed to the output it belongs on. + Ended, + /// The output that should have taken a chain was gone, so the chain was never delivered. + Abandoned, + /// The partition failed, or a chain could not be buffered: every output has to learn that. + Failed(Arc), +} + +/// Reads one input partition to its end, one whole chain at a time, routing each chain as it closes. +/// +/// A chain is assembled here and handed over as one unit, which is what keeps a shared output queue +/// from holding half of one series while another source's chain is open on it: the queue carries whole +/// chains, so two inputs can order them differently but never interleave them. The price is paid on +/// this side of the queue - nothing of a chain is sent before the chain closes, and a long chain is +/// held for as long as it is being read - and it is charged to the pool as it grows. +/// +/// What this function can be parked on is its own child or a full output queue. The queue is drained +/// by whoever polls that output, which is the module's caller contract, and it is shared with the +/// sibling tasks routing into it: what they queued there can stop this task, and what this task queued +/// there can stop them. The child is driven by nothing but this task, and nothing here waits on +/// another task's routing decision. +async fn read_chains( + stream: &mut SendableEvaluatedSeriesStream, + routing: &Routing, + senders: &[mpsc::Sender], + read_ahead: &MemoryReservation, +) -> Stop { + loop { + // One whole chain, assembled here: the chunk that closes the series ends it, and so does a + // stream that ends between two chains. + let mut chain: Chain = Vec::new(); + let mut ended = false; + loop { + match stream.next().await { + Some(Ok((series, is_last))) => { + // Charged as the chain grows, so a chain that does not fit the pool is refused + // here rather than after it has been held. + let charge = read_ahead.new_empty(); + if let Err(error) = charge.try_grow(series_bytes(&series)) { + return Stop::Failed(Arc::new(error)); + } + chain.push((series, is_last, charge)); + if is_last { + break; + } + } + Some(Err(error)) => { + // The error is the last thing this partition says: it is handed to every output + // rather than ending this one task quietly. + return Stop::Failed(Arc::new(DataFusionError::External(Box::new(error)))); + } + None => { + ended = true; + break; + } + } + } + if ended { + // A partition that ends is a partition with nothing left to route - unless it ended + // inside a chain, which no later chunk can close. The decoders refuse that, so this is a + // producer that bypassed them, and its output would hold a series no chunk can close. + return if chain.is_empty() { + Stop::Ended + } else { + Stop::Failed(Arc::new(DataFusionError::Execution( + "series repartition input ended with its series open".to_string(), + ))) + }; + } + // One hash per chain, over the labels of its first chunk: the chunks of a chain are one + // series, so the first of them names the output for all of them. + let output = routing.output(&chain[0].0.metric); + if senders[output].send(Ok(chain)).await.is_err() { + // The output was dropped, so nothing it would have received is wanted: this task stops + // instead of waiting on a queue nobody will drain. + return Stop::Abandoned; + } + } +} + +/// What one output stream holds so that the read belongs to the streams rather than to the plan. +/// +/// DataFusion's `execute_stream_partitioned` takes the plan by value and keeps only the streams, so +/// the state that started the read is dropped before the first chunk is read: a read stopped there +/// would end every output early, and an end is not something a consumer can tell from a complete +/// answer. The lease is what keeps it running instead; and because only streams hold one, a lease +/// going away is the point at which that one output can no longer take a chunk - which +/// [`SharedExecution::release_output`] turns into the end of the read only when no output is left that +/// could. +struct OutputLease { + shared: Arc, +} + +impl OutputLease { + /// What an output whose queue has closed reports. + /// + /// An end is this node's claim that every input partition finished and every chunk routed here + /// was handed over, so only a read that ended that way may produce one. Everything else is the + /// read stopping underneath its outputs, which is a failure of the answer and not the end of it. + /// + /// A failed read is an error here even though the broadcaster hands the error to every output as + /// a terminal item: the broadcast can be cut short - the read can be stopped, or the task running + /// it aborted - and an output it never reached would otherwise report a failed read as a complete + /// answer. The error is recorded beside the ending, so this reads the same one the item would + /// have carried. + fn ending(&self) -> Option> { + let (ending, terminal) = self.shared.ending(); + match ending { + Ending::Finished => None, + Ending::Failed => Some(Err(boxed(match &terminal { + Some(error) => DataFusionError::from(error), + // A failure whose error cannot be found is still a failure, and saying so is the + // point: an end here would claim that every chunk routed to this output arrived. + None => DataFusionError::Execution( + "series repartition failed and its error is no longer available".to_string(), + ), + }))), + Ending::Abandoned => Some(Err(boxed(DataFusionError::Execution( + "series repartition stopped before the read finished: an output partition was dropped" + .to_string(), + )))), + Ending::Unrecorded => Some(Err(boxed(DataFusionError::Execution( + "series repartition producer stopped unexpectedly before the read finished" + .to_string(), + )))), + } + } +} + +impl Drop for OutputLease { + fn drop(&mut self) { + // An output that is done is not by itself the end of the read: the outputs that were never + // claimed are still to come, and what is queued for them is what they will read. Giving up + // the claim therefore only says that this one output will take nothing more - whether the + // read can go on is decided from every output, claimed and unclaimed alike. + self.shared.release_output(); + } +} + +/// How a read ended, as an output whose queue has closed has to report it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Ending { + /// Nothing recorded an outcome - and a read that ends on its own terms records one before it + /// drops its queues - so this is a read that was stopped, aborted or panicked, mid-flight. + #[default] + Unrecorded, + /// Every input partition finished and every chunk routed to an output was handed over. + Finished, + /// The read stopped because an output went away, leaving the chunks read for it undelivered. + Abandoned, + /// The read failed. Its error is recorded beside this ending in the [`EndingRecord`] that holds + /// both, and every output reports it - as the terminal item the read's one broadcaster hands + /// over, or, for an output the broadcast never reached, as the error read from there. + Failed, +} + +/// How a read ended, and - when it failed - the error it owes every output. +/// +/// The ending and the error are one value under one lock on purpose: a failure is recorded in one +/// write, so an output that reads [`Ending::Failed`] always reads the error that goes with it. That +/// is what keeps the error reachable when the broadcast meant to hand it over does not finish - a +/// broadcaster records it before it sends anything, and an output whose queue closes without ever +/// receiving the item reports the stored error rather than calling the read complete. +#[derive(Default)] +struct EndingRecord { + /// How the read ended. + ending: Ending, + /// The failure the read recorded, shared rather than rebuilt so every output reports the one + /// error the child answered with. `None` until a failure is recorded, and never cleared. + terminal: Option>, +} + +/// One whole chain of one series: its chunks from the one that opened it to the one that closed it, +/// each with the bytes it is charged. +/// +/// This is what an output queue carries, and that is deliberate. A downstream frame reader needs one +/// series' chunks contiguous, so a queue of chunks would let two sources' partial chains interleave on +/// one output; a queue of chains cannot, whatever order the sources happen to send in. +type Chain = Vec<(Series, bool, MemoryReservation)>; + +/// What one output queue carries: a whole chain, charged for the bytes it holds, or the error that +/// ended one input partition's read. +/// +/// The charge a partition's task took is handed on with the chain it is for, so what one output has +/// queued is exactly what the pool has reserved for it. +type Queued = Result>; + +/// One output partition's stream: the chains routed here, handed over a chunk at a time. +struct RepartitionStream { + receiver: mpsc::Receiver, + /// The chain being handed over, and how far into it this stream is. + /// + /// Taken off the queue as one unit and published one chunk per batch, so a consumer sees the same + /// chunks it always saw while what the queue held was a whole chain: the interleaving a chunk-wise + /// queue would allow has no way to happen after the fact. + chain: std::vec::IntoIter<(Series, bool, MemoryReservation)>, + /// The read this stream is an output of. + lease: OutputLease, + /// Whether the end of the stream was already reported, so a poll after it is the end and not the + /// same failure a second time. + /// + /// Set both by the end of the queue and by the error item that ends the stream instead: an error + /// is terminal, so nothing of the read is handed over after it - and the next poll is the end + /// rather than a second report of the same failure. + reported: bool, +} + +impl Stream for RepartitionStream { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + loop { + if let Some((series, is_last, charge)) = this.chain.next() { + // The chunk is no longer the node's to hold: whoever reads it owns it from here. + drop(charge); + return Poll::Ready(Some(Ok((series, is_last)))); + } + if this.reported { + return Poll::Ready(None); + } + match this.receiver.poll_recv(cx) { + Poll::Ready(Some(Ok(chain))) => this.chain = chain.into_iter(), + // The error is shared rather than rebuilt, so every output reports the one failure the + // child answered with instead of M copies of its text. It is also terminal: the read + // failed, so what a task queued behind it belongs to an answer that is not coming, and + // the poll after this one is the end of the stream. + Poll::Ready(Some(Err(error))) => { + this.reported = true; + return Poll::Ready(Some(Err(boxed(DataFusionError::from(&error))))); + } + // The queue closing is not the end of the read on its own: aborting the read closes it + // too, and calling that an end would report every chunk it never routed as a chunk + // that does not exist. What the read recorded says which of the two this is. + Poll::Ready(None) => { + this.reported = true; + // No error item reached this output - the read never failed, or it did and the + // broadcast that carries the error was cut short before it got here. The read's + // own record answers both: a failure is reported as the error it is, and never + // as the end of the answer. + return Poll::Ready(this.lease.ending()); + } + Poll::Pending => return Poll::Pending, + } + } + } +} + +/// The boxed error a frame stream reports. +fn boxed(error: DataFusionError) -> BoxedError { + BoxedError::new(common_query::error::Error::from(error)) +} + +/// The hash configuration one execution routes with. +/// +/// The seed is what an execution builds once; a [`XxHash64`] accumulates, so a fresh hasher starts +/// from this configuration for each chunk, and that is the only thing each chunk builds. +#[derive(Clone, Copy, Debug)] +struct Routing { + /// The number of output partitions a hash is reduced modulo. + outputs: usize, + /// The seed every chunk of this execution is hashed with. + seed: u64, +} + +impl Routing { + /// The routing of an execution with `outputs` output partitions. + fn new(outputs: usize) -> Self { + Self { + outputs, + seed: ROUTING_SEED, + } + } + + /// The output partition `metric`'s canonical label set belongs on. + /// + /// The whole label set is hashed, since that is what a merge groups by: pieces of two series + /// whose label sets differ have to be able to land apart, or the split this node exists to make + /// would not happen. [`label_set`] is what canonicalizes the labels - dropping empty values and + /// keeping the metric name - so two pieces that merge hash the same. + fn output(&self, metric: &SeriesLabels) -> usize { + let mut hasher = XxHash64::with_seed(self.seed); + label_set(metric).hash(&mut hasher); + // `outputs` is at least one, which [`SeriesRepartitionExec::try_new`] is what guarantees. + (hasher.finish() % self.outputs as u64) as usize + } +} + +#[cfg(test)] +mod tests; diff --git a/src/promql/src/extension_plan/series_repartition/tests.rs b/src/promql/src/extension_plan/series_repartition/tests.rs new file mode 100644 index 00000000000..3c1c6711919 --- /dev/null +++ b/src/promql/src/extension_plan/series_repartition/tests.rs @@ -0,0 +1,3451 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! What this node has to get right: where a chunk lands, that a chain crosses it in one piece, what +//! a stalled output does to the read, what an output learns when the child fails, and that one output +//! is the degenerate case rather than a special one. +//! +//! Some properties need an input that behaves in time rather than only in sequence, so they are tested +//! with children that hold: partitions that stay silent until the test opens a [`Switch`], which is +//! how the streams' ownership of the read is checked, by making the input produce nothing before the +//! plan is dropped. +//! +//! That a partition is read on a task of its own is not one of those properties, and is deliberately +//! not tested as one: it is a structural fact about the read, so it is observed structurally, by +//! recording the task that polls each partition (see [`Recording`]), rather than by requiring two +//! tasks to run on two threads at the same instant - which the test cannot require of the runtime. +//! +//! The child here is scripted rather than planned: each of its partitions answers a list of steps, +//! so a test says which series a chunk belongs to, where on the grid it sits and whether it closes +//! the series instead of relying on where a batch boundary happens to fall. The frames are packed and +//! unpacked by the same helpers the real path uses, so an assertion about an output stream is an +//! assertion about what a consumer of this node decodes. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::Waker; +use std::time::Duration; + +use datafusion::arrow::array::Float64Array; +use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool, UnboundedMemoryPool}; +use datafusion::execution::runtime_env::RuntimeEnvBuilder; +use datafusion::physical_plan::execution_plan::Boundedness; +use datafusion::prelude::SessionContext; +use datatypes::series::Label; +use datatypes::series::samples::{FieldSpec, Samples, SeriesFields}; +use datatypes::series::time::{EvalGrid, GridSpan, GridSpec, TimeAxis}; +use futures::TryStreamExt; + +use super::*; +use crate::extension_plan::test_util::prepare_test_data; +use crate::grid_series::render_label_set; + +/// The grid every frame of this module is addressed on: a value per second, sixteen of them. +const GRID_START: i64 = 0; +const GRID_STEP: i64 = 1_000; +const GRID_LEN: u64 = 16; + +fn grid() -> Arc { + Arc::new( + EvalGrid::try_new(GridSpec::try_new(GRID_START, GRID_STEP, GRID_LEN).unwrap()).unwrap(), + ) +} + +/// A frame schema of one field on [`grid`]. +fn schema() -> Arc { + Arc::new(SeriesSchema { + fields: Arc::from([FieldSpec { + name: Arc::from("value"), + }]), + eval_grid: Some(grid()), + }) +} + +/// Complete labels of the `cpu` metric on one host. +fn labels(host: &str) -> SeriesLabels { + SeriesLabels::try_new( + Some(Arc::from("cpu")), + vec![Label { + name: Arc::from("host"), + value: Arc::from(host), + }], + ) + .expect("the labels of these tests are legal") +} + +/// One evaluated chunk: `len` rows from grid position `start`, and whether it closes its series. +/// +/// A chunk of no rows is the closing chunk a series sends when nothing is left of it, which is a +/// shape of its own: it carries the finality and no position. +fn chunk(metric: SeriesLabels, start: usize, len: usize, is_last: bool) -> (Series, bool) { + let schema = schema(); + let spans = if len == 0 { + Vec::new() + } else { + vec![GridSpan::new(start, len)] + }; + let time = TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans) + .expect("one run on the grid"); + let values = (0..len) + .map(|index| Some((start + index) as f64)) + .collect::>(); + let fields = SeriesFields::one(Samples::from_float(Float64Array::from(values))); + ( + Series::try_new(&schema, metric, time, fields).expect("a chunk of this schema"), + is_last, + ) +} + +/// One step of a scripted child partition. +#[derive(Clone)] +enum Step { + /// A chunk and its finality. + Chunk(Series, bool), + /// The child fails here. + Error, + /// The child fails here with a message of its own, for a test that has to tell two failures apart. + ErrorSaying(&'static str), +} + +impl Step { + fn chunk((series, is_last): (Series, bool)) -> Self { + Self::Chunk(series, is_last) + } +} + +/// What one scripted step hands over. +fn step_answer(step: Step) -> Result<(Series, bool), BoxedError> { + match step { + Step::Chunk(series, is_last) => Ok((series, is_last)), + Step::Error => Err(boxed(DataFusionError::Execution( + "scripted child failure".to_string(), + ))), + Step::ErrorSaying(message) => Err(boxed(DataFusionError::Execution(message.to_string()))), + } +} + +/// The steps of one partition, as the frame stream that hands them over. +struct Script { + steps: std::vec::IntoIter, +} + +impl Stream for Script { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(self.steps.next().map(step_answer)) + } +} + +/// A child whose partitions answer scripted steps, each as one evaluated frame. +struct Scripted { + steps: Vec>, + series_schema: Arc, + properties: Arc, +} + +impl Scripted { + /// The child plan over `steps`, one partition per list. + fn plan(steps: Vec>) -> Arc { + let series_schema = schema(); + let frame = pack_evaluated_series( + Box::pin(futures::stream::empty()), + Arc::clone(&series_schema), + ) + .expect("an evaluated schema declares a frame") + .schema(); + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(frame), + Partitioning::UnknownPartitioning(steps.len()), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Arc::new(Self { + steps, + series_schema, + properties, + }) + } +} + +impl fmt::Debug for Scripted { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("Scripted") + .field("partitions", &self.steps.len()) + .finish() + } +} + +impl DisplayAs for Scripted { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!(f, "Scripted: partitions={}", self.steps.len()) + } +} + +impl ExecutionPlan for Scripted { + fn name(&self) -> &str { + "Scripted" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + Vec::new() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + assert!(children.is_empty(), "a scripted child has no children"); + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + let steps = self.steps.get(partition).cloned().ok_or_else(|| { + DataFusionError::Execution(format!("scripted child has no partition {partition}")) + })?; + pack_evaluated_series( + Box::pin(Script { + steps: steps.into_iter(), + }), + Arc::clone(&self.series_schema), + ) + } +} + +/// A task context whose memory pool is `pool`, so what the node charges can be read afterwards. +fn task_context(pool: &Arc) -> Arc { + let runtime = RuntimeEnvBuilder::new() + .with_memory_pool(Arc::clone(pool) as Arc) + .build() + .expect("the runtime environment builds"); + Arc::new(TaskContext::default().with_runtime(Arc::new(runtime))) +} + +/// The node over `child` routing into `outputs` partitions. +fn node(child: Arc, outputs: usize) -> Arc { + Arc::new(SeriesRepartitionExec::try_new(child, outputs).expect("the node is built")) +} + +/// Every output partition of `plan`, decoded, and the error it ended with if it ended with one. +/// +/// All partitions are read at once, which is what an executor does: this node suspends the producer +/// on an output that is not being drained, so reading one partition to its end before starting the +/// next would test the backpressure rather than the routing. +async fn drain( + plan: &Arc, + context: &Arc, +) -> Vec, BoxedError>> { + let mut streams = Vec::new(); + for partition in 0..plan.properties().partitioning.partition_count() { + let stream = plan + .execute(partition, Arc::clone(context)) + .expect("the output executes"); + streams.push( + unpack_evaluated_series(stream, None).expect("the output declares an evaluated frame"), + ); + } + futures::future::join_all( + streams + .into_iter() + .map(|stream| stream.try_collect::>()), + ) + .await +} + +/// The output partition of `plan` at `partition`, as the frame stream a consumer reads. +fn output( + plan: &Arc, + partition: usize, + context: &Arc, +) -> SendableEvaluatedSeriesStream { + unpack_evaluated_series( + plan.execute(partition, Arc::clone(context)) + .expect("the output executes"), + None, + ) + .expect("the output declares an evaluated frame") +} + +/// The output partition of `plan` at `partition`, for a test that keeps the node itself. +/// +/// [`execution`] reaches the read through the node rather than through the plan a consumer would hold, +/// so a test that has to look at the tasks behind an output claims it here instead of coercing the +/// node to the plan it is: the two are the same call, one on a reference the test already has. +fn output_of( + plan: &Arc, + partition: usize, + context: &Arc, +) -> SendableEvaluatedSeriesStream { + unpack_evaluated_series( + plan.execute(partition, Arc::clone(context)) + .expect("the output executes"), + None, + ) + .expect("the output declares an evaluated frame") +} + +/// The labels of a chunk in the form a failure message can show. +fn named(metric: &SeriesLabels) -> String { + render_label_set(&label_set(metric)) +} + +/// What one chunk says, in the terms a test compares: its canonical label set, where its rows start, +/// how many there are, and whether it closed its series. +fn summary((series, is_last): &(Series, bool)) -> (String, Option, usize, bool) { + ( + named(&series.metric), + series.time.first_position(), + series.time.len(), + *is_last, + ) +} + +/// The summaries of a whole output stream. +fn summaries(chunks: &[(Series, bool)]) -> Vec<(String, Option, usize, bool)> { + chunks.iter().map(summary).collect() +} + +/// The summaries of an output, in an order the input tasks do not decide. +/// +/// Every input is read by a task of its own, so which of two inputs delivers a chain first is not +/// fixed - and no test may depend on it. What a test still states is that each chain arrives whole and +/// in order ([`assert_chains_are_whole`]), and that the set of chunks is exactly the set it expects; +/// this is the comparison for a chunk list that came from more than one source. +fn unordered( + summaries: &[(String, Option, usize, bool)], +) -> Vec<(String, Option, usize, bool)> { + let mut sorted = summaries.to_vec(); + sorted.sort(); + sorted +} + +/// Asserts that every chain `chunks` hands over is whole, in the terms the frame validator reads a +/// chain in. +/// +/// A chunk that leaves a series open must be followed by the same series' next chunk, at a position +/// after the last one that chain carried. Another series' chunk in between is what a merge downstream +/// cannot repair, since it would have to hold two open series to read either; a position that does not +/// advance is a chunk the merge would have to reorder to read. Ending with a chain open fails too, +/// because that means the finality of a chunk was lost on the way, and a chunk of no rows fails unless +/// it is the closing chunk of the chain it belongs to - that being the shape a series ends in when +/// nothing of it is left. +/// +/// Identity here is the label set the frame carries and not its rendering: two label sets that print +/// the same are still two series to a merge - an empty label value is not printed - so comparing the +/// displayed labels would accept a stream that changed identity mid-chain. +fn assert_chains_are_whole(chunks: &[(Series, bool)]) { + // What the validator keeps of a chain it has not seen close: the identity it opened with, and the + // last position it carried. + let mut open: Option<(SeriesLabels, usize)> = None; + for (series, is_last) in chunks { + let (Some(first), Some(last)) = (series.time.first_position(), series.time.last_position()) + else { + // No position, so the chunk carries no rows: only a closing chunk is shaped that way, and + // it closes the chain it belongs to without advancing it. + assert!( + *is_last, + "{} carries no positions and does not close its series", + named(&series.metric) + ); + if let Some((open_labels, _)) = &open { + assert_eq!( + open_labels, &series.metric, + "another series' chunk interrupted an open chain" + ); + } + open = None; + continue; + }; + if let Some((open_labels, previous)) = &open { + assert_eq!( + open_labels, &series.metric, + "another series' chunk interrupted an open chain" + ); + assert!( + first > *previous, + "the positions of one chain did not advance across its chunks: {} starts at {first} \ + after the chain's previous chunk ended at {previous}", + named(&series.metric), + ); + } + open = (!*is_last).then(|| (series.metric.clone(), last)); + } + assert!(open.is_none(), "the output ended with a chain open"); +} + +/// A label set whose output is not `other`'s, found rather than assumed. +fn labels_elsewhere(routing: &Routing, other: &SeriesLabels) -> SeriesLabels { + let taken = routing.output(other); + for index in 0..64 { + let candidate = labels(&format!("elsewhere-{index}")); + if routing.output(&candidate) != taken { + return candidate; + } + } + panic!("no label set of these tests routes to another output"); +} + +/// A node with no outputs, or over a child that does not declare a series frame, is refused before +/// the plan can run. +#[test] +fn construction_rejects_a_zero_output_count_and_a_plain_child() { + let none = SeriesRepartitionExec::try_new(Scripted::plan(vec![Vec::new()]), 0) + .expect_err("a node has to have an output"); + assert!( + none.to_string().contains("at least one output partition"), + "{none}" + ); + + let plain: Arc = Arc::new(prepare_test_data()); + let refused = SeriesRepartitionExec::try_new(plain, 2) + .expect_err("a plain record batch stream carries no series labels"); + assert!( + refused.to_string().contains("is not a series frame"), + "{refused}" + ); +} + +/// T1: two partitions each hold a piece of one canonical label set, and both pieces reach the output +/// that label set hashes to; another label set reaches the output its own hash names. +#[tokio::test] +async fn pieces_of_one_label_set_meet_on_one_output() { + let routing = Routing::new(3); + let shared = labels("web-1"); + let other = labels_elsewhere(&routing, &shared); + assert_ne!( + routing.output(&shared), + routing.output(&other), + "the two label sets have to be able to land apart for this test to mean anything" + ); + // One label set split over the child's two partitions: the first piece opens and closes on its + // own, the second continues at a later position. Neither piece alone is the series. + let child = Scripted::plan(vec![ + vec![ + Step::chunk(chunk(shared.clone(), 0, 2, false)), + Step::chunk(chunk(shared.clone(), 0, 0, true)), + Step::chunk(chunk(other.clone(), 0, 1, true)), + ], + vec![Step::chunk(chunk(shared.clone(), 8, 2, true))], + ]); + let plan: Arc = node(child, 3); + assert_eq!(3, plan.properties().partitioning.partition_count()); + + let outputs = drain(&plan, &SessionContext::default().task_ctx()).await; + assert_eq!(3, outputs.len()); + let outputs = outputs + .into_iter() + .map(|chunks| { + let chunks = chunks.expect("every output decodes"); + assert_chains_are_whole(&chunks); + summaries(&chunks) + }) + .collect::>(); + + let piece = named(&shared); + let other_piece = named(&other); + let shared_output = routing.output(&shared); + assert_eq!( + unordered(&[ + (piece.clone(), Some(0), 2, false), + (piece.clone(), None, 0, true), + (piece.clone(), Some(8), 2, true), + ]), + unordered(&outputs[shared_output]), + "both pieces of one label set, and the closing chunk between them, land on one output" + ); + assert_eq!( + vec![(other_piece, Some(0), 1, true)], + outputs[routing.output(&other)], + "another label set lands where its own labels hash to" + ); + let empty = outputs + .iter() + .enumerate() + .filter(|(partition, chunks)| *partition != shared_output && chunks.is_empty()) + .map(|(partition, _)| partition) + .collect::>(); + assert_eq!( + 1, + empty.len(), + "the third output receives neither label set" + ); +} + +/// T2: two chains of one label set cross the node whole, in the order the read reached them, and a +/// closing chunk that carries no row survives the round trip. +#[tokio::test] +async fn chains_cross_the_node_whole_and_a_closing_chunk_survives() { + let routing = Routing::new(2); + let shared = labels("web-1"); + let other = labels_elsewhere(&routing, &shared); + // Both of these chains hash to the same output, so a node that routed chunk by chunk without + // reading one chain to its end would interleave them there - which is the failure this test is + // built to see. + let child = Scripted::plan(vec![ + vec![ + Step::chunk(chunk(shared.clone(), 0, 2, false)), + Step::chunk(chunk(shared.clone(), 2, 2, true)), + Step::chunk(chunk(other.clone(), 0, 1, true)), + ], + vec![ + Step::chunk(chunk(shared.clone(), 8, 2, false)), + Step::chunk(chunk(shared.clone(), 0, 0, true)), + ], + ]); + let plan: Arc = node(child, 2); + + let outputs = drain(&plan, &SessionContext::default().task_ctx()).await; + let shared_output = routing.output(&shared); + let chunks = outputs + .into_iter() + .nth(shared_output) + .expect("an output per partition") + .expect("the output decodes"); + assert_chains_are_whole(&chunks); + + let piece = named(&shared); + assert_eq!( + unordered(&[ + (piece.clone(), Some(0), 2, false), + (piece.clone(), Some(2), 2, true), + (piece.clone(), Some(8), 2, false), + // The closing chunk of the second chain carries no position of its own. + (piece, None, 0, true), + ]), + unordered(&summaries(&chunks)), + "both chains reach the one output whole, and the empty closing chunk is still a chunk" + ); +} + +/// T3, first half: an output nobody reads suspends the input task once its queue is full, and the +/// chains it already routed are neither lost nor delivered twice once that output is drained. +/// +/// What happens, explicitly: the input's task queues [`OUTPUT_CAPACITY`] chains to the stalled output +/// and then waits on that output's send. Every other output stops receiving from that input at that +/// point - one task reads this one input, and it does not run ahead of the slowest output - so an +/// input has head-of-line blocking behind its own chains, and no scheduler to route around it. What it +/// does not have is a share of that wait with another input: each one waits on its own. It is not a +/// deadlock: the task is suspended on a channel, the rest of the query continues, and draining the +/// stalled output lets the read go on. +#[tokio::test] +async fn a_stalled_output_suspends_the_producer_without_losing_chunks() { + let routing = Routing::new(2); + let shared = labels("web-1"); + let other = labels_elsewhere(&routing, &shared); + let stalled = routing.output(&shared); + let moving = routing.output(&other); + // More chains than one queue can hold, so the producer has to stop mid-read rather than finish. + let chains = OUTPUT_CAPACITY + 2; + let mut steps = (0..chains) + .map(|index| Step::chunk(chunk(shared.clone(), index, 1, true))) + .collect::>(); + steps.push(Step::chunk(chunk(other.clone(), 0, 1, true))); + let plan: Arc = node(Scripted::plan(vec![steps]), 2); + let context = SessionContext::default().task_ctx(); + + let mut moving_stream = output(&plan, moving, &context); + let stalled_stream = output(&plan, stalled, &context); + // The other output is read first, and the read is already blocked on the stalled one: nothing it + // would have been given can arrive, which is the head-of-line blocking this test states. + assert!( + tokio::time::timeout(Duration::from_millis(200), moving_stream.next()) + .await + .is_err(), + "the stalled output did not hold the producer back" + ); + + // Draining the stalled output lets the read finish, and it loses nothing on the way. + let stalled_chunks = tokio::time::timeout( + Duration::from_secs(10), + stalled_stream.try_collect::>(), + ) + .await + .expect("draining the stalled output releases the producer") + .expect("the stalled output decodes"); + assert_eq!(chains, stalled_chunks.len()); + assert_chains_are_whole(&stalled_chunks); + for (index, (series, is_last)) in stalled_chunks.iter().enumerate() { + assert_eq!(named(&shared), named(&series.metric)); + assert_eq!(Some(index), series.time.first_position(), "in read order"); + assert!(is_last, "every chain of this test closes"); + } + + let mut moving_chunks = Vec::new(); + while let Some(chunk) = tokio::time::timeout(Duration::from_secs(10), moving_stream.next()) + .await + .expect("the other output still receives what was routed to it") + { + moving_chunks.push(chunk.expect("the other output decodes")); + } + assert_eq!( + vec![(named(&other), Some(0), 1, true)], + summaries(&moving_chunks), + "the chunk queued behind the stalled output arrives once it is unstuck, exactly once" + ); +} + +/// T3, second half: what the producer queues is charged to the execution's pool, and dropping the +/// execution releases it. +#[tokio::test] +async fn dropping_the_execution_releases_what_the_producer_reserved() { + let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); + let context = task_context(&pool); + let shared = labels("web-1"); + let child = Scripted::plan(vec![vec![ + Step::chunk(chunk(shared.clone(), 0, 1, true)), + Step::chunk(chunk(shared.clone(), 1, 1, true)), + Step::chunk(chunk(shared.clone(), 2, 1, true)), + ]]); + let plan: Arc = node(child, 2); + let stream = plan + .execute(0, Arc::clone(&context)) + .expect("the first output starts the read"); + + // The producer reads ahead into the queue, and what it holds is charged to the pool. + let held = tokio::time::timeout(Duration::from_secs(10), async { + loop { + let reserved = pool.reserved(); + if reserved > 0 { + return reserved; + } + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .expect("the producer charges what it queues"); + assert!(held >= 3 * std::mem::size_of::(), "{held}"); + + drop(stream); + drop(plan); + tokio::time::timeout(Duration::from_secs(10), async { + while pool.reserved() != 0 { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap_or_else(|_| { + panic!( + "the dropped execution still holds {} bytes", + pool.reserved() + ) + }); +} + +/// T5: one output is the same node, not a special case - every chunk arrives, in one chain after +/// another, with nothing filtered out. +#[tokio::test] +async fn one_output_keeps_every_chunk_and_its_chains_whole() { + let shared = labels("web-1"); + let other = labels("elsewhere-1"); + let child = Scripted::plan(vec![ + vec![ + Step::chunk(chunk(shared.clone(), 0, 2, false)), + Step::chunk(chunk(shared.clone(), 2, 2, true)), + Step::chunk(chunk(other.clone(), 0, 1, false)), + Step::chunk(chunk(other.clone(), 0, 0, true)), + ], + vec![Step::chunk(chunk(shared.clone(), 8, 2, true))], + ]); + let plan: Arc = node(child, 1); + assert_eq!(1, plan.properties().partitioning.partition_count()); + + let outputs = drain(&plan, &SessionContext::default().task_ctx()).await; + assert_eq!(1, outputs.len()); + let chunks = outputs + .into_iter() + .next() + .expect("one output") + .expect("the output decodes"); + assert_chains_are_whole(&chunks); + // The read rotates at every chain boundary, not at every input end: the first chain closes on + // partition 0, so the next chain read is partition 1's, and partition 0's remaining chain comes + // after it. Both label sets still reach the one output, whole. + assert_eq!( + unordered(&[ + (named(&shared), Some(0), 2, false), + (named(&shared), Some(2), 2, true), + (named(&shared), Some(8), 2, true), + (named(&other), Some(0), 1, false), + (named(&other), None, 0, true), + ]), + unordered(&summaries(&chunks)), + "every chunk of both label sets arrives, each chain in one piece" + ); +} + +/// A switch a test opens to let gated input streams produce. +/// +/// Opening it wakes the streams already parked, and a stream polled after the opening sees it +/// straight away: registering before the second read is what makes an opening that lands between the +/// two impossible to lose. +#[derive(Default)] +struct Switch { + open: AtomicBool, + wakers: Mutex>, +} + +impl Switch { + /// Lets every stream waiting on this switch produce, and wakes the ones already parked. + fn open(&self) { + self.open.store(true, Ordering::Release); + let wakers = std::mem::take(&mut *self.wakers.lock().unwrap()); + for waker in wakers { + waker.wake(); + } + } + + fn is_open(&self) -> bool { + self.open.load(Ordering::Acquire) + } + + /// Parks `cx` until the switch is opened, unless it already is. + fn wait(&self, cx: &Context<'_>) { + if self.is_open() { + return; + } + self.wakers.lock().unwrap().push(cx.waker().clone()); + if self.is_open() { + // The opening landed between the two reads, so its wake did not find this waker. + cx.waker().wake_by_ref(); + } + } +} + +/// One partition of a [`Gated`] child: what it hands over at once, and what it holds back. +#[derive(Clone, Default)] +struct GatedPartition { + before: Vec, + after: Vec, +} + +impl GatedPartition { + /// A partition that hands over `steps` only once the switch is opened. + fn held(steps: Vec) -> Self { + Self { + before: Vec::new(), + after: steps, + } + } + + /// A partition that hands over `steps` as soon as it is polled. + fn open(steps: Vec) -> Self { + Self { + before: steps, + after: Vec::new(), + } + } +} + +/// A child whose partitions hold their second half back until `switch` is opened. +/// +/// The gate is how a test states that the read starts only after the plan is gone: the input is a +/// real source that has not produced yet, not one that has already answered before the interesting +/// moment. `dropped` counts the streams a consumer let go of, which is how a test sees the read +/// cancelling the child it was reading. +struct Gated { + partitions: Vec, + switch: Arc, + dropped: Arc, + series_schema: Arc, + properties: Arc, +} + +impl Gated { + /// The child over `partitions`, gated on `switch` and counting drops in `dropped`. + fn plan( + partitions: Vec, + switch: Arc, + dropped: Arc, + ) -> Arc { + let series_schema = schema(); + let frame = pack_evaluated_series( + Box::pin(futures::stream::empty()), + Arc::clone(&series_schema), + ) + .expect("an evaluated schema declares a frame") + .schema(); + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(frame), + Partitioning::UnknownPartitioning(partitions.len()), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Arc::new(Self { + partitions, + switch, + dropped, + series_schema, + properties, + }) + } +} + +impl fmt::Debug for Gated { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("Gated") + .field("partitions", &self.partitions.len()) + .finish() + } +} + +impl DisplayAs for Gated { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!(f, "Gated: partitions={}", self.partitions.len()) + } +} + +impl ExecutionPlan for Gated { + fn name(&self) -> &str { + "Gated" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + Vec::new() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + assert!(children.is_empty(), "a gated child has no children"); + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + let steps = self.partitions.get(partition).cloned().ok_or_else(|| { + DataFusionError::Execution(format!("gated child has no partition {partition}")) + })?; + pack_evaluated_series( + Box::pin(GatedScript { + before: steps.before.into_iter(), + after: steps.after.into_iter(), + switch: Arc::clone(&self.switch), + dropped: Arc::clone(&self.dropped), + }), + Arc::clone(&self.series_schema), + ) + } +} + +/// One partition of a [`Gated`] child. +struct GatedScript { + before: std::vec::IntoIter, + after: std::vec::IntoIter, + switch: Arc, + dropped: Arc, +} + +impl Stream for GatedScript { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + if let Some(step) = this.before.next() { + return Poll::Ready(Some(step_answer(step))); + } + // Nothing of the second half is handed over before the test opens the switch, so the read + // can be started and then left waiting on a source that has not produced anything yet. + this.switch.wait(cx); + if !this.switch.is_open() { + return Poll::Pending; + } + Poll::Ready(this.after.next().map(step_answer)) + } +} + +impl Drop for GatedScript { + fn drop(&mut self) { + self.dropped.fetch_add(1, Ordering::SeqCst); + } +} + +/// The tokio task that first polled each partition of a [`Recording`] child. +type ReadTasks = Arc>>>; + +/// A child whose partitions answer scripted steps, recording the task that first polls each one. +/// +/// A partition count says how many parts a plan declares, not how many tasks compute them: one task +/// polling every partition in turn declares the same number. What is recorded here is the task +/// itself, read from [`tokio::task::try_id`] inside the poll - which is where a child partition is +/// really read, and hence what the partition count actually bought. +struct Recording { + steps: Vec>, + polled: ReadTasks, + series_schema: Arc, + properties: Arc, +} + +impl Recording { + /// The child over `steps`, one partition per list, and the record of which task polled each. + fn plan(steps: Vec>) -> (Arc, ReadTasks) { + let polled: ReadTasks = Arc::new(Mutex::new(vec![None; steps.len()])); + let series_schema = schema(); + let frame = pack_evaluated_series( + Box::pin(futures::stream::empty()), + Arc::clone(&series_schema), + ) + .expect("an evaluated schema declares a frame") + .schema(); + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(frame), + Partitioning::UnknownPartitioning(steps.len()), + EmissionType::Incremental, + Boundedness::Bounded, + )); + let child = Arc::new(Self { + steps, + polled: Arc::clone(&polled), + series_schema, + properties, + }); + (child, polled) + } +} + +impl fmt::Debug for Recording { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("Recording") + .field("partitions", &self.steps.len()) + .finish() + } +} + +impl DisplayAs for Recording { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!(f, "Recording: partitions={}", self.steps.len()) + } +} + +impl ExecutionPlan for Recording { + fn name(&self) -> &str { + "Recording" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + Vec::new() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + assert!(children.is_empty(), "a recording child has no children"); + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + let steps = self.steps.get(partition).cloned().ok_or_else(|| { + DataFusionError::Execution(format!("recording child has no partition {partition}")) + })?; + pack_evaluated_series( + Box::pin(RecordingScript { + partition, + steps: steps.into_iter(), + polled: Arc::clone(&self.polled), + recorded: false, + }), + Arc::clone(&self.series_schema), + ) + } +} + +/// One partition of a [`Recording`] child. +struct RecordingScript { + partition: usize, + steps: std::vec::IntoIter, + polled: ReadTasks, + /// Whether this partition's first poll has been recorded. + recorded: bool, +} + +impl Stream for RecordingScript { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + // Recorded on the first poll rather than in `execute`: `execute` may run on the consumer's + // task while the reading is what another task does. + if !this.recorded { + this.recorded = true; + let mut polled = this + .polled + .lock() + .unwrap_or_else(|error| error.into_inner()); + polled[this.partition] = tokio::task::try_id(); + } + Poll::Ready(this.steps.next().map(step_answer)) + } +} + +/// Waits until `done` holds, so a test states a condition rather than a duration. +async fn wait_until(what: &str, done: impl Fn() -> bool) { + tokio::time::timeout(Duration::from_secs(10), async { + while !done() { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("timed out waiting until {what}")); +} + +/// The read a node started, for a test that has to look at the task behind the outputs. +fn execution(plan: &Arc) -> Arc { + let state = plan.shared.lock().unwrap(); + Arc::clone(state.as_ref().expect("the read was started by execute")) +} + +/// Whether every input task of the read has stopped. +/// +/// There is one task per input partition and no single producer, so "the read stopped" is what has to +/// be read off the tasks themselves: none of them is still running. +fn producer_stopped(execution: &SharedExecution) -> bool { + execution.running.lock().unwrap().inputs.live() == 0 +} + +/// The error `stream` reports after the batches it delivers before it, or `None` if it ends. +async fn terminal_error(stream: &mut SendableRecordBatchStream) -> Option { + loop { + match std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await { + None => return None, + Some(Ok(_)) => {} + Some(Err(error)) => return Some(error), + } + } +} + +/// Everything `stream` hands over until it ends: the chunks it delivered and the errors it reported. +/// +/// Reading past the first error is what a test of the failure path needs. An error item is terminal, +/// so a stream that reports one and then answers again is what these tests are looking for - and so +/// is one that ends without ever reporting one, which is the clean end a failed read must not produce. +/// It also assumes the stream does end: a failure that leaves an output waiting for a chunk that will +/// never come is a hang, and the caller's timeout is what turns that into a failure. +async fn until_end( + stream: &mut SendableEvaluatedSeriesStream, +) -> (Vec<(Series, bool)>, Vec) { + let mut chunks = Vec::new(); + let mut errors = Vec::new(); + loop { + match std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await { + None => return (chunks, errors), + Some(Ok(chunk)) => chunks.push(chunk), + Some(Err(error)) => errors.push(error.to_string()), + } + } +} + +/// T-A1: the read drives each input partition on a task of its own. +/// +/// The child records the task that first polls each of its partitions, and what is asserted is that +/// the two partitions were polled by two distinct tasks, neither of them the consumer's. That is the +/// property `Forwarders::start` provides - one task per child partition - and it is what a partition +/// count on its own cannot say: one task polling every partition in turn declares the same count. +/// +/// Two distinct tasks is deliberately not a claim about simultaneous wall-clock execution: the two +/// tasks may share a worker thread and be polled one after the other, and the read is correct either +/// way. Nor does the assertion need two threads to be free at the same instant, which is what ties it +/// to the scheduling of the runtime the read runs on rather than to the read. What a read that drove +/// the partitions from one task would record instead is one id for both, or the consumer's own. +#[tokio::test] +async fn every_input_partition_is_read_on_a_task_of_its_own() { + let shared = labels("web-1"); + let (child, polled) = Recording::plan(vec![ + vec![Step::chunk(chunk(shared.clone(), 0, 1, true))], + vec![Step::chunk(chunk(shared.clone(), 4, 1, true))], + ]); + let plan: Arc = node(child, 1); + // Taken before anything is read: the task that asks for an output is the one a partition must + // not be read on. + let consumer = tokio::task::try_id(); + let outputs = tokio::time::timeout( + Duration::from_secs(10), + drain(&plan, &SessionContext::default().task_ctx()), + ) + .await + .expect("both partitions of the child answer, so the output ends"); + + let recorded = polled + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + assert_eq!( + 2, + recorded.len(), + "the child holds one partition per scripted list" + ); + let tasks = recorded + .iter() + .map(|task| task.unwrap_or_else(|| panic!("a child partition was never polled"))) + .collect::>(); + assert_ne!( + tasks[0], tasks[1], + "the two partitions were polled by two different tasks, so neither was read on the task \ + that read the other: {tasks:?}" + ); + assert!( + tasks.iter().all(|task| Some(*task) != consumer), + "neither partition ran on the consumer's task, so the read stayed on the tasks the node \ + started for the child: {tasks:?} against {consumer:?}" + ); + + let mut chunks = outputs + .into_iter() + .next() + .expect("one output") + .expect("the output decodes"); + chunks.sort_by_key(|(series, _)| series.time.first_position()); + assert_eq!( + vec![ + (named(&shared), Some(0), 1, true), + (named(&shared), Some(4), 1, true), + ], + summaries(&chunks), + "both partitions' chunks arrive, each from the task that read it" + ); +} + +/// T-B1: the streams own the read, so dropping the plan does not truncate them. +/// +/// The input produces nothing at all until the switch is opened, and the switch is opened only after +/// every plan reference is gone. Before that, an output is polled once and delivers nothing, which is +/// what makes the read that follows a read of a plan that no longer exists: if dropping the plan had +/// aborted the producer, the outputs would end here - the answer would be missing every chunk rather +/// than late. +#[tokio::test] +async fn dropping_the_plan_leaves_the_read_to_its_streams() { + let routing = Routing::new(2); + let shared = labels("web-1"); + let other = labels_elsewhere(&routing, &shared); + let switch = Arc::new(Switch::default()); + let dropped = Arc::new(AtomicUsize::new(0)); + let child = Gated::plan( + vec![ + GatedPartition::held(vec![ + Step::chunk(chunk(shared.clone(), 0, 2, false)), + Step::chunk(chunk(shared.clone(), 2, 1, true)), + ]), + GatedPartition::held(vec![Step::chunk(chunk(other.clone(), 0, 1, true))]), + ], + Arc::clone(&switch), + Arc::clone(&dropped), + ); + let plan: Arc = node(child, 2); + let context = SessionContext::default().task_ctx(); + let mut streams = (0..2) + .map(|partition| output(&plan, partition, &context)) + .collect::>(); + // Every plan reference goes away here: DataFusion's `execute_stream_partitioned` hands out the + // streams and drops the plan, and this node has to keep reading for them. + drop(plan); + + assert!( + tokio::time::timeout(Duration::from_millis(200), streams[0].next()) + .await + .is_err(), + "the gated input produced before the plan was dropped, so this test proves nothing" + ); + switch.open(); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + futures::future::join_all( + streams + .into_iter() + .map(|stream| stream.try_collect::>()), + ), + ) + .await + .expect("the read outlives the plan it was executed from") + .into_iter() + .map(|output| output.expect("every output decodes")) + .collect::>(); + for chunks in &outputs { + assert_chains_are_whole(chunks); + } + + let piece = named(&shared); + assert_eq!( + vec![ + (piece.clone(), Some(0), 2, false), + (piece, Some(2), 1, true), + ], + summaries(&outputs[routing.output(&shared)]), + "both chunks of the chain that was held back arrive, in order" + ); + assert_eq!( + vec![(named(&other), Some(0), 1, true)], + summaries(&outputs[routing.output(&other)]), + "the other partition's chunk arrives too" + ); +} + +/// T-B2: when every output is dropped the read stops, even though the plan is still alive. +/// +/// The plan is kept for the whole test, as a metrics collector holding a plan would keep it: what +/// stops the read is the outputs going away, not the plan being freed. Asserted are the three things +/// that has to release - the reading task, the child it was reading, and the memory the read +/// reserved. +#[tokio::test] +async fn dropping_every_output_stops_the_read_and_releases_it() { + let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); + let context = task_context(&pool); + let switch = Arc::new(Switch::default()); + let dropped = Arc::new(AtomicUsize::new(0)); + let shared = labels("web-1"); + // More closed chains than the two outputs can queue, so the read cannot finish on its own. + let steps = (0..OUTPUT_CAPACITY * 3) + .map(|index| Step::chunk(chunk(shared.clone(), index, 1, true))) + .collect::>(); + let child = Gated::plan( + vec![ + GatedPartition::open(steps.clone()), + GatedPartition::open(steps), + ], + Arc::clone(&switch), + Arc::clone(&dropped), + ); + let plan = node(child, 2); + let streams = (0..2) + .map(|partition| { + unpack_evaluated_series( + plan.execute(partition, Arc::clone(&context)) + .expect("the output executes"), + None, + ) + .expect("the output declares an evaluated frame") + }) + .collect::>(); + let execution = execution(&plan); + wait_until("the read reserved what it queued", || pool.reserved() > 0).await; + + drop(streams); + + wait_until("the read's reservation is released", || { + pool.reserved() == 0 + }) + .await; + wait_until("the child's streams are dropped", || { + dropped.load(Ordering::SeqCst) == 2 + }) + .await; + wait_until("the reading task stops", || producer_stopped(&execution)).await; + assert!( + plan.shared.lock().unwrap().is_some(), + "the plan is still alive, so it is the outputs that stopped the read" + ); +} + +/// T-B3: a child failure is a terminal item on every output, and the end comes after it. +/// +/// The second half matters as much as the first: an output that reports the failure and then answers +/// again would be a stream whose error was not terminal, and one that answers with a chunk before the +/// error is already covered by the contents. What must never happen is a clean end in place of the +/// failure, so the error is required on every output. +#[tokio::test] +async fn a_child_failure_is_terminal_on_every_output() { + let shared = labels("web-1"); + let child = Scripted::plan(vec![ + vec![Step::chunk(chunk(shared.clone(), 0, 2, false)), Step::Error], + vec![Step::chunk(chunk(shared.clone(), 8, 1, true)), Step::Error], + ]); + let plan: Arc = node(child, 3); + let context = SessionContext::default().task_ctx(); + let mut streams = (0..3) + .map(|partition| { + plan.execute(partition, Arc::clone(&context)) + .expect("the output executes") + }) + .collect::>(); + + for (partition, stream) in streams.iter_mut().enumerate() { + let error = tokio::time::timeout(Duration::from_secs(10), terminal_error(stream)) + .await + .unwrap_or_else(|_| panic!("output partition {partition} never ended")) + .unwrap_or_else(|| { + panic!("output partition {partition} reported a clean end, not the failure") + }); + assert!( + error.to_string().contains("scripted child failure"), + "output partition {partition} ended with {error}" + ); + let after = std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await; + assert!( + after.is_none(), + "output partition {partition} answered again after its terminal error" + ); + } +} + +/// T-B4: a read that stops without finishing is not reported as the end of the answer. +/// +/// The read is aborted through the tasks it runs on, which are reachable from this module because the +/// tests are a child of the module that defines it - so this needs no hook in the production code, and +/// the stop is the one the read stops itself with. The child hands over one chunk and then waits on a +/// switch nothing opens, so the read cannot have finished and recorded an outcome when it is aborted: +/// what an output sees after that is a queue closing on a read with no recorded ending, which must be +/// reported as the read stopping unexpectedly rather than as the end of the series. +#[tokio::test] +async fn an_aborted_producer_is_not_reported_as_a_clean_end() { + let switch = Arc::new(Switch::default()); + let dropped = Arc::new(AtomicUsize::new(0)); + let shared = labels("web-1"); + let child = Gated::plan( + vec![GatedPartition { + before: vec![Step::chunk(chunk(shared.clone(), 0, 1, true))], + after: vec![Step::chunk(chunk(shared.clone(), 1, 1, true))], + }], + switch, + Arc::clone(&dropped), + ); + let plan = node(child, 1); + let context = SessionContext::default().task_ctx(); + let mut stream = unpack_evaluated_series( + plan.execute(0, Arc::clone(&context)) + .expect("the output executes"), + None, + ) + .expect("the output declares an evaluated frame"); + + let first = tokio::time::timeout(Duration::from_secs(10), stream.next()) + .await + .expect("the read starts") + .expect("a chunk arrives") + .expect("the chunk decodes"); + assert_eq!( + (named(&shared), Some(0), 1, true), + summary(&first), + "the chunk the child handed over before the gate" + ); + + let execution = execution(&plan); + // Aborted directly, while its outputs are still being read: what an output does after that is + // the whole point of this test. This aborts every input task and records nothing, which is what a + // read stopped from outside looks like. + execution.running.lock().unwrap().inputs.stop(); + + let tail = tokio::time::timeout(Duration::from_secs(10), stream.try_collect::>()) + .await + .expect("an aborted read still ends the outputs it left behind"); + let error = tail.expect_err( + "the aborted read reported a clean end, so the chunks it never routed look like chunks that \ + do not exist", + ); + assert!( + error.to_string().contains("producer stopped unexpectedly"), + "the output ended with {error}" + ); + // The read recorded no outcome at all, and no terminal error either: the error above is the + // "stopped unexpectedly" one this output builds, not a failure the read had recorded. + let (ending, terminal) = execution.ending(); + assert_eq!( + Ending::Unrecorded, + ending, + "an aborted read records no outcome" + ); + assert!( + terminal.is_none(), + "an aborted read records no terminal error for its outputs to report" + ); +} + +/// T-C1: an output that ends takes nothing else down with it when another output was never executed. +/// +/// This is DataFusion's ordinary order rather than an unusual one: `CoalescePartitionsExec` executes +/// and consumes one partition per task, and nothing makes every stream exist before the first one is +/// read. The input here is empty, so the read finishes while partition 0 alone is handed out, and +/// reading that partition to its end releases its lease - which is exactly the moment the read must +/// not be taken as over: partition 1 has not been asked for yet, and its queue is what a later +/// `execute` comes for. A read that stopped there would answer `execute(1)` with "executed twice" for +/// a partition that was never executed. +#[tokio::test] +async fn an_output_that_ends_does_not_close_the_queue_of_an_unclaimed_output() { + let plan: Arc = node(Scripted::plan(vec![Vec::new()]), 2); + let context = SessionContext::default().task_ctx(); + + let first = output(&plan, 0, &context); + let first_chunks = tokio::time::timeout(Duration::from_secs(10), first.try_collect::>()) + .await + .expect("an empty input still ends the first output") + .expect("the first output ends without a failure"); + assert!( + first_chunks.is_empty(), + "an empty input routed nothing, so the first output has nothing to hand over" + ); + + let second = unpack_evaluated_series( + plan.execute(1, Arc::clone(&context)) + .unwrap_or_else(|error| panic!("the second output is still claimable: {error}")), + None, + ) + .expect("the second output declares an evaluated frame"); + let second_chunks = + tokio::time::timeout(Duration::from_secs(10), second.try_collect::>()) + .await + .expect("the second output is executed after the first one ended") + .expect("the second output ends without a failure"); + assert!( + second_chunks.is_empty(), + "an empty input routed nothing, so the second output has nothing to hand over" + ); +} + +/// T-C2: the output claimed last still receives its whole share after a claimed sibling ended. +/// +/// Both outputs' shares fit one queue, so the read ends on its own instead of suspending on anything: +/// what is asserted is what a late claim gets, not the backpressure. Partition 0 is read to its end +/// before partition 1 is even executed, which releases partition 0's lease; a read that treated that +/// as the end would drop partition 1's queue and the chunks queued there - the answer would be +/// truncated rather than late, and nothing on partition 1 would arrive at all. +#[tokio::test] +async fn an_unclaimed_output_delivers_its_whole_share_after_a_sibling_ended() { + let routing = Routing::new(2); + let shared = labels("web-1"); + let other = labels_elsewhere(&routing, &shared); + let ended_first = routing.output(&shared); + let claimed_later = routing.output(&other); + assert_ne!( + ended_first, claimed_later, + "the two label sets have to land apart for this test to mean anything" + ); + // One chain per label set, in a row, both of them closed: what reaches each output is a run of + // complete chains, so nothing here depends on how the read interleaves two open ones. + let chains = OUTPUT_CAPACITY - 1; + let steps = (0..chains) + .map(|index| Step::chunk(chunk(shared.clone(), index, 1, true))) + .chain((0..chains).map(|index| Step::chunk(chunk(other.clone(), index, 1, true)))) + .collect::>(); + let plan: Arc = node(Scripted::plan(vec![steps]), 2); + let context = SessionContext::default().task_ctx(); + + let first = output(&plan, ended_first, &context); + let first_chunks = tokio::time::timeout(Duration::from_secs(10), first.try_collect::>()) + .await + .expect("the first output reaches its end before the other is executed") + .expect("the first output ends without a failure"); + assert_eq!( + (0..chains) + .map(|index| (named(&shared), Some(index), 1, true)) + .collect::>(), + summaries(&first_chunks), + "the output executed first hands over every chain of its label set" + ); + + let second = unpack_evaluated_series( + plan.execute(claimed_later, Arc::clone(&context)) + .unwrap_or_else(|error| panic!("the other output is still claimable: {error}")), + None, + ) + .expect("the other output declares an evaluated frame"); + let second_chunks = + tokio::time::timeout(Duration::from_secs(10), second.try_collect::>()) + .await + .expect("the output executed last reaches its end") + .expect("the output executed last ends without a failure"); + assert_eq!( + (0..chains) + .map(|index| (named(&other), Some(index), 1, true)) + .collect::>(), + summaries(&second_chunks), + "the output executed last still receives every chain of its label set, in order" + ); +} + +/// T-C3: an output nobody claimed keeps the read running, not merely claimable. +/// +/// More chains than one queue holds are routed to the output nobody has asked for, so the read cannot +/// finish: it is parked on that output's queue. The claimed output delivered everything routed to it +/// and is then dropped, which gives up every lease the read has - and that must not be taken for +/// "nothing can take a chunk any more", because the output that has never been claimed is exactly the +/// one that will. A read that stopped here would abort a producer that is correctly waiting, and the +/// chunks it holds would be lost; the last part of the test is that it is not merely alive but that +/// every chunk it queued arrives once the output is claimed. +#[tokio::test] +async fn an_unclaimed_output_keeps_the_producer_of_a_claimed_one_running() { + let routing = Routing::new(2); + let shared = labels("web-1"); + let other = labels_elsewhere(&routing, &shared); + let read_first = routing.output(&shared); + let claimed_later = routing.output(&other); + assert_ne!( + read_first, claimed_later, + "the two label sets have to land apart for this test to mean anything" + ); + let chains = OUTPUT_CAPACITY + 2; + let steps = std::iter::once(Step::chunk(chunk(shared.clone(), 0, 1, true))) + .chain((0..chains).map(|index| Step::chunk(chunk(other.clone(), index, 1, true)))) + .collect::>(); + let plan = node(Scripted::plan(vec![steps]), 2); + let context = SessionContext::default().task_ctx(); + let mut first = unpack_evaluated_series( + plan.execute(read_first, Arc::clone(&context)) + .expect("the output that is read first executes"), + None, + ) + .expect("the output declares an evaluated frame"); + let execution = execution(&plan); + + let chunk_read = tokio::time::timeout(Duration::from_secs(10), first.next()) + .await + .expect("the first chunk of the read arrives") + .expect("the output hands over a chunk") + .expect("the chunk decodes"); + assert_eq!( + (named(&shared), Some(0), 1, true), + summary(&chunk_read), + "the chain routed to the output that is read first" + ); + assert!( + !producer_stopped(&execution), + "the read finished although nothing could have delivered the chains it never routed" + ); + + // Everything routed to this output was handed over, so the output is done being read - and the + // only output that was ever claimed is gone with it. + drop(first); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!( + !producer_stopped(&execution), + "the producer was aborted although one of its outputs had never been claimed: the chunks \ + queued for that output are what a later execute still comes for" + ); + + // And the read was not merely alive: claiming the output nobody had asked for gets all of it. + let second = unpack_evaluated_series( + plan.execute(claimed_later, Arc::clone(&context)) + .unwrap_or_else(|error| panic!("the unclaimed output is claimable: {error}")), + None, + ) + .expect("the unclaimed output declares an evaluated frame"); + let second_chunks = + tokio::time::timeout(Duration::from_secs(10), second.try_collect::>()) + .await + .expect("claiming the output unblocks the read it was parked on") + .expect("the output executed last ends without a failure"); + assert_eq!( + (0..chains) + .map(|index| (named(&other), Some(index), 1, true)) + .collect::>(), + summaries(&second_chunks), + "every chain the parked read had queued arrives once the output is claimed" + ); + wait_until("the read that was parked finishes", || { + producer_stopped(&execution) + }) + .await; +} + +/// A task context whose memory pool never refuses a reservation. +/// +/// The composition below reads further ahead than a bounded pool would allow, and a read that failed +/// on memory would end with an error instead of showing whether it finishes at all - which is the one +/// thing this test is about. +fn unbounded_context() -> Arc { + let runtime = RuntimeEnvBuilder::new() + .with_memory_pool(Arc::new(UnboundedMemoryPool::default()) as Arc) + .build() + .expect("the runtime environment builds"); + Arc::new(TaskContext::default().with_runtime(Arc::new(runtime))) +} + +/// `count` label sets of distinct series that a two-output node routes to `output`. +/// +/// Found with the node's own [`Routing`] over candidate labels rather than assumed: which output a +/// label set belongs on is a hash of it, and a label set hard-coded from watching one run would stop +/// being a label set of `output` the moment the key or the seed changed, leaving the test about +/// something else. Reading it off the same function the node reduces with is what keeps the premise +/// - every chunk lands on `output` - true by construction. +fn labels_routed_to(output: usize, count: usize) -> Vec { + let routing = Routing::new(2); + let found = (0..) + .filter_map(|index| { + let candidate = labels(&format!("many-{index}")); + (routing.output(&candidate) == output).then_some(candidate) + }) + .take(count) + .collect::>(); + assert_eq!( + count, + found.len(), + "two outputs split the candidates between them, so {count} of each are found" + ); + found +} + +/// T-D1: two of these nodes composed do not deadlock while every output of the outer one is drained. +/// +/// The child produces `SERIES` single-point chains, each with a label set of its own, every one of +/// them hashing to output 1 of a two-output node - so the inner node's output 0 is empty and output 1 +/// carries all of them. Composed as `outer(inner(child))`, the outer node's input 0 is the inner +/// node's empty output, and what the read does with that is what this test states. +/// +/// The volume is chosen against the buffers in the path, not at random. Each output holds +/// [`OUTPUT_CAPACITY`] chains and each input task holds the one chain it is assembling, so the whole +/// composition absorbs a handful of chunks: measured against the router this test was written for, +/// ten was what that path took and eleven already stopped. `SERIES` is two orders of magnitude above +/// that, so no amount of buffering makes this test pass by swallowing the child whole, and a read that +/// is merely slow is not what a failure here would be. +/// +/// Both outputs of the outer node are read at once and each is drained to its end, so nothing here +/// can be blamed on an output nobody drained - which is the one requirement this node states of its +/// caller. The count that comes out is asserted against the count that went in, so a passing run is a +/// run that lost nothing. +/// +/// What it caught is why the router is per input now: with one task routing every input, the outer +/// read parked on its input 0 - the inner node's empty output, which does not close until the inner +/// read finishes - so it routed nothing at all and both outputs stayed empty, while the inner read +/// filled the outer node's input 1 after about ten chunks and parked on its output 1. Measured: 0 of +/// 4096 series delivered, both outputs empty, timeout at 10 s. Giving the outer node's input 0 a +/// single series of its own changed nothing, which is what says the wait was the problem rather than +/// the volume; giving output 0 thousands of series of its own instead finished the same composition in +/// under a second. With one task per input there is no such wait: the outer node's task 0 is parked on +/// the inner node's empty output by itself, and its task 1 keeps routing everything the inner node +/// sends on output 1, which is what lets the inner node finish and close output 0. +#[tokio::test] +async fn composing_two_nodes_does_not_deadlock_when_the_inner_output_is_empty() { + const SERIES: usize = 4096; + let routed = labels_routed_to(1, SERIES); + let source = || { + Scripted::plan(vec![ + routed + .iter() + .map(|metric| Step::chunk(chunk(metric.clone(), 0, 1, true))) + .collect::>(), + ]) + }; + let context = unbounded_context(); + + // The same child over one node finishes, and finishes with everything on output 1: what stalls + // below is the composition, not the child and not the volume. + let alone: Arc = node(source(), 2); + let alone_outputs = tokio::time::timeout(Duration::from_secs(10), drain(&alone, &context)) + .await + .expect("one node over this child finishes"); + assert!( + alone_outputs[0] + .as_ref() + .expect("the first output decodes") + .is_empty(), + "every label set of this test hashes to output 1, so output 0 has nothing to carry" + ); + assert_eq!( + SERIES, + alone_outputs[1] + .as_ref() + .expect("the second output decodes") + .len(), + "one node delivers every series it was given" + ); + + let inner: Arc = node(source(), 2); + let plan: Arc = node(inner, 2); + + // Both outputs at once, each to its end, and each chunk counted where it arrives: the count is + // what a failure has to say when the read never gets to the assertion below. + let delivered = Arc::new([AtomicUsize::new(0), AtomicUsize::new(0)]); + let reads = (0..2) + .map(|partition| { + let plan = Arc::clone(&plan); + let context = Arc::clone(&context); + let delivered = Arc::clone(&delivered); + async move { + let mut stream = output(&plan, partition, &context); + let mut chunks = Vec::new(); + while let Some(chunk) = stream.try_next().await? { + delivered[partition].fetch_add(1, Ordering::Relaxed); + chunks.push(chunk); + } + Ok::<_, BoxedError>(chunks) + } + }) + .collect::>(); + let outputs = tokio::time::timeout(Duration::from_secs(10), futures::future::join_all(reads)) + .await + .unwrap_or_else(|_| { + panic!( + "two composed nodes never finished although both outputs of the outer one were \ + drained: {} of {SERIES} series arrived on output 0 and {} on output 1", + delivered[0].load(Ordering::Relaxed), + delivered[1].load(Ordering::Relaxed), + ) + }) + .into_iter() + .map(|chunks| chunks.expect("both outputs decode")) + .collect::>(); + + assert!( + outputs[0].is_empty(), + "the same label sets hash to output 1 of the outer node as of the inner one" + ); + for chunks in &outputs { + assert_chains_are_whole(chunks); + } + let mut names = outputs + .iter() + .flatten() + .map(|(series, is_last)| { + assert!(*is_last, "every chain of this test closes on its own"); + named(&series.metric) + }) + .collect::>(); + names.sort(); + names.dedup(); + assert_eq!( + SERIES, + names.len(), + "every series that went in comes out exactly once, none twice and none truncated" + ); + assert_eq!( + SERIES, + outputs.iter().map(Vec::len).sum::(), + "the composition delivers as many chunks as the child handed over" + ); +} + +/// T-E1: two sources whose chains belong on one output land there whole, never inside one another. +/// +/// Both label sets hash to the same output and both sources have a chain for it. One of the chains is +/// held open across a gate, so the other source's chain is the only thing that can be delivered; what +/// must not happen is that the held chain's first chunk sits on the output ahead of the other source's +/// chain, because two sources' chunks inside one open series is exactly what a downstream frame reader +/// refuses. What does happen is that the closed chain arrives first, whole, and the held one follows. +#[tokio::test] +async fn two_sources_keep_their_chains_whole_on_one_output() { + let on_one = labels_routed_to(0, 2); + let (held, closed) = (on_one[0].clone(), on_one[1].clone()); + assert_eq!( + Routing::new(2).output(&held), + Routing::new(2).output(&closed), + "two label sets of one output, found rather than assumed" + ); + let switch = Arc::new(Switch::default()); + let child = Gated::plan( + vec![ + // The chain that stays open across the gate: its first chunk is handed over at once and + // the chunk that closes it only after the switch opens. + GatedPartition { + before: vec![Step::chunk(chunk(held.clone(), 0, 2, false))], + after: vec![Step::chunk(chunk(held.clone(), 2, 2, true))], + }, + // The other source's whole chain, handed over as soon as it is polled. + GatedPartition::open(vec![ + Step::chunk(chunk(closed.clone(), 0, 2, false)), + Step::chunk(chunk(closed.clone(), 2, 2, true)), + ]), + ], + Arc::clone(&switch), + Arc::new(AtomicUsize::new(0)), + ); + let plan: Arc = node(child, 2); + let context = SessionContext::default().task_ctx(); + let mut routed = output(&plan, 0, &context); + let other = output(&plan, 1, &context); + + // The chain of the source that closed arrives while the other source is still open - and in one + // piece, since a partial chain is never put on an output in the first place. + let mut chunks = Vec::new(); + while chunks.len() < 2 { + let chunk = tokio::time::timeout(Duration::from_secs(10), routed.next()) + .await + .unwrap_or_else(|_| { + panic!( + "the closed chain of one source did not arrive while the other source's chain \ + was still open: {} chunks arrived", + chunks.len() + ) + }) + .expect("the output is not over while a source is still reading") + .expect("the chunk decodes"); + chunks.push(chunk); + } + assert_chains_are_whole(&chunks); + assert_eq!( + vec![ + (named(&closed), Some(0), 2, false), + (named(&closed), Some(2), 2, true), + ], + summaries(&chunks), + "the source whose chain closed is on the output whole, before the open chain's first chunk" + ); + + // Opening the gate closes the held chain: it follows on the same output, and everything the + // output carried over the test is a run of whole chains. + switch.open(); + chunks.extend( + tokio::time::timeout(Duration::from_secs(10), routed.try_collect::>()) + .await + .expect("the held chain arrives once the gate opens") + .expect("the output decodes"), + ); + assert_chains_are_whole(&chunks); + assert_eq!( + vec![ + (named(&closed), Some(0), 2, false), + (named(&closed), Some(2), 2, true), + (named(&held), Some(0), 2, false), + (named(&held), Some(2), 2, true), + ], + summaries(&chunks), + "both sources' chains are on one output, each of them in one piece" + ); + let empty = tokio::time::timeout(Duration::from_secs(10), other.try_collect::>()) + .await + .expect("the other output ends") + .expect("the other output decodes"); + assert!( + empty.is_empty(), + "neither label set hashes to the other output" + ); +} + +/// T-E2: a closing chunk that carries no rows is delivered, and is not mistaken for the end of the +/// stream. +/// +/// A series can close with nothing left of it, and that chunk carries the finality and no position. It +/// is a chunk of its own on the way out - it is how a consumer closes the series - and a stream that is +/// still going must not be ended by it: the chunk after it is what says the empty one was a chunk and +/// not the end. +#[tokio::test] +async fn an_empty_closing_chunk_is_a_chunk_and_not_the_end() { + let routing = Routing::new(2); + let shared = labels("web-1"); + let other = labels_elsewhere(&routing, &shared); + let child = Scripted::plan(vec![ + // One source closes a series with nothing left of it, and keeps going afterwards. + vec![ + Step::chunk(chunk(other.clone(), 0, 0, true)), + Step::chunk(chunk(other.clone(), 0, 1, true)), + ], + // The other source hands over a chain with positions, and closes it with an empty chunk. + vec![ + Step::chunk(chunk(shared.clone(), 0, 0, true)), + Step::chunk(chunk(shared.clone(), 4, 2, false)), + Step::chunk(chunk(shared.clone(), 6, 0, true)), + ], + ]); + let plan: Arc = node(child, 2); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + drain(&plan, &SessionContext::default().task_ctx()), + ) + .await + .expect("an input that only closes empty chains still ends") + .into_iter() + .map(|output| output.expect("no output ends with an error")) + .collect::>(); + for chunks in &outputs { + assert_chains_are_whole(chunks); + } + + assert_eq!( + vec![ + // The chunk with no rows of its own, then the chunk of the stream that is still going. + (named(&shared), None, 0, true), + (named(&shared), Some(4), 2, false), + (named(&shared), None, 0, true), + ], + summaries(&outputs[routing.output(&shared)]), + "an empty closing chunk is handed over, and the chunk after it is not swallowed" + ); + assert_eq!( + vec![ + (named(&other), None, 0, true), + (named(&other), Some(0), 1, true), + ], + summaries(&outputs[routing.output(&other)]), + "the same holds for a source whose whole first chain is one empty closing chunk" + ); +} + +/// T-E3: while one owner's chain is still open, the other owner's output still delivers. +/// +/// Two label sets on two outputs, one long chain each, and the first one is held open across a gate. +/// The other output has to deliver its whole chain in that time: the wait on the gated source belongs +/// to the task reading that source, and no other source's chunks wait with it. What this rules out is +/// the shape this node used to have - one reader for every input, parked on the gated source and +/// delivering nothing at all until the chain closed. +#[tokio::test] +async fn an_open_chain_on_one_output_does_not_hold_the_other_output_back() { + let routing = Routing::new(2); + let held = labels("web-1"); + let free = labels_elsewhere(&routing, &held); + let held_output = routing.output(&held); + let free_output = routing.output(&free); + assert_ne!( + held_output, free_output, + "the two label sets have to land apart for this test to mean anything" + ); + let switch = Arc::new(Switch::default()); + let child = Gated::plan( + vec![ + // A long chain, gated after its first chunk. + GatedPartition { + before: vec![Step::chunk(chunk(held.clone(), 0, 2, false))], + after: vec![ + Step::chunk(chunk(held.clone(), 2, 2, false)), + Step::chunk(chunk(held.clone(), 4, 2, false)), + Step::chunk(chunk(held.clone(), 6, 2, true)), + ], + }, + // A chain of its own, handed over as soon as it is polled. + GatedPartition::open(vec![ + Step::chunk(chunk(free.clone(), 0, 2, false)), + Step::chunk(chunk(free.clone(), 2, 2, true)), + ]), + ], + Arc::clone(&switch), + Arc::new(AtomicUsize::new(0)), + ); + let plan: Arc = node(child, 2); + let context = SessionContext::default().task_ctx(); + let mut held_stream = output(&plan, held_output, &context); + let mut free_stream = output(&plan, free_output, &context); + + // The other owner's output delivers while the gated chain is still open, and what it delivers is + // its whole chain. + let mut delivered = Vec::new(); + while delivered.len() < 2 { + let chunk = tokio::time::timeout(Duration::from_secs(10), free_stream.next()) + .await + .unwrap_or_else(|_| { + panic!( + "the other owner's output delivered {} of its 2 chunks while one chain was open", + delivered.len() + ) + }) + .expect("the other output is not over") + .expect("the chunk decodes"); + delivered.push(chunk); + } + assert_chains_are_whole(&delivered); + assert_eq!( + vec![ + (named(&free), Some(0), 2, false), + (named(&free), Some(2), 2, true), + ], + summaries(&delivered), + "the free chain is delivered in full while the other owner's chain is still open" + ); + + // The open chain is still waiting for its own source, so nothing of it has been delivered: a + // partial chain does not sit on an output waiting to be completed. + assert!( + tokio::time::timeout(Duration::from_millis(200), held_stream.next()) + .await + .is_err(), + "the held chain was delivered while its source was still open" + ); + + switch.open(); + let held_chunks = + tokio::time::timeout(Duration::from_secs(10), held_stream.try_collect::>()) + .await + .expect("the held chain arrives once the gate opens") + .expect("the held output decodes"); + assert_chains_are_whole(&held_chunks); + assert_eq!( + vec![ + (named(&held), Some(0), 2, false), + (named(&held), Some(2), 2, false), + (named(&held), Some(4), 2, false), + (named(&held), Some(6), 2, true), + ], + summaries(&held_chunks), + "the long chain arrives whole and in order once its source closes it" + ); + let rest = tokio::time::timeout(Duration::from_secs(10), free_stream.try_collect::>()) + .await + .expect("the other output ends") + .expect("the other output decodes"); + assert!( + rest.is_empty(), + "the other output carried its whole chain already" + ); +} + +/// T-E4: a partition that fails mid-stream ends every output with that error, none of them cleanly. +/// +/// One of the two input partitions fails after handing over a chunk and the other ends normally, so +/// one output has data and an end of its own that the failure has to replace. Three outputs make sure +/// the error is not merely the fate of the output the failed partition was routing to: an output that +/// ended cleanly would report the series that never arrived as series that do not exist. +#[tokio::test] +async fn a_child_partition_that_fails_mid_stream_ends_every_output_with_its_error() { + let shared = labels("web-1"); + let other = labels("elsewhere"); + let child = Scripted::plan(vec![ + // This partition fails with its series open. + vec![Step::chunk(chunk(shared.clone(), 0, 2, false)), Step::Error], + // This one ends normally. + vec![Step::chunk(chunk(other.clone(), 0, 1, true))], + ]); + let plan: Arc = node(child, 3); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + drain(&plan, &SessionContext::default().task_ctx()), + ) + .await + .expect("a failed read still ends every output"); + assert_eq!(3, outputs.len()); + for (partition, output) in outputs.iter().enumerate() { + let error = output + .as_ref() + .err() + .unwrap_or_else(|| panic!("output partition {partition} reported a clean end")); + assert!( + error.to_string().contains("scripted child failure"), + "output partition {partition} ended with {error}" + ); + } +} + +/// T-E5: with two input partitions, each is read on a task of its own, and neither on the consumer's. +/// +/// The mirror of [`every_input_partition_is_read_on_a_task_of_its_own`] over a node with two outputs - +/// the shape the per-input router is for, where each partition's chains are routed by the task that +/// read them. What the child records is the task that first polled each of its partitions, so one id +/// for both, or the consumer's own, is the shape a node with a reader shared by all its inputs has. +#[tokio::test] +async fn both_input_partitions_are_read_on_tasks_of_their_own_and_route_their_own_chunks() { + let routing = Routing::new(2); + let shared = labels("web-1"); + let other = labels_elsewhere(&routing, &shared); + let (child, polled) = Recording::plan(vec![ + vec![Step::chunk(chunk(shared.clone(), 0, 1, true))], + vec![Step::chunk(chunk(other.clone(), 4, 1, true))], + ]); + let plan: Arc = node(child, 2); + // Taken before anything is read: the task that asks for an output is the one a partition must + // not be read on. + let consumer = tokio::task::try_id(); + let outputs = tokio::time::timeout( + Duration::from_secs(10), + drain(&plan, &SessionContext::default().task_ctx()), + ) + .await + .expect("both partitions of the child answer, so every output ends"); + + let recorded = polled + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + assert_eq!( + 2, + recorded.len(), + "the child holds one partition per scripted list" + ); + let tasks = recorded + .iter() + .map(|task| task.unwrap_or_else(|| panic!("a child partition was never polled"))) + .collect::>(); + assert_ne!( + tasks[0], tasks[1], + "the two partitions were polled by two different tasks, so each input was read - and routed - \ + on a task of its own: {tasks:?}" + ); + assert!( + tasks.iter().all(|task| Some(*task) != consumer), + "neither partition ran on the consumer's task: {tasks:?} against {consumer:?}" + ); + + assert_eq!( + vec![(named(&shared), Some(0), 1, true)], + summaries( + outputs[routing.output(&shared)] + .as_ref() + .expect("the output of the first label set decodes") + ), + "the first input's chain lands on the output its labels hash to" + ); + assert_eq!( + vec![(named(&other), Some(4), 1, true)], + summaries( + outputs[routing.output(&other)] + .as_ref() + .expect("the output of the second label set decodes") + ), + "and the second input's chain on its own" + ); +} + +/// T-E6: two inputs make their own routing decisions, and neither waits for the other to make one. +/// +/// The child will not hand over a second chunk of a partition until every partition has handed over a +/// first, so nothing gets past the first chunk of either source unless both are being read at the same +/// time: a read that took one input's chain to its end before it looked at the other waits forever +/// there for a chunk that only the other input's own progress can release. Each source's chain is two +/// chunks long, so that wait lands in the middle of an open chain - the point at which a +/// chain-continuous reader that drove the inputs itself would have to stop. +/// +/// The two label sets hash to two different outputs, so what each task does here is a routing decision +/// of its own: one hash over one chain, sent to one owner. Two outputs means each of them has a +/// different decision to make and no decision of the other's to wait for, which is the property this +/// test states; a node with a single output is [`one_output_keeps_every_chunk_and_its_chains_whole`], +/// where there is nothing to decide and every chunk still arrives. +/// +/// The gate is this child and not a stopwatch: nothing here depends on two cores happening to run at +/// the same instant, only on the two inputs being driven, and routed, independently of each other. +#[tokio::test] +async fn two_inputs_are_routed_without_waiting_for_each_other() { + let routing = Routing::new(2); + let first = labels("web-1"); + let second = labels_elsewhere(&routing, &first); + assert_ne!( + routing.output(&first), + routing.output(&second), + "the two label sets have to land apart for this test to mean anything" + ); + let child = Together::plan(vec![ + vec![ + Step::chunk(chunk(first.clone(), 0, 1, false)), + Step::chunk(chunk(first.clone(), 1, 1, true)), + ], + vec![ + Step::chunk(chunk(second.clone(), 0, 1, false)), + Step::chunk(chunk(second.clone(), 1, 1, true)), + ], + ]); + let plan: Arc = node(child, 2); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + drain(&plan, &SessionContext::default().task_ctx()), + ) + .await + .expect("both inputs are read at once, so the rendezvous between them opens") + .into_iter() + .map(|output| output.expect("no output ends with an error")) + .collect::>(); + assert_eq!(2, outputs.len()); + for chunks in &outputs { + assert_chains_are_whole(chunks); + } + assert_eq!( + vec![ + (named(&first), Some(0), 1, false), + (named(&first), Some(1), 1, true), + ], + summaries(&outputs[routing.output(&first)]), + "the first input's chain is routed, whole and in order, to the output its own labels name" + ); + assert_eq!( + vec![ + (named(&second), Some(0), 1, false), + (named(&second), Some(1), 1, true), + ], + summaries(&outputs[routing.output(&second)]), + "and the second input's chain to its own output, neither decision waiting on the other" + ); +} + +/// The chunks each partition of a [`Together`] child has handed over so far. +#[derive(Default)] +struct FirstChunks { + /// Whether each partition handed over its first chunk, by partition. + handed: Mutex>, + /// The streams parked until the partitions that have not handed theirs over do. + wakers: Mutex>, +} + +impl FirstChunks { + fn new(partitions: usize) -> Arc { + Arc::new(Self { + handed: Mutex::new(vec![false; partitions]), + wakers: Mutex::new(Vec::new()), + }) + } + + /// Records that `partition` handed over its first chunk, and wakes what waited for it. + fn handed(&self, partition: usize) { + self.handed + .lock() + .unwrap_or_else(|error| error.into_inner())[partition] = true; + for waker in std::mem::take( + &mut *self + .wakers + .lock() + .unwrap_or_else(|error| error.into_inner()), + ) { + waker.wake(); + } + } + + /// Whether every partition handed over its first chunk. + fn all(&self) -> bool { + self.handed + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + .all(|handed| *handed) + } + + /// Parks `cx` until every partition has, unless they already have. + fn wait(&self, cx: &Context<'_>) { + if self.all() { + return; + } + self.wakers + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(cx.waker().clone()); + if self.all() { + // The last partition handed its chunk over between the two reads, so its wake did not + // find this waker. + cx.waker().wake_by_ref(); + } + } +} + +/// A child each of whose partitions hands over a second chunk only once every partition handed over a +/// first. +/// +/// This is the gate T-E6 is built on: progress through one partition's chain requires the other +/// partition to have progressed too, which is only possible if both are read at the same time. It is a +/// rendezvous between inputs, not a stopwatch: nothing about it depends on two threads running at +/// once. +struct Together { + steps: Vec>, + chunks: Arc, + series_schema: Arc, + properties: Arc, +} + +impl Together { + /// The child over `steps`, one partition per list. + fn plan(steps: Vec>) -> Arc { + let series_schema = schema(); + let frame = pack_evaluated_series( + Box::pin(futures::stream::empty()), + Arc::clone(&series_schema), + ) + .expect("an evaluated schema declares a frame") + .schema(); + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(frame), + Partitioning::UnknownPartitioning(steps.len()), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Arc::new(Self { + chunks: FirstChunks::new(steps.len()), + steps, + series_schema, + properties, + }) + } +} + +impl fmt::Debug for Together { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("Together") + .field("partitions", &self.steps.len()) + .finish() + } +} + +impl DisplayAs for Together { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!(f, "Together: partitions={}", self.steps.len()) + } +} + +impl ExecutionPlan for Together { + fn name(&self) -> &str { + "Together" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + Vec::new() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + assert!(children.is_empty(), "a together child has no children"); + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + let steps = self.steps.get(partition).cloned().ok_or_else(|| { + DataFusionError::Execution(format!("together child has no partition {partition}")) + })?; + pack_evaluated_series( + Box::pin(TogetherScript { + partition, + steps: steps.into_iter(), + chunks: Arc::clone(&self.chunks), + handed: false, + }), + Arc::clone(&self.series_schema), + ) + } +} + +/// One partition of a [`Together`] child. +struct TogetherScript { + partition: usize, + steps: std::vec::IntoIter, + chunks: Arc, + /// Whether this partition handed over its first chunk already. + handed: bool, +} + +impl Stream for TogetherScript { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + if this.handed { + // Everything after the first chunk waits for the other partitions to have handed theirs + // over, so this stream cannot be read past its first chunk on its own. + this.chunks.wait(cx); + if !this.chunks.all() { + return Poll::Pending; + } + } + match this.steps.next() { + Some(step) => { + if !this.handed { + this.handed = true; + this.chunks.handed(this.partition); + } + Poll::Ready(Some(step_answer(step))) + } + None => Poll::Ready(None), + } + } +} + +/// A child whose partitions hand over their `before` steps, wait until every partition got that far, +/// and only then hand over their `after` steps. +/// +/// The barrier sits between the two halves rather than before a partition's first chunk, which is what +/// [`Together`] gates: what a test of the failure path needs is two partitions that fail *at once*. +/// Every partition that gets to the gate is parked until the last one arrives, so the `after` steps of +/// two partitions are handed over in the same wake - which is the interleaving +/// [`two_failures_hand_every_output_one_error`] is built on. The gate itself is [`FirstChunks`], the +/// all-arrived barrier [`Together`] already uses, since "has every partition got here" is what both +/// need. +struct Simultaneous { + partitions: Vec, + arrived: Arc, + series_schema: Arc, + properties: Arc, +} + +impl Simultaneous { + /// The child over `partitions`, and the barrier every one of them waits at. + fn plan(partitions: Vec) -> (Arc, Arc) { + let series_schema = schema(); + let frame = pack_evaluated_series( + Box::pin(futures::stream::empty()), + Arc::clone(&series_schema), + ) + .expect("an evaluated schema declares a frame") + .schema(); + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(frame), + Partitioning::UnknownPartitioning(partitions.len()), + EmissionType::Incremental, + Boundedness::Bounded, + )); + let arrived = FirstChunks::new(partitions.len()); + let child = Arc::new(Self { + partitions, + arrived: Arc::clone(&arrived), + series_schema, + properties, + }); + (child, arrived) + } +} + +impl fmt::Debug for Simultaneous { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("Simultaneous") + .field("partitions", &self.partitions.len()) + .finish() + } +} + +impl DisplayAs for Simultaneous { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!(f, "Simultaneous: partitions={}", self.partitions.len()) + } +} + +impl ExecutionPlan for Simultaneous { + fn name(&self) -> &str { + "Simultaneous" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + Vec::new() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + assert!(children.is_empty(), "a simultaneous child has no children"); + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + let steps = self.partitions.get(partition).cloned().ok_or_else(|| { + DataFusionError::Execution(format!("simultaneous child has no partition {partition}")) + })?; + pack_evaluated_series( + Box::pin(SimultaneousScript { + partition, + before: steps.before.into_iter(), + after: steps.after.into_iter(), + arrived: Arc::clone(&self.arrived), + arrived_here: false, + }), + Arc::clone(&self.series_schema), + ) + } +} + +/// One partition of a [`Simultaneous`] child. +struct SimultaneousScript { + partition: usize, + before: std::vec::IntoIter, + after: std::vec::IntoIter, + arrived: Arc, + /// Whether this partition already reached the barrier. + arrived_here: bool, +} + +impl Stream for SimultaneousScript { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + if let Some(step) = this.before.next() { + return Poll::Ready(Some(step_answer(step))); + } + if !this.arrived_here { + // Everything after the first half waits for every partition to have handed its first half + // over, so the second halves - and the failures among them - leave two tasks together. + this.arrived_here = true; + this.arrived.handed(this.partition); + } + this.arrived.wait(cx); + if !this.arrived.all() { + return Poll::Pending; + } + Poll::Ready(this.after.next().map(step_answer)) + } +} + +/// Every output of `plan`, read to its end at once: the chunks each delivered and the errors each +/// reported. +/// +/// All partitions are drained concurrently, which is what an executor does and what a failed read +/// needs: the one broadcaster suspends on an output nobody is draining, so an output drained to its +/// end before the next one is started would wait for a sender that is waiting for that next output. +async fn every_output_until_end( + plan: &Arc, + context: &Arc, +) -> Vec<(Vec<(Series, bool)>, Vec)> { + let mut streams = Vec::new(); + for partition in 0..plan.outputs() { + streams.push( + unpack_evaluated_series( + plan.execute(partition, Arc::clone(context)) + .expect("the output executes"), + None, + ) + .expect("the output declares an evaluated frame"), + ); + } + futures::future::join_all(streams.iter_mut().map(until_end)).await +} + +/// T-F1: two partitions that fail at the same moment leave every output exactly one error. +/// +/// Between them the two partitions hand over [`OUTPUT_CAPACITY`] chains per output before they fail, +/// so both queues are exactly full and then two failures land on a read whose outputs are not being +/// drained. The one broadcaster therefore suspends on the first full queue while the other task is +/// itself on the failure path: the interleaving the read has to survive, since a failing task that +/// sweeps its peers aborts the task suspended mid-broadcast, and the outputs it had not reached wake +/// to closed queues with the read recorded as failed and no error item - which they then report as a +/// clean end. +/// +/// Both partitions are known to have reached the barrier before either failed, which is what makes +/// the two failures overlap rather than merely possible: neither can hand its failing step over before +/// the other has arrived. What is asserted is the fix from the outside - the failure is recorded with +/// the error that belongs to it, and every output ends with exactly one error, never a clean end and +/// never two errors (which only two broadcasts could produce), all of them the recorded one. +#[tokio::test] +async fn two_failures_hand_every_output_one_error() { + const FIRST: &str = "the first partition failed"; + const SECOND: &str = "the second partition failed"; + assert_eq!( + 0, + OUTPUT_CAPACITY % 2, + "the chains of one queue are split evenly between the two partitions" + ); + let half = OUTPUT_CAPACITY / 2; + let to_first = labels_routed_to(0, OUTPUT_CAPACITY); + let to_second = labels_routed_to(1, OUTPUT_CAPACITY); + + /// The steps of one partition: its half of every output's queue, a place at the barrier, and then + /// its failure. + /// + /// The failure is what comes *after* the barrier, which is the whole point: a partition cannot hand + /// it over until every partition has handed over its chains, so the two failures are released into + /// the same wake instead of one of them landing while the other task is still reading. + fn failing( + first: &[SeriesLabels], + second: &[SeriesLabels], + message: &'static str, + ) -> GatedPartition { + GatedPartition { + before: first + .iter() + .chain(second) + .map(|labels| Step::chunk(chunk(labels.clone(), 0, 1, true))) + .collect::>(), + after: vec![Step::ErrorSaying(message)], + } + } + + let (child, arrived) = Simultaneous::plan(vec![ + failing(&to_first[..half], &to_second[..half], FIRST), + failing(&to_first[half..], &to_second[half..], SECOND), + ]); + let plan = node(child, 2); + let context = SessionContext::default().task_ctx(); + // Claimed before anything is read, so the queues that fill are the ones a reader is waiting on. + let mut streams = Vec::new(); + for partition in 0..plan.outputs() { + streams.push( + unpack_evaluated_series( + plan.execute(partition, Arc::clone(&context)) + .expect("the output executes"), + None, + ) + .expect("the output declares an evaluated frame"), + ); + } + let execution = execution(&plan); + + wait_until("both partitions reach the failure path", || arrived.all()).await; + wait_until("the read records its failure", || { + execution.ending().0 == Ending::Failed + }) + .await; + let (ending, terminal) = execution.ending(); + assert_eq!(Ending::Failed, ending, "the read records that it failed"); + let recorded = terminal.expect("a recorded failure keeps the error its outputs are owed"); + let expected = recorded.to_string(); + let named = [FIRST, SECOND] + .into_iter() + .find(|message| expected.contains(message)) + .unwrap_or_else(|| panic!("the recorded error names one of the two failures: {expected}")); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + futures::future::join_all(streams.iter_mut().map(until_end)), + ) + .await + .expect("a read with two failures still ends every output"); + + for (partition, (chunks, errors)) in outputs.iter().enumerate() { + assert_eq!( + 1, + errors.len(), + "output partition {partition} reports the failure once, not once per failing input: \ + {errors:?}" + ); + // The item and the recorded error are the same failure, but each is wrapped by the path it + // takes out of the read, so what they are compared on is the failure they name. + assert!( + errors[0].contains(named), + "output partition {partition} reports the failure the read recorded ({named}), not {}", + errors[0] + ); + assert_chains_are_whole(chunks); + } +} + +/// T-F2: a task attached after the failure is swept is aborted instead of waited on. +/// +/// Partition 0 fails on its first poll, which can happen before the tasks of the partitions after it +/// are even spawned - and a handle attached after the failure's sweep is one the sweep cannot see. +/// Stored as live, it waits on a child that never answers while holding a sender to every output, so +/// the queues never close and both outputs hang here. The other partitions are gated on a switch +/// nothing opens, so the only way this test finishes is those tasks being aborted: their streams +/// record the drop an aborted task's future goes through. +#[tokio::test] +async fn a_partition_failing_before_its_peers_are_attached_still_ends_every_output() { + const MESSAGE: &str = "the first partition failed at once"; + let switch = Arc::new(Switch::default()); + let dropped = Arc::new(AtomicUsize::new(0)); + let shared = labels("web-1"); + // Ten partitions, so the failing one's sweep runs while the later ones are still being spawned and + // attached: the read must stop them anyway. `read_partitions` counts them with the failing one. + let mut partitions = vec![GatedPartition::open(vec![Step::ErrorSaying(MESSAGE)])]; + partitions.extend( + (0..10).map(|_| GatedPartition::held(vec![Step::chunk(chunk(shared.clone(), 0, 1, true))])), + ); + let read_partitions = partitions.len(); + let child = Gated::plan(partitions, switch, Arc::clone(&dropped)); + let plan = node(child, 2); + let context = SessionContext::default().task_ctx(); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + every_output_until_end(&plan, &context), + ) + .await + .expect( + "a read whose first partition fails before its peers were attached still ends: a task left \ + waiting on a child holds a sender to every output, so nothing would close", + ); + for (partition, (_, errors)) in outputs.iter().enumerate() { + assert_eq!( + 1, + errors.len(), + "output partition {partition} reports the failure: {errors:?}" + ); + assert!( + errors[0].contains(MESSAGE), + "output partition {partition} ended with {}", + errors[0] + ); + } + wait_until("every child partition's stream is dropped", || { + dropped.load(Ordering::SeqCst) == read_partitions + }) + .await; + // The read is over, which it could not be if a task attached after the sweep were still holding + // a sender to every output. + let execution = execution(&plan); + wait_until("the read stops", || producer_stopped(&execution)).await; +} + +/// Sets a flag when the future holding it is dropped, which is how a test sees a task aborted. +/// +/// Dropping the future is what aborting a task does - whether it had been polled or not - while a +/// handle that is only stored and never aborted leaves the task running until the process ends. +struct DroppedWhenAborted(Arc); + +impl Drop for DroppedWhenAborted { + fn drop(&mut self) { + self.0.store(true, Ordering::SeqCst); + } +} + +/// T-F2, without the runtime deciding when it happens: a handle that arrives after the failure is +/// aborted by the attach itself. +/// +/// The end-to-end test above can only make the race likely. This one does not race at all: the read +/// is failed first, exactly as partition 0 does in it, and only then is a task of another partition +/// handed over. What has to happen is the same thing, and it is stated here on its own: the task is +/// aborted, its slot stays empty, and the read does not end up counting a task that never ran. +#[tokio::test] +async fn a_task_attached_after_the_failure_is_aborted_and_not_counted() { + let ending = Arc::new(Mutex::new(EndingRecord::default())); + let inputs = Inputs::new(Arc::clone(&ending), 2); + // Kept alive so the failure's item has somewhere to go; the queue itself is not read. + let (sender, _receiver) = mpsc::channel::(1); + let error = Arc::new(DataFusionError::Execution( + "the first partition failed".to_string(), + )); + inputs + .failed(0, &error, std::slice::from_ref(&sender)) + .await; + assert_eq!(0, inputs.live(), "a failed read is no longer running"); + + let aborted = Arc::new(AtomicBool::new(false)); + // The guard is built before the future rather than inside it, so it is part of what the task + // holds. A task aborted before its first poll never runs its body - so a guard built there would + // never exist to be dropped, and the abort would look like nothing happened. Held this way, it is + // dropped when the runtime drops the aborted task's future, whether or not it ever ran. + let guard = DroppedWhenAborted(Arc::clone(&aborted)); + // Spawned on the test's own runtime rather than the global query one: an abort is processed by the + // runtime the task lives on, and this test has to see it happen. + let task = tokio::spawn(async move { + let _guard = guard; + futures::future::pending::<()>().await; + }); + inputs.attach(1, task); + assert!( + inputs + .state + .lock() + .unwrap_or_else(|error| error.into_inner()) + .tasks[1] + .is_none(), + "the task of a cancelled read is aborted rather than stored as one to wait for" + ); + wait_until("the task attached after the failure is aborted", || { + aborted.load(Ordering::SeqCst) + }) + .await; + assert_eq!( + 0, + inputs.live(), + "the aborted task never ran, so the read is not left waiting for it" + ); +} + +/// T-F3: a read that finished owes its outputs no error, whatever a failure elsewhere recorded. +/// +/// The error an output reports for a failed read is now read out of the read's own state, so a read +/// that finished must not be turned into a failure by it: what it records is `Finished` and no +/// terminal error at all, and every output ends cleanly once. The other half of the property - a read +/// that was stopped records nothing and is reported as an error rather than an end - is +/// [`an_aborted_producer_is_not_reported_as_a_clean_end`]. +#[tokio::test] +async fn a_finished_read_ends_cleanly_and_owes_no_error() { + let shared = labels("web-1"); + let child = Scripted::plan(vec![ + vec![Step::chunk(chunk(shared.clone(), 0, 2, true))], + vec![Step::chunk(chunk(shared.clone(), 8, 2, true))], + ]); + let plan = node(child, 2); + let context = SessionContext::default().task_ctx(); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + every_output_until_end(&plan, &context), + ) + .await + .expect("both partitions end, so both outputs end"); + // Read after the outputs are done, so the read has recorded everything it is going to. + let execution = execution(&plan); + for (partition, (chunks, errors)) in outputs.iter().enumerate() { + assert!( + errors.is_empty(), + "output partition {partition} reported {errors:?} for a read that finished" + ); + assert_chains_are_whole(chunks); + } + assert_eq!( + Ending::Finished, + execution.ending().0, + "a read that finished records no failure for its outputs to report" + ); + assert!( + execution.ending().1.is_none(), + "and no terminal error either" + ); +} + +/// T-F4: a failure whose broadcast never reaches an output is still reported, not ended cleanly. +/// +/// This is the cut-short interleaving made deterministic rather than raced for. One partition hands +/// over exactly [`OUTPUT_CAPACITY`] chains per output - both queues are then full - and fails; the +/// task that elects itself the broadcaster is suspended on the first full queue with the failure +/// already recorded, and the test then stops the read from outside, which aborts that task before it +/// can hand the error to any output. Every output is therefore left with a closed queue, a failed +/// read recorded, and no error item - the exact state the defect produced by accident. +/// +/// What it must not do is report that as the end of the answer. Each output has to report the error +/// the read recorded, exactly once, and never a clean end: the stored error is what makes that +/// possible with the broadcast gone. +#[tokio::test] +async fn a_failure_whose_broadcast_is_cut_short_still_reaches_every_output() { + const MESSAGE: &str = "the partition failed mid-broadcast"; + let mut steps = labels_routed_to(0, OUTPUT_CAPACITY) + .iter() + .chain(labels_routed_to(1, OUTPUT_CAPACITY).iter()) + .map(|labels| Step::chunk(chunk(labels.clone(), 0, 1, true))) + .collect::>(); + steps.push(Step::ErrorSaying(MESSAGE)); + let plan = node(Scripted::plan(vec![steps]), 2); + let context = SessionContext::default().task_ctx(); + // Both outputs are claimed and none of them is drained, so the broadcast is parked on a full + // queue rather than delivered. + let mut streams = Vec::new(); + for partition in 0..plan.outputs() { + streams.push( + unpack_evaluated_series( + plan.execute(partition, Arc::clone(&context)) + .expect("the output executes"), + None, + ) + .expect("the output declares an evaluated frame"), + ); + } + let execution = execution(&plan); + + wait_until( + "the read records its failure while no output is drained", + || execution.ending().0 == Ending::Failed, + ) + .await; + // The broadcast is cut short: the task carrying it is aborted before any output received the + // error, which is what a stop of the whole read does to it. + execution + .running + .lock() + .unwrap_or_else(|error| error.into_inner()) + .inputs + .stop(); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + futures::future::join_all(streams.iter_mut().map(until_end)), + ) + .await + .expect("a read whose broadcast was cut short still ends every output"); + for (partition, (chunks, errors)) in outputs.iter().enumerate() { + assert_eq!( + 1, + errors.len(), + "output partition {partition} reports the failure the read recorded exactly once: \ + {errors:?}" + ); + assert!( + errors[0].contains(MESSAGE), + "output partition {partition} ended with {} rather than the failure", + errors[0] + ); + assert_chains_are_whole(chunks); + } +} + +/// What one partition of a [`Fragile`] child does when it is polled. +#[derive(Clone)] +enum Behaviour { + /// Hands `steps` over only once the switch is opened, then ends. + Held(Vec), + /// Panics on the first poll, which is a task dying where no arm of the read's ending match is + /// reached: the unwind takes the whole future with it. + Panics, + /// Never answers, so the task reading it stays parked on it until it is aborted. + Parked, + /// Hands one step over per poll, staying pending in between, so each of them becomes a frame + /// batch of its own. + /// + /// The frame boundary coalesces what a producer hands over in one poll into one batch - the + /// builder only flushes when the source is pending or done - so a child that hands several chunks + /// over back to back reaches a consumer as ONE chunk. A chunk per poll is what keeps them apart, + /// and a test about how a chain accumulates is about chunks rather than about batches. + OneAtATime(Vec), +} + +/// A child whose partitions stop in ways of their own: one dies or is parked, another stays parked. +/// +/// A test of what a read does with a producer that dies has to be able to make exactly one producer +/// die, and to see that the others really were reading and really were stopped. [`Behaviour::Panics`] +/// is the death nothing in the read reaches, [`Behaviour::Parked`] is the peer that would wait for a +/// child that never answers, and the counters answer the two questions a timeout cannot: `polled` +/// says a partition was being read rather than skipped, and `dropped` says the read let the stream of +/// a parked partition go - which is what an aborted task does. +struct Fragile { + behaviours: Vec, + switch: Arc, + /// Whether each partition has been polled once, which every partition waits for before it does + /// what its behaviour says. + /// + /// [`Behaviour::Panics`] needs it, and needs it for the peer rather than for itself: a producer + /// that dies on its very first poll can die before the task reading the other partition has been + /// polled at all, and then the peer is aborted without ever having read anything - which is a read + /// that never had a parked input to hang on. Waiting here is what makes the shape the test is + /// about exist before the death happens. + reading: Arc, + polled: Vec>, + dropped: Vec>, + series_schema: Arc, + properties: Arc, +} + +/// A [`Fragile`] child, and the two counters of every one of its partitions. +struct FragileChild { + plan: Arc, + /// How many times each partition was polled. + polled: Vec>, + /// How many of each partition's streams were dropped. + dropped: Vec>, +} + +impl Fragile { + /// The child over `behaviours`, one partition per behaviour, gated on `switch`. + fn plan(behaviours: Vec, switch: Arc) -> FragileChild { + let series_schema = schema(); + let frame = pack_evaluated_series( + Box::pin(futures::stream::empty()), + Arc::clone(&series_schema), + ) + .expect("an evaluated schema declares a frame") + .schema(); + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(frame), + Partitioning::UnknownPartitioning(behaviours.len()), + EmissionType::Incremental, + Boundedness::Bounded, + )); + let polled = (0..behaviours.len()) + .map(|_| Arc::new(AtomicUsize::new(0))) + .collect::>(); + let dropped = (0..behaviours.len()) + .map(|_| Arc::new(AtomicUsize::new(0))) + .collect::>(); + FragileChild { + plan: Arc::new(Self { + behaviours: behaviours.clone(), + switch, + reading: FirstChunks::new(behaviours.len()), + polled: polled.clone(), + dropped: dropped.clone(), + series_schema, + properties, + }), + polled, + dropped, + } + } +} + +impl fmt::Debug for Fragile { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("Fragile") + .field("partitions", &self.behaviours.len()) + .finish() + } +} + +impl DisplayAs for Fragile { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { + write!(f, "Fragile: partitions={}", self.behaviours.len()) + } +} + +impl ExecutionPlan for Fragile { + fn name(&self) -> &str { + "Fragile" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + Vec::new() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> DataFusionResult, + ) -> DataFusionResult { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + assert!(children.is_empty(), "a fragile child has no children"); + Ok(self) + } + + fn execute( + &self, + partition: usize, + _context: Arc, + ) -> DataFusionResult { + let behaviour = self.behaviours.get(partition).cloned().ok_or_else(|| { + DataFusionError::Execution(format!("fragile child has no partition {partition}")) + })?; + let steps = match &behaviour { + Behaviour::Held(steps) | Behaviour::OneAtATime(steps) => steps.clone(), + Behaviour::Panics | Behaviour::Parked => Vec::new(), + }; + pack_evaluated_series( + Box::pin(FragileScript { + partition, + behaviour, + steps: steps.into_iter(), + switch: Arc::clone(&self.switch), + reading: Arc::clone(&self.reading), + polled: Arc::clone(&self.polled[partition]), + dropped: Arc::clone(&self.dropped[partition]), + stayed_pending: false, + }), + Arc::clone(&self.series_schema), + ) + } +} + +/// One partition of a [`Fragile`] child. +struct FragileScript { + partition: usize, + behaviour: Behaviour, + steps: std::vec::IntoIter, + switch: Arc, + reading: Arc, + polled: Arc, + dropped: Arc, + /// Whether a [`Behaviour::OneAtATime`] partition has already stayed pending since its last chunk. + stayed_pending: bool, +} + +impl Stream for FragileScript { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + this.polled.fetch_add(1, Ordering::SeqCst); + // Every partition is read once before any of them does what it is here for, so a partition + // that dies cannot do so before its peer was read. + this.reading.handed(this.partition); + this.reading.wait(cx); + if !this.reading.all() { + return Poll::Pending; + } + match &this.behaviour { + Behaviour::Held(_) => { + this.switch.wait(cx); + if !this.switch.is_open() { + return Poll::Pending; + } + Poll::Ready(this.steps.next().map(step_answer)) + } + // The child's own poll, which runs inside the task reading it: what a producer that dies + // under a read does is exactly this, and nothing of the read is told about it. + Behaviour::Panics => panic!("the fragile child partition panicked while being read"), + // Parked on a source that never answers. No waker is registered because nothing can make + // this partition answer: the only way it stops is the read aborting it. + Behaviour::Parked => Poll::Pending, + Behaviour::OneAtATime(_) => { + if !this.stayed_pending { + // One pending poll between two chunks is what makes the frame boundary flush, + // and the wake is this stream's own: nothing outside it has to poll again for the + // next chunk to arrive. + this.stayed_pending = true; + cx.waker().wake_by_ref(); + return Poll::Pending; + } + this.stayed_pending = false; + Poll::Ready(this.steps.next().map(step_answer)) + } + } + } +} + +impl Drop for FragileScript { + fn drop(&mut self) { + self.dropped.fetch_add(1, Ordering::SeqCst); + } +} + +/// T-S1: a partition whose task panics ends every output with the read's error, and stops its peers. +/// +/// Two inputs and one output. Partition 0's child panics inside its `poll_next`, which unwinds the +/// task reading it: no arm of [`route_partition`]'s ending match runs, so nothing is recorded and +/// nothing stops the peer. Partition 1's child never answers, so its task stays parked on it holding +/// a copy of the senders - the queue never closes, and the output waits for an ending that cannot +/// come. That is the hang, and the timeout below is what turns it into a failure instead of a stall. +/// +/// The panic happens on a task of the read, never on this test's, so the unwind is the runtime's to +/// catch and what the test sees is its effect: the output ends with the read's error instead of +/// waiting, the parked peer's child is dropped because its task was aborted, and nothing the read +/// reserved outlives it. +#[tokio::test] +async fn a_panicking_input_ends_every_output_and_stops_its_peers() { + let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); + let context = task_context(&pool); + let child = Fragile::plan( + vec![Behaviour::Panics, Behaviour::Parked], + Arc::new(Switch::default()), + ); + let plan = node(child.plan, 1); + let mut stream = output_of(&plan, 0, &context); + let execution = execution(&plan); + wait_until("the parked peer is reading its child", || { + child.polled[1].load(Ordering::SeqCst) > 0 + }) + .await; + + let (chunks, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut stream)) + .await + .unwrap_or_else(|_| { + panic!( + "the output never ended although one of its two inputs had died: the death recorded \ + nothing, so the parked peer kept the queue open" + ) + }); + assert!( + chunks.is_empty(), + "no chunk was routed before the read stopped, so the output owes none" + ); + assert_eq!( + 1, + errors.len(), + "the output reports the death of partition 0 once: {errors:?}" + ); + assert!( + errors[0] + .contains("series repartition input partition 0 stopped without reporting an outcome"), + "the output ended with {} rather than the death of its producer", + errors[0] + ); + // The peer did not go on waiting for a child that never answers: its task was aborted, which is + // what the drop of the stream it was reading says. + wait_until("the parked peer's child is dropped", || { + child.dropped[1].load(Ordering::SeqCst) == 1 + }) + .await; + wait_until("the read's tasks are gone", || producer_stopped(&execution)).await; + wait_until("what the read reserved is released", || { + pool.reserved() == 0 + }) + .await; +} + +/// T-S2: a partition whose task is aborted on its own ends every output, and stops its peers. +/// +/// The same shape as [`a_panicking_input_ends_every_output_and_stops_its_peers`] with the other way a +/// task disappears: nothing panics, one task is aborted where it stands - as a cancelled query's task +/// is - and the future it was running is dropped with it. Both partitions stay parked on children that +/// never answer, so the only thing that can end this read is one of them dying and the read noticing: +/// the output would otherwise wait for two sources that never speak. +/// +/// The abort reaches the handle of one partition only. [`Inputs::stop`] cannot state this: it stops +/// every task and records the read as stopped, so what its outputs report is the stop rather than one +/// producer that died while its peers were still running. +#[tokio::test] +async fn an_aborted_input_task_ends_every_output_and_stops_its_peers() { + let child = Fragile::plan( + vec![Behaviour::Parked, Behaviour::Parked], + Arc::new(Switch::default()), + ); + let plan = node(child.plan, 1); + let context = SessionContext::default().task_ctx(); + let mut stream = output_of(&plan, 0, &context); + let execution = execution(&plan); + wait_until("both partitions are reading their children", || { + child.polled[0].load(Ordering::SeqCst) > 0 && child.polled[1].load(Ordering::SeqCst) > 0 + }) + .await; + + let inputs = Arc::clone( + &execution + .running + .lock() + .unwrap_or_else(|error| error.into_inner()) + .inputs, + ); + inputs.abort(0); + + let (chunks, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut stream)) + .await + .unwrap_or_else(|_| { + panic!( + "the output never ended although one of its two inputs had been aborted: the abort \ + recorded nothing, so the parked peer kept the queue open" + ) + }); + assert!( + chunks.is_empty(), + "both partitions are parked, so nothing was routed before the read stopped" + ); + assert_eq!( + 1, + errors.len(), + "the output reports the death of partition 0 once: {errors:?}" + ); + assert!( + errors[0] + .contains("series repartition input partition 0 stopped without reporting an outcome"), + "the output ended with {} rather than the death of its producer", + errors[0] + ); + wait_until("the other parked partition's child is dropped", || { + child.dropped[1].load(Ordering::SeqCst) == 1 + }) + .await; + wait_until("the read's tasks are gone", || producer_stopped(&execution)).await; +} + +/// T-S3: an output that is dropped stops the inputs, so the outputs still read end rather than wait. +/// +/// Partition 0 holds one chain for output 0 across the switch and partition 1 never answers. Output 0 +/// is claimed and then dropped - nothing it would have been given is wanted any more - so the chain +/// partition 0 is holding has nowhere to go, which is `Stop::Abandoned`. That used to be recorded and +/// nothing more: partition 1 stayed parked on its child holding a copy of the senders, the queue output +/// 1 reads never closed, and output 1 waited for an input that cannot finish. Once an output is gone +/// the read cannot complete for anyone, so what it must do is end every output it still has - with the +/// `Abandoned` ending rather than a clean one, since the chains the dropped output would have carried +/// were lost, and not as a failure either, since nothing failed. +#[tokio::test] +async fn dropping_an_output_ends_the_outputs_that_are_still_read() { + let switch = Arc::new(Switch::default()); + let doomed = labels_routed_to(0, 1).remove(0); + let child = Fragile::plan( + vec![ + Behaviour::Held(vec![Step::chunk(chunk(doomed.clone(), 0, 1, true))]), + Behaviour::Parked, + ], + Arc::clone(&switch), + ); + let plan = node(child.plan, 2); + let context = SessionContext::default().task_ctx(); + // Both outputs are claimed, so the one that goes away releases a claim on a read that still has + // another output to serve instead of stopping it. + let dropped_output = output_of(&plan, 0, &context); + let mut kept_output = output_of(&plan, 1, &context); + let execution = execution(&plan); + + // Dropped while its queue is still empty and its producer parked on the switch, so the chain held + // for it is what finds it gone. + drop(dropped_output); + switch.open(); + + let (chunks, errors) = tokio::time::timeout( + Duration::from_secs(10), + until_end(&mut kept_output), + ) + .await + .unwrap_or_else(|_| { + panic!( + "the output that is still read never ended: the abandoned chain was recorded but the \ + partition parked on a child that never answers was left running" + ) + }); + assert!( + chunks.is_empty(), + "the only chain of this read belonged to the dropped output" + ); + assert_eq!( + 1, + errors.len(), + "the output reports that the read was abandoned once: {errors:?}" + ); + assert!( + errors[0].contains("an output partition was dropped"), + "the output ended with {} rather than the abandoned read", + errors[0] + ); + wait_until("the parked partition's child is dropped", || { + child.dropped[1].load(Ordering::SeqCst) == 1 + }) + .await; + wait_until("the read's tasks are gone", || producer_stopped(&execution)).await; + let (ending, terminal) = execution.ending(); + assert_eq!( + Ending::Abandoned, + ending, + "an output going away is an abandoned read, not a failure and not an end" + ); + assert!( + terminal.is_none(), + "nothing failed, so the read owes its outputs no terminal error" + ); +} + +/// T-S4: a chain that outgrows the pool ends every output, cancels its peers and releases the memory. +/// +/// This is what the whole-chain handover costs unless it is charged: a chain is buffered whole before +/// it is routed, so a child that keeps one series open and never closes it would grow the buffer +/// without bound. Here the chain is charged to the pool as it grows, and the pool is sized from the +/// chunks rather than from a number picked by hand. +/// +/// The arithmetic is measured rather than assumed, and both sides of it matter. `per_chunk` is what +/// one chunk costs the read: a probe reads two chunks of the same shape through the same pack/unpack +/// path the read's child goes through, and the larger of the two [`series_bytes`] reductions is taken. +/// The chain is `CHUNKS` of those, the pool holds `CHUNKS / 2` of them, so one chunk fits with room +/// to spare and the chain as a whole does not: the growth that is refused is the one that would have +/// made the buffer exceed the pool, at the `CHUNKS / 2 + 1`-th chunk. A change to what a chunk costs +/// moves the pool with it instead of silently making the refusal happen at the first chunk or not at +/// all - which is what a hard-coded byte count did here. +/// +/// The child hands one chunk over per poll ([`Behaviour::OneAtATime`]) for a reason that is not +/// cosmetic: what a producer hands over in one poll reaches the read as one chunk, so back-to-back +/// chunks would coalesce into a single one and there would be no growing chain to refuse. +/// +/// What is asserted is the whole of it: every output ends with the refusal rather than a clean end, +/// the partition parked on a child that never answers is cancelled, and the pool is back to nothing +/// once the read is over - the chain it refused to grow is not left charged for. +#[tokio::test] +async fn a_chain_that_outgrows_the_pool_ends_every_output_and_releases_it() { + const CHUNKS: usize = 8; + let shared = labels("web-1"); + // One open chain: every chunk continues the series and none of them closes it, so the read goes on + // reading until the pool refuses to hold more of it. + let steps = (0..CHUNKS) + .map(|index| Step::chunk(chunk(shared.clone(), index, 1, false))) + .collect::>(); + // What one chunk of this chain costs, measured through the read's own path on an unbounded pool. + // The probe closes its chain, so what it measures is a whole stream's worth of chunks rather than + // the error a producer that never closes one leaves behind. + let per_chunk = { + let probe = Fragile::plan( + vec![Behaviour::OneAtATime(vec![ + Step::chunk(chunk(shared.clone(), 0, 1, false)), + Step::chunk(chunk(shared.clone(), 1, 1, true)), + ])], + Arc::new(Switch::default()), + ); + let probe_context = unbounded_context(); + let mut probe_chunks = unpack_evaluated_series( + probe + .plan + .execute(0, Arc::clone(&probe_context)) + .expect("the probe partition executes"), + None, + ) + .expect("the probe declares an evaluated frame"); + let (chunks, errors) = + tokio::time::timeout(Duration::from_secs(10), until_end(&mut probe_chunks)) + .await + .expect("the probe chain ends, so its stream ends"); + assert!( + errors.is_empty(), + "the probe chain is a whole one, so nothing about it fails: {errors:?}" + ); + assert_eq!( + 2, + chunks.len(), + "one chunk per poll is what keeps the frame boundary from coalescing two chunks into one" + ); + chunks + .iter() + .map(|(series, _)| series_bytes(series)) + .max() + .expect("the probe chain has chunks of its own") + }; + let pool_size = per_chunk * (CHUNKS / 2); + assert!( + per_chunk >= 1 && pool_size < per_chunk * CHUNKS, + "the pool has to hold at least one chunk and fewer than all of them, or this test refuses \ + nothing: {pool_size} bytes against {per_chunk} per chunk" + ); + let pool = Arc::new(GreedyMemoryPool::new(pool_size)); + let context = task_context(&pool); + let child = Fragile::plan( + vec![Behaviour::OneAtATime(steps), Behaviour::Parked], + Arc::new(Switch::default()), + ); + let plan = node(child.plan, 2); + + let outputs = tokio::time::timeout( + Duration::from_secs(10), + every_output_until_end(&plan, &context), + ) + .await + .expect("a reservation that is refused ends the read instead of growing past the pool"); + for (partition, (chunks, errors)) in outputs.iter().enumerate() { + assert!( + chunks.is_empty(), + "output partition {partition} was given the first {n} chunks of a chain that was never \ + routed", + n = chunks.len() + ); + assert_eq!( + 1, + errors.len(), + "output partition {partition} reports the refusal once: {errors:?}" + ); + assert!( + errors[0].contains("Failed to allocate additional"), + "output partition {partition} ended with {} rather than the refusal", + errors[0] + ); + } + wait_until("the parked partition's child is dropped", || { + child.dropped[1].load(Ordering::SeqCst) == 1 + }) + .await; + let execution = execution(&plan); + wait_until("the read's tasks are gone", || producer_stopped(&execution)).await; + wait_until("what the refused chain reserved is released", || { + pool.reserved() == 0 + }) + .await; +}