aisle 0.2.1

Metadata-driven Parquet pruning for Rust: Skip irrelevant data before reading
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
517
518
519
520
521
use arrow_schema::{Schema, SchemaRef};
#[cfg(feature = "datafusion")]
use datafusion_expr::Expr as DfExpr;
use parquet::{
    arrow::async_reader::{AsyncFileReader, ParquetRecordBatchStreamBuilder},
    file::metadata::ParquetMetaData,
};

#[cfg(feature = "datafusion")]
use crate::AisleError;
#[cfg(feature = "datafusion")]
use crate::compile::{
    SchemaPathIndex, build_schema_path_index, collect_columns_from_df_expr,
    compile_pruning_ir_with_index,
};
use crate::{
    AisleResult,
    expr::Expr,
    prune::{
        AsyncBloomFilterProvider, PruneOptions, PruneResult, prune_compiled,
        prune_compiled_with_bloom_provider,
    },
};

/// Reusable pruning façade for a fixed schema.
///
/// Caches schema indexing so repeated pruning across many Parquet files
/// with the same Arrow schema avoids rebuilding lookup structures.
///
/// # Thread Safety
///
/// `Pruner` is both `Send` and `Sync`. It can be safely shared across threads
/// via `Arc`, as all methods take `&self` and the internal `schema` uses `Arc<Schema>`.
///
/// # Performance
///
/// Building the schema index has a one-time cost proportional to schema complexity.
/// For workloads pruning multiple Parquet files with the same schema, `Pruner`
/// amortizes this cost by reusing the cached index.
///
/// # Examples
///
/// ## Basic Usage
///
/// ```
/// # #[cfg(feature = "datafusion")]
/// # {
/// use std::sync::Arc;
///
/// use aisle::Pruner;
/// use arrow_schema::{DataType, Field, Schema};
/// use datafusion_expr::{col, lit};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let schema = Arc::new(Schema::new(vec![
///     Field::new("age", DataType::Int32, false),
///     Field::new("country", DataType::Utf8, false),
/// ]));
///
/// let pruner = Pruner::try_new(schema)?;
///
/// // Reuse for multiple files with same schema
/// # /*
/// for file in ["users1.parquet", "users2.parquet"] {
///     let metadata = load_parquet_metadata(file)?;
///     let expr = col("age").gt(lit(18));
///
///     let result = pruner.prune(&metadata, &expr);
///     println!(
///         "Keep {} of {} row groups",
///         result.row_groups().len(),
///         metadata.num_row_groups()
///     );
/// }
/// # */
/// # Ok(())
/// # }
/// # }
/// ```
///
/// ## Custom Options
///
/// ```
/// use aisle::{PruneOptions, Pruner};
/// # use std::sync::Arc;
/// # use arrow_schema::{Schema, Field, DataType};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let options = PruneOptions::builder()
///     .enable_page_index(true)
///     .emit_roaring(false)
///     .build();
///
/// # let schema = Arc::new(Schema::new(vec![
/// #     Field::new("value", DataType::Int32, false)
/// # ]));
/// let pruner = Pruner::try_with_options(schema, options)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Concurrent Usage
///
/// ```
/// use std::{sync::Arc, thread};
/// # use aisle::Pruner;
/// # use arrow_schema::Schema;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let schema = Arc::new(Schema::new(vec![
/// #     arrow_schema::Field::new("id", arrow_schema::DataType::Int64, false)
/// # ]));
/// let pruner = Arc::new(Pruner::try_new(schema)?);
///
/// let handles: Vec<_> = (0..4)
///     .map(|_| {
///         let pruner = Arc::clone(&pruner);
///         thread::spawn(move || {
///             // Each thread can safely use the same Pruner
///         # /*
///             pruner.prune(&metadata, &expr)
///         # */
///         })
///     })
///     .collect();
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Pruner {
    schema: SchemaRef,
    #[cfg(feature = "datafusion")]
    schema_index: SchemaPathIndex,
    options: PruneOptions,
}

impl Pruner {
    /// Compile a predicate and require full support.
    ///
    /// Returns an error if any part of the predicate cannot be compiled.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use aisle::Pruner;
    /// use arrow_schema::{DataType, Field, Schema};
    /// use datafusion_expr::{col, lit};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let schema = Arc::new(Schema::new(vec![Field::new("age", DataType::Int32, false)]));
    /// let pruner = Pruner::try_new(schema)?;
    ///
    /// let predicate = col("age").gt(lit(18));
    /// let compiled = pruner.try_compile(&predicate)
    ///     .map_err(|errors| format!("Compilation failed: {} errors", errors.len()))?;
    ///
    /// # /*
    /// let metadata = load_parquet_metadata("users.parquet")?;
    /// let result = compiled.prune(&metadata);
    /// println!("Keep {} row groups", result.row_groups().len());
    /// # */
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "datafusion")]
    pub fn try_compile(&self, expr: &DfExpr) -> Result<CompiledPruner, Vec<AisleError>> {
        let compile = compile_pruning_ir_with_index(expr, self.schema.as_ref(), &self.schema_index);
        if compile.has_errors() {
            Err(compile.errors().to_vec())
        } else {
            Ok(CompiledPruner {
                schema: self.schema.clone(),
                options: self.options.clone(),
                compile,
            })
        }
    }

    /// Creates a new `Pruner` with default options.
    ///
    /// This is equivalent to `Pruner::try_with_options(schema, PruneOptions::default())`.
    ///
    /// # Errors
    ///
    /// Returns an error if the schema is empty (has no fields).
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use aisle::Pruner;
    /// use arrow_schema::{DataType, Field, Schema};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
    ///
    /// let pruner = Pruner::try_new(schema)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_new(schema: SchemaRef) -> Result<Self, String> {
        Self::try_with_options(schema, PruneOptions::default())
    }

    /// Creates a new `Pruner` with explicit options.
    ///
    /// # Errors
    ///
    /// Returns an error if the schema is empty (has no fields).
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use aisle::{PruneOptions, Pruner};
    /// use arrow_schema::{DataType, Field, Schema};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let schema = Arc::new(Schema::new(vec![Field::new(
    ///     "value",
    ///     DataType::Float64,
    ///     true,
    /// )]));
    ///
    /// let options = PruneOptions::builder().enable_page_index(false).build();
    ///
    /// let pruner = Pruner::try_with_options(schema, options)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_with_options(schema: SchemaRef, options: PruneOptions) -> Result<Self, String> {
        // Validate schema is not empty
        if schema.fields().is_empty() {
            return Err("Schema must have at least one field".to_string());
        }

        #[cfg(feature = "datafusion")]
        let schema_index = build_schema_path_index(schema.as_ref());

        Ok(Self {
            schema,
            #[cfg(feature = "datafusion")]
            schema_index,
            options,
        })
    }

    /// Returns a reference to the underlying Arrow schema.
    ///
    /// # Examples
    ///
    /// ```
    /// # use aisle::Pruner;
    /// # use std::sync::Arc;
    /// # use arrow_schema::{Schema, Field, DataType};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
    /// let pruner = Pruner::try_new(schema)?;
    ///
    /// println!("Schema has {} fields", pruner.schema().fields().len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn schema(&self) -> &Schema {
        self.schema.as_ref()
    }

    /// Returns a reference to the pruning options.
    ///
    /// # Examples
    ///
    /// ```
    /// # use aisle::{Pruner, PruneOptions};
    /// # use std::sync::Arc;
    /// # use arrow_schema::{Schema, Field, DataType};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
    /// let options = PruneOptions::builder().enable_page_index(true).build();
    ///
    /// let pruner = Pruner::try_with_options(schema, options)?;
    /// let opts = pruner.options();
    /// # Ok(())
    /// # }
    /// ```
    pub fn options(&self) -> &PruneOptions {
        &self.options
    }

    /// Prunes Parquet metadata using the cached schema index.
    ///
    /// Returns a [`PruneResult`] containing:
    /// - Which row groups to read ([`row_groups()`](PruneResult::row_groups))
    /// - Optional row-level selection ([`row_selection()`](PruneResult::row_selection))
    /// - Compilation result with any errors ([`compile_result()`](PruneResult::compile_result))
    ///
    /// If compilation errors occur, all row groups are conservatively kept
    /// (the predicate falls back to runtime evaluation).
    ///
    /// # Examples
    ///
    /// ```
    /// use datafusion_expr::{col, lit};
    /// # use aisle::Pruner;
    /// # use std::sync::Arc;
    /// # use arrow_schema::{Schema, Field, DataType};
    /// # use parquet::file::metadata::ParquetMetaData;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let schema = Arc::new(Schema::new(vec![Field::new("age", DataType::Int32, false)]));
    /// let pruner = Pruner::try_new(schema)?;
    /// let expr = col("age").gt(lit(18));
    ///
    /// # /*
    /// let metadata = load_parquet_metadata("users.parquet")?;
    /// let result = pruner.prune(&metadata, &expr);
    ///
    /// println!(
    ///     "Keep {} of {} row groups",
    ///     result.row_groups().len(),
    ///     metadata.num_row_groups()
    /// );
    ///
    /// if !result.compile_result().errors().is_empty() {
    ///     eprintln!("Compilation errors: {:?}", result.compile_result().errors());
    /// }
    /// # */
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "datafusion")]
    pub fn prune(&self, metadata: &ParquetMetaData, expr: &DfExpr) -> PruneResult {
        let compile = compile_pruning_ir_with_index(expr, self.schema.as_ref(), &self.schema_index);
        let predicate_columns = collect_columns_from_df_expr(expr);
        prune_compiled(
            metadata,
            self.schema.as_ref(),
            compile,
            &self.options,
            None,
            predicate_columns,
        )
    }

    /// Prune Parquet metadata using pre-built IR predicates.
    ///
    /// This bypasses DataFusion compilation and uses the IR as-is.
    pub fn prune_ir(&self, metadata: &ParquetMetaData, predicates: &[Expr]) -> PruneResult {
        let compile = AisleResult::from_ir_slice(predicates);
        prune_compiled(
            metadata,
            self.schema.as_ref(),
            compile,
            &self.options,
            None,
            None,
        )
    }

    /// Prune Parquet metadata using the cached schema index and bloom filters from the async
    /// reader.
    #[cfg(feature = "datafusion")]
    pub async fn prune_with_async_reader<T: AsyncFileReader + 'static>(
        &self,
        builder: &mut ParquetRecordBatchStreamBuilder<T>,
        expr: &DfExpr,
    ) -> PruneResult {
        let compile = compile_pruning_ir_with_index(expr, self.schema.as_ref(), &self.schema_index);
        let predicate_columns = collect_columns_from_df_expr(expr);
        let metadata = builder.metadata().clone();
        prune_compiled_with_bloom_provider(
            metadata.as_ref(),
            self.schema.as_ref(),
            compile,
            &self.options,
            builder,
            None,
            predicate_columns,
        )
        .await
    }

    /// Prune Parquet metadata using pre-built IR predicates and bloom filters from the async
    /// reader.
    pub async fn prune_ir_with_async_reader<T: AsyncFileReader + 'static>(
        &self,
        builder: &mut ParquetRecordBatchStreamBuilder<T>,
        predicates: &[Expr],
    ) -> PruneResult {
        let compile = AisleResult::from_ir_slice(predicates);
        let metadata = builder.metadata().clone();
        prune_compiled_with_bloom_provider(
            metadata.as_ref(),
            self.schema.as_ref(),
            compile,
            &self.options,
            builder,
            None,
            None,
        )
        .await
    }

    /// Prune Parquet metadata using the cached schema index and a custom async bloom provider.
    #[cfg(feature = "datafusion")]
    pub async fn prune_with_bloom_provider<P: AsyncBloomFilterProvider>(
        &self,
        metadata: &ParquetMetaData,
        expr: &DfExpr,
        provider: &mut P,
    ) -> PruneResult {
        let compile = compile_pruning_ir_with_index(expr, self.schema.as_ref(), &self.schema_index);
        let predicate_columns = collect_columns_from_df_expr(expr);
        prune_compiled_with_bloom_provider(
            metadata,
            self.schema.as_ref(),
            compile,
            &self.options,
            provider,
            None,
            predicate_columns,
        )
        .await
    }

    /// Prune Parquet metadata using pre-built IR predicates and a custom async bloom provider.
    pub async fn prune_ir_with_bloom_provider<P: AsyncBloomFilterProvider>(
        &self,
        metadata: &ParquetMetaData,
        predicates: &[Expr],
        provider: &mut P,
    ) -> PruneResult {
        let compile = AisleResult::from_ir_slice(predicates);
        prune_compiled_with_bloom_provider(
            metadata,
            self.schema.as_ref(),
            compile,
            &self.options,
            provider,
            None,
            None,
        )
        .await
    }
}

/// Pre-compiled pruning plan for reuse across multiple Parquet files.
///
/// Use [`Pruner::try_compile`] to build this once, then call [`CompiledPruner::prune`]
/// for each file's metadata.
#[derive(Debug, Clone)]
pub struct CompiledPruner {
    schema: SchemaRef,
    options: PruneOptions,
    compile: AisleResult,
}

impl CompiledPruner {
    /// Returns the compilation result for this pruner.
    pub fn compile_result(&self) -> &AisleResult {
        &self.compile
    }

    /// Returns a reference to the pruning options used by this pruner.
    pub fn options(&self) -> &PruneOptions {
        &self.options
    }

    /// Prunes Parquet metadata using the pre-compiled predicate.
    pub fn prune(&self, metadata: &ParquetMetaData) -> PruneResult {
        prune_compiled(
            metadata,
            self.schema.as_ref(),
            self.compile.clone(),
            &self.options,
            None,
            None,
        )
    }

    /// Prune Parquet metadata using the pre-compiled predicate and bloom filters
    /// from the async reader.
    pub async fn prune_with_async_reader<T: AsyncFileReader + 'static>(
        &self,
        builder: &mut ParquetRecordBatchStreamBuilder<T>,
    ) -> PruneResult {
        let metadata = builder.metadata().clone();
        prune_compiled_with_bloom_provider(
            metadata.as_ref(),
            self.schema.as_ref(),
            self.compile.clone(),
            &self.options,
            builder,
            None,
            None,
        )
        .await
    }

    /// Prune Parquet metadata using the pre-compiled predicate and a custom
    /// async bloom provider.
    pub async fn prune_with_bloom_provider<P: AsyncBloomFilterProvider>(
        &self,
        metadata: &ParquetMetaData,
        provider: &mut P,
    ) -> PruneResult {
        prune_compiled_with_bloom_provider(
            metadata,
            self.schema.as_ref(),
            self.compile.clone(),
            &self.options,
            provider,
            None,
            None,
        )
        .await
    }
}