Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
2151 lines (1946 loc) · 77.5 KB
/
Copy pathmod.rs
File metadata and controls
2151 lines (1946 loc) · 77.5 KB
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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
use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;
use arrow::datatypes::Schema;
use datafusion_catalog::memory::MemorySourceConfig;
use datafusion_common::{
DataFusionError, Result, internal_datafusion_err, internal_err, not_impl_err,
};
use datafusion_datasource_arrow::source::ArrowSource;
#[cfg(feature = "avro")]
use datafusion_datasource_avro::source::AvroSource;
use datafusion_datasource_csv::file_format::CsvSink;
use datafusion_datasource_csv::source::CsvSource;
use datafusion_datasource_json::file_format::JsonSink;
use datafusion_datasource_json::source::JsonSource;
#[cfg(feature = "parquet")]
use datafusion_datasource_parquet::file_format::ParquetSink;
#[cfg(feature = "parquet")]
use datafusion_datasource_parquet::source::ParquetSource;
use datafusion_execution::{FunctionRegistry, TaskContext};
use datafusion_expr::physical_planning_context::ScalarSubqueryResults;
use datafusion_expr::{AggregateUDF, HigherOrderUDF, ScalarUDF, WindowUDF};
use datafusion_functions_table::generate_series;
use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
use datafusion_physical_plan::aggregates::AggregateExec;
use datafusion_physical_plan::analyze::AnalyzeExec;
use datafusion_physical_plan::async_func::AsyncFuncExec;
use datafusion_physical_plan::buffer::BufferExec;
#[expect(
deprecated,
reason = "`CoalesceBatchesExec` remains supported for protobuf compatibility"
)]
use datafusion_physical_plan::coalesce_batches::CoalesceBatchesExec;
use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec;
use datafusion_physical_plan::coop::CooperativeExec;
use datafusion_physical_plan::empty::EmptyExec;
use datafusion_physical_plan::explain::ExplainExec;
use datafusion_physical_plan::filter::FilterExec;
use datafusion_physical_plan::joins::{
AsOfJoinExec, CrossJoinExec, HashJoinExec, NestedLoopJoinExec,
PiecewiseMergeJoinExec, SortMergeJoinExec, SymmetricHashJoinExec,
};
use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec};
use datafusion_physical_plan::memory::LazyMemoryExec;
use datafusion_physical_plan::placeholder_row::PlaceholderRowExec;
use datafusion_physical_plan::projection::ProjectionExec;
use datafusion_physical_plan::proto::{
ExecutionPlanDecode, ExecutionPlanDecodeCtx, ExecutionPlanEncode,
ExecutionPlanEncodeCtx, ProtoDecoderRegistry, decode_execution_plan,
execution_plan_names,
};
use datafusion_physical_plan::repartition::RepartitionExec;
use datafusion_physical_plan::scalar_subquery::ScalarSubqueryExec;
use datafusion_physical_plan::sorts::sort::SortExec;
use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
use datafusion_physical_plan::union::{InterleaveExec, UnionExec};
use datafusion_physical_plan::unnest::UnnestExec;
use datafusion_physical_plan::windows::WindowAggExec;
use datafusion_physical_plan::{ExecutionPlan, PhysicalExpr};
use prost::Message;
use prost::bytes::BufMut;
use crate::physical_plan::from_proto::parse_physical_expr_with_converter;
use crate::physical_plan::to_proto::serialize_physical_expr_with_converter;
use crate::protobuf::physical_plan_node::PhysicalPlanType;
use crate::protobuf::{self, proto_error};
pub mod from_proto;
pub mod to_proto;
const HUMAN_DISPLAY_ALIAS_PREFIX: &str = "\u{1f}datafusion_human_display_alias_v1:";
fn encode_human_display_alias(human_display: &str, alias: &str) -> String {
format!(
"{HUMAN_DISPLAY_ALIAS_PREFIX}{}:{alias}{human_display}",
alias.len()
)
}
#[cfg(test)]
mod file_scan_config_serde {
use super::*;
use arrow::datatypes::{DataType, Field, SchemaRef};
use datafusion::physical_expr_adapter::{
DefaultPhysicalExprAdapterFactory, PhysicalExprAdapter,
PhysicalExprAdapterFactory,
};
use datafusion_common::{Constraint, Constraints, ScalarValue, Statistics};
use datafusion_datasource::file::FileSource;
use datafusion_datasource::file_compression_type::FileCompressionType;
use datafusion_datasource::file_groups::FileGroup;
use datafusion_datasource::file_scan_config::{
FileScanConfig, FileScanConfigBuilder,
};
use datafusion_datasource::file_stream::FileOpener;
use datafusion_datasource::{PartitionedFile, TableSchema};
use datafusion_execution::object_store::ObjectStoreUrl;
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr::projection::{
ProjectionExpr as FileProjectionExpr, ProjectionExprs as FileProjectionExprs,
};
use datafusion_physical_expr::{
LexOrdering, Partitioning, PhysicalSortExpr, RangePartitioning, SplitPoint,
};
use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
use object_store::ObjectStore;
#[derive(Clone)]
struct SerdeTestSource {
metrics: ExecutionPlanMetricsSet,
table_schema: TableSchema,
projection: Option<FileProjectionExprs>,
}
impl SerdeTestSource {
fn new(
table_schema: TableSchema,
projection: Option<FileProjectionExprs>,
) -> Self {
Self {
metrics: ExecutionPlanMetricsSet::new(),
table_schema,
projection,
}
}
}
#[derive(Debug)]
struct SerdeTestExprAdapter;
impl PhysicalExprAdapter for SerdeTestExprAdapter {
fn rewrite(&self, expr: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {
Ok(expr)
}
}
#[derive(Debug)]
struct SerdeTestExprAdapterFactory;
impl PhysicalExprAdapterFactory for SerdeTestExprAdapterFactory {
fn create(
&self,
_logical_file_schema: SchemaRef,
_physical_file_schema: SchemaRef,
) -> Result<Arc<dyn PhysicalExprAdapter>> {
Ok(Arc::new(SerdeTestExprAdapter))
}
}
impl FileSource for SerdeTestSource {
fn create_file_opener(
&self,
_object_store: Arc<dyn ObjectStore>,
_base_config: &FileScanConfig,
_partition: usize,
) -> Result<Arc<dyn FileOpener>> {
internal_err!("not needed for FileScanConfig serde tests")
}
fn table_schema(&self) -> &TableSchema {
&self.table_schema
}
fn with_batch_size(&self, _batch_size: usize) -> Arc<dyn FileSource> {
Arc::new(self.clone())
}
fn metrics(&self) -> &ExecutionPlanMetricsSet {
&self.metrics
}
fn file_type(&self) -> &str {
"serde-test"
}
fn apply_expressions(
&self,
f: &mut dyn FnMut(
&Arc<dyn PhysicalExpr>,
)
-> Result<datafusion_common::tree_node::TreeNodeRecursion>,
) -> Result<datafusion_common::tree_node::TreeNodeRecursion> {
datafusion_physical_plan::apply_expression_roots(
self.projection.iter().flatten(),
f,
)
}
fn try_pushdown_projection(
&self,
projection: &FileProjectionExprs,
) -> Result<Option<Arc<dyn FileSource>>> {
Ok(Some(Arc::new(Self {
projection: Some(projection.clone()),
..self.clone()
})))
}
fn projection(&self) -> Option<&FileProjectionExprs> {
self.projection.as_ref()
}
}
fn populated_projection() -> FileProjectionExprs {
FileProjectionExprs::new(vec![FileProjectionExpr::new(
Arc::new(Column::new("value", 0)),
"projected_value",
)])
}
fn test_config(output_partitioning: Option<Partitioning>) -> FileScanConfig {
test_config_with_projection(output_partitioning, Some(populated_projection()))
}
fn test_config_with_projection(
output_partitioning: Option<Partitioning>,
projection: Option<FileProjectionExprs>,
) -> FileScanConfig {
let file_schema = Arc::new(
Schema::new(vec![
Field::new("value", DataType::Int32, false),
Field::new("label", DataType::Utf8, true),
])
.with_metadata(HashMap::from([(
"serde_test_key".to_string(),
"serde_test_value".to_string(),
)])),
);
let table_schema = TableSchema::builder(Arc::clone(&file_schema))
.with_table_partition_cols(vec![Arc::new(Field::new(
"part",
DataType::Utf8,
false,
))])
.build();
let table_statistics = Statistics::new_unknown(table_schema.table_schema());
let source = Arc::new(SerdeTestSource::new(table_schema, projection));
let first_file = PartitionedFile::new("data/part=a/file.arrow", 1024)
.with_partition_values(vec![ScalarValue::Utf8(Some("a".to_string()))])
.with_range(10, 900)
.with_arrow_schema(Arc::clone(&file_schema))
.with_statistics(Arc::new(table_statistics.clone()));
let second_file = PartitionedFile::new("data/part=b/file.arrow", 2048)
.with_partition_values(vec![ScalarValue::Utf8(Some("b".to_string()))]);
let third_file = PartitionedFile::new("data/part=c/file.arrow", 4096)
.with_partition_values(vec![ScalarValue::Utf8(Some("c".to_string()))])
.with_arrow_schema(Arc::clone(&file_schema));
let ordering = LexOrdering::new(vec![PhysicalSortExpr::new_default(Arc::new(
Column::new("value", 0),
))])
.expect("single expression ordering");
FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), source)
.with_file_groups(vec![
FileGroup::new(vec![first_file, second_file]),
FileGroup::new(vec![third_file]),
])
.with_constraints(Constraints::new_unverified(vec![Constraint::PrimaryKey(
vec![0],
)]))
.with_statistics(table_statistics)
.with_limit(Some(17))
.with_batch_size(Some(256))
.with_file_compression_type(FileCompressionType::GZIP)
.with_output_ordering(vec![ordering])
.with_output_partitioning(output_partitioning)
.build()
}
fn hash_partitioning() -> Partitioning {
Partitioning::Hash(vec![Arc::new(Column::new("value", 0))], 3)
}
fn range_partitioning() -> Partitioning {
let ordering = LexOrdering::new(vec![PhysicalSortExpr::new_default(Arc::new(
Column::new("value", 0),
))])
.expect("single expression ordering");
Partitioning::Range(
RangePartitioning::try_new_with_samples(
ordering,
vec![SplitPoint::new(vec![ScalarValue::Int32(Some(10))])],
2,
)
.unwrap(),
)
}
fn decode_source(conf: &protobuf::FileScanExecConf) -> Result<Arc<dyn FileSource>> {
Ok(Arc::new(SerdeTestSource::new(
FileScanConfig::parse_table_schema_from_proto(conf)?,
None,
)))
}
struct FileScanSerdeHarness {
codec: DefaultPhysicalExtensionCodec,
converter: DefaultPhysicalProtoConverter,
task_ctx: TaskContext,
}
impl FileScanSerdeHarness {
fn new() -> Self {
Self {
codec: DefaultPhysicalExtensionCodec {},
converter: DefaultPhysicalProtoConverter {},
task_ctx: TaskContext::default(),
}
}
fn encode(&self, config: &FileScanConfig) -> Result<protobuf::FileScanExecConf> {
let encoder = ConverterPlanEncoder {
codec: &self.codec,
proto_converter: &self.converter,
};
config.try_to_proto(&ExecutionPlanEncodeCtx::new(&encoder))
}
fn decode(&self, conf: &protobuf::FileScanExecConf) -> Result<FileScanConfig> {
self.decode_with_source(conf, decode_source(conf)?)
}
fn decode_with_source(
&self,
conf: &protobuf::FileScanExecConf,
file_source: Arc<dyn FileSource>,
) -> Result<FileScanConfig> {
let physical_decode_ctx =
PhysicalPlanDecodeContext::new(&self.task_ctx, &self.codec);
let decoder = ConverterPlanDecoder {
ctx: &physical_decode_ctx,
proto_converter: &self.converter,
};
FileScanConfig::try_from_proto(
conf,
&ExecutionPlanDecodeCtx::new(&decoder),
file_source,
)
}
}
#[test]
fn new_file_scan_config_serde_roundtrips_all_partitioning_variants() -> Result<()> {
let serde = FileScanSerdeHarness::new();
for config in [
test_config(None),
test_config(Some(Partitioning::RoundRobinBatch(2))),
test_config(Some(hash_partitioning())),
test_config(Some(range_partitioning())),
test_config(Some(Partitioning::UnknownPartitioning(4))),
] {
let encoded = serde.encode(&config)?;
let reencoded = serde.encode(&serde.decode(&encoded)?)?;
assert_eq!(reencoded.output_partitioning, encoded.output_partitioning);
}
Ok(())
}
#[test]
fn new_file_scan_config_serde_preserves_complete_fixture() -> Result<()> {
let serde = FileScanSerdeHarness::new();
let config = test_config(None);
let decoded = serde.decode(&serde.encode(&config)?)?;
assert_eq!(decoded.constraints, config.constraints);
assert_eq!(
decoded.file_schema().metadata,
config.file_schema().metadata
);
assert_eq!(decoded.file_groups.len(), 2);
assert_eq!(decoded.file_groups[0].len(), 2);
assert_eq!(decoded.file_groups[1].len(), 1);
assert!(decoded.file_groups[0].files()[0].arrow_schema.is_some());
assert!(decoded.file_groups[0].files()[1].arrow_schema.is_none());
assert_eq!(decoded.file_compression_type, FileCompressionType::GZIP);
Ok(())
}
#[test]
fn new_file_scan_config_serde_preserves_explicit_order_flag() -> Result<()> {
let serde = FileScanSerdeHarness::new();
let preserve_without_ordering = FileScanConfigBuilder::from(test_config(None))
.with_output_ordering(vec![])
.with_preserve_order(true)
.build();
let encoded = serde.encode(&preserve_without_ordering)?;
assert_eq!(encoded.preserve_order, Some(true));
let decoded = serde.decode(&encoded)?;
assert!(decoded.preserve_order);
assert!(decoded.output_ordering.is_empty());
let mut do_not_preserve_with_ordering = test_config(None);
do_not_preserve_with_ordering.preserve_order = false;
assert!(!do_not_preserve_with_ordering.output_ordering.is_empty());
let mut encoded = serde.encode(&do_not_preserve_with_ordering)?;
assert_eq!(encoded.preserve_order, Some(false));
let decoded = serde.decode(&encoded)?;
assert!(!decoded.preserve_order);
// The output ordering alone keeps the files in order.
assert!(decoded.preserves_file_order());
// Older payloads had no flag and derived it from the ordering.
encoded.preserve_order = None;
assert!(serde.decode(&encoded)?.preserve_order);
Ok(())
}
#[test]
fn new_file_scan_config_encode_handles_expr_adapter_factories() -> Result<()> {
let serde = FileScanSerdeHarness::new();
let default_config = FileScanConfigBuilder::from(test_config(None))
.with_expr_adapter(Some(Arc::new(DefaultPhysicalExprAdapterFactory)))
.build();
let encoded = serde.encode(&default_config)?;
assert!(serde.decode(&encoded)?.expr_adapter_factory.is_none());
let custom_config = FileScanConfigBuilder::from(test_config(None))
.with_expr_adapter(Some(Arc::new(SerdeTestExprAdapterFactory)))
.build();
let err = serde
.encode(&custom_config)
.expect_err("custom expression adapter must not be dropped");
assert!(
err.to_string().contains("expr_adapter_factory"),
"unexpected error: {err}"
);
Ok(())
}
#[test]
fn new_file_scan_config_decode_without_compression_uses_legacy_default() -> Result<()>
{
let serde = FileScanSerdeHarness::new();
let mut encoded = serde.encode(&test_config(None))?;
assert!(encoded.file_compression_type.is_some());
encoded.file_compression_type = None;
let decoded = serde.decode(&encoded)?;
assert_eq!(
decoded.file_compression_type,
FileCompressionType::UNCOMPRESSED
);
Ok(())
}
#[test]
fn new_file_scan_config_serde_preserves_projection_presence() -> Result<()> {
let serde = FileScanSerdeHarness::new();
let absent = serde.encode(&test_config_with_projection(None, None))?;
assert!(absent.projection_exprs.is_none());
assert!(serde.decode(&absent)?.file_source().projection().is_none());
let empty = serde.encode(&test_config_with_projection(
None,
Some(FileProjectionExprs::new(vec![])),
))?;
assert!(
empty
.projection_exprs
.as_ref()
.is_some_and(|projection| projection.projections.is_empty())
);
assert!(
serde
.decode(&empty)?
.file_source()
.projection()
.is_some_and(|projection| projection.as_ref().is_empty())
);
Ok(())
}
#[test]
fn new_file_scan_config_decode_rejects_malformed_required_fields() -> Result<()> {
let serde = FileScanSerdeHarness::new();
let valid = serde.encode(&test_config(None))?;
let file_source = decode_source(&valid)?;
for (field, malformed) in [
(
"schema",
protobuf::FileScanExecConf {
schema: None,
..valid.clone()
},
),
(
"constraints",
protobuf::FileScanExecConf {
constraints: None,
..valid.clone()
},
),
(
"statistics",
protobuf::FileScanExecConf {
statistics: None,
..valid.clone()
},
),
] {
let err = serde
.decode_with_source(&malformed, Arc::clone(&file_source))
.expect_err("missing required field must fail");
assert!(err.to_string().contains(field), "unexpected error: {err}");
}
let mut missing_projection_expr = valid.clone();
missing_projection_expr
.projection_exprs
.as_mut()
.expect("test config has projection expressions")
.projections[0]
.expr = None;
let err = serde
.decode_with_source(&missing_projection_expr, file_source)
.expect_err("missing projection expression must fail");
assert!(
err.to_string()
.contains("ProjectionExpr missing expr field"),
"unexpected error: {err}"
);
let mut unknown_compression = valid;
unknown_compression.file_compression_type = Some(i32::MAX);
let err = serde
.decode(&unknown_compression)
.expect_err("unknown compression type must fail");
assert!(
err.to_string().contains("Unknown file compression type"),
"unexpected error: {err}"
);
Ok(())
}
#[test]
fn new_file_scan_config_decode_rejects_invalid_range_ordering() -> Result<()> {
let serde = FileScanSerdeHarness::new();
let mut proto = serde.encode(&test_config(Some(range_partitioning())))?;
let mut duplicate_ordering = proto.clone();
let range = match duplicate_ordering
.output_partitioning
.as_mut()
.and_then(|p| p.partition_method.as_mut())
{
Some(protobuf::partitioning::PartitionMethod::Range(range)) => range,
other => panic!("expected range partitioning, got {other:?}"),
};
range.sort_expr.push(range.sort_expr[0].clone());
let err = serde
.decode(&duplicate_ordering)
.expect_err("duplicate range ordering must fail");
assert!(
err.to_string().contains("duplicate expressions"),
"unexpected error: {err}"
);
let range = match proto
.output_partitioning
.as_mut()
.and_then(|p| p.partition_method.as_mut())
{
Some(protobuf::partitioning::PartitionMethod::Range(range)) => range,
other => panic!("expected range partitioning, got {other:?}"),
};
range.sort_expr.clear();
let err = serde
.decode(&proto)
.expect_err("empty range ordering must fail");
assert!(
err.to_string().contains("requires non-empty ordering"),
"unexpected error: {err}"
);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Unit tests for the bytes-only function serde exposed on
/// [`ExecutionPlanEncodeCtx`] / [`ExecutionPlanDecodeCtx`] and backed by
/// [`ConverterPlanEncoder`] / [`ConverterPlanDecoder`]. Function-carrying
/// plans migrate in follow-up PRs, so these paths have no in-tree plan
/// caller yet; the tests pin the payload semantics (`None` == encode by
/// name) and the decode lookup order (payload → codec; else registry →
/// codec fallback with an empty buffer) that those migrations rely on.
mod function_serde {
use super::*;
use arrow::datatypes::{DataType, Field, FieldRef};
use datafusion_common::plan_err;
use datafusion_execution::config::SessionConfig;
use datafusion_execution::runtime_env::RuntimeEnv;
use datafusion_expr::function::AccumulatorArgs;
use datafusion_expr::{
Accumulator, AggregateUDFImpl, ColumnarValue, PartitionEvaluator,
ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, WindowUDFImpl,
};
use datafusion_functions_window_common::field::WindowUDFFieldArgs;
use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
#[derive(Debug, PartialEq, Eq, Hash)]
struct TestUdf {
signature: Signature,
}
impl TestUdf {
fn new() -> Self {
Self {
signature: Signature::exact(
vec![DataType::Int64],
Volatility::Immutable,
),
}
}
}
impl ScalarUDFImpl for TestUdf {
fn name(&self) -> &str {
"test_udf"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
Ok(DataType::Int64)
}
fn invoke_with_args(
&self,
_args: ScalarFunctionArgs,
) -> Result<ColumnarValue> {
plan_err!("test only")
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct TestUdaf {
signature: Signature,
}
impl TestUdaf {
fn new() -> Self {
Self {
signature: Signature::exact(
vec![DataType::Int64],
Volatility::Immutable,
),
}
}
}
impl AggregateUDFImpl for TestUdaf {
fn name(&self) -> &str {
"test_udaf"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
Ok(DataType::Int64)
}
fn accumulator(
&self,
_acc_args: AccumulatorArgs,
) -> Result<Box<dyn Accumulator>> {
plan_err!("test only")
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct TestUdwf {
signature: Signature,
}
impl TestUdwf {
fn new() -> Self {
Self {
signature: Signature::exact(
vec![DataType::Int64],
Volatility::Immutable,
),
}
}
}
impl WindowUDFImpl for TestUdwf {
fn name(&self) -> &str {
"test_udwf"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn partition_evaluator(
&self,
_partition_evaluator_args: PartitionEvaluatorArgs,
) -> Result<Box<dyn PartitionEvaluator>> {
plan_err!("test only")
}
fn field(&self, field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
Ok(Field::new(field_args.name(), DataType::Int64, true).into())
}
}
/// Codec that encodes every function as its name bytes and decodes by
/// checking the payload it receives, so tests can observe exactly what
/// crosses the bytes-only boundary.
#[derive(Debug)]
struct PayloadCodec;
impl PhysicalExtensionCodec for PayloadCodec {
fn try_decode(
&self,
_buf: &[u8],
_inputs: &[Arc<dyn ExecutionPlan>],
_ctx: &TaskContext,
_proto_converter: &dyn PhysicalProtoConverterExtension,
) -> Result<Arc<dyn ExecutionPlan>> {
internal_err!("not needed for these tests")
}
fn try_encode(
&self,
_node: Arc<dyn ExecutionPlan>,
_buf: &mut Vec<u8>,
_proto_converter: &dyn PhysicalProtoConverterExtension,
) -> Result<()> {
internal_err!("not needed for these tests")
}
fn try_encode_udf(&self, node: &ScalarUDF, buf: &mut Vec<u8>) -> Result<()> {
buf.extend_from_slice(node.name().as_bytes());
Ok(())
}
fn try_decode_udf(&self, name: &str, buf: &[u8]) -> Result<Arc<ScalarUDF>> {
assert_eq!(name, "test_udf");
assert_eq!(buf, name.as_bytes());
Ok(Arc::new(ScalarUDF::from(TestUdf::new())))
}
fn try_encode_udaf(
&self,
node: &AggregateUDF,
buf: &mut Vec<u8>,
) -> Result<()> {
buf.extend_from_slice(node.name().as_bytes());
Ok(())
}
fn try_decode_udaf(
&self,
name: &str,
buf: &[u8],
) -> Result<Arc<AggregateUDF>> {
assert_eq!(name, "test_udaf");
assert_eq!(buf, name.as_bytes());
Ok(Arc::new(AggregateUDF::from(TestUdaf::new())))
}
fn try_encode_udwf(&self, node: &WindowUDF, buf: &mut Vec<u8>) -> Result<()> {
buf.extend_from_slice(node.name().as_bytes());
Ok(())
}
fn try_decode_udwf(&self, name: &str, buf: &[u8]) -> Result<Arc<WindowUDF>> {
assert_eq!(name, "test_udwf");
assert_eq!(buf, name.as_bytes());
Ok(Arc::new(WindowUDF::from(TestUdwf::new())))
}
}
/// Codec whose decode hooks only accept an empty payload, to pin the
/// by-name decode fallback (registry miss → codec with `&[]`).
#[derive(Debug)]
struct EmptyPayloadOnlyCodec;
impl PhysicalExtensionCodec for EmptyPayloadOnlyCodec {
fn try_decode(
&self,
_buf: &[u8],
_inputs: &[Arc<dyn ExecutionPlan>],
_ctx: &TaskContext,
_proto_converter: &dyn PhysicalProtoConverterExtension,
) -> Result<Arc<dyn ExecutionPlan>> {
internal_err!("not needed for these tests")
}
fn try_encode(
&self,
_node: Arc<dyn ExecutionPlan>,
_buf: &mut Vec<u8>,
_proto_converter: &dyn PhysicalProtoConverterExtension,
) -> Result<()> {
internal_err!("not needed for these tests")
}
fn try_decode_udf(&self, _name: &str, buf: &[u8]) -> Result<Arc<ScalarUDF>> {
assert!(buf.is_empty());
Ok(Arc::new(ScalarUDF::from(TestUdf::new())))
}
fn try_decode_udaf(
&self,
_name: &str,
buf: &[u8],
) -> Result<Arc<AggregateUDF>> {
assert!(buf.is_empty());
Ok(Arc::new(AggregateUDF::from(TestUdaf::new())))
}
fn try_decode_udwf(&self, _name: &str, buf: &[u8]) -> Result<Arc<WindowUDF>> {
assert!(buf.is_empty());
Ok(Arc::new(WindowUDF::from(TestUdwf::new())))
}
}
fn encode_ctx_over<'a>(
codec: &'a dyn PhysicalExtensionCodec,
proto_converter: &'a dyn PhysicalProtoConverterExtension,
) -> ConverterPlanEncoder<'a> {
ConverterPlanEncoder {
codec,
proto_converter,
}
}
#[test]
fn encode_by_name_functions_produce_no_payload() -> Result<()> {
let codec = DefaultPhysicalExtensionCodec {};
let converter = DefaultPhysicalProtoConverter {};
let encoder = encode_ctx_over(&codec, &converter);
let ctx = ExecutionPlanEncodeCtx::new(&encoder);
assert!(ctx.encode_udf(&ScalarUDF::from(TestUdf::new()))?.is_none());
assert!(
ctx.encode_udaf(&AggregateUDF::from(TestUdaf::new()))?
.is_none()
);
assert!(
ctx.encode_udwf(&WindowUDF::from(TestUdwf::new()))?
.is_none()
);
Ok(())
}
#[test]
fn encode_functions_surface_codec_payload() -> Result<()> {
let codec = PayloadCodec;
let converter = DefaultPhysicalProtoConverter {};
let encoder = encode_ctx_over(&codec, &converter);
let ctx = ExecutionPlanEncodeCtx::new(&encoder);
assert_eq!(
ctx.encode_udf(&ScalarUDF::from(TestUdf::new()))?.as_deref(),
Some(b"test_udf".as_slice())
);
assert_eq!(
ctx.encode_udaf(&AggregateUDF::from(TestUdaf::new()))?
.as_deref(),
Some(b"test_udaf".as_slice())
);
assert_eq!(
ctx.encode_udwf(&WindowUDF::from(TestUdwf::new()))?
.as_deref(),
Some(b"test_udwf".as_slice())
);
Ok(())
}
#[test]
fn decode_functions_prefer_explicit_payload() -> Result<()> {
let task_ctx = TaskContext::default();
let codec = PayloadCodec;
let decode_context = PhysicalPlanDecodeContext::new(&task_ctx, &codec);
let converter = DefaultPhysicalProtoConverter {};
let decoder = ConverterPlanDecoder {
ctx: &decode_context,
proto_converter: &converter,
};
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
assert_eq!(
ctx.decode_udf("test_udf", Some(b"test_udf"))?.name(),
"test_udf"
);
assert_eq!(
ctx.decode_udaf("test_udaf", Some(b"test_udaf"))?.name(),
"test_udaf"
);
assert_eq!(
ctx.decode_udwf("test_udwf", Some(b"test_udwf"))?.name(),
"test_udwf"
);
Ok(())
}
#[test]
fn decode_functions_by_name_resolve_from_registry() -> Result<()> {
let udf = Arc::new(ScalarUDF::from(TestUdf::new()));
let udaf = Arc::new(AggregateUDF::from(TestUdaf::new()));
let udwf = Arc::new(WindowUDF::from(TestUdwf::new()));
let task_ctx = TaskContext::new(
None,
"test".to_string(),
SessionConfig::new(),
HashMap::from([("test_udf".to_string(), Arc::clone(&udf))]),
HashMap::new(),
HashMap::from([("test_udaf".to_string(), Arc::clone(&udaf))]),
HashMap::from([("test_udwf".to_string(), Arc::clone(&udwf))]),
Arc::new(RuntimeEnv::default()),
);
// The default codec fails any decode, so a success proves the
// registry satisfied the lookup without a codec fallback.
let codec = DefaultPhysicalExtensionCodec {};
let decode_context = PhysicalPlanDecodeContext::new(&task_ctx, &codec);
let converter = DefaultPhysicalProtoConverter {};
let decoder = ConverterPlanDecoder {
ctx: &decode_context,
proto_converter: &converter,
};
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
assert!(Arc::ptr_eq(&ctx.decode_udf("test_udf", None)?, &udf));
assert!(Arc::ptr_eq(&ctx.decode_udaf("test_udaf", None)?, &udaf));
assert!(Arc::ptr_eq(&ctx.decode_udwf("test_udwf", None)?, &udwf));
assert_eq!(ctx.task_ctx().session_id(), "test");
Ok(())
}
#[test]
fn decode_functions_by_name_fall_back_to_codec_on_registry_miss() -> Result<()> {
let task_ctx = TaskContext::default();
let codec = EmptyPayloadOnlyCodec;
let decode_context = PhysicalPlanDecodeContext::new(&task_ctx, &codec);
let converter = DefaultPhysicalProtoConverter {};
let decoder = ConverterPlanDecoder {
ctx: &decode_context,
proto_converter: &converter,
};
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
assert_eq!(ctx.decode_udf("test_udf", None)?.name(), "test_udf");
assert_eq!(ctx.decode_udaf("test_udaf", None)?.name(), "test_udaf");
assert_eq!(ctx.decode_udwf("test_udwf", None)?.name(), "test_udwf");
Ok(())
}
#[test]
fn decode_required_helpers_error_on_missing_fields() {
let task_ctx = TaskContext::default();
let codec = DefaultPhysicalExtensionCodec {};
let decode_context = PhysicalPlanDecodeContext::new(&task_ctx, &codec);
let converter = DefaultPhysicalProtoConverter {};
let decoder = ConverterPlanDecoder {
ctx: &decode_context,
proto_converter: &converter,
};
let ctx = ExecutionPlanDecodeCtx::new(&decoder);
let err = ctx
.decode_required_child(None, "FooExec", "input")
.unwrap_err();
assert!(
err.to_string()
.contains("FooExec is missing required field 'input'"),
"unexpected error: {err}"
);
let schema = Schema::empty();
let err = ctx
.decode_required_expr(None, &schema, "FooExec", "predicate")
.unwrap_err();
assert!(
err.to_string()
.contains("FooExec is missing required field 'predicate'"),
"unexpected error: {err}"
);
}
#[test]