-
Notifications
You must be signed in to change notification settings - Fork 421
/
optimize.rs
1714 lines (1535 loc) · 61.4 KB
/
optimize.rs
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
//! Optimize a Delta Table
//!
//! Perform bin-packing on a Delta Table which merges small files into a large
//! file. Bin-packing reduces the number of API calls required for read
//! operations.
//!
//! Optimize will fail if a concurrent write operation removes files from the
//! table (such as in an overwrite). It will always succeed if concurrent writers
//! are only appending.
//!
//! Optimize increments the table's version and creates remove actions for
//! optimized files. Optimize does not delete files from storage. To delete
//! files that were removed, call `vacuum` on [`DeltaTable`].
//!
//! See [`OptimizeBuilder`] for configuration.
//!
//! # Example
//! ```rust ignore
//! let table = open_table("../path/to/table")?;
//! let (table, metrics) = OptimizeBuilder::new(table.object_store(), table.state).await?;
//! ````
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arrow_array::RecordBatch;
use arrow_schema::SchemaRef as ArrowSchemaRef;
use delta_kernel::expressions::Scalar;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use futures::{Future, StreamExt, TryStreamExt};
use indexmap::IndexMap;
use itertools::Itertools;
use num_cpus;
use parquet::arrow::async_reader::{ParquetObjectReader, ParquetRecordBatchStreamBuilder};
use parquet::basic::{Compression, ZstdLevel};
use parquet::errors::ParquetError;
use parquet::file::properties::WriterProperties;
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer};
use tracing::*;
use url::Url;
use super::transaction::PROTOCOL;
use super::writer::{PartitionWriter, PartitionWriterConfig};
use crate::errors::{DeltaResult, DeltaTableError};
use crate::kernel::{scalars::ScalarExt, Action, PartitionsExt, Remove};
use crate::logstore::LogStoreRef;
use crate::operations::transaction::{CommitBuilder, CommitProperties, DEFAULT_RETRIES};
use crate::protocol::DeltaOperation;
use crate::storage::ObjectStoreRef;
use crate::table::state::DeltaTableState;
use crate::writer::utils::arrow_schema_without_partitions;
use crate::{crate_version, DeltaTable, ObjectMeta, PartitionFilter};
/// Metrics from Optimize
#[derive(Default, Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Metrics {
/// Number of optimized files added
pub num_files_added: u64,
/// Number of unoptimized files removed
pub num_files_removed: u64,
/// Detailed metrics for the add operation
#[serde(
serialize_with = "serialize_metric_details",
deserialize_with = "deserialize_metric_details"
)]
pub files_added: MetricDetails,
/// Detailed metrics for the remove operation
#[serde(
serialize_with = "serialize_metric_details",
deserialize_with = "deserialize_metric_details"
)]
pub files_removed: MetricDetails,
/// Number of partitions that had at least one file optimized
pub partitions_optimized: u64,
/// The number of batches written
pub num_batches: u64,
/// How many files were considered during optimization. Not every file considered is optimized
pub total_considered_files: usize,
/// How many files were considered for optimization but were skipped
pub total_files_skipped: usize,
/// The order of records from source files is preserved
pub preserve_insertion_order: bool,
}
// Custom serialization function that serializes metric details as a string
fn serialize_metric_details<S>(value: &MetricDetails, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&value.to_string())
}
// Custom deserialization that parses a JSON string into MetricDetails
fn deserialize_metric_details<'de, D>(deserializer: D) -> Result<MetricDetails, D::Error>
where
D: Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
serde_json::from_str(&s).map_err(DeError::custom)
}
/// Statistics on files for a particular operation
/// Operation can be remove or add
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricDetails {
/// Average file size of a operation
pub avg: f64,
/// Maximum file size of a operation
pub max: i64,
/// Minimum file size of a operation
pub min: i64,
/// Number of files encountered during operation
pub total_files: usize,
/// Sum of file sizes of a operation
pub total_size: i64,
}
impl MetricDetails {
/// Add a partial metric to the metrics
pub fn add(&mut self, partial: &MetricDetails) {
self.min = std::cmp::min(self.min, partial.min);
self.max = std::cmp::max(self.max, partial.max);
self.total_files += partial.total_files;
self.total_size += partial.total_size;
self.avg = self.total_size as f64 / self.total_files as f64;
}
}
impl fmt::Display for MetricDetails {
/// Display the metric details using serde serialization
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
serde_json::to_string(self).map_err(|_| fmt::Error)?.fmt(f)
}
}
#[derive(Debug)]
/// Metrics for a single partition
pub struct PartialMetrics {
/// Number of optimized files added
pub num_files_added: u64,
/// Number of unoptimized files removed
pub num_files_removed: u64,
/// Detailed metrics for the add operation
pub files_added: MetricDetails,
/// Detailed metrics for the remove operation
pub files_removed: MetricDetails,
/// The number of batches written
pub num_batches: u64,
}
impl Metrics {
/// Add a partial metric to the metrics
pub fn add(&mut self, partial: &PartialMetrics) {
self.num_files_added += partial.num_files_added;
self.num_files_removed += partial.num_files_removed;
self.files_added.add(&partial.files_added);
self.files_removed.add(&partial.files_removed);
self.num_batches += partial.num_batches;
}
}
impl Default for MetricDetails {
fn default() -> Self {
MetricDetails {
min: i64::MAX,
max: 0,
avg: 0.0,
total_files: 0,
total_size: 0,
}
}
}
/// Type of optimization to perform.
#[derive(Debug)]
pub enum OptimizeType {
/// Compact files into pre-determined bins
Compact,
/// Z-order files based on provided columns
ZOrder(Vec<String>),
}
/// Optimize a Delta table with given options
///
/// If a target file size is not provided then `delta.targetFileSize` from the
/// table's configuration is read. Otherwise a default value is used.
#[derive(Debug)]
pub struct OptimizeBuilder<'a> {
/// A snapshot of the to-be-optimized table's state
snapshot: DeltaTableState,
/// Delta object store for handling data files
log_store: LogStoreRef,
/// Filters to select specific table partitions to be optimized
filters: &'a [PartitionFilter],
/// Desired file size after bin-packing files
target_size: Option<i64>,
/// Properties passed to underlying parquet writer
writer_properties: Option<WriterProperties>,
/// Commit properties and configuration
commit_properties: CommitProperties,
/// Whether to preserve insertion order within files (default false)
preserve_insertion_order: bool,
/// Maximum number of concurrent tasks (default is number of cpus)
max_concurrent_tasks: usize,
/// Maximum number of bytes allowed in memory before spilling to disk
max_spill_size: usize,
/// Optimize type
optimize_type: OptimizeType,
min_commit_interval: Option<Duration>,
}
impl super::Operation<()> for OptimizeBuilder<'_> {}
impl<'a> OptimizeBuilder<'a> {
/// Create a new [`OptimizeBuilder`]
pub fn new(log_store: LogStoreRef, snapshot: DeltaTableState) -> Self {
Self {
snapshot,
log_store,
filters: &[],
target_size: None,
writer_properties: None,
commit_properties: CommitProperties::default(),
preserve_insertion_order: false,
max_concurrent_tasks: num_cpus::get(),
max_spill_size: 20 * 1024 * 1024 * 1024, // 20 GB.
optimize_type: OptimizeType::Compact,
min_commit_interval: None,
}
}
/// Choose the type of optimization to perform. Defaults to [OptimizeType::Compact].
pub fn with_type(mut self, optimize_type: OptimizeType) -> Self {
self.optimize_type = optimize_type;
self
}
/// Only optimize files that return true for the specified partition filter
pub fn with_filters(mut self, filters: &'a [PartitionFilter]) -> Self {
self.filters = filters;
self
}
/// Set the target file size
pub fn with_target_size(mut self, target: i64) -> Self {
self.target_size = Some(target);
self
}
/// Writer properties passed to parquet writer
pub fn with_writer_properties(mut self, writer_properties: WriterProperties) -> Self {
self.writer_properties = Some(writer_properties);
self
}
/// Additonal information to write to the commit
pub fn with_commit_properties(mut self, commit_properties: CommitProperties) -> Self {
self.commit_properties = commit_properties;
self
}
/// Whether to preserve insertion order within files
pub fn with_preserve_insertion_order(mut self, preserve_insertion_order: bool) -> Self {
self.preserve_insertion_order = preserve_insertion_order;
self
}
/// Max number of concurrent tasks
pub fn with_max_concurrent_tasks(mut self, max_concurrent_tasks: usize) -> Self {
self.max_concurrent_tasks = max_concurrent_tasks;
self
}
/// Max spill size
pub fn with_max_spill_size(mut self, max_spill_size: usize) -> Self {
self.max_spill_size = max_spill_size;
self
}
/// Min commit interval
pub fn with_min_commit_interval(mut self, min_commit_interval: Duration) -> Self {
self.min_commit_interval = Some(min_commit_interval);
self
}
}
impl<'a> std::future::IntoFuture for OptimizeBuilder<'a> {
type Output = DeltaResult<(DeltaTable, Metrics)>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
let this = self;
Box::pin(async move {
PROTOCOL.can_write_to(&this.snapshot.snapshot)?;
if !&this.snapshot.load_config().require_files {
return Err(DeltaTableError::NotInitializedWithFiles("OPTIMIZE".into()));
}
let writer_properties = this.writer_properties.unwrap_or_else(|| {
WriterProperties::builder()
.set_compression(Compression::ZSTD(ZstdLevel::try_new(4).unwrap()))
.set_created_by(format!("delta-rs version {}", crate_version()))
.build()
});
let plan = create_merge_plan(
this.optimize_type,
&this.snapshot,
this.filters,
this.target_size.to_owned(),
writer_properties,
)?;
let metrics = plan
.execute(
this.log_store.clone(),
&this.snapshot,
this.max_concurrent_tasks,
this.max_spill_size,
this.min_commit_interval,
this.commit_properties,
)
.await?;
let mut table = DeltaTable::new_with_state(this.log_store, this.snapshot);
table.update().await?;
Ok((table, metrics))
})
}
}
#[derive(Debug, Clone)]
struct OptimizeInput {
target_size: i64,
predicate: Option<String>,
}
impl From<OptimizeInput> for DeltaOperation {
fn from(opt_input: OptimizeInput) -> Self {
DeltaOperation::Optimize {
target_size: opt_input.target_size,
predicate: opt_input.predicate,
}
}
}
/// Generate an appropriate remove action for the optimization task
fn create_remove(
path: &str,
partitions: &IndexMap<String, Scalar>,
size: i64,
) -> Result<Action, DeltaTableError> {
// NOTE unwrap is safe since UNIX_EPOCH will always be earlier then now.
let deletion_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let deletion_time = deletion_time.as_millis() as i64;
Ok(Action::Remove(Remove {
path: path.to_string(),
deletion_timestamp: Some(deletion_time),
data_change: false,
extended_file_metadata: None,
partition_values: Some(
partitions
.iter()
.map(|(k, v)| {
(
k.clone(),
if v.is_null() {
None
} else {
Some(v.serialize())
},
)
})
.collect(),
),
size: Some(size),
deletion_vector: None,
tags: None,
base_row_id: None,
default_row_commit_version: None,
}))
}
/// Layout for optimizing a plan
///
/// Within each partition, we identify a set of files that need to be merged
/// together and/or sorted together.
#[derive(Debug)]
enum OptimizeOperations {
/// Plan to compact files into pre-determined bins
///
/// Bins are determined by the bin-packing algorithm to reach an optimal size.
/// Files that are large enough already are skipped. Bins of size 1 are dropped.
Compact(HashMap<String, (IndexMap<String, Scalar>, Vec<MergeBin>)>),
/// Plan to Z-order each partition
ZOrder(
Vec<String>,
HashMap<String, (IndexMap<String, Scalar>, MergeBin)>,
),
// TODO: Sort
}
impl Default for OptimizeOperations {
fn default() -> Self {
OptimizeOperations::Compact(HashMap::new())
}
}
#[derive(Debug)]
/// Encapsulates the operations required to optimize a Delta Table
pub struct MergePlan {
operations: OptimizeOperations,
/// Metrics collected during operation
metrics: Metrics,
/// Parameters passed down to merge tasks
task_parameters: Arc<MergeTaskParameters>,
/// Version of the table at beginning of optimization. Used for conflict resolution.
read_table_version: i64,
}
/// Parameters passed to individual merge tasks
#[derive(Debug)]
pub struct MergeTaskParameters {
/// Parameters passed to optimize operation
input_parameters: OptimizeInput,
/// Schema of written files
file_schema: ArrowSchemaRef,
/// Properties passed to parquet writer
writer_properties: WriterProperties,
/// Num index cols to collect stats for
num_indexed_cols: i32,
/// Stats columns, specific columns to collect stats from, takes precedence over num_indexed_cols
stats_columns: Option<Vec<String>>,
}
/// A stream of record batches, with a ParquetError on failure.
type ParquetReadStream = BoxStream<'static, Result<RecordBatch, ParquetError>>;
impl MergePlan {
/// Rewrites files in a single partition.
///
/// Returns a vector of add and remove actions, as well as the partial metrics
/// collected during the operation.
async fn rewrite_files<F>(
task_parameters: Arc<MergeTaskParameters>,
partition_values: IndexMap<String, Scalar>,
files: MergeBin,
object_store: ObjectStoreRef,
read_stream: F,
) -> Result<(Vec<Action>, PartialMetrics), DeltaTableError>
where
F: Future<Output = Result<ParquetReadStream, DeltaTableError>> + Send + 'static,
{
debug!("Rewriting files in partition: {:?}", partition_values);
// First, initialize metrics
let mut partial_actions = files
.iter()
.map(|file_meta| {
create_remove(
file_meta.location.as_ref(),
&partition_values,
file_meta.size as i64,
)
})
.collect::<Result<Vec<_>, DeltaTableError>>()?;
let files_removed = files
.iter()
.fold(MetricDetails::default(), |mut curr, file| {
curr.total_files += 1;
curr.total_size += file.size as i64;
curr.max = std::cmp::max(curr.max, file.size as i64);
curr.min = std::cmp::min(curr.min, file.size as i64);
curr
});
let mut partial_metrics = PartialMetrics {
num_files_added: 0,
num_files_removed: files.len() as u64,
files_added: MetricDetails::default(),
files_removed,
num_batches: 0,
};
// Next, initialize the writer
let writer_config = PartitionWriterConfig::try_new(
task_parameters.file_schema.clone(),
partition_values.clone(),
Some(task_parameters.writer_properties.clone()),
Some(task_parameters.input_parameters.target_size as usize),
None,
)?;
let mut writer = PartitionWriter::try_with_config(
object_store,
writer_config,
task_parameters.num_indexed_cols,
task_parameters.stats_columns.clone(),
)?;
let mut read_stream = read_stream.await?;
while let Some(maybe_batch) = read_stream.next().await {
let mut batch = maybe_batch?;
batch = super::cast::cast_record_batch(
&batch,
task_parameters.file_schema.clone(),
false,
true,
)?;
partial_metrics.num_batches += 1;
writer.write(&batch).await.map_err(DeltaTableError::from)?;
}
let add_actions = writer.close().await?.into_iter().map(|mut add| {
add.data_change = false;
let size = add.size;
partial_metrics.num_files_added += 1;
partial_metrics.files_added.total_files += 1;
partial_metrics.files_added.total_size += size;
partial_metrics.files_added.max = std::cmp::max(partial_metrics.files_added.max, size);
partial_metrics.files_added.min = std::cmp::min(partial_metrics.files_added.min, size);
Action::Add(add)
});
partial_actions.extend(add_actions);
debug!(
"Finished rewriting files in partition: {:?}",
partition_values
);
Ok((partial_actions, partial_metrics))
}
/// Creates a stream of batches that are Z-ordered.
///
/// Currently requires loading all the data into memory. This is run for each
/// partition, so it is not a problem for tables where each partition is small.
/// But for large unpartitioned tables, this could be a problem.
#[cfg(not(feature = "datafusion"))]
async fn read_zorder(
files: MergeBin,
context: Arc<zorder::ZOrderExecContext>,
) -> Result<BoxStream<'static, Result<RecordBatch, ParquetError>>, DeltaTableError> {
use arrow_array::cast::as_generic_binary_array;
use arrow_array::ArrayRef;
use arrow_schema::ArrowError;
let object_store_ref = context.object_store.clone();
// Read all batches into a vec
let batches = zorder::collect_batches(object_store_ref, files).await?;
// For each batch, compute the zorder key
let zorder_keys: Vec<ArrayRef> =
batches
.iter()
.map(|batch| {
let mut zorder_columns = Vec::new();
for column in context.columns.iter() {
let array = batch.column_by_name(column).ok_or(ArrowError::SchemaError(
format!("Column not found in data file: {column}"),
))?;
zorder_columns.push(array.clone());
}
zorder::zorder_key(zorder_columns.as_ref())
})
.collect::<Result<Vec<_>, ArrowError>>()?;
let mut indices = zorder_keys
.iter()
.enumerate()
.flat_map(|(batch_i, key)| {
let key = as_generic_binary_array::<i32>(key);
key.iter()
.enumerate()
.map(move |(row_i, key)| (key.unwrap(), batch_i, row_i))
})
.collect_vec();
indices.sort_by_key(|(key, _, _)| *key);
let indices = indices
.into_iter()
.map(|(_, batch_i, row_i)| (batch_i, row_i))
.collect_vec();
// Interleave the batches
Ok(
util::interleave_batches(batches, indices, 10_000, context.use_inner_threads)
.await
.map_err(|err| ParquetError::General(format!("Failed to reorder data: {:?}", err)))
.boxed(),
)
}
/// Datafusion-based z-order read.
#[cfg(feature = "datafusion")]
async fn read_zorder(
files: MergeBin,
context: Arc<zorder::ZOrderExecContext>,
) -> Result<BoxStream<'static, Result<RecordBatch, ParquetError>>, DeltaTableError> {
use datafusion::prelude::{col, ParquetReadOptions};
use datafusion_common::Column;
use datafusion_expr::expr::ScalarFunction;
use datafusion_expr::{Expr, ScalarUDF};
// This code is ... not ideal. Essentially `read_parquet` expects Strings that it will then
// parse as URLs and then pass back to the object store (x_x). This can cause problems when
// paths in object storage have special characters like spaces, etc.
//
// This [str::replace] i kind of a hack to address
// <https://github.com/delta-io/delta-rs/issues/2834 >
let locations: Vec<String> = files
.iter()
.map(|om| {
format!(
"delta-rs:///{}",
str::replace(om.location.as_ref(), "%", "%25")
)
})
.collect();
debug!("Reading z-order with locations are: {locations:?}");
let df = context
.ctx
// TODO: should read options have the partition columns
.read_parquet(locations, ParquetReadOptions::default())
.await?;
let original_columns = df
.schema()
.fields()
.iter()
.map(|f| Expr::Column(Column::from_qualified_name_ignore_case(f.name())))
.collect_vec();
// Add a temporary z-order column we will sort by, and then drop.
const ZORDER_KEY_COLUMN: &str = "__zorder_key";
let cols = context
.columns
.iter()
.map(|col| Expr::Column(Column::from_qualified_name_ignore_case(col)))
.collect_vec();
let expr = Expr::ScalarFunction(ScalarFunction::new_udf(
Arc::new(ScalarUDF::from(zorder::datafusion::ZOrderUDF)),
cols,
));
let df = df.with_column(ZORDER_KEY_COLUMN, expr)?;
let df = df.sort(vec![col(ZORDER_KEY_COLUMN).sort(true, true)])?;
let df = df.select(original_columns)?;
let stream = df
.execute_stream()
.await?
.map_err(|err| {
ParquetError::General(format!("Z-order failed while scanning data: {:?}", err))
})
.boxed();
Ok(stream)
}
/// Perform the operations outlined in the plan.
pub async fn execute(
mut self,
log_store: LogStoreRef,
snapshot: &DeltaTableState,
max_concurrent_tasks: usize,
#[allow(unused_variables)] // used behind a feature flag
max_spill_size: usize,
min_commit_interval: Option<Duration>,
commit_properties: CommitProperties,
) -> Result<Metrics, DeltaTableError> {
let operations = std::mem::take(&mut self.operations);
let stream = match operations {
OptimizeOperations::Compact(bins) => futures::stream::iter(bins)
.flat_map(|(_, (partition, bins))| {
futures::stream::iter(bins).map(move |bin| (partition.clone(), bin))
})
.map(|(partition, files)| {
debug!(
"merging a group of {} files in partition {:?}",
files.len(),
partition,
);
for file in files.iter() {
debug!(" file {}", file.location);
}
let object_store_ref = log_store.object_store();
let batch_stream = futures::stream::iter(files.clone())
.then(move |file| {
let object_store_ref = object_store_ref.clone();
async move {
let file_reader = ParquetObjectReader::new(object_store_ref, file);
ParquetRecordBatchStreamBuilder::new(file_reader)
.await?
.build()
}
})
.try_flatten()
.boxed();
let rewrite_result = tokio::task::spawn(Self::rewrite_files(
self.task_parameters.clone(),
partition,
files,
log_store.object_store().clone(),
futures::future::ready(Ok(batch_stream)),
));
util::flatten_join_error(rewrite_result)
})
.boxed(),
OptimizeOperations::ZOrder(zorder_columns, bins) => {
debug!("Starting zorder with the columns: {zorder_columns:?} {bins:?}");
#[cfg(not(feature = "datafusion"))]
let exec_context = Arc::new(zorder::ZOrderExecContext::new(
zorder_columns,
log_store.object_store(),
// If there aren't enough bins to use all threads, then instead
// use threads within the bins. This is important for the case where
// the table is un-partitioned, in which case the entire table is just
// one big bin.
bins.len() <= num_cpus::get(),
));
#[cfg(feature = "datafusion")]
let exec_context = Arc::new(zorder::ZOrderExecContext::new(
zorder_columns,
log_store.object_store(),
max_spill_size,
)?);
let task_parameters = self.task_parameters.clone();
let log_store = log_store.clone();
futures::stream::iter(bins)
.map(move |(_, (partition, files))| {
let batch_stream = Self::read_zorder(files.clone(), exec_context.clone());
let rewrite_result = tokio::task::spawn(Self::rewrite_files(
task_parameters.clone(),
partition,
files,
log_store.object_store(),
batch_stream,
));
util::flatten_join_error(rewrite_result)
})
.boxed()
}
};
let mut stream = stream.buffer_unordered(max_concurrent_tasks);
let mut table = DeltaTable::new_with_state(log_store.clone(), snapshot.clone());
// Actions buffered so far. These will be flushed either at the end
// or when we reach the commit interval.
let mut actions = vec![];
// Each time we commit, we'll reset buffered_metrics to orig_metrics.
let orig_metrics = std::mem::take(&mut self.metrics);
let mut buffered_metrics = orig_metrics.clone();
let mut total_metrics = orig_metrics.clone();
let mut last_commit = Instant::now();
let mut commits_made = 0;
loop {
let next = stream.next().await.transpose()?;
let end = next.is_none();
if let Some((partial_actions, partial_metrics)) = next {
debug!("Recording metrics for a completed partition");
actions.extend(partial_actions);
buffered_metrics.add(&partial_metrics);
total_metrics.add(&partial_metrics);
}
let now = Instant::now();
let mature = match min_commit_interval {
None => false,
Some(i) => now.duration_since(last_commit) > i,
};
if !actions.is_empty() && (mature || end) {
let actions = std::mem::take(&mut actions);
last_commit = now;
buffered_metrics.preserve_insertion_order = true;
let mut properties = CommitProperties::default();
properties.app_metadata = commit_properties.app_metadata.clone();
properties
.app_metadata
.insert("readVersion".to_owned(), self.read_table_version.into());
let maybe_map_metrics = serde_json::to_value(std::mem::replace(
&mut buffered_metrics,
orig_metrics.clone(),
));
if let Ok(map) = maybe_map_metrics {
properties
.app_metadata
.insert("operationMetrics".to_owned(), map);
}
debug!("committing {} actions", actions.len());
CommitBuilder::from(properties)
.with_actions(actions)
.with_max_retries(DEFAULT_RETRIES + commits_made)
.build(
Some(snapshot),
log_store.clone(),
self.task_parameters.input_parameters.clone().into(),
)
.await?;
commits_made += 1;
}
if end {
break;
}
}
total_metrics.preserve_insertion_order = true;
if total_metrics.num_files_added == 0 {
total_metrics.files_added.min = 0;
}
if total_metrics.num_files_removed == 0 {
total_metrics.files_removed.min = 0;
}
table.update().await?;
Ok(total_metrics)
}
}
/// Build a Plan on which files to merge together. See [OptimizeBuilder]
pub fn create_merge_plan(
optimize_type: OptimizeType,
snapshot: &DeltaTableState,
filters: &[PartitionFilter],
target_size: Option<i64>,
writer_properties: WriterProperties,
) -> Result<MergePlan, DeltaTableError> {
let target_size = target_size.unwrap_or_else(|| snapshot.table_config().target_file_size());
let partitions_keys = &snapshot.metadata().partition_columns;
let (operations, metrics) = match optimize_type {
OptimizeType::Compact => build_compaction_plan(snapshot, filters, target_size)?,
OptimizeType::ZOrder(zorder_columns) => {
build_zorder_plan(zorder_columns, snapshot, partitions_keys, filters)?
}
};
let input_parameters = OptimizeInput {
target_size,
predicate: serde_json::to_string(filters).ok(),
};
let file_schema =
arrow_schema_without_partitions(&Arc::new(snapshot.schema().try_into()?), partitions_keys);
Ok(MergePlan {
operations,
metrics,
task_parameters: Arc::new(MergeTaskParameters {
input_parameters,
file_schema,
writer_properties,
num_indexed_cols: snapshot.table_config().num_indexed_cols(),
stats_columns: snapshot
.table_config()
.stats_columns()
.map(|v| v.iter().map(|v| v.to_string()).collect::<Vec<String>>()),
}),
read_table_version: snapshot.version(),
})
}
/// A collection of bins for a particular partition
#[derive(Debug, Clone)]
struct MergeBin {
files: Vec<ObjectMeta>,
size_bytes: i64,
}
impl MergeBin {
pub fn new() -> Self {
MergeBin {
files: Vec::new(),
size_bytes: 0,
}
}
fn total_file_size(&self) -> i64 {
self.size_bytes
}
fn len(&self) -> usize {
self.files.len()
}
fn add(&mut self, meta: ObjectMeta) {
self.size_bytes += meta.size as i64;
self.files.push(meta);
}
fn iter(&self) -> impl Iterator<Item = &ObjectMeta> {
self.files.iter()
}
}
impl IntoIterator for MergeBin {
type Item = ObjectMeta;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.files.into_iter()
}
}
fn build_compaction_plan(
snapshot: &DeltaTableState,
filters: &[PartitionFilter],
target_size: i64,
) -> Result<(OptimizeOperations, Metrics), DeltaTableError> {
let mut metrics = Metrics::default();
let mut partition_files: HashMap<String, (IndexMap<String, Scalar>, Vec<ObjectMeta>)> =
HashMap::new();
for add in snapshot.get_active_add_actions_by_partitions(filters)? {
let add = add?;
metrics.total_considered_files += 1;
let object_meta = ObjectMeta::try_from(&add)?;
if (object_meta.size as i64) > target_size {
metrics.total_files_skipped += 1;
continue;
}
let partition_values = add
.partition_values()?
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect::<IndexMap<_, _>>();
partition_files
.entry(add.partition_values()?.hive_partition_path())
.or_insert_with(|| (partition_values, vec![]))
.1
.push(object_meta);
}
for (_, file) in partition_files.values_mut() {
// Sort files by size: largest to smallest
file.sort_by(|a, b| b.size.cmp(&a.size));
}
let mut operations: HashMap<String, (IndexMap<String, Scalar>, Vec<MergeBin>)> = HashMap::new();
for (part, (partition, files)) in partition_files {
let mut merge_bins = vec![MergeBin::new()];
'files: for file in files {
for bin in merge_bins.iter_mut() {
if bin.total_file_size() + file.size as i64 <= target_size {
bin.add(file);
// Move to next file
continue 'files;
}
}
// Didn't find a bin to add to, so create a new one
let mut new_bin = MergeBin::new();
new_bin.add(file);
merge_bins.push(new_bin);
}
operations.insert(part, (partition, merge_bins));
}
// Prune merge bins with only 1 file, since they have no effect
for (_, (_, bins)) in operations.iter_mut() {
bins.retain(|bin| {
if bin.len() == 1 {
metrics.total_files_skipped += 1;
false
} else {
true
}
})
}
operations.retain(|_, (_, files)| !files.is_empty());
metrics.partitions_optimized = operations.len() as u64;
Ok((OptimizeOperations::Compact(operations), metrics))