use std::fmt::Write as _;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use crate::metrics::{BaselineMetrics, ExecutionPlanMetricsSet};
use crate::sorts::streaming_merge::StreamingMergeBuilder;
use crate::stream::RecordBatchStreamAdapter;
use crate::{RecordBatchStream, SendableRecordBatchStream};
use arrow::array::{AsArray, Int32Array, RecordBatch};
use arrow::datatypes::{DataType, Field, Int32Type, Schema, SchemaRef};
use datafusion_common::Result;
use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr, expressions::col};
use futures::{Stream, StreamExt};
use insta::assert_snapshot;
#[derive(Debug)]
enum TraceEvent {
Batch { partition: usize, keys: Vec<i32> },
Eof { partition: usize },
Row { partition: usize, key: i32 },
}
type TraceLog = Arc<Mutex<Vec<TraceEvent>>>;
struct TracingStream {
partition: usize,
inner: SendableRecordBatchStream,
log: TraceLog,
}
impl Stream for TracingStream {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let partition = self.partition;
let polled = self.inner.poll_next_unpin(cx);
match &polled {
Poll::Ready(Some(Ok(batch))) => {
let keys = batch
.column(0)
.as_primitive::<Int32Type>()
.values()
.to_vec();
self.log
.lock()
.unwrap()
.push(TraceEvent::Batch { partition, keys });
}
Poll::Ready(None) => {
self.log.lock().unwrap().push(TraceEvent::Eof { partition });
}
Poll::Ready(Some(Err(_))) | Poll::Pending => {}
}
polled
}
}
impl RecordBatchStream for TracingStream {
fn schema(&self) -> SchemaRef {
self.inner.schema()
}
}
fn trace_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("key", DataType::Int32, false),
Field::new("src", DataType::Int32, false),
]))
}
fn input_stream(partition: usize, batches: &[&[i32]], log: &TraceLog) -> TracingStream {
let schema = trace_schema();
let batches: Vec<Result<RecordBatch>> = batches
.iter()
.map(|keys| {
RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(keys.to_vec())),
Arc::new(Int32Array::from(vec![partition as i32; keys.len()])),
],
)
.map_err(Into::into)
})
.collect();
TracingStream {
partition,
inner: Box::pin(RecordBatchStreamAdapter::new(
schema,
futures::stream::iter(batches),
)),
log: Arc::clone(log),
}
}
async fn trace_merge(inputs: &[&[&[i32]]], round_robin_tie_breaker: bool) -> String {
let schema = trace_schema();
let log: TraceLog = Arc::new(Mutex::new(Vec::new()));
let streams: Vec<SendableRecordBatchStream> = inputs
.iter()
.enumerate()
.map(|(partition, batches)| {
Box::pin(input_stream(partition, batches, &log)) as SendableRecordBatchStream
})
.collect();
let ordering: LexOrdering =
[PhysicalSortExpr::new_default(col("key", &schema).unwrap())].into();
let mut merged = StreamingMergeBuilder::new()
.with_streams(streams)
.with_schema(Arc::clone(&schema))
.with_expressions(&ordering)
.with_metrics(BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0))
.with_batch_size(1)
.with_bypass_mempool()
.with_round_robin_tie_breaker(round_robin_tie_breaker)
.build()
.unwrap();
while let Some(batch) = merged.next().await {
let batch = batch.unwrap();
let keys = batch.column(0).as_primitive::<Int32Type>();
let sources = batch.column(1).as_primitive::<Int32Type>();
let mut log = log.lock().unwrap();
for row in 0..batch.num_rows() {
log.push(TraceEvent::Row {
partition: sources.value(row) as usize,
key: keys.value(row),
});
}
}
render(inputs, round_robin_tie_breaker, &log.lock().unwrap())
}
fn render(
inputs: &[&[&[i32]]],
round_robin_tie_breaker: bool,
events: &[TraceEvent],
) -> String {
let mut out = String::new();
writeln!(out, "round_robin_tie_breaker = {round_robin_tie_breaker}").unwrap();
writeln!(out, "inputs:").unwrap();
for (partition, batches) in inputs.iter().enumerate() {
let batches = batches
.iter()
.map(|keys| format!("[{}]", join(keys)))
.collect::<Vec<_>>()
.join(" ");
writeln!(out, " S{partition}: {batches}").unwrap();
}
writeln!(out, "trace:").unwrap();
for event in events {
match event {
TraceEvent::Batch { partition, keys } => {
writeln!(out, " poll S{partition} -> [{}]", join(keys)).unwrap()
}
TraceEvent::Eof { partition } => {
writeln!(out, " poll S{partition} -> done").unwrap()
}
TraceEvent::Row { partition, key } => {
writeln!(out, " row S{partition} key={key}").unwrap()
}
}
}
out
}
fn join(keys: &[i32]) -> String {
keys.iter()
.map(|k| k.to_string())
.collect::<Vec<_>>()
.join(",")
}
async fn trace_both(inputs: &[&[&[i32]]]) -> String {
format!(
"{}\n{}",
trace_merge(inputs, true).await,
trace_merge(inputs, false).await
)
}
#[tokio::test]
async fn test_tied_keys_alternate_between_inputs() {
let inputs: &[&[&[i32]]] = &[&[&[1, 1, 1]], &[&[1, 1, 1]]];
assert_snapshot!(trace_both(inputs).await, @r"
round_robin_tie_breaker = true
inputs:
S0: [1,1,1]
S1: [1,1,1]
trace:
poll S0 -> [1,1,1]
poll S1 -> [1,1,1]
row S0 key=1
row S1 key=1
row S0 key=1
row S1 key=1
row S0 key=1
poll S0 -> done
row S1 key=1
poll S1 -> done
round_robin_tie_breaker = false
inputs:
S0: [1,1,1]
S1: [1,1,1]
trace:
poll S0 -> [1,1,1]
poll S1 -> [1,1,1]
row S0 key=1
row S0 key=1
row S0 key=1
poll S0 -> done
row S1 key=1
row S1 key=1
row S1 key=1
poll S1 -> done
");
}
#[tokio::test]
async fn test_poll_counts_reset_between_runs_of_ties() {
let inputs: &[&[&[i32]]] = &[&[&[1, 1], &[2, 2]], &[&[1, 1, 1, 1], &[2, 2]]];
assert_snapshot!(trace_both(inputs).await, @r"
round_robin_tie_breaker = true
inputs:
S0: [1,1] [2,2]
S1: [1,1,1,1] [2,2]
trace:
poll S0 -> [1,1]
poll S1 -> [1,1,1,1]
row S0 key=1
row S1 key=1
row S0 key=1
poll S0 -> [2,2]
row S1 key=1
row S1 key=1
row S1 key=1
poll S1 -> [2,2]
row S0 key=2
row S1 key=2
row S0 key=2
poll S0 -> done
row S1 key=2
poll S1 -> done
round_robin_tie_breaker = false
inputs:
S0: [1,1] [2,2]
S1: [1,1,1,1] [2,2]
trace:
poll S0 -> [1,1]
poll S1 -> [1,1,1,1]
row S0 key=1
row S0 key=1
poll S0 -> [2,2]
row S1 key=1
row S1 key=1
row S1 key=1
row S1 key=1
poll S1 -> [2,2]
row S0 key=2
row S0 key=2
poll S0 -> done
row S1 key=2
row S1 key=2
poll S1 -> done
");
}
#[tokio::test]
async fn test_distinct_keys_are_unaffected_by_the_tie_breaker() {
let inputs: &[&[&[i32]]] = &[&[&[1, 3, 5]], &[&[2, 4, 6]]];
assert_snapshot!(trace_both(inputs).await, @r"
round_robin_tie_breaker = true
inputs:
S0: [1,3,5]
S1: [2,4,6]
trace:
poll S0 -> [1,3,5]
poll S1 -> [2,4,6]
row S0 key=1
row S1 key=2
row S0 key=3
row S1 key=4
row S0 key=5
poll S0 -> done
row S1 key=6
poll S1 -> done
round_robin_tie_breaker = false
inputs:
S0: [1,3,5]
S1: [2,4,6]
trace:
poll S0 -> [1,3,5]
poll S1 -> [2,4,6]
row S0 key=1
row S1 key=2
row S0 key=3
row S1 key=4
row S0 key=5
poll S0 -> done
row S1 key=6
poll S1 -> done
");
}
#[tokio::test]
async fn test_tie_breaker_only_balances_the_root_comparison() {
let inputs: &[&[&[i32]]] = &[&[&[1, 1]], &[&[1, 1]], &[&[1, 1]], &[&[1, 1]]];
assert_snapshot!(trace_merge(inputs, true).await, @r"
round_robin_tie_breaker = true
inputs:
S0: [1,1]
S1: [1,1]
S2: [1,1]
S3: [1,1]
trace:
poll S0 -> [1,1]
poll S3 -> [1,1]
poll S2 -> [1,1]
poll S1 -> [1,1]
row S0 key=1
row S2 key=1
row S0 key=1
poll S0 -> done
row S1 key=1
row S1 key=1
poll S1 -> done
row S2 key=1
poll S2 -> done
row S3 key=1
row S3 key=1
poll S3 -> done
");
}