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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// 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

//! Shared test helpers for the colocated `try_to_proto` / `try_from_proto`
//! plan unit tests.
//!
//! These let a test drive a plan's serde hooks without depending on
//! `datafusion-proto` (which sits above this crate and would create a
//! dependency cycle): the dispatch inversion in [`crate::proto`] means a test
//! can supply its own [`ExecutionPlanEncode`] / [`ExecutionPlanDecode`].
//!
//! This is the plan-level sibling of `datafusion_physical_expr::proto_test_util`.
//!
//! # What this tier is for
//!
//! Colocated tests prove a plan handles *its own fields*: enum conversions that
//! must be by-name, the `[u32::MAX]` empty-projection sentinel, `fetch`
//! presence semantics (absent → `None`, not `Some(0)`). They live next to the
//! field so they rot when someone adds one, and they can assert on wire state
//! that a plan's `Debug` output never shows.
//!
//! They do *not* replace the central round-trip tests in `datafusion-proto`,
//! which prove things this tier structurally cannot: that the real
//! `PhysicalExtensionCodec` works, that dispatch actually reaches the hook, and
//! that bytes survive bytes.

use std::cell::Cell;
use std::sync::Arc;

use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_execution::TaskContext;
use datafusion_expr::physical_planning_context::ScalarSubqueryResults;
use datafusion_expr::{AggregateUDF, ScalarUDF, WindowUDF};
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr::expressions::Column;
use datafusion_proto_models::protobuf::{
    self, PhysicalExprNode, PhysicalPlanNode, physical_expr_node,
};

use crate::ExecutionPlan;
use crate::empty::EmptyExec;
use crate::proto::{ExecutionPlanDecode, ExecutionPlanEncode};

/// The schema shared by the stub child plans: `a: Int32, b: Int32`.
///
/// Two columns so a test can build an ordering (or a join key pair) whose
/// members stay distinguishable through the hooks.
pub(crate) fn stub_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("a", DataType::Int32, true),
        Field::new("b", DataType::Int32, true),
    ]))
}

/// A child plan to hang the plan under test off of.
pub(crate) fn stub_child() -> Arc<dyn ExecutionPlan> {
    Arc::new(EmptyExec::new(stub_schema()))
}

/// A proto node for a `Column`, as a stand-in child node when building a plan's
/// proto representation by hand.
pub(crate) fn column_node(name: &str, index: u32) -> PhysicalExprNode {
    PhysicalExprNode {
        expr_id: None,
        expr_type: Some(physical_expr_node::ExprType::Column(
            protobuf::PhysicalColumn {
                name: name.to_string(),
                index,
            },
        )),
    }
}

/// A proto node for a sort expression over `name`, as written by the sort
/// plans' `try_to_proto`.
pub(crate) fn sort_expr_node(
    name: &str,
    index: u32,
    asc: bool,
    nulls_first: bool,
) -> PhysicalExprNode {
    PhysicalExprNode {
        expr_id: None,
        expr_type: Some(physical_expr_node::ExprType::Sort(Box::new(
            protobuf::PhysicalSortExprNode {
                expr: Some(Box::new(column_node(name, index))),
                asc,
                nulls_first,
            },
        ))),
    }
}

/// The placeholder node [`StubPlanEncoder`] emits for every child plan.
///
/// Distinct from `PhysicalPlanNode::default()` so a test can tell "the hook
/// encoded the child" apart from "the field was left at its default".
pub(crate) fn encoded_child_node() -> PhysicalPlanNode {
    PhysicalPlanNode {
        physical_plan_type: Some(protobuf::physical_plan_node::PhysicalPlanType::Empty(
            protobuf::EmptyExecNode {
                schema: None,
                partitions: 0,
            },
        )),
    }
}

/// Encoder stub for driving `try_to_proto`.
///
/// Emits a recognizable placeholder for each child plan and expression, counts
/// the calls, and can fail on the Nth call so the `ctx.encode_child(..)?` /
/// `ctx.encode_expr(..)?` error arms are exercised too.
pub(crate) struct StubPlanEncoder {
    plan_calls: Cell<usize>,
    expr_calls: Cell<usize>,
    fail_plan_on: Option<usize>,
    fail_expr_on: Option<usize>,
}

impl StubPlanEncoder {
    /// Always succeeds.
    pub(crate) fn ok() -> Self {
        Self {
            plan_calls: Cell::new(0),
            expr_calls: Cell::new(0),
            fail_plan_on: None,
            fail_expr_on: None,
        }
    }

    /// Fails on the `call`-th child-plan encode (1-based).
    pub(crate) fn failing_on_plan(call: usize) -> Self {
        Self {
            fail_plan_on: Some(call),
            ..Self::ok()
        }
    }

    /// Fails on the `call`-th expression encode (1-based).
    pub(crate) fn failing_on_expr(call: usize) -> Self {
        Self {
            fail_expr_on: Some(call),
            ..Self::ok()
        }
    }

    /// How many child plans were encoded.
    pub(crate) fn plan_calls(&self) -> usize {
        self.plan_calls.get()
    }

    /// How many expressions were encoded.
    pub(crate) fn expr_calls(&self) -> usize {
        self.expr_calls.get()
    }
}

impl ExecutionPlanEncode for StubPlanEncoder {
    fn encode_plan(&self, _plan: &Arc<dyn ExecutionPlan>) -> Result<PhysicalPlanNode> {
        let call = self.plan_calls.get() + 1;
        self.plan_calls.set(call);
        if Some(call) == self.fail_plan_on {
            return Err(DataFusionError::Internal(format!(
                "stub plan encode failure on call {call}"
            )));
        }
        Ok(encoded_child_node())
    }

    fn encode_expr(&self, _expr: &Arc<dyn PhysicalExpr>) -> Result<PhysicalExprNode> {
        let call = self.expr_calls.get() + 1;
        self.expr_calls.set(call);
        if Some(call) == self.fail_expr_on {
            return Err(DataFusionError::Internal(format!(
                "stub expr encode failure on call {call}"
            )));
        }
        Ok(column_node("child", 0))
    }

    fn encode_udf(&self, _udf: &ScalarUDF) -> Result<Option<Vec<u8>>> {
        Ok(None)
    }

    fn encode_udaf(&self, _udaf: &AggregateUDF) -> Result<Option<Vec<u8>>> {
        Ok(None)
    }

    fn encode_udwf(&self, _udwf: &WindowUDF) -> Result<Option<Vec<u8>>> {
        Ok(None)
    }
}

/// Decoder stub for driving `try_from_proto`.
///
/// Returns a fixed [`stub_child`] plan for every child node and decodes column
/// nodes for real (so a test can still tell two sort keys apart), counting
/// calls and optionally failing on the Nth one.
pub(crate) struct StubPlanDecoder {
    task_ctx: Arc<TaskContext>,
    plan_calls: Cell<usize>,
    expr_calls: Cell<usize>,
    fail_plan_on: Option<usize>,
    fail_expr_on: Option<usize>,
}

impl StubPlanDecoder {
    /// Always succeeds.
    pub(crate) fn ok() -> Self {
        Self {
            task_ctx: Arc::new(TaskContext::default()),
            plan_calls: Cell::new(0),
            expr_calls: Cell::new(0),
            fail_plan_on: None,
            fail_expr_on: None,
        }
    }

    /// Fails on the `call`-th child-plan decode (1-based).
    pub(crate) fn failing_on_plan(call: usize) -> Self {
        Self {
            fail_plan_on: Some(call),
            ..Self::ok()
        }
    }

    /// Fails on the `call`-th expression decode (1-based).
    pub(crate) fn failing_on_expr(call: usize) -> Self {
        Self {
            fail_expr_on: Some(call),
            ..Self::ok()
        }
    }

    /// How many child plans were decoded.
    pub(crate) fn plan_calls(&self) -> usize {
        self.plan_calls.get()
    }

    /// How many expressions were decoded.
    pub(crate) fn expr_calls(&self) -> usize {
        self.expr_calls.get()
    }
}

impl ExecutionPlanDecode for StubPlanDecoder {
    fn decode_plan(&self, _node: &PhysicalPlanNode) -> Result<Arc<dyn ExecutionPlan>> {
        let call = self.plan_calls.get() + 1;
        self.plan_calls.set(call);
        if Some(call) == self.fail_plan_on {
            return Err(DataFusionError::Internal(format!(
                "stub plan decode failure on call {call}"
            )));
        }
        Ok(stub_child())
    }

    fn decode_plan_with_scalar_subquery_results(
        &self,
        node: &PhysicalPlanNode,
        _results: ScalarSubqueryResults,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        self.decode_plan(node)
    }

    fn decode_expr(
        &self,
        node: &PhysicalExprNode,
        _input_schema: &Schema,
    ) -> Result<Arc<dyn PhysicalExpr>> {
        let call = self.expr_calls.get() + 1;
        self.expr_calls.set(call);
        if Some(call) == self.fail_expr_on {
            return Err(DataFusionError::Internal(format!(
                "stub expr decode failure on call {call}"
            )));
        }
        match &node.expr_type {
            Some(physical_expr_node::ExprType::Column(c)) => {
                Ok(Arc::new(Column::new(&c.name, c.index as usize)))
            }
            _ => Ok(Arc::new(Column::new("a", 0))),
        }
    }

    fn task_ctx(&self) -> &TaskContext {
        &self.task_ctx
    }

    fn decode_udf(&self, name: &str, _payload: Option<&[u8]>) -> Result<Arc<ScalarUDF>> {
        internal_err!("stub decoder cannot decode the scalar UDF {name}")
    }

    fn decode_udaf(
        &self,
        name: &str,
        _payload: Option<&[u8]>,
    ) -> Result<Arc<AggregateUDF>> {
        internal_err!("stub decoder cannot decode the aggregate UDF {name}")
    }

    fn decode_udwf(&self, name: &str, _payload: Option<&[u8]>) -> Result<Arc<WindowUDF>> {
        internal_err!("stub decoder cannot decode the window UDF {name}")
    }
}

/// Minimal extension plans for the [`crate::proto::registry`] tests.
///
/// Deliberately tiny: they exist to exercise name registration, collision
/// detection and the extension-node encode / decode pair, not to
/// execute.
pub(crate) mod registry_test_plan {
    use super::stub_schema;
    use crate::execution_plan::{Boundedness, EmissionType};
    use crate::proto::{
        ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx, ExtensionPlanFromProto,
    };
    use crate::{
        DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
        SendableRecordBatchStream,
    };
    use datafusion_common::tree_node::TreeNodeRecursion;
    use datafusion_common::{Result, internal_err};
    use datafusion_execution::TaskContext;
    use datafusion_physical_expr::{EquivalenceProperties, Partitioning};
    use datafusion_proto_models::protobuf::PhysicalPlanNode;
    use std::fmt::Formatter;
    use std::sync::Arc;

    fn stub_properties() -> Arc<PlanProperties> {
        Arc::new(PlanProperties::new(
            EquivalenceProperties::new(stub_schema()),
            Partitioning::UnknownPartitioning(1),
            EmissionType::Incremental,
            Boundedness::Bounded,
        ))
    }

    /// Defines an extension plan carrying a `String` payload and its children,
    /// serialized through the extension helpers on the plan contexts.
    macro_rules! extension_plan {
        ($name:ident, $plan_name:literal) => {
            #[derive(Debug)]
            pub(crate) struct $name {
                pub(crate) payload: String,
                pub(crate) children: Vec<Arc<dyn ExecutionPlan>>,
                properties: Arc<PlanProperties>,
            }

            impl $name {
                pub(crate) fn new(
                    payload: impl Into<String>,
                    children: Vec<Arc<dyn ExecutionPlan>>,
                ) -> Self {
                    Self {
                        payload: payload.into(),
                        children,
                        properties: stub_properties(),
                    }
                }
            }

            impl DisplayAs for $name {
                fn fmt_as(
                    &self,
                    _t: DisplayFormatType,
                    f: &mut Formatter,
                ) -> std::fmt::Result {
                    write!(f, "{}({})", $plan_name, self.payload)
                }
            }

            impl ExecutionPlan for $name {
                fn name(&self) -> &str {
                    $plan_name
                }

                fn properties(&self) -> &Arc<PlanProperties> {
                    &self.properties
                }

                fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
                    self.children.iter().collect()
                }

                fn apply_expressions(
                    &self,
                    _f: &mut dyn FnMut(
                        &Arc<dyn crate::PhysicalExpr>,
                    ) -> Result<TreeNodeRecursion>,
                ) -> Result<TreeNodeRecursion> {
                    Ok(TreeNodeRecursion::Continue)
                }

                fn with_new_children(
                    self: Arc<Self>,
                    children: Vec<Arc<dyn ExecutionPlan>>,
                ) -> Result<Arc<dyn ExecutionPlan>> {
                    Ok(Arc::new(Self::new(self.payload.clone(), children)))
                }

                fn execute(
                    &self,
                    _partition: usize,
                    _context: Arc<TaskContext>,
                ) -> Result<SendableRecordBatchStream> {
                    internal_err!("{} is a serde-only test stub", $plan_name)
                }

                fn try_to_proto(
                    &self,
                    ctx: &ExecutionPlanEncodeCtx<'_>,
                ) -> Result<Option<PhysicalPlanNode>> {
                    Ok(Some(ctx.extension_node::<Self>(
                        self.payload.as_bytes().to_vec(),
                        self.children(),
                    )?))
                }
            }

            impl ExtensionPlanFromProto for $name {
                const NAME: &'static str = $plan_name;

                fn try_from_proto(
                    node: &PhysicalPlanNode,
                    ctx: &ExecutionPlanDecodeCtx<'_>,
                ) -> Result<Arc<dyn ExecutionPlan>> {
                    let extension = crate::expect_plan_variant!(
                        node,
                        datafusion_proto_models::protobuf::physical_plan_node::PhysicalPlanType::Extension,
                        "Extension"
                    );
                    let children = ctx.decode_children(&extension.inputs)?;
                    let Ok(payload) = std::str::from_utf8(&extension.node) else {
                        return internal_err!("{} payload is not UTF-8", $plan_name);
                    };
                    Ok(Arc::new(Self::new(payload, children)))
                }
            }

        };
    }

    extension_plan!(RegisteredExec, "datafusion-test.RegisteredExec");
    // A *different* Rust type claiming the same name: the collision two
    // independent crates could hit.
    extension_plan!(RegisteredExecClone, "datafusion-test.RegisteredExec");
    extension_plan!(OtherRegisteredExec, "datafusion-test.OtherRegisteredExec");
    // A plan whose author forgot to fill in `NAME`: registration must
    // reject it rather than let an unnamed node reach the wire.
    extension_plan!(UnnamedExec, "");
}

/// Decoder that must never run: asserts that the reject paths of a
/// `try_from_proto` (wrong node variant, missing required child) bail out
/// before any decoding happens.
pub(crate) struct UnreachablePlanDecoder {
    task_ctx: Arc<TaskContext>,
}

impl UnreachablePlanDecoder {
    pub(crate) fn new() -> Self {
        Self {
            task_ctx: Arc::new(TaskContext::default()),
        }
    }
}

impl ExecutionPlanDecode for UnreachablePlanDecoder {
    fn decode_plan(&self, _node: &PhysicalPlanNode) -> Result<Arc<dyn ExecutionPlan>> {
        unreachable!("decode_plan must not be reached when the node is rejected")
    }

    fn decode_plan_with_scalar_subquery_results(
        &self,
        _node: &PhysicalPlanNode,
        _results: ScalarSubqueryResults,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        unreachable!("decode_plan must not be reached when the node is rejected")
    }

    fn decode_expr(
        &self,
        _node: &PhysicalExprNode,
        _input_schema: &Schema,
    ) -> Result<Arc<dyn PhysicalExpr>> {
        unreachable!("decode_expr must not be reached when the node is rejected")
    }

    fn task_ctx(&self) -> &TaskContext {
        &self.task_ctx
    }

    fn decode_udf(&self, _name: &str, _payload: Option<&[u8]>) -> Result<Arc<ScalarUDF>> {
        unreachable!("decode_udf must not be reached when the node is rejected")
    }

    fn decode_udaf(
        &self,
        _name: &str,
        _payload: Option<&[u8]>,
    ) -> Result<Arc<AggregateUDF>> {
        unreachable!("decode_udaf must not be reached when the node is rejected")
    }

    fn decode_udwf(
        &self,
        _name: &str,
        _payload: Option<&[u8]>,
    ) -> Result<Arc<WindowUDF>> {
        unreachable!("decode_udwf must not be reached when the node is rejected")
    }
}