datafusion-physical-plan 56.0.0

Physical (ExecutionPlan) implementations for DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! Snapshot tests for *which input the merge drains, and in what order*.
//!
//! The round-robin tie breaker in [`SortPreservingMergeStream`] never changes
//! the merged output: rows with equal sort keys are interchangeable, so the
//! sorted values are identical whether it is on or off. All it changes is
//! which tied input gets consumed next, and therefore which upstream producers
//! keep making progress. Ordinary correctness tests are blind to that, which
//! makes the behavior easy to regress silently.
//!
//! This module drives a merge over hand-written inputs and records an
//! interleaved trace of everything an outside observer can see:
//!
//! * `poll S<n>` — the merge asked input `n` for another batch
//! * `row  S<n>` — the merge emitted a row that came from input `n`
//!
//! The traces are asserted with inline `insta` snapshots, so a change in poll
//! order shows up as a snapshot diff instead of passing unnoticed. To accept
//! an intended change, run the tests with `INSTA_FORCE_UPDATE=1` and apply the
//! result with `cargo insta accept`, rather than hand-editing the expected
//! text -- the point is that changing it is a deliberate act.
//!
//! [`SortPreservingMergeStream`]: crate::sorts::merge::SortPreservingMergeStream

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;

/// One event observed while driving a merge.
#[derive(Debug)]
enum TraceEvent {
    /// The merge polled input `partition`, which returned a batch of `keys`.
    Batch { partition: usize, keys: Vec<i32> },
    /// The merge polled input `partition`, which reported end of stream.
    Eof { partition: usize },
    /// The merge emitted an output row that originated in `partition`.
    Row { partition: usize, key: i32 },
}

/// Shared, append-only log of [`TraceEvent`]s.
///
/// The input streams append to it from inside the merge's `poll_next`, and the
/// driver appends emitted rows in between, which is what makes the two kinds
/// of event interleave in issue order.
type TraceLog = Arc<Mutex<Vec<TraceEvent>>>;

/// Wraps one input of the merge and logs every poll that resolves.
///
/// `Poll::Pending` is not logged: these inputs are always immediately ready,
/// so a pending poll never happens.
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()
    }
}

/// `(key, source partition)` pairs; `key` is the sort key, the partition index
/// rides along so emitted rows can be attributed back to their input.
fn trace_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("key", DataType::Int32, false),
        Field::new("src", DataType::Int32, false),
    ]))
}

/// Builds one input stream: `batches` is a list of batches, each a list of
/// sort keys. All rows are tagged with `partition`.
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),
    }
}

/// Merges `inputs` (partition -> batch -> sort keys) and returns the rendered
/// trace of polls and emitted rows.
///
/// The merge runs with `batch_size = 1` so every output row is handed back
/// individually and can be slotted into the log at the point it was produced.
/// Output batching is independent of the loser tree and the tie breaker, so
/// this makes the trace finer-grained without changing what is being traced.
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())
}

/// Renders the inputs and the recorded events as the snapshot text.
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(",")
}

/// Traces the same inputs with the tie breaker enabled and disabled, so a
/// single snapshot shows what the tie breaker changes.
async fn trace_both(inputs: &[&[&[i32]]]) -> String {
    format!(
        "{}\n{}",
        trace_merge(inputs, true).await,
        trace_merge(inputs, false).await
    )
}

/// With every key tied, the tie breaker must hand rows out in strict
/// round-robin order; with it off, the lowest-index input is drained first and
/// the other producer is left idle.
#[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
    ");
}

/// Regression test for stale poll counts leaking across runs of ties.
///
/// `S0` runs out of `1`s first, so the first run of ties ends with `S1` still
/// holding several rows that it drains on its own. The second run (key `2`)
/// is a fresh tie-breaker round and must alternate from its very first row.
///
/// Before the fix, `is_poll_count_gt` compared the challenger's *raw* counter,
/// which still held the count `S1` accumulated during the key `1` run, and the
/// key `2` run started `S1 S0 S0 S1` instead of alternating.
#[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
    ");
}

/// Without ties there is nothing to break: both settings must produce the same
/// poll order. A diff here means the tie breaker started interfering with the
/// ordinary loser-tree path.
#[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
    ");
}

/// The tie breaker only runs at the root of the loser tree (`cmp_node == 1`),
/// so with four tied inputs it balances the two sub-tree winners rather than
/// all four producers: `S1` and `S3` still drain in one go.
///
/// This is a known limitation, recorded here so that widening the tie breaker
/// to inner nodes shows up as a deliberate snapshot change. Note also that the
/// initial polls are not in partition order — `initialize_all_partitions` uses
/// `swap_remove`, which reorders the pending list.
#[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
    ");
}