This repository was archived by the owner on Feb 27, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathdeduplicate.rs
More file actions
1834 lines (1646 loc) · 56.8 KB
/
Copy pathdeduplicate.rs
File metadata and controls
1834 lines (1646 loc) · 56.8 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
//! Implemention of DeduplicateExec operator (resolves primary key conflicts) plumbing and tests
mod algo;
use std::collections::HashMap;
use std::{collections::HashSet, fmt, sync::Arc};
use arrow::{error::ArrowError, record_batch::RecordBatch};
use datafusion::physical_plan::ExecutionPlanProperties;
use datafusion_util::{AdapterStream, watch::WatchedTask};
use crate::CHUNK_ORDER_COLUMN_NAME;
pub use self::algo::RecordBatchDeduplicator;
use self::algo::get_col_name;
use datafusion::physical_expr::{EquivalenceProperties, LexOrdering, OrderingRequirements};
use datafusion::{
error::{DataFusionError, Result},
execution::context::TaskContext,
physical_plan::{
DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, Partitioning, PlanProperties,
SendableRecordBatchStream, Statistics,
expressions::{Column, PhysicalSortExpr},
metrics::{
self, BaselineMetrics, ExecutionPlanMetricsSet, MetricBuilder, MetricsSet, RecordOutput,
},
},
};
use futures::StreamExt;
use tokio::sync::mpsc;
use tracing::{debug, trace};
/// # DeduplicateExec
///
/// This operator takes an input stream of RecordBatches that is
/// already sorted on "sort_key" and applies IOx specific deduplication
/// logic.
///
/// The output is dependent on the order of the the input rows which
/// have the same key.
///
/// Specifically, the value chosen for each non-sort_key column is the
/// "last" non-null value. This is used to model "upserts" when new
/// rows with the same primary key are inserted a second time to update
/// existing values.
///
/// # Example
/// For example, given a sort key of (t1, t2) and the following input
/// (already sorted on t1 and t2):
///
/// ```text
/// +----+----+----+----+
/// | t1 | t2 | f1 | f2 |
/// +----+----+----+----+
/// | a | x | 2 | |
/// | a | x | 2 | 1 |
/// | a | x | | 3 |
/// | a | y | 3 | 1 |
/// | b | y | 3 | |
/// | c | y | 1 | 1 |
/// +----+----+----+----+
/// ```
///
/// This operator will produce the following output (note the values
/// chosen for (a, x)):
///
/// ```text
/// +----+----+----+----+
/// | t1 | t2 | f1 | f2 |
/// +----+----+----+----+
/// | a | x | 2 | 3 |
/// | a | y | 3 | 1 |
/// | b | y | 3 | |
/// | c | y | 1 | 1 |
/// +----+----+----+----+
/// ```
///
/// # Field Resolution (why the last non-null value?)
///
/// The choice of the latest non-null value instead of the latest value is
/// subtle and thus we try to document the rationale here. It is a
/// consequence of the LineProtocol update model.
///
/// Some observations about line protocol are:
///
/// 1. Lines are treated as "UPSERT"s (aka updating any existing
/// values, possibly adding new fields)
///
/// 2. Fields can not be removed or set to NULL via a line (So if a
/// field has a NULL value it means the user didn't provide a value
/// for that field)
///
/// For example, this data (with a NULL for `f2`):
///
/// ```text
/// t1 | f1 | f2
/// ---+----+----
/// a | 1 | 3
// a | 2 |
/// ```
///
/// Would have come from line protocol like
/// ```text
/// m,t1=a f1=1,f2=3
/// m,t1=a f1=3
/// ```
/// (note there was no value for f2 provided in the second line, it can
/// be read as "upsert value of f1=3, the value of f2 is not modified).
///
/// Thus it would not be correct to take the latest value from f2
/// (NULL) as in the source input the field's value was not provided.
#[derive(Debug)]
pub struct DeduplicateExec {
input: Arc<dyn ExecutionPlan>,
sort_keys: LexOrdering,
input_order: LexOrdering,
use_chunk_order_col: bool,
/// Execution metrics
metrics: ExecutionPlanMetricsSet,
/// Cache holding plan properties like equivalences, output partitioning, output ordering etc.
cache: PlanProperties,
}
impl DeduplicateExec {
pub fn new(
input: Arc<dyn ExecutionPlan>,
sort_keys: LexOrdering,
use_chunk_order_col: bool,
) -> Self {
let mut input_order = sort_keys.clone();
if use_chunk_order_col {
input_order.push(PhysicalSortExpr {
expr: Arc::new(
Column::new_with_schema(CHUNK_ORDER_COLUMN_NAME, &input.schema())
.expect("input has chunk order col"),
),
options: Default::default(),
})
}
let cache = Self::compute_properties(&input, &sort_keys);
Self {
input,
sort_keys,
input_order,
use_chunk_order_col,
metrics: ExecutionPlanMetricsSet::new(),
cache,
}
}
pub fn sort_keys(&self) -> &LexOrdering {
&self.sort_keys
}
/// Combination of all columns within the sort key and potentially the chunk order column.
pub fn sort_columns(&self) -> HashSet<&str> {
self.input_order
.iter()
.map(|sk| get_col_name(sk.expr.as_ref()))
.collect()
}
/// Combination of all columns within the sort key and potentially the chunk order column.
///
/// This is similar to [`sort_columns`](Self::sort_columns) but also provides the ordinal position of the
/// respective column. That is helpful for optimizer passes that want to preserve the original order.
pub fn sort_columns_ordered(&self) -> HashMap<&str, usize> {
self.input_order
.iter()
.enumerate()
.map(|(i, sk)| (get_col_name(sk.expr.as_ref()), i))
.collect()
}
/// Iterator of all of the columns in the sort key and potentially the chunk order column.
pub fn sort_column_iter(&self) -> impl Iterator<Item = Column> + '_ {
self.input_order
.iter()
.filter_map(|sk| sk.expr.as_any().downcast_ref::<Column>().cloned())
}
pub fn use_chunk_order_col(&self) -> bool {
self.use_chunk_order_col
}
/// This function creates the cache object that stores the plan properties such as equivalence properties, partitioning, ordering, etc.
fn compute_properties(
input: &Arc<dyn ExecutionPlan>,
sort_keys: &LexOrdering,
) -> PlanProperties {
trace!("Deduplicate output ordering: {:?}", sort_keys);
let eq_properties =
EquivalenceProperties::new_with_orderings(input.schema(), [sort_keys.iter().cloned()]);
let output_partitioning = Partitioning::UnknownPartitioning(1);
PlanProperties::new(
eq_properties,
output_partitioning,
input.pipeline_behavior(),
input.boundedness(),
)
}
}
#[derive(Debug)]
struct DeduplicateMetrics {
baseline_metrics: BaselineMetrics,
num_dupes: metrics::Count,
}
impl DeduplicateMetrics {
fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
Self {
baseline_metrics: BaselineMetrics::new(metrics, partition),
num_dupes: MetricBuilder::new(metrics).counter("num_dupes", partition),
}
}
}
impl ExecutionPlan for DeduplicateExec {
fn name(&self) -> &str {
Self::static_name()
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn schema(&self) -> arrow::datatypes::SchemaRef {
self.input.schema()
}
fn properties(&self) -> &datafusion::physical_plan::PlanProperties {
&self.cache
}
fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
vec![Some(OrderingRequirements::new(
self.input_order.clone().into(),
))]
}
fn maintains_input_order(&self) -> Vec<bool> {
vec![true]
}
fn benefits_from_input_partitioning(&self) -> Vec<bool> {
vec![false]
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
assert_eq!(children.len(), 1);
let input = Arc::clone(&children[0]);
Ok(Arc::new(Self::new(
input,
self.sort_keys.clone(),
self.use_chunk_order_col,
)))
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
trace!(partition, "Start DeduplicationExec::execute");
if partition != 0 {
return Err(DataFusionError::Internal(
"DeduplicateExec only supports a single input stream".to_string(),
));
}
let deduplicate_metrics = DeduplicateMetrics::new(&self.metrics, partition);
let input_stream = self.input.execute(0, context)?;
// the deduplication is performed in a separate task which is
// then sent via a channel to the output
let (tx, rx) = mpsc::channel(1);
let fut = deduplicate(
input_stream,
self.sort_keys.clone(),
tx.clone(),
deduplicate_metrics,
);
// A second task watches the output of the worker task and reports errors
let handle = WatchedTask::new(fut, vec![tx], "deduplicate batches");
debug!(
partition,
"End building stream for DeduplicationExec::execute"
);
Ok(AdapterStream::adapt(self.schema(), rx, handle))
}
fn required_input_distribution(&self) -> Vec<Distribution> {
// For now use a single input -- it might be helpful
// eventually to deduplicate in parallel by hash partitioning
// the inputs (based on sort keys)
vec![Distribution::SinglePartition]
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
fn statistics(&self) -> Result<Statistics> {
// use a guess from our input but they are NOT exact
Ok(self.input.partition_statistics(None)?.to_inexact())
}
}
impl DisplayAs for DeduplicateExec {
fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match t {
DisplayFormatType::Default
| DisplayFormatType::Verbose
| DisplayFormatType::TreeRender => {
let expr: Vec<String> = self.sort_keys.iter().map(|e| e.to_string()).collect();
write!(f, "DeduplicateExec: [{}]", expr.join(","))
}
}
}
}
async fn deduplicate(
mut input_stream: SendableRecordBatchStream,
sort_keys: LexOrdering,
tx: mpsc::Sender<Result<RecordBatch, DataFusionError>>,
deduplicate_metrics: DeduplicateMetrics,
) -> Result<(), DataFusionError> {
let DeduplicateMetrics {
baseline_metrics,
num_dupes,
} = deduplicate_metrics;
let elapsed_compute = baseline_metrics.elapsed_compute();
let mut deduplicator = RecordBatchDeduplicator::new(sort_keys, num_dupes, None);
// Stream input through the indexer
while let Some(batch) = input_stream.next().await {
let batch = batch?;
// First check if this batch has same sort key with its previous batch
let timer = elapsed_compute.timer();
if let Some(last_batch) = deduplicator
.last_batch_with_no_same_sort_key(&batch)?
.record_output(&baseline_metrics)
{
timer.done();
// No, different sort key, so send the last batch downstream first
if last_batch.num_rows() > 0 {
tx.send(Ok(last_batch))
.await
.map_err(|e| ArrowError::from_external_error(Box::new(e)))?;
}
} else {
timer.done()
}
// deduplicate data of the batch
let timer = elapsed_compute.timer();
let output_batch = deduplicator.push(batch)?.record_output(&baseline_metrics);
timer.done();
if output_batch.num_rows() > 0 {
tx.send(Ok(output_batch))
.await
.map_err(|e| ArrowError::from_external_error(Box::new(e)))?;
}
}
debug!("before sending the left over batch");
// send any left over batch
let timer = elapsed_compute.timer();
if let Some(output_batch) = deduplicator.finish()?.record_output(&baseline_metrics) {
timer.done();
if output_batch.num_rows() > 0 {
tx.send(Ok(output_batch))
.await
.map_err(|e| ArrowError::from_external_error(Box::new(e)))?;
}
} else {
timer.done()
}
debug!("done sending the left over batch");
Ok(())
}
#[cfg(test)]
mod test {
use arrow::compute::{SortOptions, concat_batches};
use arrow::datatypes::{Int32Type, SchemaRef};
use arrow::{
array::{ArrayRef, Float64Array, StringArray, TimestampNanosecondArray},
record_batch::RecordBatch,
};
use arrow_util::assert_batches_eq;
use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
use datafusion::physical_plan::expressions::col;
use datafusion::physical_plan::test::exec::MockExec;
use datafusion_util::test_collect;
use super::*;
use arrow::array::{DictionaryArray, Int64Array};
use arrow_util::display::pretty_format_batches;
use schema::TIME_DATA_TIMEZONE;
use std::{iter::FromIterator, slice};
#[tokio::test]
async fn test_single_tag() {
// input:
// t1 | f1 | f2
// ---+----+----
// a | 1 |
// a | 2 | 3
// a | | 4
// b | 5 | 6
// c | 7 |
// c | |
// c | | 8
//
// expected output:
//
// t1 | f1 | f2
// ---+----+----
// a | 2 | 4
// b | 5 | 6
// c | 7 | 8
let t1 = StringArray::from(vec![
Some("a"),
Some("a"),
Some("a"),
Some("b"),
Some("c"),
Some("c"),
Some("c"),
]);
let f1 = Float64Array::from(vec![
Some(1.0),
Some(2.0),
None,
Some(5.0),
Some(7.0),
None,
None,
]);
let f2 = Float64Array::from(vec![
None,
Some(3.0),
Some(4.0),
Some(6.0),
None,
None,
Some(8.0),
]);
let batch = RecordBatch::try_from_iter(vec![
("t1", Arc::new(t1) as ArrayRef),
("f1", Arc::new(f1) as ArrayRef),
("f2", Arc::new(f2) as ArrayRef),
])
.unwrap();
let sort_keys = vec![PhysicalSortExpr {
expr: col("t1", &batch.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: false,
},
}];
let results = dedupe(vec![batch], sort_keys).await;
let expected = vec![
"+----+-----+-----+",
"| t1 | f1 | f2 |",
"+----+-----+-----+",
"| a | 2.0 | 4.0 |",
"| b | 5.0 | 6.0 |",
"| c | 7.0 | 8.0 |",
"+----+-----+-----+",
];
assert_batches_eq!(&expected, &results.output);
}
#[tokio::test]
async fn test_with_timestamp() {
// input:
// f1 | f2 | time
// ---+----+------
// 1 | | 100
// | 3 | 100
//
// expected output:
//
// f1 | f2 | time
// ---+----+-------
// 1 | 3 | 100
let f1 = Float64Array::from(vec![Some(1.0), None]);
let f2 = Float64Array::from(vec![None, Some(3.0)]);
let time = TimestampNanosecondArray::from(vec![Some(100), Some(100)])
.with_timezone_opt(TIME_DATA_TIMEZONE());
let batch = RecordBatch::try_from_iter(vec![
("f1", Arc::new(f1) as ArrayRef),
("f2", Arc::new(f2) as ArrayRef),
("time", Arc::new(time) as ArrayRef),
])
.unwrap();
let sort_keys = vec![PhysicalSortExpr {
expr: col("time", &batch.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: false,
},
}];
let results = dedupe(vec![batch], sort_keys).await;
let expected = vec![
"+-----+-----+--------------------------------+",
"| f1 | f2 | time |",
"+-----+-----+--------------------------------+",
"| 1.0 | 3.0 | 1970-01-01T00:00:00.000000100Z |",
"+-----+-----+--------------------------------+",
];
assert_batches_eq!(&expected, &results.output);
}
#[tokio::test]
async fn test_multi_tag() {
// input:
// t1 | t2 | f1 | f2
// ---+----+----+----
// a | b | 1 |
// a | b | 2 | 3
// a | b | | 4
// a | z | 5 |
// b | b | 6 |
// b | c | 7 | 6
// c | c | 8 |
// d | b | | 9
// e | | 10 | 11
// e | | 12 |
// | f | 13 |
// | f | | 14
//
// expected output:
// t1 | t2 | f1 | f2
// ---+----+----+----
// a | b | 2 | 4
// a | z | 5 |
// b | b | 6 |
// b | c | 7 | 6
// c | c | 8 |
// d | b | | 9
// e | | 12 | 11
// | f | 13 | 14
let t1 = StringArray::from(vec![
Some("a"),
Some("a"),
Some("a"),
Some("a"),
Some("b"),
Some("b"),
Some("c"),
Some("d"),
Some("e"),
Some("e"),
None,
None,
]);
let t2 = StringArray::from(vec![
Some("b"),
Some("b"),
Some("b"),
Some("z"),
Some("b"),
Some("c"),
Some("c"),
Some("b"),
None,
None,
Some("f"),
Some("f"),
]);
let f1 = Float64Array::from(vec![
Some(1.0),
Some(2.0),
None,
Some(5.0),
Some(6.0),
Some(7.0),
Some(8.0),
None,
Some(10.0),
Some(12.0),
Some(13.0),
None,
]);
let f2 = Float64Array::from(vec![
None,
Some(3.0),
Some(4.0),
None,
None,
Some(6.0),
None,
Some(9.0),
Some(11.0),
None,
None,
Some(14.0),
]);
let batch = RecordBatch::try_from_iter(vec![
("t1", Arc::new(t1) as ArrayRef),
("t2", Arc::new(t2) as ArrayRef),
("f1", Arc::new(f1) as ArrayRef),
("f2", Arc::new(f2) as ArrayRef),
])
.unwrap();
let sort_keys = vec![
PhysicalSortExpr {
expr: col("t1", &batch.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: false,
},
},
PhysicalSortExpr {
expr: col("t2", &batch.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: false,
},
},
];
let results = dedupe(vec![batch], sort_keys).await;
let expected = vec![
"+----+----+------+------+",
"| t1 | t2 | f1 | f2 |",
"+----+----+------+------+",
"| a | b | 2.0 | 4.0 |",
"| a | z | 5.0 | |",
"| b | b | 6.0 | |",
"| b | c | 7.0 | 6.0 |",
"| c | c | 8.0 | |",
"| d | b | | 9.0 |",
"| e | | 12.0 | 11.0 |",
"| | f | 13.0 | 14.0 |",
"+----+----+------+------+",
];
assert_batches_eq!(&expected, &results.output);
}
#[tokio::test]
async fn test_string_with_timestamp() {
// input:
// s | i | time
// -------+----+------
// "cat" | | 100
// | 3 | 100
// | 4 | 200
// "dog" | | 200
//
// expected output:
//
// s | i | time
// -------+----+-------
// "cat" | 3 | 100
// "dog" | 4 | 200
let s = StringArray::from(vec![Some("cat"), None, None, Some("dog")]);
let i = Int64Array::from(vec![None, Some(3), Some(4), None]);
let time = TimestampNanosecondArray::from(vec![Some(100), Some(100), Some(200), Some(200)]);
let batch = RecordBatch::try_from_iter(vec![
("s", Arc::new(s) as ArrayRef),
("i", Arc::new(i) as ArrayRef),
("time", Arc::new(time) as ArrayRef),
])
.unwrap();
let sort_keys = vec![PhysicalSortExpr {
expr: col("time", &batch.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: false,
},
}];
let results = dedupe(vec![batch], sort_keys).await;
let expected = vec![
"+-----+---+--------------------------------+",
"| s | i | time |",
"+-----+---+--------------------------------+",
"| cat | 3 | 1970-01-01T00:00:00.000000100Z |",
"| dog | 4 | 1970-01-01T00:00:00.000000200Z |",
"+-----+---+--------------------------------+",
];
assert_batches_eq!(&expected, &results.output);
}
#[tokio::test]
async fn test_last_is_null_with_timestamp() {
// input:
// s | i | time
// -------+----+------
// "cat" | | 1639612800000000000
// | 10 | 1639612800000000000
//
// expected output:
//
// s | i | time
// -------+----+-------
// "cat" | 10 | 1639612800000000000
let s = StringArray::from(vec![Some("cat"), None]);
let i = Int64Array::from(vec![None, Some(10)]);
let time = TimestampNanosecondArray::from(vec![
Some(1639612800000000000),
Some(1639612800000000000),
]);
let batch = RecordBatch::try_from_iter(vec![
("s", Arc::new(s) as ArrayRef),
("i", Arc::new(i) as ArrayRef),
("time", Arc::new(time) as ArrayRef),
])
.unwrap();
let sort_keys = vec![PhysicalSortExpr {
expr: col("time", &batch.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: true,
},
}];
let results = dedupe(vec![batch], sort_keys).await;
let expected = vec![
"+-----+----+----------------------+",
"| s | i | time |",
"+-----+----+----------------------+",
"| cat | 10 | 2021-12-16T00:00:00Z |",
"+-----+----+----------------------+",
];
assert_batches_eq!(&expected, &results.output);
}
#[tokio::test]
async fn test_multi_record_batch() {
// input:
// t1 | t2 | f1 | f2
// ---+----+----+----
// a | b | 1 | 2
// a | c | 3 |
// a | c | 4 | 5
// ====(next batch)====
// a | c | | 6
// b | d | 7 | 8
//
// expected output:
// t1 | t2 | f1 | f2
// ---+----+----+----
// a | b | 1 | 2
// a | c | 4 | 6
// b | d | 7 | 8
let t1 = StringArray::from(vec![Some("a"), Some("a"), Some("a")]);
let t2 = StringArray::from(vec![Some("b"), Some("c"), Some("c")]);
let f1 = Float64Array::from(vec![Some(1.0), Some(3.0), Some(4.0)]);
let f2 = Float64Array::from(vec![Some(2.0), None, Some(5.0)]);
let batch1 = RecordBatch::try_from_iter_with_nullable(vec![
("t1", Arc::new(t1) as ArrayRef, true),
("t2", Arc::new(t2) as ArrayRef, true),
("f1", Arc::new(f1) as ArrayRef, true),
("f2", Arc::new(f2) as ArrayRef, true),
])
.unwrap();
let t1 = StringArray::from(vec![Some("a"), Some("b")]);
let t2 = StringArray::from(vec![Some("c"), Some("d")]);
let f1 = Float64Array::from(vec![None, Some(7.0)]);
let f2 = Float64Array::from(vec![Some(6.0), Some(8.0)]);
let batch2 = RecordBatch::try_from_iter_with_nullable(vec![
("t1", Arc::new(t1) as ArrayRef, true),
("t2", Arc::new(t2) as ArrayRef, true),
("f1", Arc::new(f1) as ArrayRef, true),
("f2", Arc::new(f2) as ArrayRef, true),
])
.unwrap();
let sort_keys = vec![
PhysicalSortExpr {
expr: col("t1", &batch2.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: false,
},
},
PhysicalSortExpr {
expr: col("t2", &batch2.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: false,
},
},
];
let results = dedupe(vec![batch1, batch2], sort_keys).await;
let expected = vec![
"+----+----+-----+-----+",
"| t1 | t2 | f1 | f2 |",
"+----+----+-----+-----+",
"| a | b | 1.0 | 2.0 |",
"| a | c | 4.0 | 6.0 |",
"| b | d | 7.0 | 8.0 |",
"+----+----+-----+-----+",
];
assert_batches_eq!(&expected, &results.output);
// 5 rows in initial input, 3 rows in output ==> 2 dupes
assert_eq!(results.num_dupes(), 5 - 3);
}
fn make_single_row_batch(t1: Option<&str>, t2: Option<&str>, f1: Option<f64>) -> RecordBatch {
make_multi_row_batch(vec![t1], vec![t2], vec![f1])
}
fn make_multi_row_batch(
t1: Vec<Option<&str>>,
t2: Vec<Option<&str>>,
f1: Vec<Option<f64>>,
) -> RecordBatch {
RecordBatch::try_from_iter_with_nullable(vec![
("t1", Arc::new(StringArray::from(t1)) as ArrayRef, true),
("t2", Arc::new(StringArray::from(t2)) as ArrayRef, true),
("f1", Arc::new(Float64Array::from(f1)) as ArrayRef, true),
])
.unwrap()
}
#[tokio::test]
async fn test_with_nulls_multitag_and_multiple_batches() {
// INPUT
// sort order on t1,t2 with nulls in the tags and nulls that span batch boundaries.
//
// t1 | t2 | f1
// ---+----+----
// | | 1
// | | 2
// | a | 3
// | a | 4
// | b | 5
// a | | 6
// a | | 7
// b | | 8
// b | | 9
// b | a | 10
// b | a | 11
// b | b | 12
// OUTPUT
let expected = vec![
"+----+----+------+",
"| t1 | t2 | f1 |",
"+----+----+------+",
"| | | 2.0 |",
"| | a | 4.0 |",
"| | b | 5.0 |",
"| a | | 7.0 |",
"| b | | 9.0 |",
"| b | a | 11.0 |",
"| b | b | 12.0 |",
"+----+----+------+",
];
// Example -- how to construct an example single input batch
let b1 = make_single_row_batch(None, None, Some(1.0));
let expected_input_batch = vec![
"+----+----+-----+",
"| t1 | t2 | f1 |",
"+----+----+-----+",
"| | | 1.0 |",
"+----+----+-----+",
];
assert_batches_eq!(&expected_input_batch, slice::from_ref(&b1));
// sort on t1, t2
let sort_keys = vec![
PhysicalSortExpr {
expr: col("t1", &b1.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: true,
},
},
PhysicalSortExpr {
expr: col("t2", &b1.schema()).unwrap(),
options: SortOptions {
descending: false,
nulls_first: true,
},
},
];
// TEST CASE 1. DEDUPE ACROSS BATCH BOUNDARIES
//
// each row is a separate batch (to dedupe across):
// t1 | t2 | f1
// ---+----+----
// | | 1
// | | 2
// | a | 3
// | a | 4
// | b | 5
// a | | 6
// a | | 7
// b | | 8
// b | | 9
// b | a | 10
// b | a | 11
// b | b | 12
let input_batches = vec![
b1,
make_single_row_batch(None, None, Some(2.0)),
make_single_row_batch(None, Some("a"), Some(3.0)),
make_single_row_batch(None, Some("a"), Some(4.0)),
make_single_row_batch(None, Some("b"), Some(5.0)),
make_single_row_batch(Some("a"), None, Some(6.0)),
make_single_row_batch(Some("a"), None, Some(7.0)),
make_single_row_batch(Some("b"), None, Some(8.0)),
make_single_row_batch(Some("b"), None, Some(9.0)),
make_single_row_batch(Some("b"), Some("a"), Some(10.0)),
make_single_row_batch(Some("b"), Some("a"), Some(11.0)),
make_single_row_batch(Some("b"), Some("b"), Some(12.0)),
];
// see that the dupes at the batch boundaries are de-duped
let results = dedupe(input_batches, sort_keys.clone()).await;
assert_batches_eq!(&expected, &results.output);
// TEST CASE 2. DEDUPES WITHIN BACTHES TOO
//
// multi-row batches for the input:
// t1 | t2 | f1
// ---+----+----
// | | 1
// | | 2
// | a | 3
// ---------------- batch boundary
// | a | 4
// | b | 5
// a | | 6
// a | | 7
// b | | 8
// b | | 9
// b | a | 10
// ---------------- batch boundary
// b | a | 11
// b | b | 12
let input_batches = vec![
make_multi_row_batch(
vec![None, None, None],
vec![None, None, Some("a")],