diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs index 3bcc18213ae..13a6637a2a4 100644 --- a/src/promql/src/extension_plan/fused_series/tests.rs +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -148,9 +148,8 @@ const SAMPLES: i64 = 10; const QUIET_SAMPLES: i64 = 541; /// One second between those samples, so the series rates at 1 once it is read to its end. /// -/// The step is a second and not a minute on purpose: at a minute the series would arrive in ten -/// batches, fewer than [`POLL_BUDGET`], and the budget the test above exists to check would never -/// be reached. +/// At a minute the series would arrive in ten batches, fewer than [`POLL_BUDGET`], and the budget +/// would never be reached. const QUIET_STEP: i64 = 1_000; const TIME: &str = "time"; @@ -1326,16 +1325,8 @@ fn partition_disjoint_rejects_a_multi_input_tree() { .expect("the logical node accepts two dense sources"); let exec = node .to_execution_plan(vec![ - ( - raw_source(per_series_scan(2)), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - raw_source(per_series_scan(2)), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), + explicit(raw_source(per_series_scan(2))), + explicit(raw_source(per_series_scan(2))), ]) .expect("both sources are per-series scans"); let fused = exec @@ -1443,22 +1434,10 @@ async fn scalar_binary_matching_key_is_not_routed_by_dropped_names() { super::InputLocality::SinglePartition )); let exec = node - .to_execution_plan(vec![ - ( - left_input, - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - right_input, - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ]) + .to_execution_plan(vec![explicit(left_input), explicit(right_input)]) .expect("the scalar binary executes"); - // A bare tree is conservatively classified as SinglePartition because its computed operands - // dropped the requested key. Planner segmentation cuts those per-series prefixes and routes - // their evaluated outputs by the actual labels; see the planner and integration regressions. + // A bare tree is classified as SinglePartition because its computed operands dropped the + // requested key. let batches = collect(exec, SessionContext::default().task_ctx()) .await .expect("the scalar binary completes"); @@ -1836,7 +1815,7 @@ fn subtracted_scaled_tree() -> NativeTree { /// /// A group is identified by labels, and a value field is not one: its value varies between the /// samples of one series, so a group keyed by it would be a group per point. The runtime refuses the -/// grouping rather than folding series into groups the previous route keeps apart. +/// grouping. fn ungroupable_aggregate_tree() -> NativeTree { let complete = aggregate_tree(); let root = complete.root(); @@ -1898,12 +1877,8 @@ fn aggregate_tree() -> NativeTree { .expect("the bound tree is legal") } -/// What the tree's input was compiled against, for the input schema and output tags given. -fn binding_of( - tree: &NativeTree, - _series_schema: Arc, - tags: Vec, -) -> FusedSeriesBinding { +/// What the tree's input was compiled against, for the output tags given. +fn binding_of(tree: &NativeTree, tags: Vec) -> FusedSeriesBinding { FusedSeriesBinding { grid: match &tree.root().output { NativeType::Samples(schema) => schema @@ -1921,7 +1896,7 @@ fn binding_of( /// What the tree's input was compiled against, read off the tree itself. fn binding(tree: &NativeTree) -> FusedSeriesBinding { - binding_of(tree, raw_schema(), vec![HOST.to_string(), NAME.to_string()]) + binding_of(tree, vec![HOST.to_string(), NAME.to_string()]) } /// The schema of a frame carrying series of `schema` with their labels explicit. @@ -2069,7 +2044,6 @@ fn zone_node() -> FusedSeries { fn zone_node_with(tree: NativeTree) -> FusedSeries { let binding = binding_of( &tree, - raw_schema(), vec![HOST.to_string(), ZONE.to_string(), NAME.to_string()], ); FusedSeries::try_new( @@ -2464,13 +2438,7 @@ fn fused_series_canonical_producer_exec_tracks_physical_routing() { FusedOutputFormat::SeriesFrame, ) .unwrap(); - let input = || { - ( - memory_exec_with(frame_schema(), vec![]), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ) - }; + let input = || explicit(memory_exec_with(frame_schema(), vec![])); let router = canonical.to_execution_plan(vec![input()]).unwrap(); let producer = router.children()[0]; let ordinary_exec = ordinary.to_execution_plan(vec![input()]).unwrap(); @@ -2586,7 +2554,7 @@ fn fused_series_ordinary_encoding_round_trip_and_rejects_unsupported_payloads() // The output schema owns the label layout; the source binding may have no tags or different // labels after a tree operation such as label rewriting. - let empty_binding = binding_of(rows.tree(), raw_schema(), Vec::new()); + let empty_binding = binding_of(rows.tree(), Vec::new()); let empty_tags = FusedSeries::try_new( Arc::from(PROMQL), rate_tree(), @@ -2718,7 +2686,7 @@ fn fused_series_decodes_a_version_1_payload_and_keeps_input_time_units() { /// [`canonical_frame_schema`] rather than with the plain row [`output_schema`]. fn envelope_node_with_tags(tags: Vec) -> FusedSeries { let tree = rate_tree(); - let binding = binding_of(&tree, raw_schema(), tags); + let binding = binding_of(&tree, tags); let output_schema = canonical_frame_schema(&tree); FusedSeries::try_new_with_format( Arc::from(PROMQL), @@ -2800,7 +2768,7 @@ fn renamed_reordered_value_columns_keep_field_identity_after_decode() { let node = FusedSeries::try_new( Arc::from(PROMQL), tree.clone(), - binding_of(&tree, two_field_schema(), vec![HOST.to_string()]), + binding_of(&tree, vec![HOST.to_string()]), vec![input_plan(frame_schema_of(&two_field_schema()))], Arc::new(datafusion::common::DFSchema::try_from(schema.as_ref().clone()).unwrap()), ) @@ -3037,7 +3005,7 @@ fn plain_rows_decode_rejects_invalid_schemas() { assert_eq!(scalar_decoded.schema(), scalar.schema()); // Binding tags describe the source; the carried schema independently describes outputs. - let empty_binding = binding_of(node.tree(), raw_schema(), Vec::new()); + let empty_binding = binding_of(node.tree(), Vec::new()); let cross_table = FusedSeries::try_new( Arc::from(PROMQL), node.tree().clone(), @@ -3108,22 +3076,11 @@ fn state_export_decode_rejects_schema_and_format_mismatch() { let node = FusedSeries::try_new_state_export( Arc::from(PROMQL), tree.clone(), - binding_of(&tree, raw_schema(), vec![HOST.to_string(), JOB.to_string()]), + binding_of(&tree, vec![HOST.to_string(), JOB.to_string()]), vec![input_plan(frame_schema())], ) .unwrap(); - // A state exporter is refused by the serializer, so its decode-time contracts are exercised - // through a payload that says what a state exporter's payload would say. - let bytes = mutate_envelope_payload( - &envelope_node_with_tags(vec![HOST.into(), NAME.into()]) - .serialize() - .unwrap(), - |payload| { - payload.tree = node.tree().clone(); - payload.output_schema = node.schema().as_arrow().clone(); - payload.format = FusedOutputFormat::SeriesFrame; - }, - ); + let bytes = node.serialize().unwrap(); assert_eq!( FusedSeries::deserialize(&bytes).unwrap().tree(), node.tree() @@ -3332,16 +3289,81 @@ fn fused(tree: NativeTree) -> FusedSeries { .expect("the binding matches the tree") } +/// The evaluated series that `batches` of a frame declared as `schema` decode to. +async fn decode_frames(schema: SchemaRef, batches: Vec) -> Vec<(Series, bool)> { + unpack_evaluated_series( + Box::pin(RecordBatchStreamAdapter::new( + schema, + futures::stream::iter(batches.into_iter().map(Ok)), + )), + None, + ) + .expect("the schema declares an evaluated frame") + .try_collect() + .await + .expect("the frames decode") +} + +/// Everything `exec` answers, decoded as an evaluated frame. +async fn frame_decode(exec: Arc) -> Vec<(Series, bool)> { + let batches = collect(Arc::clone(&exec), SessionContext::default().task_ctx()) + .await + .expect("frame output executes"); + decode_frames(exec.schema(), batches).await +} + +/// An input that hands over explicit-label raw frames in `Contiguous` order. +fn explicit( + input: Arc, +) -> (Arc, RawLabelSource, SeriesOrdering) { + (input, RawLabelSource::Explicit, SeriesOrdering::Contiguous) +} + +/// The partition-local state exporter of a split aggregate. +fn state_export_node(partial: &NativeTree) -> FusedSeries { + FusedSeries::try_new_state_export( + Arc::from("partial"), + partial.clone(), + binding(partial), + vec![input_plan(frame_schema())], + ) + .expect("the partial tree exports state") +} + +/// The final stage of a split aggregate, reading the state `partial` exports. +fn final_node(partial: &NativeTree, final_tree: &NativeTree) -> FusedSeries { + FusedSeries::try_new_with_format( + Arc::from("final"), + final_tree.clone(), + binding(final_tree), + vec![input_plan( + canonical_state_frame_schema(partial).inner().clone(), + )], + canonical_frame_schema(final_tree), + FusedOutputFormat::SeriesFrame, + ) + .expect("the final tree reads the exported state") +} + +/// The single-input node over `tree` emitting its canonical series frame. +fn frame_node(tree: &NativeTree) -> FusedSeries { + FusedSeries::try_new_with_format( + Arc::from(PROMQL), + tree.clone(), + binding(tree), + vec![input_plan(frame_schema())], + canonical_frame_schema(tree), + FusedOutputFormat::SeriesFrame, + ) + .expect("the tree is evaluated on a grid") +} + /// The physical node of `node` over `input`, reading the complete labels every frame carries. fn plan_of( node: FusedSeries, input: Arc, ) -> DataFusionResult> { - node.to_execution_plan(vec![( - input, - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + node.to_execution_plan(vec![explicit(input)]) } /// The physical node of `tree` over `input`. @@ -4290,13 +4312,7 @@ async fn every_node_of_an_executed_tree_reaches_its_own_figures() { .to_execution_plan( [frame(&up), frame(&info), frame(&up), frame(&threshold)] .into_iter() - .map(|batch| { - ( - memory_exec(vec![batch]), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ) - }) + .map(|batch| explicit(memory_exec(vec![batch]))) .collect(), ) .expect("the tree runs"); @@ -4501,13 +4517,7 @@ async fn displayed_tree_of( .to_execution_plan( sources .into_iter() - .map(|batches| { - ( - memory_exec(batches), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ) - }) + .map(|batches| explicit(memory_exec(batches))) .collect(), ) .expect("the tree runs"); @@ -4836,11 +4846,7 @@ fn repeated_source_bindings_validate_fields_and_second_ordering() { ); let node = fused(second_ordering); let error = node - .to_execution_plan(vec![( - memory_exec(Vec::new()), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + .to_execution_plan(vec![explicit(memory_exec(Vec::new()))]) .expect_err("the second repeated leaf's incompatible ordering is rejected"); assert!(error.to_string().contains("ordering"), "{error}"); } @@ -4911,11 +4917,7 @@ async fn contiguous_raw_input_runs_rate_directly_at_any_width() { ] { let input = memory_exec_partitioned_with(frame_schema(), partitions); let exec = fused(rate_tree()) - .to_execution_plan(vec![( - input, - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + .to_execution_plan(vec![explicit(input)]) .unwrap(); assert!( exec.children()[0] @@ -5047,18 +5049,7 @@ async fn logical_two_source_tree_is_accepted_by_physical_adapter() { }) as Arc }; let plan = node - .to_execution_plan(vec![ - ( - source(), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - source(), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ]) + .to_execution_plan(vec![explicit(source()), explicit(source())]) .expect("the physical boundary accepts independent source bindings"); assert_eq!(2, plan.children().len()); let results = collect(Arc::clone(&plan), SessionContext::default().task_ctx()) @@ -5122,16 +5113,8 @@ async fn matching_parallelism_uses_configured_width_without_changing_rows() { .unwrap(); let mk_inputs = |left_parts: Vec>, right_parts: Vec>| { vec![ - ( - memory_exec_partitioned(left_parts), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - memory_exec_partitioned(right_parts), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), + explicit(memory_exec_partitioned(left_parts)), + explicit(memory_exec_partitioned(right_parts)), ] }; let left = frame(&series_chunk("web-1", &[(GRID_START, 3.0)], true)); @@ -5237,10 +5220,7 @@ async fn independent_sources_execute_all_partitions() { ) .unwrap(); let exec = node - .to_execution_plan(vec![ - (left, RawLabelSource::Explicit, SeriesOrdering::Contiguous), - (right, RawLabelSource::Explicit, SeriesOrdering::Contiguous), - ]) + .to_execution_plan(vec![explicit(left), explicit(right)]) .unwrap(); assert_eq!(3, exec.properties().output_partitioning().partition_count()); let results = collect(Arc::clone(&exec), SessionContext::default().task_ctx()) @@ -5307,18 +5287,7 @@ async fn both_inputs_are_read_concurrently() { ) .unwrap(); let exec = node - .to_execution_plan(vec![ - ( - fed(left_rx), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - fed(right_rx), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ]) + .to_execution_plan(vec![explicit(fed(left_rx)), explicit(fed(right_rx))]) .unwrap(); let results = tokio::time::timeout( std::time::Duration::from_secs(5), @@ -5360,10 +5329,7 @@ async fn binary_output_tags_are_projected_but_raw_binding_is_full() { true, ))]); let exec = node - .to_execution_plan(vec![ - (left, RawLabelSource::Explicit, SeriesOrdering::Contiguous), - (right, RawLabelSource::Explicit, SeriesOrdering::Contiguous), - ]) + .to_execution_plan(vec![explicit(left), explicit(right)]) .unwrap(); let results = collect(exec, SessionContext::default().task_ctx()) .await @@ -5376,10 +5342,18 @@ async fn binary_output_tags_are_projected_but_raw_binding_is_full() { ); } -/// Empty earlier sources do not stop later sources, and one-to-one matching can yield no rows. +/// An empty first source does not end the gather: with `fill(0)` for the missing left side, the +/// second source's series still yields `0 - 2`. #[tokio::test] async fn empty_first_source_does_not_end_gather_early() { - let tree = binary_tree_over_sources(BinaryOp::Sub, raw_schema(), raw_schema(), 0, 1); + let mut root = binary_tree_over_sources(BinaryOp::Sub, raw_schema(), raw_schema(), 0, 1) + .root() + .clone(); + let NativeExpr::Binary { matching, .. } = &mut root.expr else { + unreachable!("the helper builds a binary root"); + }; + matching.fill.lhs = Some(0.0); + let tree = NativeTree::try_new(root).unwrap(); let node = FusedSeries::try_new( Arc::from("left - right"), tree.clone(), @@ -5394,19 +5368,12 @@ async fn empty_first_source_does_not_end_gather_early() { true, ))]); let exec = node - .to_execution_plan(vec![ - ( - memory_exec(Vec::new()), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - (second, RawLabelSource::Explicit, SeriesOrdering::Contiguous), - ]) + .to_execution_plan(vec![explicit(memory_exec(Vec::new())), explicit(second)]) .unwrap(); let results = collect(exec, SessionContext::default().task_ctx()) .await .unwrap(); - assert!(rows(&results).is_empty()); + assert_eq!(vec![-2.0], binary_values(&results)); } /// A multiparty gather requires Contiguous input, not global KeyThenTime ordering. @@ -5431,11 +5398,7 @@ fn multiparty_gather_rejects_key_then_time_leaf_requirement() { RawLabelSource::Explicit, SeriesOrdering::KeyThenTime, ), - ( - memory_exec_partitioned(vec![vec![], vec![]]), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), + explicit(memory_exec_partitioned(vec![vec![], vec![]])), ]) .expect_err("concatenated partitions are not globally KeyThenTime"); assert!(error.to_string().contains("ordering"), "{error}"); @@ -5478,10 +5441,7 @@ async fn later_source_error_drops_all_gathered_inputs() { ) }); let exec = node - .to_execution_plan(vec![ - (left, RawLabelSource::Explicit, SeriesOrdering::Contiguous), - (right, RawLabelSource::Explicit, SeriesOrdering::Contiguous), - ]) + .to_execution_plan(vec![explicit(left), explicit(right)]) .unwrap(); let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); let mut stream = exec.execute(0, task_context(&pool)).unwrap(); @@ -5828,13 +5788,7 @@ fn physical_plan_requires_matching_source_count() { assert!(zero.to_string().contains("count") || zero.to_string().contains("source")); let source = memory_exec(Vec::new()); - let tuple = || { - ( - Arc::clone(&source), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ) - }; + let tuple = || explicit(Arc::clone(&source)); let many = node .to_execution_plan(vec![tuple(), tuple()]) .expect_err("physical input count differs from the tree's source count"); @@ -6407,16 +6361,9 @@ async fn repeated_source_runs_once_per_partition_with_ordered_operands() { /// The optimizer inserts no exchange between a two-partition scan and this node. /// -/// This is the claim the whole arrangement rests on, so it is checked against the real rule rather -/// than against the flags that are supposed to satisfy it: a plan that reports the right -/// requirements can still be repartitioned, and that is exactly how the previous `KeyPartitioned` -/// requirement failed - a hash requirement is classed as necessary for any child with more than one -/// partition, so a hash exchange was inserted even though the child already satisfied it. -/// -/// The input here is a two-partition source, and `target_partitions` is raised above it because -/// that is when an optimizer is most willing to repartition. Both are the conditions under which the -/// old requirement broke, so a plan that survives them is one where the guarantee the scan makes -/// arrives at this node intact. +/// Checked against the real rule rather than the declared requirements: `EnsureRequirements` treats +/// a hash requirement as necessary for any child with more than one partition. `target_partitions` +/// is raised above the input's two partitions, where the rule is most willing to repartition. #[test] fn the_optimizer_inserts_no_exchange_between_the_input_and_this_node() { let exec = plan( @@ -6445,9 +6392,8 @@ fn the_optimizer_inserts_no_exchange_between_the_input_and_this_node() { "the optimizer inserted {exchanges:?} between the input and the node, and an exchange \ reorders a series' chunks: the node would close a series it has not finished" ); - // No exchange is not the same as no change: a rule that raised the count some other way would - // The count is the input's, which is what the node reports and what it - // runs one evaluator per. + // No exchange is not the same as no change: the node must keep the input's partition count, + // which is what it runs one evaluator per. assert_eq!( 2, optimized @@ -6566,21 +6512,10 @@ async fn a_partition_past_the_inputs_count_is_refused() { ); } -/// Binding ordering includes field names, while schema ordering refuses unequal DF schemas. +/// Nodes that differ only in their output schema are neither equal nor ordered equal. #[test] -fn unequal_binding_and_output_schema_are_not_ordered_equal() { +fn unequal_output_schemas_are_not_ordered_equal() { let tree = rate_tree(); - let left = binding(&tree); - let other_schema = Arc::new(SeriesSchema { - fields: Arc::from([FieldSpec { - name: "different".into(), - }]), - eval_grid: None, - }); - let right = binding_of(&tree, other_schema, left.tags.clone()); - assert_eq!(left, right); - assert_eq!(Some(std::cmp::Ordering::Equal), left.partial_cmp(&right)); - let left_node = fused(tree.clone()); let nullability_changed = Arc::new(Schema::new(vec![ Field::new(VALUE, DataType::Float64, false), @@ -7059,7 +6994,7 @@ fn partial_node(kind: AggregateKind) -> FusedSeries { FusedSeries::try_new_with_format( Arc::from(PROMQL), tree.clone(), - binding_of(&tree, raw_schema(), vec![HOST.to_string()]), + binding_of(&tree, vec![HOST.to_string()]), vec![input_plan(frame_schema())], schema, FusedOutputFormat::SeriesFrame, @@ -7080,20 +7015,12 @@ fn partial_plan( FusedSeries::try_new_with_format( Arc::from(PROMQL), tree.clone(), - binding_of( - &tree, - raw_schema(), - tags.iter().map(|s| s.to_string()).collect(), - ), + binding_of(&tree, tags.iter().map(|s| s.to_string()).collect()), vec![input_plan(frame_schema())], canonical_state_frame_schema(&tree), FusedOutputFormat::SeriesFrame, )? - .to_execution_plan(vec![( - input, - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + .to_execution_plan(vec![explicit(input)]) } /// Reads the output state frames for one partition and validates their declared binding. @@ -7146,7 +7073,7 @@ async fn a_state_export_keys_its_labels_by_the_cut_aggregate_grouping() { Arc::from(PROMQL), tree.clone(), // The scan is bound with `host`; the aggregate groups by `job`. - binding_of(&tree, raw_schema(), vec![HOST.to_string()]), + binding_of(&tree, vec![HOST.to_string()]), vec![input_plan(frame_schema())], canonical_state_frame_schema(&tree), FusedOutputFormat::SeriesFrame, @@ -7155,11 +7082,9 @@ async fn a_state_export_keys_its_labels_by_the_cut_aggregate_grouping() { let labels = [(HOST, "web-0"), (JOB, "shared")]; let rows = series_samples(1.0); let exec = node - .to_execution_plan(vec![( - memory_exec(vec![frame(&labelled_chunk("web-0", &labels, &rows, true))]), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + .to_execution_plan(vec![explicit(memory_exec(vec![frame(&labelled_chunk( + "web-0", &labels, &rows, true, + ))]))]) .expect("the state export is executable"); let states = decode_state_batches(state_batches(&exec, 0).await).await; let tags = states @@ -7271,10 +7196,6 @@ async fn a_partial_root_exports_state_frames_from_every_partition() { } /// A state export releases everything it held: when drained, and when the consumer drops it early. -/// -/// This is lifecycle coverage, not the regression for the producer hand-off: other reservations are -/// alive at the same moment, so a positive figure here would not by itself prove the batch is the -/// charged one. `a_handed_state_chunk_holds_its_charge_until_it_is_dropped` owns that claim. #[tokio::test] async fn a_state_export_releases_its_charge_on_drain_and_on_early_drop() { const GROUPS: usize = 600; @@ -7507,11 +7428,7 @@ async fn mixed_raw_and_evaluated_inputs_execute_with_source_local_decoders() { let exec = FusedSeries::try_new( Arc::from("mixed raw/evaluated"), tree.clone(), - binding_of( - &tree, - raw_schema(), - vec![HOST.to_string(), NAME.to_string()], - ), + binding_of(&tree, vec![HOST.to_string(), NAME.to_string()]), vec![ input_plan(frame_schema()), input_plan(evaluated_frame_schema.clone()), @@ -7520,16 +7437,8 @@ async fn mixed_raw_and_evaluated_inputs_execute_with_source_local_decoders() { ) .unwrap() .to_execution_plan(vec![ - ( - memory_exec(raw_batches), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - memory_exec_with(evaluated_frame_schema, evaluated_batches), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), + explicit(memory_exec(raw_batches)), + explicit(memory_exec_with(evaluated_frame_schema, evaluated_batches)), ]) .unwrap(); let mut actual = rows( @@ -7799,15 +7708,7 @@ fn series_frame_output_schema_matches_evaluated_packer() { #[tokio::test] async fn series_frame_output_uses_evaluated_codec_schema() { let tree = rate_tree(); - let frame_node = FusedSeries::try_new_with_format( - Arc::from(PROMQL), - tree.clone(), - binding(&tree), - vec![input_plan(frame_schema())], - canonical_frame_schema(&tree), - FusedOutputFormat::SeriesFrame, - ) - .expect("evaluated samples have a frame schema"); + let frame_node = frame_node(&tree); assert!( frame_node .schema() @@ -7852,16 +7753,8 @@ fn series_frame_accepts_multiple_sources_with_equal_partition_counts() { .unwrap(); let plan = node .to_execution_plan(vec![ - ( - memory_exec_partitioned(vec![vec![], vec![]]), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - memory_exec_partitioned(vec![vec![], vec![]]), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), + explicit(memory_exec_partitioned(vec![vec![], vec![]])), + explicit(memory_exec_partitioned(vec![vec![], vec![]])), ]) .expect("equal source partition counts are accepted"); assert_eq!(2, plan.properties().partitioning.partition_count()); @@ -7880,15 +7773,7 @@ async fn series_frame_preserves_four_input_partitions() { }) .collect::>(); let tree = rate_tree(); - let node = FusedSeries::try_new_with_format( - Arc::from(PROMQL), - tree.clone(), - binding(&tree), - vec![input_plan(frame_schema())], - canonical_frame_schema(&tree), - FusedOutputFormat::SeriesFrame, - ) - .unwrap(); + let node = frame_node(&tree); let exec = plan_of(node, memory_exec_partitioned(partitions)).unwrap(); assert_eq!(4, exec.properties().partitioning.partition_count()); let schema = exec.schema(); @@ -7920,72 +7805,6 @@ async fn series_frame_preserves_four_input_partitions() { assert_eq!(4, closes); } -/// PlainRows and SeriesFrame encode precisely the same rate values, timestamps and labels. -#[tokio::test] -async fn series_frame_rate_matches_plain_rows_bitwise() { - let input = memory_exec(two_series_frames()); - let plain = plan(rate_tree(), Arc::clone(&input)).unwrap(); - let plain_rows = rows( - &collect(plain, SessionContext::default().task_ctx()) - .await - .unwrap(), - ); - let tree = rate_tree(); - let node = FusedSeries::try_new_with_format( - Arc::from(PROMQL), - tree.clone(), - binding(&tree), - vec![input_plan(frame_schema())], - canonical_frame_schema(&tree), - FusedOutputFormat::SeriesFrame, - ) - .unwrap(); - let exec = plan_of(node, input).unwrap(); - let batches = collect(exec.clone(), SessionContext::default().task_ctx()) - .await - .unwrap(); - assert!(batches.iter().all(|batch| batch.schema() == exec.schema())); - let stream = Box::pin(RecordBatchStreamAdapter::new( - exec.schema(), - futures::stream::iter(batches.into_iter().map(Ok)), - )); - let decoded = unpack_evaluated_series(stream, None) - .unwrap() - .try_collect::>() - .await - .unwrap(); - let mut frame_rows = Vec::new(); - for (series, _) in decoded { - let timestamps = series.time.timestamps().unwrap(); - let samples = series.fields.get(0).unwrap(); - for (row, timestamp) in timestamps.iter().enumerate() { - let value = samples.iter().nth(row).unwrap(); - let datatypes::series::samples::SampleRef::Float(value) = value else { - panic!("float sample expected") - }; - frame_rows.push(( - *timestamp, - value.to_bits(), - series.metric.get(HOST).map(str::to_owned), - series.metric.name().map(str::to_owned), - )); - } - } - let mut expected = plain_rows - .into_iter() - .map(|(time, value, host, name)| (time, value.map(f64::to_bits), host, name)) - .collect::>(); - frame_rows.sort(); - expected.sort(); - assert_eq!( - expected, - frame_rows - .into_iter() - .map(|(time, bits, host, name)| (time, Some(bits), host, name)) - .collect::>() - ); -} - /// An empty Partial input ends cleanly while retaining the declared state-frame schema. #[tokio::test] async fn partial_empty_input_yields_valid_empty_state_frame_stream() { @@ -8252,15 +8071,7 @@ async fn a_pending_input_does_not_hold_the_rows_a_frame_buffered() { .await .expect("the stream resumes where the pending poll left it"), ); - let stream = Box::pin(RecordBatchStreamAdapter::new( - declared, - futures::stream::iter(answered.into_iter().map(Ok)), - )); - let decoded = unpack_evaluated_series(stream, None) - .expect("the node declares the frame it yields") - .try_collect::>() - .await - .expect("every batch of the frame decodes"); + let decoded = decode_frames(declared, answered).await; assert_eq!( 1, decoded.iter().filter(|(_, last)| *last).count(), @@ -8362,15 +8173,13 @@ async fn a_frame_carries_the_closing_chunk_a_row_table_drops() { true, ); let tree = rate_tree(); - let node = FusedSeries::try_new_with_format( - Arc::from(PROMQL), - tree.clone(), - binding(&tree), - vec![input_plan(frame_schema())], - canonical_frame_schema(&tree), - FusedOutputFormat::SeriesFrame, - ) - .expect("a rate tree is evaluated on a grid"); + // One runtime input takes the chunk, so the push moves it instead of cloning it. + let execution = + NativeExecutionState::try_new(&tree, Arc::new(UnboundedMemoryPool::default()), None) + .expect("a rate tree has a runtime"); + assert_eq!(1, execution.input_ids(0).count()); + drop(execution); + let node = frame_node(&tree); let exec = plan_of(node, memory_exec(vec![frame_of(&schema, &chunk)])) .expect("the runtime executes the tree"); let declared = exec.schema(); @@ -8383,15 +8192,7 @@ async fn a_frame_carries_the_closing_chunk_a_row_table_drops() { .all(|batch| batch.schema().as_ref() == declared.as_ref()), "every batch carries the declared schema" ); - let stream = Box::pin(RecordBatchStreamAdapter::new( - declared, - futures::stream::iter(batches.into_iter().map(Ok)), - )); - let decoded = unpack_evaluated_series(stream, None) - .expect("the node declares the frame it yields") - .try_collect::>() - .await - .expect("the frame decodes"); + let decoded = decode_frames(declared, batches).await; assert_eq!( 1, @@ -8420,78 +8221,6 @@ async fn a_frame_carries_the_closing_chunk_a_row_table_drops() { ); } -/// The one runtime input takes the empty closing chunk by value and its frame keeps it. -/// -/// A single-consumer push moves the chunk into the executor rather than cloning it, so this is the -/// chunk a move could lose: it carries no grid position at all, and the tree binds exactly one -/// runtime input to take it. -#[tokio::test] -async fn a_single_consumer_keeps_the_empty_closing_chunk_in_its_frame() { - let schema = raw_schema(); - // Every sample is newer than the last grid point, so `rate` decides nothing at any of them and - // the series closes with a chunk that carries no position. - let late = [(GRID_START + RANGE_MS + SAMPLE_STEP, 1.0)]; - let chunk = chunk_of( - &schema, - "late", - metric(&[(HOST, "late")], Some(METRIC)), - &late.iter().map(|(time, _)| *time).collect::>(), - vec![late.iter().map(|(_, value)| Some(*value)).collect()], - true, - ); - let tree = rate_tree(); - // The shape the push moves for: one source bound to one runtime input. - let execution = - NativeExecutionState::try_new(&tree, Arc::new(UnboundedMemoryPool::default()), None) - .expect("a rate tree has a runtime"); - assert_eq!( - 1, - execution.input_ids(0).count(), - "one runtime input takes the closing chunk" - ); - drop(execution); - - let node = FusedSeries::try_new_with_format( - Arc::from(PROMQL), - tree.clone(), - binding(&tree), - vec![input_plan(frame_schema())], - canonical_frame_schema(&tree), - FusedOutputFormat::SeriesFrame, - ) - .expect("a rate tree is evaluated on a grid"); - let exec = plan_of(node, memory_exec(vec![frame_of(&schema, &chunk)])) - .expect("the runtime executes the tree"); - let declared = exec.schema(); - let batches = collect(exec, SessionContext::default().task_ctx()) - .await - .expect("the frame runs"); - let decoded = unpack_evaluated_series( - Box::pin(RecordBatchStreamAdapter::new( - declared, - futures::stream::iter(batches.into_iter().map(Ok)), - )), - None, - ) - .expect("the node declares the frame it yields") - .try_collect::>() - .await - .expect("the frame decodes"); - - assert_eq!( - 1, - decoded.len(), - "the closing chunk is one frame row, not a dropped chunk: {decoded:?}" - ); - let (series, is_last) = &decoded[0]; - assert!(is_last, "that row is the one that closes the chain"); - assert!( - series.time.is_empty(), - "it carries no grid position: {:?}", - series.time.positions().collect::>() - ); -} - /// Two chains that close on one label set are both emitted, each closing itself. /// /// A range function drops the metric name, so two different raw series can reach the output under the @@ -8519,15 +8248,7 @@ async fn two_chains_that_close_on_one_label_set_each_keep_their_frame() { vec![frame_of(&schema, &chunk_of_host("web-2", 2.0))], ]; let tree = rate_tree(); - let node = FusedSeries::try_new_with_format( - Arc::from(PROMQL), - tree.clone(), - binding(&tree), - vec![input_plan(frame_schema())], - canonical_frame_schema(&tree), - FusedOutputFormat::SeriesFrame, - ) - .expect("a rate tree is evaluated on a grid"); + let node = frame_node(&tree); let exec = plan_of(node, memory_exec_partitioned(partitions)).expect("the runtime executes the tree"); assert_eq!( @@ -8539,17 +8260,7 @@ async fn two_chains_that_close_on_one_label_set_each_keep_their_frame() { let batches = collect(exec, SessionContext::default().task_ctx()) .await .expect("both chains are legal"); - let decoded = unpack_evaluated_series( - Box::pin(RecordBatchStreamAdapter::new( - declared, - futures::stream::iter(batches.into_iter().map(Ok)), - )), - None, - ) - .expect("the node declares the frame it yields") - .try_collect::>() - .await - .expect("the frame decodes"); + let decoded = decode_frames(declared, batches).await; assert_eq!( 2, @@ -8678,16 +8389,8 @@ fn duplicate_evidence_partitioned_exec( .expect("the tree binds to its two physical sources"); let exec = node .to_execution_plan(vec![ - ( - memory_exec_partitioned(left_partitions), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), - ( - memory_exec_partitioned(right_partitions), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - ), + explicit(memory_exec_partitioned(left_partitions)), + explicit(memory_exec_partitioned(right_partitions)), ]) .expect("two-source binary runs over partitioned inputs"); assert_eq!(2, exec.properties().partitioning.partition_count()); @@ -9092,31 +8795,11 @@ async fn histogram_split_carries_a_rewrite_above_the_histogram() { ]), ]; let reference_frames = [partitions[0].clone(), partitions[1].clone()].concat(); - let partial_node = FusedSeries::try_new_state_export( - Arc::from("partial"), - partial.clone(), - binding(&partial), - vec![input_plan(frame_schema())], - ) - .unwrap(); + let partial_node = state_export_node(&partial); let producer = partial_node - .to_execution_plan(vec![( - memory_exec_partitioned(partitions), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + .to_execution_plan(vec![explicit(memory_exec_partitioned(partitions))]) .unwrap(); - let final_node = FusedSeries::try_new_with_format( - Arc::from("final"), - final_tree.clone(), - binding(&final_tree), - vec![input_plan( - canonical_state_frame_schema(&partial).inner().clone(), - )], - canonical_frame_schema(&final_tree), - FusedOutputFormat::SeriesFrame, - ) - .unwrap(); + let final_node = final_node(&partial, &final_tree); let split = plan_of(final_node, producer).unwrap(); let reference_node = FusedSeries::try_new_with_format( Arc::from("reference"), @@ -9128,20 +8811,7 @@ async fn histogram_split_carries_a_rewrite_above_the_histogram() { ) .unwrap(); let reference = plan_of(reference_node, memory_exec(reference_frames)).unwrap(); - let decode = |batches: Vec| async move { - let schema = batches[0].schema(); - unpack_evaluated_series( - Box::pin(RecordBatchStreamAdapter::new( - schema, - futures::stream::iter(batches.into_iter().map(Ok)), - )), - None, - ) - .unwrap() - .try_collect::>() - .await - .unwrap() - }; + let decode = |batches: Vec| decode_frames(batches[0].schema(), batches); let answers = |decoded: &[(Series, bool)]| { let mut rows = decoded .iter() @@ -9521,19 +9191,12 @@ fn histogram_final_replaces_incompatible_state_router() { ] { let tree = histogram_over_sum_tree(group, HistogramFunction::Quantile(0.5)); let (partial, final_tree) = FusedSeries::split_aggregate(&tree, TIME).unwrap().unwrap(); - let partial_node = FusedSeries::try_new_state_export( - Arc::from("partial"), - partial.clone(), - binding(&partial), - vec![input_plan(frame_schema())], - ) - .unwrap(); + let partial_node = state_export_node(&partial); let producer = partial_node - .to_execution_plan(vec![( - memory_exec_partitioned(vec![vec![], vec![]]), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + .to_execution_plan(vec![explicit(memory_exec_partitioned(vec![ + vec![], + vec![], + ]))]) .unwrap(); let old_router = Arc::new( SeriesRepartitionExec::try_new_with_routing( @@ -9543,23 +9206,10 @@ fn histogram_final_replaces_incompatible_state_router() { ) .unwrap(), ) as Arc; - let final_node = FusedSeries::try_new_with_format( - Arc::from("final"), - final_tree.clone(), - binding(&final_tree), - vec![input_plan( - canonical_state_frame_schema(&partial).inner().clone(), - )], - canonical_frame_schema(&final_tree), - FusedOutputFormat::SeriesFrame, - ) - .unwrap(); + let final_node = final_node(&partial, &final_tree); let build = |input| { final_node - .to_execution_plan_with_parallelism( - vec![(input, RawLabelSource::Explicit, SeriesOrdering::Contiguous)], - target_width, - ) + .to_execution_plan_with_parallelism(vec![explicit(input)], target_width) .unwrap() }; let plan = build(Arc::clone(&old_router)); @@ -9629,20 +9279,10 @@ async fn histogram_split_routes_whole_state_batches_and_preserves_each_bound() { ), ]), ]; - let partial_node = FusedSeries::try_new_state_export( - Arc::from("partial"), - partial.clone(), - binding(&partial), - vec![input_plan(frame_schema())], - ) - .unwrap(); + let partial_node = state_export_node(&partial); let make_partial = || { partial_node - .to_execution_plan(vec![( - memory_exec_partitioned(partitions.clone()), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + .to_execution_plan(vec![explicit(memory_exec_partitioned(partitions.clone()))]) .unwrap() }; let partial_exec = make_partial(); @@ -9676,25 +9316,12 @@ async fn histogram_split_routes_whole_state_batches_and_preserves_each_bound() { ]) ); } - let final_node = FusedSeries::try_new_with_format( - Arc::from("final"), - final_tree.clone(), - binding(&final_tree), - vec![input_plan( - canonical_state_frame_schema(&partial).inner().clone(), - )], - canonical_frame_schema(&final_tree), - FusedOutputFormat::SeriesFrame, - ) - .unwrap(); + let final_node = final_node(&partial, &final_tree); let execute = |width| { // Region exit is a one-output state router, which forwards whole packed batches. let region = Arc::new(SeriesRepartitionExec::try_new(make_partial(), 1).unwrap()); final_node - .to_execution_plan_with_parallelism( - vec![(region, RawLabelSource::Explicit, SeriesOrdering::Contiguous)], - width, - ) + .to_execution_plan_with_parallelism(vec![explicit(region)], width) .unwrap() }; let parallel = execute(8); @@ -9712,20 +9339,7 @@ async fn histogram_split_routes_whole_state_batches_and_preserves_each_bound() { 1 ); } - let decode = |batches: Vec| async move { - let schema = batches[0].schema(); - unpack_evaluated_series( - Box::pin(RecordBatchStreamAdapter::new( - schema, - futures::stream::iter(batches.into_iter().map(Ok)), - )), - None, - ) - .unwrap() - .try_collect::>() - .await - .unwrap() - }; + let decode = |batches: Vec| decode_frames(batches[0].schema(), batches); let got = decode( collect(parallel, SessionContext::default().task_ctx()) .await @@ -9822,57 +9436,19 @@ async fn histogram_split_colocates_metadata_distinct_results_before_their_merge( partitions[partition].push(frame(&item)); } } - let partial_node = FusedSeries::try_new_state_export( - Arc::from("partial"), - partial.clone(), - binding(&partial), - vec![input_plan(frame_schema())], - ) - .unwrap(); + let partial_node = state_export_node(&partial); let partial_exec = partial_node - .to_execution_plan(vec![( - memory_exec_partitioned(partitions), - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )]) + .to_execution_plan(vec![explicit(memory_exec_partitioned(partitions))]) .unwrap(); - let final_node = FusedSeries::try_new_with_format( - Arc::from("final"), - final_tree.clone(), - binding(&final_tree), - vec![input_plan( - canonical_state_frame_schema(&partial).inner().clone(), - )], - canonical_frame_schema(&final_tree), - FusedOutputFormat::SeriesFrame, - ) - .unwrap(); + let final_node = final_node(&partial, &final_tree); final_node - .to_execution_plan_with_parallelism( - vec![( - partial_exec, - RawLabelSource::Explicit, - SeriesOrdering::Contiguous, - )], - 8, - ) + .to_execution_plan_with_parallelism(vec![explicit(partial_exec)], 8) .unwrap() }; let output = collect(build(false), SessionContext::default().task_ctx()) .await .unwrap(); - let schema = output[0].schema(); - let series = unpack_evaluated_series( - Box::pin(RecordBatchStreamAdapter::new( - schema, - futures::stream::iter(output.into_iter().map(Ok)), - )), - None, - ) - .unwrap() - .try_collect::>() - .await - .unwrap(); + let series = decode_frames(output[0].schema(), output).await; let mut values = series .iter() .flat_map(|(series, _)| { @@ -10057,12 +9633,6 @@ fn summed_window_over(input: Arc) -> Arc { } /// Every owner `plan` publishes, read at once, with the chunks each of them handed over. -/// -/// Reading them together states the partitioned shape this node is part of: the routing decides -/// which owner an identity belongs to, so a caller claims every owner's stream and reads them as -/// one composition. The owners' queues are unbounded, so this is the shape being tested rather than -/// a requirement the read has to meet - draining one owner to its end before starting the next -/// would still see the same chunks. async fn owner_chunks(plan: &Arc) -> Vec> { let context = SessionContext::default().task_ctx(); let reads = (0..plan.properties().partitioning.partition_count()) @@ -11719,10 +11289,8 @@ fn two_group_state_producer() -> Arc { /// A group a reader keeps stays charged after the export that produced it is gone. /// -/// The reviewer's case, and the one the sibling above does not cover: a consumer polls a group, keeps -/// it, and then exhausts or drops the export. The reservation the export carried has to travel with -/// the group rather than stay in the stream, or reading to the end - or letting the stream go - would -/// release bytes the reader is still holding, and the pool would hand them to somebody else. +/// A consumer polls a group, keeps it, and then exhausts or drops the export. The reservation has to +/// travel with the group, or the pool would hand out bytes the reader still holds. /// /// The figures are read once the export and its producer are gone, so what the pool counts is the /// group's alone; the second figure is what that group holds by itself, so a reservation released diff --git a/src/promql/src/extension_plan/fused_series/tests/frame_output.rs b/src/promql/src/extension_plan/fused_series/tests/frame_output.rs index 3955c07f610..0c25a5c3c0c 100644 --- a/src/promql/src/extension_plan/fused_series/tests/frame_output.rs +++ b/src/promql/src/extension_plan/fused_series/tests/frame_output.rs @@ -46,23 +46,6 @@ fn instant_tree(schema: Arc, grid: Arc) -> NativeTree { .expect("instant selector tree is valid") } -async fn frame_decode( - exec: Arc, -) -> Vec<(datatypes::series::samples::Series, bool)> { - let batches = collect(Arc::clone(&exec), SessionContext::default().task_ctx()) - .await - .expect("frame output executes"); - let stream = Box::pin(RecordBatchStreamAdapter::new( - exec.schema(), - futures::stream::iter(batches.into_iter().map(Ok)), - )); - unpack_evaluated_series(stream, None) - .expect("evaluated frame schema decodes") - .try_collect::>() - .await - .expect("evaluated frame decodes") -} - fn compact_float_rows( decoded: &[(datatypes::series::samples::Series, bool)], ) -> Vec<(i64, Vec>)> { @@ -156,7 +139,7 @@ async fn sparse_instant_frame_preserves_positions_nulls_and_nan_across_formats() true, ); let batches = vec![frame_of(&schema, &chunk)]; - let binding = binding_of(&tree, Arc::clone(&schema), vec![HOST.into(), NAME.into()]); + let binding = binding_of(&tree, vec![HOST.into(), NAME.into()]); let make_node = |format| { FusedSeries::try_new_with_format( Arc::from("instant(x)"), @@ -202,9 +185,9 @@ async fn sparse_instant_frame_preserves_positions_nulls_and_nan_across_formats() } #[tokio::test] -async fn abs_rate_frame_matches_plain_rows_with_exact_values_and_labels() { +async fn rate_frame_matches_plain_rows_with_exact_values_and_labels() { let rate = rate_tree(); - let tree = NativeTree::try_new(NativeNode { + let abs_rate = NativeTree::try_new(NativeNode { expr: NativeExpr::Map { input: Box::new(rate.root().clone()), op: BoundMap { @@ -214,11 +197,17 @@ async fn abs_rate_frame_matches_plain_rows_with_exact_values_and_labels() { output: rate.root().output.clone(), }) .unwrap(); + for (promql, tree) in [("rate(x[5m])", rate), ("abs(rate(x[5m]))", abs_rate)] { + assert_frame_matches_plain_rows(promql, tree).await; + } +} + +async fn assert_frame_matches_plain_rows(promql: &'static str, tree: NativeTree) { let batches = two_series_frames(); let binding = binding(&tree); let make_node = |format| { FusedSeries::try_new_with_format( - Arc::from("abs(rate(x[5m]))"), + Arc::from(promql), tree.clone(), binding.clone(), vec![input_plan(frame_schema())], @@ -319,7 +308,7 @@ async fn rewritten_identical_labels_keep_disjoint_chains_in_one_encoder() { ), ]; let batches = frames_of(&schema, &chunks); - let binding = binding_of(&tree, Arc::clone(&schema), vec![HOST.into(), NAME.into()]); + let binding = binding_of(&tree, vec![HOST.into(), NAME.into()]); let make_node = |format| { FusedSeries::try_new_with_format( Arc::from("rewritten instant"), diff --git a/src/promql/src/extension_plan/series_repartition/tests.rs b/src/promql/src/extension_plan/series_repartition/tests.rs index 097d70133f2..fbd71787bd8 100644 --- a/src/promql/src/extension_plan/series_repartition/tests.rs +++ b/src/promql/src/extension_plan/series_repartition/tests.rs @@ -12,25 +12,10 @@ // 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. +//! The children here are scripted [`TestChild`]s: each partition answers a list of steps, so a test +//! states which series a chunk belongs to, where it sits on the grid and whether it closes the series. +//! Frames are packed and unpacked by the helpers the real path uses. Timing-dependent properties use +//! partitions that stay silent until the test opens a [`Switch`], rather than sleeps. use std::pin::Pin; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; @@ -78,7 +63,6 @@ use crate::native::execute::merge_workspace_bytes; use crate::vector_match::MatchingLabels; use common_query::series_frame::pack_raw_series; -const TEST_FIXTURE_VOLUME: usize = 4; const GRID_START: i64 = 0; const GRID_STEP: i64 = 1_000; const GRID_LEN: u64 = 256; @@ -245,7 +229,7 @@ async fn public_frame_retains_large_series_charge_until_remainder_is_dropped() { .collect(); let probe_pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); let probe_context = task_context(&probe_pool); - let probe = Scripted::plan_with_schema(vec![steps.clone()], Arc::clone(&series_schema)); + let probe = scripted_with_schema(vec![steps.clone()], Arc::clone(&series_schema)); let mut probe = unpack_evaluated_series(probe.execute(0, probe_context).unwrap(), None).unwrap(); let (decoded, errors) = until_end(&mut probe).await; @@ -275,7 +259,7 @@ async fn public_frame_retains_large_series_charge_until_remainder_is_dropped() { let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); let context = task_context(&pool); let plan = node( - Scripted::plan_with_schema(vec![steps.clone()], Arc::clone(&series_schema)), + scripted_with_schema(vec![steps.clone()], Arc::clone(&series_schema)), 1, ); let mut frames = plan.execute(0, Arc::clone(&context)).unwrap(); @@ -306,7 +290,7 @@ async fn public_frame_retains_large_series_charge_until_remainder_is_dropped() { let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); let context = task_context(&pool); - let plan = node(Scripted::plan_with_schema(vec![steps], series_schema), 1); + let plan = node(scripted_with_schema(vec![steps], series_schema), 1); let mut frames = plan.execute(0, Arc::clone(&context)).unwrap(); let mut retained_frames = Vec::new(); while let Some(frame) = futures::future::poll_fn(|cx| frames.as_mut().poll_next(cx)).await { @@ -361,12 +345,8 @@ async fn public_frame_retains_large_series_charge_until_remainder_is_dropped() { /// The charge of a handed-over chunk is released with the chunk. /// -/// The frame path keeps an owner's reservation in the packer's handoff until the batch it backs is -/// flushed; a chunk handed over in process has no packer, so the reservation travels with the value -/// instead. Both halves of that are asserted here: while a consumer holds the chunk the pool still -/// holds its bytes, so it cannot hand them out twice, and the moment the consumer drops the chunk -/// they are back. A release that ran early would let the pool over-commit; one that never ran would -/// leak the read - `drop` is the whole of what has to happen, so neither can hide behind a call. +/// A chunk handed over in process has no packer to hold its reservation, so the reservation travels +/// with the value: the pool holds the bytes while the consumer holds the chunk, and not after. #[tokio::test] async fn a_handed_chunk_holds_its_charge_until_it_is_dropped() { const FRAGMENTS: usize = 257; @@ -398,7 +378,7 @@ async fn a_handed_chunk_holds_its_charge_until_it_is_dropped() { let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); let context = task_context(&pool); let plan = node( - Scripted::plan_with_schema(vec![steps], Arc::clone(&series_schema)), + scripted_with_schema(vec![steps], Arc::clone(&series_schema)), 1, ); let mut chunks = series_execution_plan(plan.as_ref()) @@ -496,74 +476,75 @@ fn step_answer(step: Step) -> Result<(Series, bool), BoxedError> { } } -/// The steps of one partition, as the frame stream that hands them over. -struct Script { - steps: std::vec::IntoIter, -} +type OpenPartition = + dyn Fn(usize) -> DataFusionResult + Send + Sync + 'static; -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, +/// A leaf child whose partition `i` is the frame stream `open(i)` returns. +struct TestChild { + open: Box, properties: Arc, } -impl Scripted { - /// The child plan over `steps`, one partition per list. - fn plan(steps: Vec>) -> Arc { - Self::plan_with_schema(steps, schema()) +impl TestChild { + fn plan( + frame: SchemaRef, + partitions: usize, + open: impl Fn(usize) -> DataFusionResult + Send + Sync + 'static, + ) -> Arc { + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(frame), + Partitioning::UnknownPartitioning(partitions), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Arc::new(Self { + open: Box::new(open), + properties, + }) } - /// The child plan over `steps` with an explicitly declared evaluated frame schema. - fn plan_with_schema( - steps: Vec>, + /// A child over evaluated frames of `series_schema`; partition `i` packs `open(i)`. + fn evaluated( series_schema: Arc, - ) -> Arc { + partitions: usize, + open: impl Fn(usize) -> S + Send + Sync + 'static, + ) -> Arc + where + S: Stream> + Send + 'static, + { 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, + Self::plan(frame, partitions, move |partition| { + pack_evaluated_series(Box::pin(open(partition)), Arc::clone(&series_schema)) }) } + + fn partitions(&self) -> usize { + self.properties.partitioning.partition_count() + } } -impl fmt::Debug for Scripted { +impl fmt::Debug for TestChild { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - f.debug_struct("Scripted") - .field("partitions", &self.steps.len()) + f.debug_struct("TestChild") + .field("partitions", &self.partitions()) .finish() } } -impl DisplayAs for Scripted { +impl DisplayAs for TestChild { fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { - write!(f, "Scripted: partitions={}", self.steps.len()) + write!(f, "TestChild: partitions={}", self.partitions()) } } -impl ExecutionPlan for Scripted { +impl ExecutionPlan for TestChild { fn name(&self) -> &str { - "Scripted" + "TestChild" } fn properties(&self) -> &Arc { @@ -585,7 +566,7 @@ impl ExecutionPlan for Scripted { self: Arc, children: Vec>, ) -> DataFusionResult> { - assert!(children.is_empty(), "a scripted child has no children"); + assert!(children.is_empty(), "a test child has no children"); Ok(self) } @@ -594,18 +575,29 @@ impl ExecutionPlan for Scripted { 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), - ) + if partition >= self.partitions() { + return Err(DataFusionError::Execution(format!( + "test child has no partition {partition}" + ))); + } + (self.open)(partition) } } +/// A child whose partitions answer `steps`, one partition per list. +fn scripted(steps: Vec>) -> Arc { + scripted_with_schema(steps, schema()) +} + +fn scripted_with_schema( + steps: Vec>, + series_schema: Arc, +) -> Arc { + TestChild::evaluated(series_schema, steps.len(), move |partition| { + futures::stream::iter(steps[partition].clone().into_iter().map(step_answer)) + }) +} + /// 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() @@ -725,9 +717,39 @@ fn raw_metric(host: &str) -> SeriesLabels { struct RawPartition { chunks: Vec, gate: Option>, + /// Whether the gate also holds the chunks, not only the end. gate_chunks: bool, } +impl RawPartition { + /// Hands `chunks` over and ends. + fn new(chunks: Vec) -> Self { + Self { + chunks, + gate: None, + gate_chunks: false, + } + } + + /// Hands `chunks` over, then holds its end until `gate` opens. + fn open_until(chunks: Vec, gate: &Arc) -> Self { + Self { + chunks, + gate: Some(Arc::clone(gate)), + gate_chunks: false, + } + } + + /// Hands nothing over, not even its end, until `gate` opens. + fn held_by(chunks: Vec, gate: &Arc) -> Self { + Self { + chunks, + gate: Some(Arc::clone(gate)), + gate_chunks: true, + } + } +} + struct RawScript { chunks: std::vec::IntoIter, schema: Arc, @@ -737,7 +759,6 @@ struct RawScript { ordering: SeriesOrdering, gate: Option>, gate_chunks: bool, - fail_after_gate: bool, } impl Stream for RawScript { @@ -759,11 +780,6 @@ impl Stream for RawScript { gate.wait(cx); return Poll::Pending; } - if std::mem::take(&mut self.fail_after_gate) { - return Poll::Ready(Some(Err(boxed(DataFusionError::Execution( - "late raw scripted failure".into(), - ))))); - } Poll::Ready(None) } } @@ -783,147 +799,57 @@ impl RawSeriesStream for RawScript { } } -/// A child whose partitions hand over raw chunks, one partition per list. -struct RawScripted { +/// A child whose partitions hand over raw chunks with explicit labels. +fn raw_scripted(partitions: Vec) -> Arc { + raw_scripted_with_ordering(partitions, SeriesOrdering::Contiguous) +} + +fn raw_scripted_with_ordering( + partitions: Vec, + ordering: SeriesOrdering, +) -> Arc { + let frame = common_query::series_frame::raw_series_frame_schema_with_ordering( + &raw_schema(), + &RawLabelSource::Explicit, + ordering, + ) + .expect("a raw schema declares an explicit-label frame"); + raw_child(frame, partitions, None, ordering) +} + +/// A child whose frames name their labels by their key, as a region's scan does. +fn raw_keyed(partitions: Vec) -> Arc { + let decode = host_decode(); + let frame = common_query::series_frame::frame_schema_with( + &raw_schema(), + FrameLabelMode::Key, + Some(&decode), + SeriesOrdering::KeyThenTime, + ) + .expect("a key schema declares a key frame and its ordering"); + raw_child(frame, partitions, Some(decode), SeriesOrdering::KeyThenTime) +} + +/// The stream's ordering must match the plan's frame: the sequence validator and the receiver both +/// read it off the frame. +fn raw_child( + frame: SchemaRef, partitions: Vec, - series_schema: Arc, decode: Option, ordering: SeriesOrdering, - fail_after_gate: bool, - properties: Arc, -} - -impl RawScripted { - fn plan(partitions: Vec) -> Arc { - Self::plan_with_ordering(partitions, SeriesOrdering::Contiguous) - } - - /// The child over `partitions` declaring `ordering` for its keys. - fn plan_with_ordering( - partitions: Vec, - ordering: SeriesOrdering, - ) -> Arc { - Self::plan_with_ordering_and_failure(partitions, ordering, false) - } - - fn plan_with_ordering_and_failure( - partitions: Vec, - ordering: SeriesOrdering, - fail_after_gate: bool, - ) -> Arc { - let series_schema = raw_schema(); - let frame = common_query::series_frame::raw_series_frame_schema_with_ordering( - &series_schema, - &store_api::region_engine::RawLabelSource::Explicit, - ordering, - ) - .expect("a raw schema declares an explicit-label frame"); - let properties = Arc::new(PlanProperties::new( - EquivalenceProperties::new(frame), - Partitioning::UnknownPartitioning(partitions.len()), - EmissionType::Incremental, - Boundedness::Bounded, - )); - Arc::new(Self { - partitions, - series_schema, - decode: None, - ordering, - fail_after_gate, - properties, - }) - } - - /// The child over `partitions` whose frames name their labels by their key instead. - /// - /// This is what a region hands the node when it scanned the series itself, so a test that - /// routes by labels has to start from it rather than from an already-labelled frame. - fn plan_keyed(partitions: Vec) -> Arc { - let series_schema = raw_schema(); - let decode = host_decode(); - let frame = common_query::series_frame::frame_schema_with( - &series_schema, - FrameLabelMode::Key, - Some(&decode), - SeriesOrdering::KeyThenTime, - ) - .expect("a key schema declares a key frame and its ordering"); - let properties = Arc::new(PlanProperties::new( - EquivalenceProperties::new(frame), - Partitioning::UnknownPartitioning(partitions.len()), - EmissionType::Incremental, - Boundedness::Bounded, - )); - Arc::new(Self { - partitions, - series_schema, - decode: Some(decode), - ordering: SeriesOrdering::KeyThenTime, - fail_after_gate: false, - properties, - }) - } -} - -impl fmt::Debug for RawScripted { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - f.debug_struct("RawScripted") - .field("partitions", &self.partitions.len()) - .finish() - } -} - -impl DisplayAs for RawScripted { - fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result { - write!(f, "RawScripted: partitions={}", self.partitions.len()) - } -} - -impl ExecutionPlan for RawScripted { - fn name(&self) -> &str { - "RawScripted" - } - 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 raw scripted child has no children"); - Ok(self) - } - fn execute( - &self, - partition: usize, - _context: Arc, - ) -> DataFusionResult { - let spec = self.partitions.get(partition).cloned().ok_or_else(|| { - DataFusionError::Execution(format!("raw child has no partition {partition}")) - })?; +) -> Arc { + TestChild::plan(frame, partitions.len(), move |partition| { + let spec = partitions[partition].clone(); pack_raw_series(Box::pin(RawScript { chunks: spec.chunks.into_iter(), - schema: Arc::clone(&self.series_schema), - binding: store_api::region_engine::RawLabelSource::Explicit, - decode: self.decode.clone(), - // The packed batches have to declare what this child's own plan declares: the - // sequence validator and the receiver both read the ordering off the frame, so a - // stream that reported a different one would be validated under the wrong contract. - ordering: self.ordering, + schema: raw_schema(), + binding: RawLabelSource::Explicit, + decode: decode.clone(), + ordering, gate: spec.gate, gate_chunks: spec.gate_chunks, - fail_after_gate: self.fail_after_gate, })) - } + }) } /// Every output partition of a raw plan, decoded, with the error it ended with if any. @@ -953,11 +879,12 @@ async fn drain_raw_all( /// unroutable, which is the shape the matching policies exist for. #[tokio::test] async fn a_key_labelled_raw_input_is_routed() { - let child = RawScripted::plan_keyed(vec![RawPartition { - chunks: vec![keyed_raw_chunk("a", &[1], vec![Some(1.0)], true)], - gate: None, - gate_chunks: false, - }]); + let child = raw_keyed(vec![RawPartition::new(vec![keyed_raw_chunk( + "a", + &[1], + vec![Some(1.0)], + true, + )])]); let plan = Arc::new(raw_node(child, 2)); let context = task_context(&Arc::new(GreedyMemoryPool::new(8 << 20))); let outputs = drain_raw_all(&plan, &context).await; @@ -984,31 +911,21 @@ async fn a_key_labelled_raw_input_is_routed() { /// series would. Their labels are only readable after decoding, so this fails if the node routes /// before it decodes: the pieces would then land in different owners instead of joining. /// -/// What the owner publishes is one identity, but its frame may present that identity as several -/// chunks: a merge keeps the source sample segments, and the frame cannot span a segment boundary. -/// What the consumer relies on is that the pieces of one label set arrive together and that only -/// the last of them closes the identity. +/// The frame may present the merged identity as several chunks, one per source segment; only the +/// last closes it. #[tokio::test] async fn matching_routes_a_key_labelled_input_by_its_decoded_labels() { let policy = MatchingLabels::On(vec![Arc::from("host")]); - let child = RawScripted::plan_keyed(vec![ - RawPartition { - chunks: vec![ - // `is_last` closes this input's contribution, not the series: the other input - // still holds a piece of `host="a"`, and the two must reach one owner. - keyed_raw_chunk("a", &[1], vec![Some(1.0)], true), - ], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![ - keyed_raw_chunk("a", &[2], vec![Some(3.0)], true), - keyed_raw_chunk("b", &[1], vec![Some(2.0)], true), - ], - gate: None, - gate_chunks: false, - }, + let child = raw_keyed(vec![ + RawPartition::new(vec![ + // `is_last` closes this input's contribution, not the series: the other input + // still holds a piece of `host="a"`, and the two must reach one owner. + keyed_raw_chunk("a", &[1], vec![Some(1.0)], true), + ]), + RawPartition::new(vec![ + keyed_raw_chunk("a", &[2], vec![Some(3.0)], true), + keyed_raw_chunk("b", &[1], vec![Some(2.0)], true), + ]), ]); let plan = Arc::new( raw_node_with_routing(child, 2, SeriesRouting::Matching(policy)) @@ -1055,17 +972,9 @@ async fn matching_routes_a_key_labelled_input_by_its_decoded_labels() { /// decode them to publish them. #[tokio::test] async fn raw_primary_key_still_groups_a_key_labelled_input_by_its_key() { - let child = RawScripted::plan_keyed(vec![ - RawPartition { - chunks: vec![keyed_raw_chunk("a", &[1], vec![Some(1.0)], true)], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![keyed_raw_chunk("a", &[2], vec![Some(3.0)], true)], - gate: None, - gate_chunks: false, - }, + let child = raw_keyed(vec![ + RawPartition::new(vec![keyed_raw_chunk("a", &[1], vec![Some(1.0)], true)]), + RawPartition::new(vec![keyed_raw_chunk("a", &[2], vec![Some(3.0)], true)]), ]); let plan = Arc::new(raw_node(child, 2)); let context = task_context(&Arc::new(GreedyMemoryPool::new(8 << 20))); @@ -1714,15 +1623,9 @@ async fn aggregate_state_router_cancelled_consumer_releases_queued_charge() { /// A router that reads its child's chunks keeps the child's charge on the groups it hands over. /// -/// A `StateChunk::Row` is a zero-copy slice of the batch it was decoded out of, and `state_bytes` -/// bills only the slice: the parent's buffers are charged to the child's publication, and they are -/// live for exactly as long as a group cut from it is. A router that released that charge once it had -/// charged its own figures would leave those buffers charged to nobody while a consumer still holds -/// them - which is what the frame path avoids by sharing one charge across every row of a batch. -/// -/// The figure is read at the moment only the group is left: the stream that produced it, the router -/// and the region under it are gone, so what the pool still counts is what the held group accounts -/// for. +/// A `StateChunk::Row` is a zero-copy slice of its parent batch and `state_bytes` bills only the +/// slice, so the parent's charge must live as long as any row cut from it. The figure is read once the +/// streams, the router and the region are gone and only the held row is left. #[tokio::test] async fn a_chunk_fed_state_router_holds_the_parent_batch_until_its_row_is_dropped() { const GROUPS: usize = 32; @@ -1834,14 +1737,8 @@ async fn a_chunk_fed_state_router_holds_the_parent_batch_until_its_row_is_droppe ); } -/// Every contribution of a duplicated state input survives the chunk path as it does the frame path. -/// -/// `aggregate_state_router_slices_and_preserves_group_validity` states the rule for a frame: two -/// producers contributing one group at the same grid point are two rows the owner forwards, never a -/// duplicate collapsed into one. A chunk input is routed by the same rule - the form of the -/// publication is not the identity of a contribution - so the twin below is that fixture read as -/// chunks, through `execute_series`, and it has to count the same four rows with the overlapping -/// point counted twice. +/// Two producers contributing one group at the same grid point are two rows on the chunk path too, +/// never a duplicate collapsed into one. #[tokio::test] async fn a_duplicated_state_input_survives_the_chunk_path_as_it_does_the_frame_path() { let series = schema(); @@ -1953,9 +1850,8 @@ async fn a_duplicated_state_input_survives_the_chunk_path_as_it_does_the_frame_p /// path has to make the same check: a publication of another kind, layout or grid names state this /// node's owners would merge as theirs, which is not a merge any declaration allows. /// -/// The reader is driven directly because no real producer can make that publication: every node in -/// the chain publishes the same declaration it hands over, which is what makes the check a guard -/// rather than a filter on ordinary input. +/// The reader is driven directly because no real producer publishes a declaration other than the +/// one it hands over. #[tokio::test] async fn a_state_router_refuses_a_chunk_of_another_state() { let series = schema(); @@ -2126,7 +2022,6 @@ async fn drain( .await } -/// The output partition of `plan` at `partition`, as the frame stream a consumer reads. /// The evaluated view of one owner publication, for tests that drive the internal stream. fn evaluated(output: ReadyOutput) -> (Series, bool) { match output { @@ -2135,26 +2030,9 @@ fn evaluated(output: ReadyOutput) -> (Series, bool) { } } -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, +/// The output partition of `plan` at `partition`, as the frame stream a consumer reads. +fn output( + plan: &Arc

, partition: usize, context: &Arc, ) -> SendableEvaluatedSeriesStream { @@ -2187,20 +2065,10 @@ fn summaries(chunks: &[(Series, bool)]) -> Vec<(String, Option, usize, bo chunks.iter().map(summary).collect() } -/// 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. +/// Asserts that every chain `chunks` hands over is whole, as the frame validator reads one: an open +/// chain is continued by the same identity at an advancing position, no chain is left open, and a +/// chunk of no rows closes its chain. Identity is the label set, not its rendering, since an empty +/// label value is not printed. 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. @@ -2307,7 +2175,7 @@ fn labels_elsewhere(routing: &Routing, other: &SeriesLabels) -> SeriesLabels { /// 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) + let none = SeriesRepartitionExec::try_new(scripted(vec![Vec::new()]), 0) .expect_err("a node has to have an output"); assert!( none.to_string().contains("at least one output partition"), @@ -2323,7 +2191,7 @@ fn construction_rejects_a_zero_output_count_and_a_plain_child() { ); } -/// T1: two partitions each hold a piece of one canonical label set, and both pieces reach the output +/// 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() { @@ -2337,7 +2205,7 @@ async fn pieces_of_one_label_set_meet_on_one_output() { ); // 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![ + let child = scripted(vec![ vec![ Step::chunk(chunk(shared.clone(), 0, 2, false)), Step::chunk(chunk(shared.clone(), 0, 0, true)), @@ -2394,17 +2262,15 @@ async fn pieces_of_one_label_set_meet_on_one_output() { ); } -/// 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. +/// An input whose only contribution to an identity is an empty closing chunk adds no second close: +/// the identity is published once, with the other input's rows, and a multi-chunk chain of another +/// identity merges whole beside it. #[tokio::test] -async fn chains_cross_the_node_whole_and_a_closing_chunk_survives() { +async fn an_empty_close_from_one_input_adds_no_second_close() { 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![ + let child = scripted(vec![ vec![ Step::chunk(chunk(shared.clone(), 0, 2, false)), Step::chunk(chunk(shared.clone(), 2, 2, true)), @@ -2418,15 +2284,14 @@ async fn chains_cross_the_node_whole_and_a_closing_chunk_survives() { 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") + let shared_chunks = outputs[routing.output(&shared)] + .as_ref() .expect("the output decodes"); - assert_chains_are_whole(&chunks); - - assert_output_contract(&chunks, &[(shared.clone(), vec![0, 1, 2, 3, 8, 9])]); + assert_output_contract(shared_chunks, &[(shared.clone(), vec![0, 1, 2, 3, 8, 9])]); + let other_chunks = outputs[routing.output(&other)] + .as_ref() + .expect("the output decodes"); + assert_output_contract(other_chunks, &[(other.clone(), vec![0])]); } /// An unread output does not prevent routing to another owner, and a completed series is readable @@ -2438,9 +2303,7 @@ async fn an_unread_owner_does_not_stall_routing_and_outputs_publish_incrementall 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 = TEST_FIXTURE_VOLUME + 2; - let completed = (0..chains) + let completed = (0..6) .map(|index| labels(&format!("unread-{index}"))) .filter(|metric| routing.output(metric) == stalled) .collect::>(); @@ -2455,7 +2318,7 @@ async fn an_unread_owner_does_not_stall_routing_and_outputs_publish_incrementall .collect::>(); steps.push(Step::chunk(chunk(other.clone(), 0, 1, true))); let switch = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![GatedPartition { before: steps, after: Vec::new(), @@ -2526,7 +2389,7 @@ async fn an_unread_owner_does_not_stall_routing_and_outputs_publish_incrementall ); } -/// An exactly full output frame releases its completed identity before the next poll yields. +/// An output frame filled to its row budget releases its completed identity before the next poll. #[tokio::test] async fn exact_full_frame_releases_completed_identity_while_other_chains_stay_open() { let metric = labels("exact-full-frame"); @@ -2559,7 +2422,7 @@ async fn exact_full_frame_releases_completed_identity_while_other_chains_stay_op } }) .collect(); - let child = Gated::plan( + let child = gated( partitions, Arc::clone(&switch), Arc::new(AtomicUsize::new(0)), @@ -2610,7 +2473,7 @@ async fn absent_identity_waits_for_normal_eof_before_publishing_other_input_chai let other = labels_routed_to(1, 2).remove(0); let input_zero = Arc::new(Switch::default()); let input_one = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![ GatedPartition { before: vec![Step::chunk(chunk(metric.clone(), 0, 2, true))], @@ -2628,7 +2491,7 @@ async fn absent_identity_waits_for_normal_eof_before_publishing_other_input_chai ); let plan = node(child, 2); let context = SessionContext::default().task_ctx(); - let mut stream = output_of(&plan, 0, &context); + let mut stream = output(&plan, 0, &context); assert!( futures::future::poll_fn(|cx| match stream.as_mut().poll_next(cx) { Poll::Pending => Poll::Ready(true), @@ -2699,14 +2562,14 @@ async fn completed_identity_is_published_before_inputs_finish() { } }) .collect::>(); - let child = Gated::plan( + let child = gated( partitions, Arc::clone(&switch), Arc::new(AtomicUsize::new(0)), ); let plan = node(child, 2); let owner = routing.output(&metric); - let mut stream = output_of(&plan, owner, &context); + let mut stream = output(&plan, owner, &context); // Each of the three held fragments is two float rows, so what they keep between them is six // values: that is the payload the charge has to cover once A is handed off. let held_rows = 3 * 2; @@ -2783,7 +2646,7 @@ async fn completed_identity_is_published_before_inputs_finish() { async fn complete_disjoint_publishes_before_gated_input_contributes_or_eof() { let metric = labels("disjoint-early"); let gate = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![ GatedPartition::open(vec![Step::chunk(chunk(metric.clone(), 0, 1, true))]), GatedPartition { @@ -2797,7 +2660,7 @@ async fn complete_disjoint_publishes_before_gated_input_contributes_or_eof() { ); let plan = Arc::new(SeriesRepartitionExec::try_new_complete_disjoint(child, 1).unwrap()); let context = SessionContext::default().task_ctx(); - let mut stream = output_of(&plan, 0, &context); + let mut stream = output(&plan, 0, &context); let first = tokio::time::timeout( Duration::from_secs(10), futures::future::poll_fn(|cx| stream.as_mut().poll_next(cx)), @@ -2826,7 +2689,7 @@ async fn fused_instant_complete_disjoint_publishes_before_other_input_eof() { let grid = grid(); let raw_schema = raw_schema(); let raw = NativeType::Samples(Arc::clone(&raw_schema)); - let output = NativeType::Samples(Arc::new(SeriesSchema { + let output_type = NativeType::Samples(Arc::new(SeriesSchema { fields: Arc::clone(&raw_schema.fields), eval_grid: Some(Arc::clone(&grid)), })); @@ -2849,7 +2712,7 @@ async fn fused_instant_complete_disjoint_publishes_before_other_input_eof() { output_grid: Arc::clone(&grid), }, }, - output: output.clone(), + output: output_type.clone(), }) .unwrap(); let frame_schema = common_query::series_frame::raw_series_frame_schema_with_ordering( @@ -2881,23 +2744,15 @@ async fn fused_instant_complete_disjoint_publishes_before_other_input_eof() { ) .unwrap(); let open = Arc::new(Switch::default()); - let child = RawScripted::plan(vec![ - RawPartition { - chunks: vec![raw_chunk( - "instant", - Some(labels("instant")), - &[0], - vec![Some(1.0)], - true, - )], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: Vec::new(), - gate: Some(Arc::clone(&open)), - gate_chunks: false, - }, + let child = raw_scripted(vec![ + RawPartition::new(vec![raw_chunk( + "instant", + Some(labels("instant")), + &[0], + vec![Some(1.0)], + true, + )]), + RawPartition::open_until(Vec::new(), &open), ]); let fused = logical .to_execution_plan(vec![( @@ -2908,7 +2763,7 @@ async fn fused_instant_complete_disjoint_publishes_before_other_input_eof() { .unwrap(); let routed = Arc::new(SeriesRepartitionExec::try_new_complete_disjoint(fused, 1).unwrap()); let context = SessionContext::default().task_ctx(); - let mut stream = output_of(&routed, 0, &context); + let mut stream = output(&routed, 0, &context); let first = tokio::time::timeout( Duration::from_secs(10), futures::future::poll_fn(|cx| stream.as_mut().poll_next(cx)), @@ -2928,7 +2783,7 @@ async fn fused_instant_complete_disjoint_publishes_before_other_input_eof() { async fn merge_inputs_waits_for_gated_input_before_publishing_identity() { let metric = labels("disjoint-early"); let gate = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![ GatedPartition::open(vec![Step::chunk(chunk(metric.clone(), 0, 1, true))]), GatedPartition { @@ -2942,7 +2797,7 @@ async fn merge_inputs_waits_for_gated_input_before_publishing_identity() { ); let plan = Arc::new(SeriesRepartitionExec::try_new(child, 1).unwrap()); let context = SessionContext::default().task_ctx(); - let mut stream = output_of(&plan, 0, &context); + let mut stream = output(&plan, 0, &context); assert!( futures::future::poll_fn(|cx| match stream.as_mut().poll_next(cx) { Poll::Pending => Poll::Ready(true), @@ -2985,7 +2840,7 @@ async fn complete_disjoint_memory_does_not_grow_with_published_identity_history( .collect(); let finish_first = Arc::new(Switch::default()); let gate_other = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![ GatedPartition { before: steps, @@ -3004,7 +2859,7 @@ async fn complete_disjoint_memory_does_not_grow_with_published_identity_history( let pool = Arc::new(GreedyMemoryPool::new(MEMORY_BUDGET)); let context = task_context(&pool); let plan = Arc::new(SeriesRepartitionExec::try_new_complete_disjoint(child, 1).unwrap()); - let mut stream = output_of(&plan, 0, &context); + let mut stream = output(&plan, 0, &context); finish_first.open(); let drain = async { for index in 0..IDENTITIES { @@ -3043,10 +2898,8 @@ async fn complete_disjoint_memory_does_not_grow_with_published_identity_history( "the input remains live after its identities drain" ); - // The previous implementation retained each published identity key and its history reservation - // until stream teardown. This lower bound excludes the group/map overhead, making it conservative: - // 2,000 host values of 1,019 bytes alone exceed 1.9 MiB. The 4 MiB pool allows transient queued chains, but the - // fully drained state must be far below the retained-history charge. + // Retaining every published key would hold at least the 2,000 host values of 1,019 bytes, over + // 1.9 MiB. The 4 MiB pool admits that, so the bound below is what catches it. let old_history_lower_bound = IDENTITIES * (LABEL_VALUE_LEN - 5); assert!(old_history_lower_bound > MEMORY_BUDGET / 4); assert!( @@ -3106,10 +2959,10 @@ async fn single_fragment_large_identity_fits_finite_payload_budget() { let pool = Arc::new(GreedyMemoryPool::new(budget)); let context = task_context(&pool); let plan = node( - Scripted::plan_with_schema(vec![vec![Step::Chunk(series, true)]], long_schema), + scripted_with_schema(vec![vec![Step::Chunk(series, true)]], long_schema), 1, ); - let mut output = output_of(&plan, 0, &context); + let mut output = output(&plan, 0, &context); let (chunks, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut output)) .await .expect("single-fragment identity fits its finite pool"); @@ -3139,7 +2992,7 @@ async fn single_fragment_large_identity_fits_finite_payload_budget() { async fn eof_before_first_identity_contribution_makes_group_ready() { let metric = labels("late-first-chain"); let switch = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![ GatedPartition::open(Vec::new()), GatedPartition::held(vec![Step::chunk(chunk(metric.clone(), 7, 1, true))]), @@ -3149,7 +3002,7 @@ async fn eof_before_first_identity_contribution_makes_group_ready() { ); let plan = node(child, 1); let context = SessionContext::default().task_ctx(); - let mut stream = output_of(&plan, 0, &context); + let mut stream = output(&plan, 0, &context); assert!( futures::future::poll_fn(|cx| match stream.as_mut().poll_next(cx) { Poll::Pending => Poll::Ready(true), @@ -3166,14 +3019,14 @@ async fn eof_before_first_identity_contribution_makes_group_ready() { assert_output_contract(&chunks, &[(metric, vec![7])]); } -/// T3, second half: what the producer queues is charged to the execution's pool, and dropping the +/// 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![ + let child = scripted(vec![vec![ Step::chunk(chunk(shared.clone(), 0, 1, false)), Step::chunk(chunk(shared.clone(), 1, 1, false)), Step::chunk(chunk(shared.clone(), 2, 1, true)), @@ -3216,13 +3069,12 @@ async fn dropping_the_execution_releases_what_the_producer_reserved() { }); } -/// T5: one output is the same node, not a special case - every chunk arrives, in one chain after -/// another, with nothing filtered out. +/// With one output every chunk arrives, chains whole, 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![ + let child = scripted(vec![ vec![ Step::chunk(chunk(shared.clone(), 0, 2, false)), Step::chunk(chunk(shared.clone(), 2, 2, true)), @@ -3253,10 +3105,6 @@ async fn one_output_keeps_every_chunk_and_its_chains_whole() { } /// 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, @@ -3290,7 +3138,7 @@ impl Switch { } } -/// One partition of a [`Gated`] child: what it hands over at once, and what it holds back. +/// One partition of a [`gated`] child: what it hands over at once, and what it holds back. /// `switch` overrides the child's shared gate when a test needs independent input progress. #[derive(Clone, Default)] struct GatedPartition { @@ -3309,7 +3157,7 @@ impl GatedPartition { } } - /// A partition that hands over `steps` as soon as it is polled. + /// A partition that hands over `steps` at once; its end still waits for the switch. fn open(steps: Vec) -> Self { Self { before: steps, @@ -3319,123 +3167,34 @@ impl GatedPartition { } } -/// 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 { +/// A child whose partitions hold their `after` steps and their end until their switch opens. +/// `dropped` counts the partition streams dropped, which is how a test sees the read cancel its child. +fn gated( + partitions: Vec, + switch: Arc, + dropped: Arc, +) -> Arc { + gated_with_schema(partitions, switch, dropped, schema()) +} + +fn gated_with_schema( partitions: Vec, switch: Arc, dropped: Arc, series_schema: Arc, - properties: Arc, +) -> Arc { + TestChild::evaluated(series_schema, partitions.len(), move |partition| { + let steps = partitions[partition].clone(); + GatedScript { + before: steps.before.into_iter(), + after: steps.after.into_iter(), + switch: steps.switch.unwrap_or_else(|| Arc::clone(&switch)), + dropped: Arc::clone(&dropped), + } + }) } -impl Gated { - /// The child over `partitions`, gated on `switch` and counting drops in `dropped`. - fn plan( - partitions: Vec, - switch: Arc, - dropped: Arc, - ) -> Arc { - Self::plan_with_schema(partitions, switch, dropped, schema()) - } - - /// The same child over an explicit schema, for trees with more than one field. - fn plan_with_schema( - partitions: Vec, - switch: Arc, - dropped: Arc, - series_schema: Arc, - ) -> Arc { - 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}")) - })?; - let switch = steps.switch.unwrap_or_else(|| Arc::clone(&self.switch)); - pack_evaluated_series( - Box::pin(GatedScript { - before: steps.before.into_iter(), - after: steps.after.into_iter(), - switch, - dropped: Arc::clone(&self.dropped), - }), - Arc::clone(&self.series_schema), - ) - } -} - -/// One partition of a [`Gated`] child. +/// One partition of a [`gated`] child. struct GatedScript { before: std::vec::IntoIter, after: std::vec::IntoIter, @@ -3467,112 +3226,23 @@ impl Drop for GatedScript { } } -/// The tokio task that first polled each partition of a [`Recording`] child. +/// 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, +/// A child whose partitions answer `steps`, recording the task that first polls each one. +fn recording(steps: Vec>) -> (Arc, ReadTasks) { + let polled: ReadTasks = Arc::new(Mutex::new(vec![None; steps.len()])); + let record = Arc::clone(&polled); + let child = TestChild::evaluated(schema(), steps.len(), move |partition| RecordingScript { + partition, + steps: steps[partition].clone().into_iter(), + polled: Arc::clone(&record), + recorded: false, + }); + (child, polled) } -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. +/// One partition of a [`recording`] child. struct RecordingScript { partition: usize, steps: std::vec::IntoIter, @@ -3618,9 +3288,6 @@ fn execution(plan: &Arc) -> Arc { } /// 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 } @@ -3648,13 +3315,8 @@ async fn evaluated_terminal_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. +/// Everything `stream` hands over until it ends: the chunks it delivered and the errors it reported, +/// read past the first error so a non-terminal error shows up. A hang is the caller's timeout to catch. async fn until_end( stream: &mut SendableEvaluatedSeriesStream, ) -> (Vec<(Series, bool)>, Vec) { @@ -3669,22 +3331,13 @@ async fn until_end( } } -/// 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 the node 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. +/// The read drives each input partition on a task of its own: the two partitions are first polled by +/// two distinct tasks, neither of them the consumer's. This does not require the tasks to run at the +/// same instant. #[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![ + let (child, polled) = recording(vec![ vec![Step::chunk(chunk(shared.clone(), 0, 1, true))], vec![Step::chunk(chunk(shared.clone(), 4, 1, true))], ]); @@ -3733,13 +3386,9 @@ async fn every_input_partition_is_read_on_a_task_of_its_own() { assert_eq!(1, chunks.iter().filter(|(_, closed)| *closed).count()); } -/// 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. +/// The streams own the read, so dropping the plan does not truncate them. The input produces nothing +/// until every plan reference is gone, as `execute_stream_partitioned` drops the plan after handing +/// out the streams. #[tokio::test] async fn dropping_the_plan_leaves_the_read_to_its_streams() { let routing = Routing::new(2); @@ -3747,7 +3396,7 @@ async fn dropping_the_plan_leaves_the_read_to_its_streams() { let other = labels_elsewhere(&routing, &shared); let switch = Arc::new(Switch::default()); let dropped = Arc::new(AtomicUsize::new(0)); - let child = Gated::plan( + let child = gated( vec![ GatedPartition::held(vec![ Step::chunk(chunk(shared.clone(), 0, 2, false)), @@ -3813,7 +3462,7 @@ async fn dropping_the_plan_leaves_the_read_to_its_streams() { async fn eof_readies_two_groups_but_poll_merges_one_at_a_time() { let first_metric = labels("eof-ready-first"); let second_metric = labels("eof-ready-second"); - let child = Scripted::plan(vec![vec![ + let child = scripted(vec![vec![ Step::chunk(chunk(first_metric.clone(), 0, 1, true)), Step::chunk(chunk(second_metric.clone(), 0, 1, true)), ]]); @@ -3875,12 +3524,8 @@ async fn eof_readies_two_groups_but_poll_merges_one_at_a_time() { assert_eq!(0, pool.reserved(), "finished stream releases all charges"); } -/// 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. +/// Dropping every output stops the read and releases its task, its child and its memory, while the +/// plan stays alive as a metrics collector would keep it. #[tokio::test] async fn dropping_every_output_stops_the_read_and_releases_it() { let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); @@ -3888,11 +3533,12 @@ async fn dropping_every_output_stops_the_read_and_releases_it() { 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..TEST_FIXTURE_VOLUME * 3) + // The switch is never opened, so both partitions hold their end and the read cannot finish on + // its own. + let steps = (0..12) .map(|index| Step::chunk(chunk(shared.clone(), index, 1, true))) .collect::>(); - let child = Gated::plan( + let child = gated( vec![ GatedPartition::open(steps.clone()), GatedPartition::open(steps), @@ -3931,30 +3577,31 @@ async fn dropping_every_output_stops_the_read_and_releases_it() { ); } -/// 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. +/// A partition that fails with its chain open ends every output with the error, never a clean end, +/// though its peer ended normally; nothing is answered after the error. Three outputs make sure the +/// error is not only the fate of the output the failed chain was routed to. #[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, true)), Step::Error], - vec![Step::chunk(chunk(shared.clone(), 8, 1, true)), Step::Error], + let child = scripted(vec![ + vec![ + Step::chunk(chunk(labels("web-1"), 0, 2, false)), + Step::Error, + ], + vec![Step::chunk(chunk(labels("elsewhere"), 0, 1, true))], ]); 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") + let frames = plan + .execute(partition, Arc::clone(&context)) + .expect("the output executes"); + unpack_evaluated_series(frames, None).expect("the output declares an evaluated frame") }) .collect::>(); for (partition, stream) in streams.iter_mut().enumerate() { - let error = tokio::time::timeout(Duration::from_secs(10), terminal_error(stream)) + let error = tokio::time::timeout(Duration::from_secs(10), evaluated_terminal_error(stream)) .await .unwrap_or_else(|_| panic!("output partition {partition} never ended")) .unwrap_or_else(|| { @@ -3972,18 +3619,12 @@ async fn a_child_failure_is_terminal_on_every_output() { } } -/// 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. +/// An output that ends does not close the queue of an output never executed yet, as +/// `CoalescePartitionsExec` executes one partition per task. Otherwise `execute(1)` would answer +/// "executed twice" for a partition that never was. #[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 plan: Arc = node(scripted(vec![Vec::new()]), 2); let context = SessionContext::default().task_ctx(); let first = output(&plan, 0, &context); @@ -4013,10 +3654,8 @@ async fn an_output_that_ends_does_not_close_the_queue_of_an_unclaimed_output() { ); } -/// the output claimed last still receives its whole share after a claimed sibling ended. -/// -/// Partition 0 is read to its end before partition 1 is executed. Its released lease must not discard -/// the unclaimed sibling queue, whose complete result is verified after the later claim. +/// The output claimed last still receives its whole share after a claimed sibling ended and released +/// its lease. #[tokio::test] async fn an_unclaimed_output_delivers_its_whole_share_after_a_sibling_ended() { let routing = Routing::new(2); @@ -4029,7 +3668,7 @@ async fn an_unclaimed_output_delivers_its_whole_share_after_a_sibling_ended() { "the two label sets have to land apart for this test to mean anything" ); // One distinct label set per identity and output; chunks belonging to an identity form one chain. - let chains = TEST_FIXTURE_VOLUME - 1; + let chains = 3; let identities = labels_routed_to(claimed_later, chains); let steps = (0..chains) .map(|index| Step::chunk(chunk(shared.clone(), index, 1, index + 1 == chains))) @@ -4040,7 +3679,7 @@ async fn an_unclaimed_output_delivers_its_whole_share_after_a_sibling_ended() { .map(|(index, metric)| Step::chunk(chunk(metric.clone(), index, 1, true))), ) .collect::>(); - let plan: Arc = node(Scripted::plan(vec![steps]), 2); + let plan: Arc = node(scripted(vec![steps]), 2); let context = SessionContext::default().task_ctx(); let first = output(&plan, ended_first, &context); @@ -4082,10 +3721,10 @@ async fn an_unclaimed_output_keeps_the_producer_of_a_claimed_one_running() { read_first, claimed_later, "the two label sets have to land apart for this test to mean anything" ); - let chains = TEST_FIXTURE_VOLUME + 2; + let chains = 6; let queued_identities = labels_routed_to(claimed_later, 2 * chains); let switch = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![ GatedPartition { before: vec![Step::chunk(chunk(shared.clone(), 0, 1, true))], @@ -4160,11 +3799,8 @@ async fn an_unclaimed_output_keeps_the_producer_of_a_claimed_one_running() { assert_output_contract(&second_chunks, &expected); } -/// 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. +/// A task context whose memory pool never refuses a reservation, for tests about whether a read +/// finishes rather than what it costs. fn unbounded_context() -> Arc { let runtime = RuntimeEnvBuilder::new() .with_memory_pool(Arc::new(UnboundedMemoryPool::default()) as Arc) @@ -4173,13 +3809,8 @@ fn unbounded_context() -> Arc { 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. +/// `count` label sets that a two-output node routes to `output`, found with the node's own +/// [`Routing`] so the premise survives a change of hash. fn labels_routed_to(output: usize, count: usize) -> Vec { let routing = Routing::new(2); let found = (0..) @@ -4197,30 +3828,15 @@ fn labels_routed_to(output: usize, count: usize) -> Vec { found } -/// 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 input has many more chains than the bounded output queues can hold, so the test needs the -/// empty inner output to close through independent input-task progress rather than by buffering the -/// child whole. Both outer outputs are drained concurrently, as required by the node. -/// -/// 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. -/// -/// Independent input tasks let the outer node route the inner node's non-empty output while its -/// other task waits for the inner empty output to close, allowing that inner execution to finish. +/// Two composed nodes finish when the inner node's output 0 is empty: every label set hashes to +/// output 1, so the outer node's input 0 is an output that only ends once the inner read finishes. +/// The outer read must keep routing input 1 meanwhile, and lose nothing. #[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![ + scripted(vec![ routed .iter() .map(|metric| Step::chunk(chunk(metric.clone(), 0, 1, true))) @@ -4317,10 +3933,10 @@ async fn composing_two_nodes_does_not_deadlock_when_the_inner_output_is_empty() } #[tokio::test] -async fn owner_merges_across_inputs_and_sorts_late_positions_until_eof() { +async fn owner_merges_a_late_earlier_position_into_one_close() { let metric = labels("owner-order"); let switch = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![ GatedPartition::open(vec![Step::chunk(chunk(metric.clone(), 10, 1, true))]), GatedPartition::held(vec![Step::chunk(chunk(metric.clone(), 0, 1, true))]), @@ -4381,17 +3997,17 @@ async fn multiple_producers_and_owners_merge_exact_full_label_identities() { let mut partitions = vec![Vec::new(), Vec::new(), Vec::new()]; for metric in identities.iter() { for (partition, position) in [0, 10, 20].into_iter().enumerate() { - partitions[partition].push(Step::chunk(chunk(metric.clone(), position, 1, true))); + partitions[partition].push(Step::chunk(chunk(metric.clone(), position, 2, true))); } } - let plan: Arc = node(Scripted::plan(partitions), 2); + let plan: Arc = node(scripted(partitions), 2); let outputs = drain(&plan, &SessionContext::default().task_ctx()).await; for (owner, output) in outputs.iter().enumerate() { let chunks = output.as_ref().expect("each owner succeeds"); let expected = identities .iter() .filter(|metric| routing.output(metric) == owner) - .map(|metric| (metric.clone(), vec![0, 10, 20])) + .map(|metric| (metric.clone(), vec![0, 1, 10, 11, 20, 21])) .collect::>(); assert!(!expected.is_empty(), "each output receives a real identity"); assert_output_contract(chunks, &expected); @@ -4409,7 +4025,7 @@ async fn error_after_early_public_chain_is_reported_once_and_releases_pool() { let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); let context = task_context(&pool); // Both inputs contribute A before their gates; only input 0 fails after the gate opens. - let child = Gated::plan( + let child = gated( vec![ GatedPartition { before: vec![Step::chunk(chunk(metric.clone(), 0, 1, true))], @@ -4426,7 +4042,7 @@ async fn error_after_early_public_chain_is_reported_once_and_releases_pool() { Arc::new(AtomicUsize::new(0)), ); let plan = node(child, 2); - let mut stream = output_of(&plan, 0, &context); + let mut stream = output(&plan, 0, &context); let mut emitted = Vec::new(); tokio::time::timeout(Duration::from_secs(10), async { loop { @@ -4472,7 +4088,7 @@ async fn late_unclaimed_output_receives_first_merge_error_once_after_early_outpu }; let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); let context = task_context(&pool); - let child = Scripted::plan(vec![ + let child = scripted(vec![ vec![ Step::chunk(chunk(other.clone(), 0, 1, true)), conflicting(1.0), @@ -4480,7 +4096,7 @@ async fn late_unclaimed_output_receives_first_merge_error_once_after_early_outpu vec![conflicting(2.0)], ]); let plan = node(child, 2); - let mut early = output_of(&plan, 0, &context); + let mut early = output(&plan, 0, &context); let mut emitted = Vec::new(); let error = tokio::time::timeout(Duration::from_secs(10), async { loop { @@ -4558,7 +4174,7 @@ async fn owner_merges_complementary_fields_across_input_positions() { ) }; let switch = Arc::new(Switch::default()); - let child = Gated::plan_with_schema( + let child = gated_with_schema( vec![ GatedPartition::open(vec![make(0, Some(10.0), None)]), GatedPartition { @@ -4620,7 +4236,7 @@ async fn owner_rejects_conflicting_values_at_same_identity_and_position() { SeriesFields::one(Samples::from_float(Float64Array::from(vec![99.0]))), ) .unwrap(); - let child = Scripted::plan(vec![ + let child = scripted(vec![ vec![Step::Chunk(first, true)], vec![Step::Chunk(conflicting, true)], ]); @@ -4632,23 +4248,6 @@ async fn owner_rejects_conflicting_values_at_same_identity_and_position() { ); } -/// Same-identity input chunks are collected and emitted as one closed series. -#[tokio::test] -async fn same_canonical_key_chains_merge_into_one_series() { - let metric = labels("same"); - let child = Scripted::plan(vec![ - vec![Step::chunk(chunk(metric.clone(), 0, 2, true))], - vec![Step::chunk(chunk(metric.clone(), 8, 2, true))], - ]); - let plan: Arc = node(child, 2); - let outputs = drain(&plan, &SessionContext::default().task_ctx()).await; - let owner = Routing::new(2).output(&metric); - let chunks = outputs[owner].as_ref().expect("the owner output decodes"); - assert_output_contract(chunks, &[(metric.clone(), vec![0, 1, 8, 9])]); - assert_eq!(1, chunks.iter().filter(|(_, closed)| *closed).count()); - assert!(outputs[1 - owner].as_ref().unwrap().is_empty()); -} - #[tokio::test] async fn canonical_label_key_variants_route_consistently_without_merging_chains() { let base = SeriesLabels::try_new(Some(Arc::from("cpu")), Vec::new()).unwrap(); @@ -4708,7 +4307,7 @@ async fn canonical_label_key_variants_route_consistently_without_merging_chains( ); } - let child = Scripted::plan(vec![ + let child = scripted(vec![ vec![Step::chunk(chunk(left.clone(), 0, 1, true))], vec![Step::chunk(chunk(right.clone(), 4, 1, true))], ]); @@ -4749,13 +4348,8 @@ async fn canonical_label_key_variants_route_consistently_without_merging_chains( } } -/// 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. +/// Two identities of one output, one held open across a gate: the closed one is delivered whole +/// first, and the held chain's first chunk never lands inside it, which a frame reader would refuse. #[tokio::test] async fn two_sources_keep_their_chains_whole_on_one_output() { let on_one = labels_routed_to(0, 2); @@ -4766,7 +4360,7 @@ async fn two_sources_keep_their_chains_whole_on_one_output() { "two label sets of one output, found rather than assumed" ); let switch = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( 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. @@ -4841,19 +4435,13 @@ async fn two_sources_keep_their_chains_whole_on_one_output() { ); } -/// 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. +/// A closing chunk that carries no rows is delivered as a chunk and does not end the stream. #[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![ + let child = scripted(vec![ // One source closes a series with nothing left of it, and keeps going afterwards. vec![ Step::chunk(chunk(other.clone(), 0, 0, true)), @@ -4897,13 +4485,8 @@ async fn an_empty_closing_chunk_is_a_chunk_and_not_the_end() { } } -/// 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. +/// While one owner's chain is held open across a gate, the other owner's output still delivers its +/// whole identity: the wait belongs to the task reading the gated source. #[tokio::test] async fn an_open_chain_on_one_output_does_not_hold_the_other_output_back() { let routing = Routing::new(2); @@ -4916,7 +4499,7 @@ async fn an_open_chain_on_one_output_does_not_hold_the_other_output_back() { "the two label sets have to land apart for this test to mean anything" ); let switch = Arc::new(Switch::default()); - let child = Gated::plan( + let child = gated( vec![ GatedPartition::open(vec![ Step::chunk(chunk(free.clone(), 0, 2, false)), @@ -5019,60 +4602,9 @@ async fn an_open_chain_on_one_output_does_not_hold_the_other_output_back() { ); } -/// 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}" - ); - } -} - -/// 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. +/// Two inputs are read and routed independently. The child hands over no second chunk until every +/// partition handed over a first, so a read that took one input's chain to its end before reading the +/// other would stop mid-chain and never finish. #[tokio::test] async fn two_inputs_are_routed_without_waiting_for_each_other() { let routing = Routing::new(2); @@ -5083,7 +4615,7 @@ async fn two_inputs_are_routed_without_waiting_for_each_other() { routing.output(&second), "the two label sets have to land apart for this test to mean anything" ); - let child = Together::plan(vec![ + let child = together(vec![ vec![ Step::chunk(chunk(first.clone(), 0, 1, false)), Step::chunk(chunk(first.clone(), 1, 1, true)), @@ -5126,7 +4658,7 @@ async fn two_inputs_are_routed_without_waiting_for_each_other() { ); } -/// The chunks each partition of a [`Together`] child has handed over so far. +/// 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. @@ -5185,105 +4717,18 @@ impl FirstChunks { } /// A child each of whose partitions hands over a second chunk only once every partition handed over a -/// first. -/// -/// Progress through one partition's chain requires every partition to have progressed too. This is -/// a rendezvous between inputs, not a stopwatch: nothing depends on two threads running at once. -struct Together { - steps: Vec>, - chunks: Arc, - series_schema: Arc, - properties: Arc, +/// first: a rendezvous between inputs that does not depend on two threads running at once. +fn together(steps: Vec>) -> Arc { + let chunks = FirstChunks::new(steps.len()); + TestChild::evaluated(schema(), steps.len(), move |partition| TogetherScript { + partition, + steps: steps[partition].clone().into_iter(), + chunks: Arc::clone(&chunks), + handed: false, + }) } -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. +/// One partition of a [`together`] child. struct TogetherScript { partition: usize, steps: std::vec::IntoIter, @@ -5319,113 +4764,25 @@ impl Stream for TogetherScript { } /// 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, +/// and only then hand over their `after` steps, so the `after` steps of all partitions are released +/// in the same wake. +fn simultaneous(partitions: Vec) -> (Arc, Arc) { + let arrived = FirstChunks::new(partitions.len()); + let barrier = Arc::clone(&arrived); + let child = TestChild::evaluated(schema(), partitions.len(), move |partition| { + let steps = partitions[partition].clone(); + SimultaneousScript { + partition, + before: steps.before.into_iter(), + after: steps.after.into_iter(), + arrived: Arc::clone(&barrier), + arrived_here: false, + } + }); + (child, arrived) } -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. +/// One partition of a [`simultaneous`] child. struct SimultaneousScript { partition: usize, before: std::vec::IntoIter, @@ -5457,12 +4814,8 @@ impl Stream for SimultaneousScript { } } -/// 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: an input 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. +/// Every output of `plan`, claimed together and drained concurrently: the chunks each delivered and +/// the errors each reported. async fn every_output_until_end( plan: &Arc, context: &Arc, @@ -5485,7 +4838,7 @@ async fn every_output_until_end( async fn coalesce_local_limit_reads_repartitioned_outputs_without_sibling_error() { let first = labels_routed_to(0, 1).remove(0); let second = labels_routed_to(1, 1).remove(0); - let steps = labels_routed_to(0, 3 * TEST_FIXTURE_VOLUME) + let steps = labels_routed_to(0, 12) .into_iter() .map(|metric| Step::chunk(chunk(metric, 0, 1, true))) .chain(std::iter::once(Step::chunk(chunk( @@ -5496,7 +4849,7 @@ async fn coalesce_local_limit_reads_repartitioned_outputs_without_sibling_error( )))) .collect(); let routed: Arc = node( - Fragile::plan( + fragile( vec![Behaviour::OneAtATime(steps)], Arc::new(Switch::default()), ) @@ -5540,7 +4893,7 @@ async fn coalesce_local_limit_reads_repartitioned_outputs_without_sibling_error( #[test] fn ensure_cooperative_preserves_direct_repartition_child() { - let repartition: Arc = node(Scripted::plan(vec![Vec::new()]), 2); + let repartition: Arc = node(scripted(vec![Vec::new()]), 2); let optimized = EnsureCooperative::new() .optimize(repartition, &ConfigOptions::default()) .expect("EnsureCooperative optimizes the plan"); @@ -5549,11 +4902,13 @@ fn ensure_cooperative_preserves_direct_repartition_child() { "EnsureCooperative preserves the bare repartition root" ); } -/// Regression: a paced producer fills output 0 with closed chains, then fails while output 1 is drained first. + +/// The input fails after queueing chains for output 0, which nobody has claimed. The failure drains +/// that unclaimed queue, and the claimed output 1 must still end with the error. #[tokio::test] -async fn failure_after_filling_another_output_does_not_hang_early_output_drain() { - const MESSAGE: &str = "failure after output 0 filled"; - let mut steps = labels_routed_to(0, TEST_FIXTURE_VOLUME - 1) +async fn a_claimed_output_reports_a_failure_while_its_sibling_is_unclaimed() { + const MESSAGE: &str = "failure after queueing for an unclaimed output"; + let mut steps = labels_routed_to(0, 3) .into_iter() .map(|metric| Step::chunk(chunk(metric, 0, 1, true))) .collect::>(); @@ -5564,7 +4919,7 @@ async fn failure_after_filling_another_output_does_not_hang_early_output_drain() ); steps.push(Step::ErrorSaying(MESSAGE)); let plan = node( - Fragile::plan( + fragile( vec![Behaviour::OneAtATime(steps)], Arc::new(Switch::default()), ) @@ -5572,45 +4927,26 @@ async fn failure_after_filling_another_output_does_not_hang_early_output_drain() 2, ); let context = SessionContext::default().task_ctx(); - let mut output1 = output_of(&plan, 1, &context); - let (chunks, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut output1)) + let mut output1 = output(&plan, 1, &context); + let (_, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut output1)) .await - .expect("output 1 sees the failure despite output 0 being full"); - let _ = chunks; + .expect("output 1 sees the failure while output 0 is unclaimed"); assert_eq!(1, errors.len()); assert!(errors[0].contains(MESSAGE)); } -/// two partitions that fail at the same moment leave every output exactly one error. -/// -/// Between them the two partitions hand over [`TEST_FIXTURE_VOLUME`] 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. A failing task cancels its peers while another input may be suspended on a full output; -/// every output must still learn the elected failure from the shared ending record when senders close. -/// -/// 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 that the first failure and its error are retained, and -/// every output ends with exactly one error, never a clean end and never a duplicate. +/// Two partitions queue chains for both outputs and then fail in the same wake, while neither output +/// is drained. Every output must report the elected failure exactly once. #[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, - TEST_FIXTURE_VOLUME % 2, - "the chains of one queue are split evenly between the two partitions" - ); - let half = TEST_FIXTURE_VOLUME / 2; - let to_first = labels_routed_to(0, TEST_FIXTURE_VOLUME); - let to_second = labels_routed_to(1, TEST_FIXTURE_VOLUME); + let half = 2; + let to_first = labels_routed_to(0, 2 * half); + let to_second = labels_routed_to(1, 2 * half); - /// 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. + /// The partition's chains, then its failure behind the barrier, so neither failure lands while the + /// other partition is still reading. fn failing( first: &[SeriesLabels], second: &[SeriesLabels], @@ -5627,24 +4963,16 @@ async fn two_failures_hand_every_output_one_error() { } } - let (child, arrived) = Simultaneous::plan(vec![ + let (child, arrived) = simultaneous(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(); // Claim both owners before reading so either partition can observe its terminal failure. - 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 mut streams = (0..plan.outputs()) + .map(|partition| output(&plan, partition, &context)) + .collect::>(); let execution = execution(&plan); wait_until("both partitions reach the failure path", || arrived.all()).await; @@ -5687,14 +5015,9 @@ async fn two_failures_hand_every_output_one_error() { } } -/// 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. +/// A task attached after the failure is swept is aborted instead of waited on. Partition 0 fails on +/// its first poll, possibly before later partitions' tasks are attached; those wait on a switch +/// nothing opens and hold a sender to every output, so only aborting them ends the outputs. #[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"; @@ -5708,7 +5031,7 @@ async fn a_partition_failing_before_its_peers_are_attached_still_ends_every_outp (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 child = gated(partitions, switch, Arc::clone(&dropped)); let plan = node(child, 2); let context = SessionContext::default().task_ctx(); @@ -5792,13 +5115,11 @@ async fn a_task_attached_after_the_failure_is_aborted_and_not_counted() { .expect("the attached route task's ReportIfUnreported guard counts it out on abort"); } -/// a read that finished owes its outputs no error, whatever a failure elsewhere recorded. -/// -/// A read that finished records `Finished`, and every output ends cleanly once. +/// A read that finished records `Finished`, and every output ends cleanly. #[tokio::test] async fn a_finished_read_ends_cleanly_and_owes_no_error() { let shared = labels("web-1"); - let child = Scripted::plan(vec![ + let child = scripted(vec![ vec![Step::chunk(chunk(shared.clone(), 0, 2, true))], vec![Step::chunk(chunk(shared.clone(), 8, 2, true))], ]); @@ -5826,16 +5147,14 @@ async fn a_finished_read_ends_cleanly_and_owes_no_error() { ); } -/// a failure recorded before outputs are drained is still reported by every output. -/// -/// One input fills the output queues and then fails while the outputs are not being drained. The -/// failure cancels its peers; outputs observe closed queues and must report the recorded terminal -/// error exactly once rather than ending cleanly. +/// One input queues chains for both outputs and then fails while neither output is drained. Every +/// output reports the recorded error exactly once, publishes none of the discarded chains, and the +/// queued charges are released. #[tokio::test] async fn a_recorded_failure_reaches_every_output_once() { const MESSAGE: &str = "the partition failed"; - let to_zero = labels_routed_to(0, TEST_FIXTURE_VOLUME); - let to_one = labels_routed_to(1, TEST_FIXTURE_VOLUME); + let to_zero = labels_routed_to(0, 4); + let to_one = labels_routed_to(1, 4); let mut steps = to_zero .into_iter() .zip(to_one) @@ -5847,7 +5166,7 @@ async fn a_recorded_failure_reaches_every_output_once() { // the very charges this test reads, and the retention assertion below could never hold. let switch = Arc::new(Switch::default()); let plan = node( - Fragile::plan(vec![Behaviour::Gated(steps)], Arc::clone(&switch)).plan, + fragile(vec![Behaviour::Gated(steps)], Arc::clone(&switch)).plan, 2, ); let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); @@ -5923,7 +5242,7 @@ async fn a_recorded_failure_reaches_every_output_once() { assert_eq!(0, pool.reserved(), "draining releases all queued charges"); } -/// What one partition of a [`Fragile`] child does when it is polled. +/// 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. @@ -5933,45 +5252,15 @@ enum Behaviour { 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. + /// Hands one step over per poll, staying pending in between. The frame builder flushes only when + /// its source is pending or done, so back-to-back chunks would reach the read as one. OneAtATime(Vec), /// Delivers one chunk, waits until the test opens the gate, then delivers the rest. Gated(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. +/// A child whose partitions stop in ways of their own. `polled` says a partition was being read, and +/// `dropped` says the read let its stream go, as an aborted task does. struct FragileChild { plan: Arc, /// How many times each partition was polled. @@ -5980,117 +5269,46 @@ struct FragileChild { 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()) +/// The child over `behaviours`, one partition per behaviour, gated on `switch`. +fn fragile(behaviours: Vec, switch: Arc) -> FragileChild { + let counters = || { + (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}")) - })?; + .collect::>() + }; + let (polled, dropped) = (counters(), counters()); + // Every partition waits until all were polled once: a partition that panics on its first poll + // could otherwise die before its peer's task ever polled, leaving no parked input to stop. + let reading = FirstChunks::new(behaviours.len()); + let partitions = behaviours.len(); + let (polls, drops) = (polled.clone(), dropped.clone()); + let plan = TestChild::evaluated(schema(), partitions, move |partition| { + let behaviour = behaviours[partition].clone(); let steps = match &behaviour { Behaviour::Held(steps) | Behaviour::OneAtATime(steps) | Behaviour::Gated(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), - ) + FragileScript { + partition, + behaviour, + steps: steps.into_iter(), + switch: Arc::clone(&switch), + reading: Arc::clone(&reading), + polled: Arc::clone(&polls[partition]), + dropped: Arc::clone(&drops[partition]), + stayed_pending: false, + } + }); + FragileChild { + plan, + polled, + dropped, } } -/// One partition of a [`Fragile`] child. +/// One partition of a [`fragile`] child. struct FragileScript { partition: usize, behaviour: Behaviour, @@ -6548,25 +5766,19 @@ async fn sibling_failure_aborts_budget_yielded_route_and_releases_prefix() { /// 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, keeping its sender alive and preventing -/// the output from observing an ending. The timeout makes the missing terminal error visible. -/// -/// 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. +/// The panic unwinds the task without reaching any arm of [`route_partition`]'s ending match, while +/// partition 1 never answers and keeps its sender alive. Without the drop guard the output would wait +/// forever. #[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( + let child = fragile( vec![Behaviour::Panics, Behaviour::Parked], Arc::new(Switch::default()), ); let plan = node(child.plan, 1); - let mut stream = output_of(&plan, 0, &context); + let mut stream = output(&plan, 0, &context); let execution = execution(&plan); wait_until("the parked peer is reading its child", || { child.polled[1].load(Ordering::SeqCst) > 0 @@ -6609,26 +5821,18 @@ async fn a_panicking_input_ends_every_output_and_stops_its_peers() { .await; } -/// 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. +/// A partition whose task alone is aborted ends every output, and stops its peers. Both partitions +/// are parked, so only the read noticing the aborted task can end it. [`Inputs::stop`] would stop +/// every task instead, which is a different outcome. #[tokio::test] async fn an_aborted_input_task_ends_every_output_and_stops_its_peers() { - let child = Fragile::plan( + let child = fragile( 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 mut stream = output(&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 @@ -6702,7 +5906,7 @@ async fn dropped_output_discards_oversized_chain_and_keeps_live_output() { let pool = Arc::new(GreedyMemoryPool::new(byte_budget)); let context = task_context(&pool); let switch = Arc::new(Switch::default()); - let child = Fragile::plan( + let child = fragile( vec![Behaviour::Held({ let mut steps = many_chunks; steps.push(Step::chunk(live_chunk)); @@ -6711,8 +5915,8 @@ async fn dropped_output_discards_oversized_chain_and_keeps_live_output() { Arc::clone(&switch), ); let plan = node(child.plan, 2); - let dropped_output = output_of(&plan, 0, &context); - let mut kept_output = output_of(&plan, 1, &context); + let dropped_output = output(&plan, 0, &context); + let mut kept_output = output(&plan, 1, &context); assert_eq!(0, pool.reserved(), "held child has not produced a chunk"); drop(dropped_output); assert_eq!( @@ -6754,7 +5958,7 @@ async fn discarded_open_chain_is_validated_before_live_chain_routes() { let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); let context = task_context(&pool); let switch = Arc::new(Switch::default()); - let child = Fragile::plan( + let child = fragile( vec![Behaviour::Gated(vec![ Step::chunk(chunk(doomed, 0, 1, false)), Step::chunk(invalid), @@ -6762,8 +5966,8 @@ async fn discarded_open_chain_is_validated_before_live_chain_routes() { Arc::clone(&switch), ); let plan = node(child.plan, 2); - let dropped_output = output_of(&plan, 0, &context); - let mut kept_output = output_of(&plan, 1, &context); + let dropped_output = output(&plan, 0, &context); + let mut kept_output = output(&plan, 1, &context); wait_until("valid prefix is flushed and child parks at gate", || { pool.reserved() > 0 && child.polled[0].load(Ordering::SeqCst) >= 2 }) @@ -6825,7 +6029,7 @@ async fn closing_destination_releases_an_open_chain_before_child_resumes() { let switch = Arc::new(Switch::default()); let pool = Arc::new(GreedyMemoryPool::new(1 << 20)); let context = task_context(&pool); - let child = Fragile::plan( + let child = fragile( vec![Behaviour::Gated(vec![ Step::chunk(chunk(doomed.clone(), 0, 1, false)), Step::chunk(chunk(doomed, 1, 1, true)), @@ -6834,8 +6038,8 @@ async fn closing_destination_releases_an_open_chain_before_child_resumes() { Arc::clone(&switch), ); let plan = node(child.plan, 2); - let dropped_output = output_of(&plan, 0, &context); - let mut kept_output = output_of(&plan, 1, &context); + let dropped_output = output(&plan, 0, &context); + let mut kept_output = output(&plan, 1, &context); wait_until("open chain is retained and child is gated", || { pool.reserved() > 0 }) @@ -6868,7 +6072,7 @@ async fn dropping_an_output_leaves_surviving_outputs_running() { let switch = Arc::new(Switch::default()); let doomed = labels_routed_to(0, 1).remove(0); let survivor = labels_routed_to(1, 1).remove(0); - let child = Fragile::plan( + let child = fragile( vec![ Behaviour::OneAtATime(vec![ Step::chunk(chunk(doomed.clone(), 0, 1, true)), @@ -6882,8 +6086,8 @@ async fn dropping_an_output_leaves_surviving_outputs_running() { 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 dropped_output = output(&plan, 0, &context); + let mut kept_output = output(&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 @@ -6925,7 +6129,7 @@ async fn dropping_an_output_leaves_surviving_outputs_running() { async fn sliced_chunk_memory_is_charged_by_rows_and_released_after_success_drop_and_failure() { let slices = sliced_chunks(labels("sliced")); let probe_context = task_context(&Arc::new(GreedyMemoryPool::new(usize::MAX))); - let probe_child = Scripted::plan(vec![ + let probe_child = scripted(vec![ slices .iter() .cloned() @@ -6949,7 +6153,7 @@ async fn sliced_chunk_memory_is_charged_by_rows_and_released_after_success_drop_ let pool = Arc::new(GreedyMemoryPool::new(success_budget)); let context = task_context(&pool); let plan = node( - Scripted::plan(vec![ + scripted(vec![ slices .iter() .cloned() @@ -6958,8 +6162,8 @@ async fn sliced_chunk_memory_is_charged_by_rows_and_released_after_success_drop_ ]), 1, ); - let mut output = output_of(&plan, 0, &context); - let (chunks, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut output)) + let mut stream = output(&plan, 0, &context); + let (chunks, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut stream)) .await .unwrap(); assert!( @@ -6977,7 +6181,7 @@ async fn sliced_chunk_memory_is_charged_by_rows_and_released_after_success_drop_ let pool = Arc::new(GreedyMemoryPool::new(success_budget)); let context = task_context(&pool); let plan = node( - Scripted::plan(vec![ + scripted(vec![ slices .iter() .cloned() @@ -6986,13 +6190,13 @@ async fn sliced_chunk_memory_is_charged_by_rows_and_released_after_success_drop_ ]), 1, ); - let mut output = output_of(&plan, 0, &context); - let first = futures::future::poll_fn(|cx| output.as_mut().poll_next(cx)) + let mut stream = output(&plan, 0, &context); + let first = futures::future::poll_fn(|cx| stream.as_mut().poll_next(cx)) .await .expect("first slice arrives") .expect("first slice succeeds"); drop(first); - drop(output); + drop(stream); drop(plan); wait_until("dropping the output releases slice memory", || { pool.reserved() == 0 @@ -7012,7 +6216,7 @@ async fn sliced_chunk_memory_is_charged_by_rows_and_released_after_success_drop_ let pool = Arc::new(GreedyMemoryPool::new(budget)); let context = task_context(&pool); let plan = node( - Scripted::plan(vec![ + scripted(vec![ slices .iter() .cloned() @@ -7021,8 +6225,8 @@ async fn sliced_chunk_memory_is_charged_by_rows_and_released_after_success_drop_ ]), 1, ); - let mut output = output_of(&plan, 0, &context); - let (_, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut output)) + let mut stream = output(&plan, 0, &context); + let (_, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut stream)) .await .unwrap(); assert_eq!( @@ -7048,7 +6252,7 @@ async fn internal_stream_releases_each_chunk_charge_only_when_polled() { let ceiling = 2 * std::mem::size_of::() + 2 * 1024; let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); let context = task_context(&pool); - let child = Scripted::plan(vec![ + let child = scripted(vec![ slices .into_iter() .map(|(series, is_last)| Step::Chunk(series, is_last)) @@ -7160,7 +6364,7 @@ async fn public_repartition_interleaved_histogram_tables_stay_linear() { ) .unwrap(); inputs.push(vec![Step::chunk((float_series, true))]); - let child = Scripted::plan(inputs); + let child = scripted(inputs); let context = unbounded_context(); let plan = node(child, 1); let mut frames = plan.execute(0, Arc::clone(&context)).unwrap(); @@ -7247,7 +6451,7 @@ async fn public_repartition_interleaved_histogram_tables_stay_linear() { #[tokio::test] async fn packed_child_frame_decodes_all_256_closing_chunks() { let metric = labels("packed-child"); - let child = Scripted::plan(vec![ + let child = scripted(vec![ (0..256) .map(|position| Step::chunk(chunk(metric.clone(), position, 1, position == 255))) .collect(), @@ -7269,7 +6473,7 @@ async fn packed_child_frame_decodes_all_256_closing_chunks() { let plan = node(child, 1); let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); let context = task_context(&pool); - let mut output = output_of(&plan, 0, &context); + let mut output = output(&plan, 0, &context); let (chunks, errors) = until_end(&mut output).await; assert!( errors.is_empty(), @@ -7299,7 +6503,7 @@ async fn histogram_chain_slices_fit_a_budget_below_the_full_table_charge() { Step::Chunk(series, position == 255) }) .collect::>(); - let child = Scripted::plan(vec![steps]); + let child = scripted(vec![steps]); let probe_context = task_context(&Arc::new(GreedyMemoryPool::new(usize::MAX))); let mut frames = child.execute(0, Arc::clone(&probe_context)).unwrap(); let batch = frames @@ -7434,12 +6638,12 @@ async fn histogram_table_memory_is_charged_and_released_with_retained_chain() { } _ => panic!("histogram sample expected"), }; - let child = Scripted::plan(vec![vec![Step::Chunk(series, is_last)]]); + let child = scripted(vec![vec![Step::Chunk(series, is_last)]]); let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); let context = task_context(&pool); let plan = node(child, 1); - let mut output = output_of(&plan, 0, &context); - let result = tokio::time::timeout(Duration::from_secs(10), until_end(&mut output)) + let mut stream = output(&plan, 0, &context); + let result = tokio::time::timeout(Duration::from_secs(10), until_end(&mut stream)) .await .expect("histogram output completes"); assert!(result.1.is_empty()); @@ -7456,19 +6660,19 @@ async fn histogram_table_memory_is_charged_and_released_with_retained_chain() { let pool = Arc::new(GreedyMemoryPool::new(usize::MAX)); let context = task_context(&pool); let plan = node( - Scripted::plan(vec![vec![ + scripted(vec![vec![ Step::Chunk(first.clone(), false), Step::Chunk(second.clone(), true), ]]), 1, ); - let mut output = output_of(&plan, 0, &context); + let mut stream = output(&plan, 0, &context); let current_execution = execution(&plan); wait_until("producer queued both shared-table chunks", || { producer_stopped(¤t_execution) }) .await; - let probe_child = Scripted::plan(vec![vec![ + let probe_child = scripted(vec![vec![ Step::Chunk(first.clone(), false), Step::Chunk(second.clone(), true), ]]); @@ -7526,12 +6730,12 @@ async fn histogram_table_memory_is_charged_and_released_with_retained_chain() { the two chunks hold", pool.reserved() ); - let first = futures::future::poll_fn(|cx| output.as_mut().poll_next(cx)) + let first = futures::future::poll_fn(|cx| stream.as_mut().poll_next(cx)) .await .unwrap() .unwrap(); drop(first); - drop(output); + drop(stream); drop(plan); assert_eq!( 0, @@ -7540,7 +6744,7 @@ async fn histogram_table_memory_is_charged_and_released_with_retained_chain() { ); let (many, _) = histogram_rows_chunk(labels("histogram-many"), 0, 256); - let probe_child = Scripted::plan(vec![vec![Step::Chunk(many.clone(), true)]]); + let probe_child = scripted(vec![vec![Step::Chunk(many.clone(), true)]]); let probe_context = task_context(&Arc::new(GreedyMemoryPool::new(usize::MAX))); let decoded = unpack_evaluated_series( probe_child.execute(0, Arc::clone(&probe_context)).unwrap(), @@ -7566,35 +6770,19 @@ async fn histogram_table_memory_is_charged_and_released_with_retained_chain() { // descriptor and rows on top of that, so it is refused and leaves nothing behind. let pool = Arc::new(GreedyMemoryPool::new(table_cost)); let context = task_context(&pool); - let plan = node(Scripted::plan(vec![vec![Step::Chunk(many, true)]]), 1); - let mut output = output_of(&plan, 0, &context); - let (_, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut output)) + let plan = node(scripted(vec![vec![Step::Chunk(many, true)]]), 1); + let mut stream = output(&plan, 0, &context); + let (_, errors) = tokio::time::timeout(Duration::from_secs(10), until_end(&mut stream)) .await .unwrap(); assert_eq!(1, errors.len(), "underbudget histogram slice is refused"); assert_eq!(0, pool.reserved(), "refusal releases slice charge"); } -/// 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 has room for one -/// chunk of the chain and not for two: the growth that is refused is the one that would have made -/// the buffer exceed the pool. -/// -/// The room is counted in the data the chunks hold and not in the figure the read charges them with: -/// every chunk of the chain is a `Series` descriptor around a single float row, and four of those -/// descriptors are what the pool is made of, so one chunk fits and the chain of `CHUNKS` does not, -/// whatever the read goes on to charge for one. -/// -/// 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. +/// A chain is buffered whole before it is routed, so an open chain is charged as it grows. One that +/// outgrows the pool ends every stream with the refusal, cancels the parked peer and releases what it +/// held. The pool is sized in `Series` descriptors, one per chunk, so the bound does not depend on the +/// figure the read charges. #[tokio::test] async fn a_chain_that_outgrows_the_pool_ends_every_output_and_releases_it() { const CHUNKS: usize = 8; @@ -7609,7 +6797,7 @@ async fn a_chain_that_outgrows_the_pool_ends_every_output_and_releases_it() { // per poll -- not for how much one chunk costs. let per_chunk = std::mem::size_of::(); { - let probe = Fragile::plan( + let probe = fragile( vec![Behaviour::OneAtATime(vec![ Step::chunk(chunk(shared.clone(), 0, 1, false)), Step::chunk(chunk(shared.clone(), 1, 1, true)), @@ -7647,7 +6835,7 @@ async fn a_chain_that_outgrows_the_pool_ends_every_output_and_releases_it() { ); let pool = Arc::new(GreedyMemoryPool::new(pool_size)); let context = task_context(&pool); - let child = Fragile::plan( + let child = fragile( vec![Behaviour::OneAtATime(steps), Behaviour::Parked], Arc::new(Switch::default()), ); @@ -7692,16 +6880,17 @@ async fn a_chain_that_outgrows_the_pool_ends_every_output_and_releases_it() { #[tokio::test] async fn dropping_a_raw_open_chain_cancels_and_releases_its_reservation() { let switch = Arc::new(Switch::default()); - let child = RawScripted::plan(vec![RawPartition { - chunks: vec![ - raw_chunk("k", Some(raw_metric("a")), &[1], vec![Some(1.0)], false), - raw_chunk("k", Some(raw_metric("a")), &[2], vec![Some(2.0)], false), - ], - gate: Some(Arc::clone(&switch)), - // The switch stays closed while this partial chunk is delivered and charged; the producer - // then parks at EOF until the destination is dropped. - gate_chunks: false, - }]); + // One open chunk, so the drop always lands while the producer is parked at EOF. + let child = raw_scripted(vec![RawPartition::open_until( + vec![raw_chunk( + "k", + Some(raw_metric("a")), + &[1], + vec![Some(1.0)], + false, + )], + &switch, + )]); let plan = raw_node(child, 1); let pool = Arc::new(GreedyMemoryPool::new(8 << 20)); let context = task_context(&pool); @@ -7719,39 +6908,6 @@ async fn dropping_a_raw_open_chain_cancels_and_releases_its_reservation() { assert_eq!(0, pool.reserved()); } -#[tokio::test] -async fn dropping_a_raw_destination_releases_its_partial_chain() { - let switch = Arc::new(Switch::default()); - let child = RawScripted::plan(vec![RawPartition { - chunks: vec![raw_chunk( - "k", - Some(raw_metric("a")), - &[1], - vec![Some(1.0)], - false, - )], - gate: Some(Arc::clone(&switch)), - // The switch stays closed while this partial chunk is delivered and charged; the producer - // then parks at EOF until the destination is dropped. - gate_chunks: false, - }]); - let plan = raw_node(child, 1); - let pool = Arc::new(GreedyMemoryPool::new(8 << 20)); - let context = task_context(&pool); - let frames = plan.execute(0, Arc::clone(&context)).unwrap(); - let stream = unpack_raw_series(frames, Some(raw_schema())).unwrap(); - wait_until("raw partial chain is reserved", || pool.reserved() > 0).await; - drop(stream); - tokio::time::timeout(Duration::from_secs(10), async { - while !producer_stopped(&execution(&plan)) { - tokio::task::yield_now().await; - } - }) - .await - .expect("dropping the destination stops its raw producer"); - assert_eq!(0, pool.reserved()); -} - #[tokio::test] async fn raw_chain_pool_refusal_releases_partial_reservation() { let first = raw_chunk("k", Some(raw_metric("a")), &[1], vec![Some(1.0)], false); @@ -7760,11 +6916,10 @@ async fn raw_chain_pool_refusal_releases_partial_reservation() { let probe_pool = Arc::new(GreedyMemoryPool::new(8 << 20)); let probe_switch = Arc::new(Switch::default()); let probe_plan = raw_node( - RawScripted::plan(vec![RawPartition { - chunks: vec![first.clone()], - gate: Some(Arc::clone(&probe_switch)), - gate_chunks: false, - }]), + raw_scripted(vec![RawPartition::open_until( + vec![first.clone()], + &probe_switch, + )]), 1, ); let probe_context = task_context(&probe_pool); @@ -7775,11 +6930,7 @@ async fn raw_chain_pool_refusal_releases_partial_reservation() { drop(probe_stream); probe_switch.open(); let pool = Arc::new(GreedyMemoryPool::new(budget)); - let child = RawScripted::plan(vec![RawPartition { - chunks: vec![first, second], - gate: None, - gate_chunks: false, - }]); + let child = raw_scripted(vec![RawPartition::new(vec![first, second])]); let plan = raw_node(child, 1); let context = task_context(&pool); let (_, error) = tokio::time::timeout(Duration::from_secs(10), drain_raw(&plan, &context)) @@ -7812,29 +6963,21 @@ async fn raw_matching_routing_groups_by_match_key() { ) .expect("legal labels") }; - let child = RawScripted::plan(vec![ - RawPartition { - chunks: vec![raw_chunk( - "ka", - Some(with_zone("a")), - &[1], - vec![Some(1.0)], - true, - )], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![raw_chunk( - "kb", - Some(with_zone("b")), - &[1], - vec![Some(2.0)], - true, - )], - gate: None, - gate_chunks: false, - }, + let child = raw_scripted(vec![ + RawPartition::new(vec![raw_chunk( + "ka", + Some(with_zone("a")), + &[1], + vec![Some(1.0)], + true, + )]), + RawPartition::new(vec![raw_chunk( + "kb", + Some(with_zone("b")), + &[1], + vec![Some(2.0)], + true, + )]), ]); let plan = Arc::new( raw_node_with_routing( @@ -7895,11 +7038,7 @@ async fn raw_matching_routing_groups_by_match_key() { #[test] fn raw_canonical_labels_routing_is_refused() { - let child = RawScripted::plan(vec![RawPartition { - chunks: vec![], - gate: None, - gate_chunks: false, - }]); + let child = raw_scripted(vec![RawPartition::new(vec![])]); let error = raw_node_with_routing(child, 1, SeriesRouting::CanonicalLabels) .expect_err("raw canonical labels routing must remain unsupported"); assert!(error.to_string().contains("cannot use CanonicalLabels")); @@ -7908,29 +7047,24 @@ fn raw_canonical_labels_routing_is_refused() { #[tokio::test] async fn raw_identity_publishes_once_every_input_contributed() { let switch = Arc::new(Switch::default()); - let child = RawScripted::plan(vec![ - RawPartition { - chunks: vec![raw_chunk( - "k", - Some(raw_metric("a")), - &[1, 3], - vec![Some(1.0), Some(3.0)], - true, - )], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![raw_chunk( + let child = raw_scripted(vec![ + RawPartition::new(vec![raw_chunk( + "k", + Some(raw_metric("a")), + &[1, 3], + vec![Some(1.0), Some(3.0)], + true, + )]), + RawPartition::open_until( + vec![raw_chunk( "k", Some(raw_metric("a")), &[2, 4], vec![Some(2.0), Some(4.0)], true, )], - gate: Some(Arc::clone(&switch)), - gate_chunks: false, - }, + &switch, + ), ]); let plan = raw_node(child, 1); let context = task_context(&Arc::new(GreedyMemoryPool::new(8 << 20))); @@ -7958,29 +7092,24 @@ async fn raw_identity_publishes_once_every_input_contributed() { #[tokio::test] async fn raw_identity_waits_for_an_input_that_has_not_contributed() { let switch = Arc::new(Switch::default()); - let child = RawScripted::plan(vec![ - RawPartition { - chunks: vec![raw_chunk( - "k", - Some(raw_metric("a")), - &[1, 3], - vec![Some(1.0), Some(3.0)], - true, - )], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![raw_chunk( + let child = raw_scripted(vec![ + RawPartition::new(vec![raw_chunk( + "k", + Some(raw_metric("a")), + &[1, 3], + vec![Some(1.0), Some(3.0)], + true, + )]), + RawPartition::held_by( + vec![raw_chunk( "k", Some(raw_metric("a")), &[2, 4], vec![Some(2.0), Some(4.0)], true, )], - gate: Some(Arc::clone(&switch)), - gate_chunks: true, - }, + &switch, + ), ]); let plan = raw_node(child, 1); let context = task_context(&Arc::new(GreedyMemoryPool::new(8 << 20))); @@ -8011,9 +7140,9 @@ async fn raw_chunks_of_one_batch_are_charged_their_own_slice() { const SERIES: usize = 64; const ROWS: usize = 64; let switch = Arc::new(Switch::default()); - let child = RawScripted::plan(vec![ - RawPartition { - chunks: (0..SERIES) + let child = raw_scripted(vec![ + RawPartition::new( + (0..SERIES) .map(|series| { let times: Vec = (0..ROWS as i64) .map(|row| series as i64 * 1000 + row) @@ -8028,14 +7157,8 @@ async fn raw_chunks_of_one_batch_are_charged_their_own_slice() { ) }) .collect(), - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: Vec::new(), - gate: Some(Arc::clone(&switch)), - gate_chunks: false, - }, + ), + RawPartition::open_until(Vec::new(), &switch), ]); let plan = raw_node(child, 1); let pool = Arc::new(GreedyMemoryPool::new(64 << 20)); @@ -8119,19 +7242,11 @@ async fn raw_histogram_index_arrays_are_charged() { ) .expect("one series' samples are a legal raw chunk"); let switch = Arc::new(Switch::default()); - let child = RawScripted::plan(vec![ - RawPartition { - chunks: vec![chunk], - gate: None, - gate_chunks: false, - }, + let child = raw_scripted(vec![ + RawPartition::new(vec![chunk]), // An input that has contributed nothing keeps the group unpublished, which is what holds // the first input's charges alive to be measured. - RawPartition { - chunks: Vec::new(), - gate: Some(Arc::clone(&switch)), - gate_chunks: false, - }, + RawPartition::open_until(Vec::new(), &switch), ]); let plan = raw_node(child, 1); let pool = Arc::new(GreedyMemoryPool::new(64 << 20)); @@ -8158,29 +7273,24 @@ async fn raw_histogram_index_arrays_are_charged() { #[tokio::test] async fn an_ordered_frame_publishes_a_key_its_inputs_have_passed() { let switch = Arc::new(Switch::default()); - let child = RawScripted::plan_with_ordering( + let child = raw_scripted_with_ordering( vec![ - RawPartition { - chunks: vec![ - raw_chunk("a", Some(raw_metric("a")), &[1], vec![Some(1.0)], true), - raw_chunk("b", Some(raw_metric("b")), &[1], vec![Some(2.0)], true), - ], - gate: None, - gate_chunks: false, - }, + RawPartition::new(vec![ + raw_chunk("a", Some(raw_metric("a")), &[1], vec![Some(1.0)], true), + raw_chunk("b", Some(raw_metric("b")), &[1], vec![Some(2.0)], true), + ]), // Contributes `a` and then stays open: `a` is complete, and nothing has been seen past // `b`, so `b` waits. - RawPartition { - chunks: vec![raw_chunk( + RawPartition::open_until( + vec![raw_chunk( "a", Some(raw_metric("a")), &[3], vec![Some(3.0)], true, )], - gate: Some(Arc::clone(&switch)), - gate_chunks: false, - }, + &switch, + ), ], SeriesOrdering::KeyThenTime, ); @@ -8224,32 +7334,27 @@ async fn an_ordered_frame_publishes_a_key_its_inputs_have_passed() { #[tokio::test] async fn an_ordered_watermark_lets_an_identity_publish_without_input_eof() { let switch = Arc::new(Switch::default()); - let child = RawScripted::plan_with_ordering( + let child = raw_scripted_with_ordering( vec![ - RawPartition { - chunks: vec![raw_chunk( - "a", - Some(raw_metric("a")), - &[1], - vec![Some(1.0)], - true, - )], - gate: None, - gate_chunks: false, - }, + RawPartition::new(vec![raw_chunk( + "a", + Some(raw_metric("a")), + &[1], + vec![Some(1.0)], + true, + )]), // Delivers `b`, which proves this input passed `a`, then stays open so neither input // ends before `a` is published. - RawPartition { - chunks: vec![raw_chunk( + RawPartition::open_until( + vec![raw_chunk( "b", Some(raw_metric("b")), &[2], vec![Some(2.0)], true, )], - gate: Some(Arc::clone(&switch)), - gate_chunks: false, - }, + &switch, + ), ], SeriesOrdering::KeyThenTime, ); @@ -8274,24 +7379,16 @@ async fn an_ordered_watermark_lets_an_identity_publish_without_input_eof() { #[tokio::test] async fn an_ordered_identity_waits_for_an_input_that_has_not_passed_the_key() { let switch = Arc::new(Switch::default()); - let child = RawScripted::plan_with_ordering( + let child = raw_scripted_with_ordering( vec![ - RawPartition { - chunks: vec![raw_chunk( - "a", - Some(raw_metric("a")), - &[1], - vec![Some(1.0)], - true, - )], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: Vec::new(), - gate: Some(Arc::clone(&switch)), - gate_chunks: true, - }, + RawPartition::new(vec![raw_chunk( + "a", + Some(raw_metric("a")), + &[1], + vec![Some(1.0)], + true, + )]), + RawPartition::held_by(Vec::new(), &switch), ], SeriesOrdering::KeyThenTime, ); @@ -8321,29 +7418,21 @@ async fn an_ordered_identity_waits_for_an_input_that_has_not_passed_the_key() { #[tokio::test] async fn raw_identity_groups_by_primary_key_not_labels() { - let child = RawScripted::plan(vec![ - RawPartition { - chunks: vec![raw_chunk( - "k1", - Some(raw_metric("a")), - &[1], - vec![Some(1.0)], - true, - )], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![raw_chunk( - "k2", - Some(raw_metric("a")), - &[2], - vec![Some(2.0)], - true, - )], - gate: None, - gate_chunks: false, - }, + let child = raw_scripted(vec![ + RawPartition::new(vec![raw_chunk( + "k1", + Some(raw_metric("a")), + &[1], + vec![Some(1.0)], + true, + )]), + RawPartition::new(vec![raw_chunk( + "k2", + Some(raw_metric("a")), + &[2], + vec![Some(2.0)], + true, + )]), ]); let plan = raw_node(child, 1); let pool = Arc::new(GreedyMemoryPool::new(8 << 20)); @@ -8363,29 +7452,21 @@ async fn raw_identity_groups_by_primary_key_not_labels() { #[tokio::test] async fn raw_pieces_of_one_key_must_agree_on_labels() { - let child = RawScripted::plan(vec![ - RawPartition { - chunks: vec![raw_chunk( - "k", - Some(raw_metric("a")), - &[1], - vec![Some(1.0)], - true, - )], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![raw_chunk( - "k", - Some(raw_metric("b")), - &[2], - vec![Some(2.0)], - true, - )], - gate: None, - gate_chunks: false, - }, + let child = raw_scripted(vec![ + RawPartition::new(vec![raw_chunk( + "k", + Some(raw_metric("a")), + &[1], + vec![Some(1.0)], + true, + )]), + RawPartition::new(vec![raw_chunk( + "k", + Some(raw_metric("b")), + &[2], + vec![Some(2.0)], + true, + )]), ]); let plan = raw_node(child, 1); let pool = Arc::new(GreedyMemoryPool::new(8 << 20)); @@ -8401,29 +7482,21 @@ async fn raw_pieces_of_one_key_must_agree_on_labels() { #[tokio::test] async fn a_raw_merge_conflict_fails_the_execution() { - let child = RawScripted::plan(vec![ - RawPartition { - chunks: vec![raw_chunk( - "k", - Some(raw_metric("a")), - &[1], - vec![Some(1.0)], - true, - )], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![raw_chunk( - "k", - Some(raw_metric("a")), - &[1], - vec![Some(2.0)], - true, - )], - gate: None, - gate_chunks: false, - }, + let child = raw_scripted(vec![ + RawPartition::new(vec![raw_chunk( + "k", + Some(raw_metric("a")), + &[1], + vec![Some(1.0)], + true, + )]), + RawPartition::new(vec![raw_chunk( + "k", + Some(raw_metric("a")), + &[1], + vec![Some(2.0)], + true, + )]), ]); let plan = raw_node(child, 1); let pool = Arc::new(GreedyMemoryPool::new(8 << 20)); @@ -8645,17 +7718,10 @@ async fn the_child_is_read_the_way_the_consumer_reads_this_node() { ); } -/// A merged field is charged for every segment it is made of, not for one view of all of them. -/// -/// An inner router folds two pieces of one identity into a chunk whose field is two dense segments, -/// and asking such a field for a single dense view answers `None`. Charging that answer billed the -/// merged chunk as timestamps alone, so a router that queued it held live bytes nothing accounted -/// for - and the charge it was merged under was released as soon as the read that produced it ended. -/// -/// The figure is read at exactly that moment: the inner publication has been read to its end and -/// dropped, the outer queue has not been consumed, so what the pool still counts is the bytes the -/// queue is holding. Both are checked against the buffers themselves, so a field that costs -/// nothing cannot pass on the strength of the timestamps beside it. +/// A merged field is charged for every segment it is made of. An inner router folds two pieces of one +/// identity into a field of two dense segments, which has no single dense view. The charge is read +/// after the inner publication is dropped and before the outer queue is consumed, so the pool counts +/// only what the queue holds. #[tokio::test] async fn a_merged_field_is_charged_what_the_queue_holds_once_the_merge_charge_is_gone() { const SEGMENT: usize = 4096; @@ -8672,17 +7738,9 @@ async fn a_merged_field_is_charged_what_the_queue_holds_once_the_merge_charge_is // Two inputs, one closed piece of one identity each: what the inner router folds them into is one // chunk whose field is the two segments it was merged from. let inner = raw_node( - RawScripted::plan(vec![ - RawPartition { - chunks: vec![fragment(0)], - gate: None, - gate_chunks: false, - }, - RawPartition { - chunks: vec![fragment(SEGMENT as i64)], - gate: None, - gate_chunks: false, - }, + raw_scripted(vec![ + RawPartition::new(vec![fragment(0)]), + RawPartition::new(vec![fragment(SEGMENT as i64)]), ]), 1, );