forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable_sample.rs
More file actions
820 lines (738 loc) · 27.8 KB
/
table_sample.rs
File metadata and controls
820 lines (738 loc) · 27.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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! # TABLESAMPLE Example
//!
//! This example demonstrates implementing SQL `TABLESAMPLE` support using
//! DataFusion's extensibility APIs.
//!
//! This is a working `TABLESAMPLE` implementation that can serve as a starting
//! point for your own projects. It also works as a template for adding other
//! custom SQL operators, covering the full pipeline from parsing to execution.
//!
//! It shows how to:
//!
//! 1. **Parse** TABLESAMPLE syntax via a custom [`RelationPlanner`]
//! 2. **Plan** sampling as a custom logical node ([`TableSamplePlanNode`])
//! 3. **Execute** sampling via a custom physical operator ([`SampleExec`])
//!
//! ## Supported Syntax
//!
//! ```sql
//! -- Bernoulli sampling (each row has N% chance of selection)
//! SELECT * FROM table TABLESAMPLE BERNOULLI(10 PERCENT)
//!
//! -- Fractional sampling (0.0 to 1.0)
//! SELECT * FROM table TABLESAMPLE (0.1)
//!
//! -- Row count limit
//! SELECT * FROM table TABLESAMPLE (100 ROWS)
//!
//! -- Reproducible sampling with a seed
//! SELECT * FROM table TABLESAMPLE (10 PERCENT) REPEATABLE(42)
//! ```
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ SQL Query │
//! │ SELECT * FROM t TABLESAMPLE BERNOULLI(10 PERCENT) REPEATABLE(1)│
//! └─────────────────────────────────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ TableSamplePlanner │
//! │ (RelationPlanner: parses TABLESAMPLE, creates logical node) │
//! └─────────────────────────────────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ TableSamplePlanNode │
//! │ (UserDefinedLogicalNode: stores sampling params) │
//! └─────────────────────────────────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ TableSampleExtensionPlanner │
//! │ (ExtensionPlanner: creates physical execution plan) │
//! └─────────────────────────────────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ SampleExec │
//! │ (ExecutionPlan: performs actual row sampling at runtime) │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
use std::{
any::Any,
fmt::{self, Debug, Formatter},
hash::{Hash, Hasher},
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use arrow::datatypes::{Float64Type, Int64Type};
use arrow::{
array::{ArrayRef, Int32Array, RecordBatch, StringArray, UInt32Array},
compute,
};
use arrow_schema::SchemaRef;
use futures::{
ready,
stream::{Stream, StreamExt},
};
use rand::{Rng, SeedableRng, rngs::StdRng};
use tonic::async_trait;
use datafusion::optimizer::simplify_expressions::simplify_literal::parse_literal;
use datafusion::{
execution::{
RecordBatchStream, SendableRecordBatchStream, SessionState, SessionStateBuilder,
TaskContext, context::QueryPlanner,
},
physical_expr::EquivalenceProperties,
physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet, RecordOutput},
},
physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner},
prelude::*,
};
use datafusion_common::{
DFSchemaRef, DataFusionError, Result, Statistics, internal_err, not_impl_err,
plan_datafusion_err, plan_err,
};
use datafusion_expr::{
UserDefinedLogicalNode, UserDefinedLogicalNodeCore,
logical_plan::{Extension, LogicalPlan, LogicalPlanBuilder},
planner::{
PlannedRelation, RelationPlanner, RelationPlannerContext, RelationPlanning,
},
};
use datafusion_sql::sqlparser::ast::{
self, TableFactor, TableSampleMethod, TableSampleUnit,
};
use insta::assert_snapshot;
// ============================================================================
// Example Entry Point
// ============================================================================
/// Runs the TABLESAMPLE examples demonstrating various sampling techniques.
pub async fn table_sample() -> Result<()> {
// Build session with custom query planner for physical planning
let state = SessionStateBuilder::new()
.with_default_features()
.with_query_planner(Arc::new(TableSampleQueryPlanner))
.build();
let ctx = SessionContext::new_with_state(state);
// Register custom relation planner for logical planning
ctx.register_relation_planner(Arc::new(TableSamplePlanner))?;
register_sample_data(&ctx)?;
println!("TABLESAMPLE Example");
println!("===================\n");
run_examples(&ctx).await
}
async fn run_examples(ctx: &SessionContext) -> Result<()> {
// Example 1: Baseline - full table scan
let results = run_example(
ctx,
"Example 1: Full table (baseline)",
"SELECT * FROM sample_data",
)
.await?;
assert_snapshot!(results, @r"
+---------+---------+
| column1 | column2 |
+---------+---------+
| 1 | row_1 |
| 2 | row_2 |
| 3 | row_3 |
| 4 | row_4 |
| 5 | row_5 |
| 6 | row_6 |
| 7 | row_7 |
| 8 | row_8 |
| 9 | row_9 |
| 10 | row_10 |
+---------+---------+
");
// Example 2: Percentage-based Bernoulli sampling
// REPEATABLE(seed) ensures deterministic results for snapshot testing
let results = run_example(
ctx,
"Example 2: BERNOULLI percentage sampling",
"SELECT * FROM sample_data TABLESAMPLE BERNOULLI(30 PERCENT) REPEATABLE(123)",
)
.await?;
assert_snapshot!(results, @r"
+---------+---------+
| column1 | column2 |
+---------+---------+
| 1 | row_1 |
| 2 | row_2 |
| 7 | row_7 |
| 8 | row_8 |
+---------+---------+
");
// Example 3: Fractional sampling (0.0 to 1.0)
// REPEATABLE(seed) ensures deterministic results for snapshot testing
let results = run_example(
ctx,
"Example 3: Fractional sampling",
"SELECT * FROM sample_data TABLESAMPLE (0.5) REPEATABLE(456)",
)
.await?;
assert_snapshot!(results, @r"
+---------+---------+
| column1 | column2 |
+---------+---------+
| 2 | row_2 |
| 4 | row_4 |
| 8 | row_8 |
+---------+---------+
");
// Example 4: Row count limit (deterministic, no seed needed)
let results = run_example(
ctx,
"Example 4: Row count limit",
"SELECT * FROM sample_data TABLESAMPLE (3 ROWS)",
)
.await?;
assert_snapshot!(results, @r"
+---------+---------+
| column1 | column2 |
+---------+---------+
| 1 | row_1 |
| 2 | row_2 |
| 3 | row_3 |
+---------+---------+
");
// Example 5: Sampling combined with filtering
let results = run_example(
ctx,
"Example 5: Sampling with WHERE clause",
"SELECT * FROM sample_data TABLESAMPLE (5 ROWS) WHERE column1 > 2",
)
.await?;
assert_snapshot!(results, @r"
+---------+---------+
| column1 | column2 |
+---------+---------+
| 3 | row_3 |
| 4 | row_4 |
| 5 | row_5 |
+---------+---------+
");
// Example 6: Sampling in JOIN queries
// REPEATABLE(seed) ensures deterministic results for snapshot testing
let results = run_example(
ctx,
"Example 6: Sampling in JOINs",
r#"SELECT t1.column1, t2.column1, t1.column2, t2.column2
FROM sample_data t1 TABLESAMPLE (0.7) REPEATABLE(789)
JOIN sample_data t2 TABLESAMPLE (0.7) REPEATABLE(123)
ON t1.column1 = t2.column1"#,
)
.await?;
assert_snapshot!(results, @r"
+---------+---------+---------+---------+
| column1 | column1 | column2 | column2 |
+---------+---------+---------+---------+
| 2 | 2 | row_2 | row_2 |
| 5 | 5 | row_5 | row_5 |
| 7 | 7 | row_7 | row_7 |
| 8 | 8 | row_8 | row_8 |
| 10 | 10 | row_10 | row_10 |
+---------+---------+---------+---------+
");
Ok(())
}
/// Helper to run a single example query and capture results.
async fn run_example(ctx: &SessionContext, title: &str, sql: &str) -> Result<String> {
println!("{title}:\n{sql}\n");
let df = ctx.sql(sql).await?;
println!("{}\n", df.logical_plan().display_indent());
let batches = df.collect().await?;
let results = arrow::util::pretty::pretty_format_batches(&batches)?.to_string();
println!("{results}\n");
Ok(results)
}
/// Register test data: 10 rows with column1=1..10 and column2="row_1".."row_10"
fn register_sample_data(ctx: &SessionContext) -> Result<()> {
let column1: ArrayRef = Arc::new(Int32Array::from((1..=10).collect::<Vec<i32>>()));
let column2: ArrayRef = Arc::new(StringArray::from(
(1..=10).map(|i| format!("row_{i}")).collect::<Vec<_>>(),
));
let batch =
RecordBatch::try_from_iter(vec![("column1", column1), ("column2", column2)])?;
ctx.register_batch("sample_data", batch)?;
Ok(())
}
// ============================================================================
// Logical Planning: TableSamplePlanner + TableSamplePlanNode
// ============================================================================
/// Relation planner that intercepts `TABLESAMPLE` clauses in SQL and creates
/// [`TableSamplePlanNode`] logical nodes.
#[derive(Debug)]
struct TableSamplePlanner;
impl RelationPlanner for TableSamplePlanner {
fn plan_relation(
&self,
relation: TableFactor,
context: &mut dyn RelationPlannerContext,
) -> Result<RelationPlanning> {
// Only handle Table relations with TABLESAMPLE clause
let TableFactor::Table {
sample: Some(sample),
alias,
name,
args,
with_hints,
version,
with_ordinality,
partitions,
json_path,
index_hints,
} = relation
else {
return Ok(RelationPlanning::Original(Box::new(relation)));
};
// Extract sample spec (handles both before/after alias positions)
let sample = match sample {
ast::TableSampleKind::BeforeTableAlias(s)
| ast::TableSampleKind::AfterTableAlias(s) => s,
};
// Validate sampling method
if let Some(method) = &sample.name
&& *method != TableSampleMethod::Bernoulli
&& *method != TableSampleMethod::Row
{
return not_impl_err!(
"Sampling method {} is not supported (only BERNOULLI and ROW)",
method
);
}
// Offset sampling (ClickHouse-style) not supported
if sample.offset.is_some() {
return not_impl_err!(
"TABLESAMPLE with OFFSET is not supported (requires total row count)"
);
}
// Parse optional REPEATABLE seed
let seed = sample
.seed
.map(|s| {
s.value.to_string().parse::<u64>().map_err(|_| {
plan_datafusion_err!("REPEATABLE seed must be an integer")
})
})
.transpose()?;
// Plan the underlying table without the sample clause
let base_relation = TableFactor::Table {
sample: None,
alias: alias.clone(),
name,
args,
with_hints,
version,
with_ordinality,
partitions,
json_path,
index_hints,
};
let input = context.plan(base_relation)?;
// Handle bucket sampling (Hive-style: TABLESAMPLE(BUCKET x OUT OF y))
if let Some(bucket) = sample.bucket {
if bucket.on.is_some() {
return not_impl_err!(
"TABLESAMPLE BUCKET with ON clause requires CLUSTERED BY table"
);
}
let bucket_num: u64 =
bucket.bucket.to_string().parse().map_err(|_| {
plan_datafusion_err!("bucket number must be an integer")
})?;
let total: u64 =
bucket.total.to_string().parse().map_err(|_| {
plan_datafusion_err!("bucket total must be an integer")
})?;
let fraction = bucket_num as f64 / total as f64;
let plan = TableSamplePlanNode::new(input, fraction, seed).into_plan();
return Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new(
plan, alias,
))));
}
// Handle quantity-based sampling
let Some(quantity) = sample.quantity else {
return plan_err!(
"TABLESAMPLE requires a quantity (percentage, fraction, or row count)"
);
};
let quantity_value_expr = context.sql_to_expr(quantity.value, input.schema())?;
match quantity.unit {
// TABLESAMPLE (N ROWS) - exact row limit
Some(TableSampleUnit::Rows) => {
let rows: i64 = parse_literal::<Int64Type>(&quantity_value_expr)?;
if rows < 0 {
return plan_err!("row count must be non-negative, got {}", rows);
}
let plan = LogicalPlanBuilder::from(input)
.limit(0, Some(rows as usize))?
.build()?;
Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new(
plan, alias,
))))
}
// TABLESAMPLE (N PERCENT) - percentage sampling
Some(TableSampleUnit::Percent) => {
let percent: f64 = parse_literal::<Float64Type>(&quantity_value_expr)?;
let fraction = percent / 100.0;
let plan = TableSamplePlanNode::new(input, fraction, seed).into_plan();
Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new(
plan, alias,
))))
}
// TABLESAMPLE (N) - fraction if <1.0, row limit if >=1.0
None => {
let value = parse_literal::<Float64Type>(&quantity_value_expr)?;
if value < 0.0 {
return plan_err!("sample value must be non-negative, got {}", value);
}
let plan = if value >= 1.0 {
// Interpret as row limit
LogicalPlanBuilder::from(input)
.limit(0, Some(value as usize))?
.build()?
} else {
// Interpret as fraction
TableSamplePlanNode::new(input, value, seed).into_plan()
};
Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new(
plan, alias,
))))
}
}
}
}
/// Custom logical plan node representing a TABLESAMPLE operation.
///
/// Stores sampling parameters (bounds, seed) and wraps the input plan.
/// Gets converted to [`SampleExec`] during physical planning.
#[derive(Debug, Clone, Hash, Eq, PartialEq, PartialOrd)]
struct TableSamplePlanNode {
input: LogicalPlan,
lower_bound: HashableF64,
upper_bound: HashableF64,
seed: u64,
}
impl TableSamplePlanNode {
/// Create a new sampling node with the given fraction (0.0 to 1.0).
fn new(input: LogicalPlan, fraction: f64, seed: Option<u64>) -> Self {
Self {
input,
lower_bound: HashableF64(0.0),
upper_bound: HashableF64(fraction),
seed: seed.unwrap_or_else(rand::random),
}
}
/// Wrap this node in a LogicalPlan::Extension.
fn into_plan(self) -> LogicalPlan {
LogicalPlan::Extension(Extension {
node: Arc::new(self),
})
}
}
impl UserDefinedLogicalNodeCore for TableSamplePlanNode {
fn name(&self) -> &str {
"TableSample"
}
fn inputs(&self) -> Vec<&LogicalPlan> {
vec![&self.input]
}
fn schema(&self) -> &DFSchemaRef {
self.input.schema()
}
fn expressions(&self) -> Vec<Expr> {
vec![]
}
fn fmt_for_explain(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"Sample: bounds=[{}, {}], seed={}",
self.lower_bound.0, self.upper_bound.0, self.seed
)
}
fn with_exprs_and_inputs(
&self,
_exprs: Vec<Expr>,
mut inputs: Vec<LogicalPlan>,
) -> Result<Self> {
Ok(Self {
input: inputs.swap_remove(0),
lower_bound: self.lower_bound,
upper_bound: self.upper_bound,
seed: self.seed,
})
}
}
/// Wrapper for f64 that implements Hash and Eq (required for LogicalPlan).
#[derive(Debug, Clone, Copy, PartialOrd)]
struct HashableF64(f64);
impl PartialEq for HashableF64 {
fn eq(&self, other: &Self) -> bool {
self.0.to_bits() == other.0.to_bits()
}
}
impl Eq for HashableF64 {}
impl Hash for HashableF64 {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
// ============================================================================
// Physical Planning: TableSampleQueryPlanner + TableSampleExtensionPlanner
// ============================================================================
/// Custom query planner that registers [`TableSampleExtensionPlanner`] to
/// convert [`TableSamplePlanNode`] into [`SampleExec`].
#[derive(Debug)]
struct TableSampleQueryPlanner;
#[async_trait]
impl QueryPlanner for TableSampleQueryPlanner {
async fn create_physical_plan(
&self,
logical_plan: &LogicalPlan,
session_state: &SessionState,
) -> Result<Arc<dyn ExecutionPlan>> {
let planner = DefaultPhysicalPlanner::with_extension_planners(vec![Arc::new(
TableSampleExtensionPlanner,
)]);
planner
.create_physical_plan(logical_plan, session_state)
.await
}
}
/// Extension planner that converts [`TableSamplePlanNode`] to [`SampleExec`].
struct TableSampleExtensionPlanner;
#[async_trait]
impl ExtensionPlanner for TableSampleExtensionPlanner {
async fn plan_extension(
&self,
_planner: &dyn PhysicalPlanner,
node: &dyn UserDefinedLogicalNode,
_logical_inputs: &[&LogicalPlan],
physical_inputs: &[Arc<dyn ExecutionPlan>],
_session_state: &SessionState,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
let Some(sample_node) = node.as_any().downcast_ref::<TableSamplePlanNode>()
else {
return Ok(None);
};
let exec = SampleExec::try_new(
Arc::clone(&physical_inputs[0]),
sample_node.lower_bound.0,
sample_node.upper_bound.0,
sample_node.seed,
)?;
Ok(Some(Arc::new(exec)))
}
}
// ============================================================================
// Physical Execution: SampleExec + BernoulliSampler
// ============================================================================
/// Physical execution plan that samples rows from its input using Bernoulli sampling.
///
/// Each row is independently selected with probability `(upper_bound - lower_bound)`
/// and appears at most once.
#[derive(Debug, Clone)]
pub struct SampleExec {
input: Arc<dyn ExecutionPlan>,
lower_bound: f64,
upper_bound: f64,
seed: u64,
metrics: ExecutionPlanMetricsSet,
cache: Arc<PlanProperties>,
}
impl SampleExec {
/// Create a new SampleExec with Bernoulli sampling (without replacement).
///
/// # Arguments
/// * `input` - The input execution plan
/// * `lower_bound` - Lower bound of sampling range (typically 0.0)
/// * `upper_bound` - Upper bound of sampling range (0.0 to 1.0)
/// * `seed` - Random seed for reproducible sampling
pub fn try_new(
input: Arc<dyn ExecutionPlan>,
lower_bound: f64,
upper_bound: f64,
seed: u64,
) -> Result<Self> {
if lower_bound < 0.0 || upper_bound > 1.0 || lower_bound > upper_bound {
return internal_err!(
"Sampling bounds must satisfy 0.0 <= lower <= upper <= 1.0, got [{}, {}]",
lower_bound,
upper_bound
);
}
let cache = PlanProperties::new(
EquivalenceProperties::new(input.schema()),
input.properties().partitioning.clone(),
input.properties().emission_type,
input.properties().boundedness,
);
Ok(Self {
input,
lower_bound,
upper_bound,
seed,
metrics: ExecutionPlanMetricsSet::new(),
cache: Arc::new(cache),
})
}
/// Create a sampler for the given partition.
fn create_sampler(&self, partition: usize) -> BernoulliSampler {
let seed = self.seed.wrapping_add(partition as u64);
BernoulliSampler::new(self.lower_bound, self.upper_bound, seed)
}
}
impl DisplayAs for SampleExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
write!(
f,
"SampleExec: bounds=[{}, {}], seed={}",
self.lower_bound, self.upper_bound, self.seed
)
}
}
impl ExecutionPlan for SampleExec {
fn name(&self) -> &'static str {
"SampleExec"
}
fn as_any(&self) -> &dyn Any {
self
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.cache
}
fn maintains_input_order(&self) -> Vec<bool> {
// Sampling preserves row order (rows are filtered, not reordered)
vec![true]
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn with_new_children(
self: Arc<Self>,
mut children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(Self::try_new(
children.swap_remove(0),
self.lower_bound,
self.upper_bound,
self.seed,
)?))
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
Ok(Box::pin(SampleStream {
input: self.input.execute(partition, context)?,
sampler: self.create_sampler(partition),
metrics: BaselineMetrics::new(&self.metrics, partition),
}))
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
fn partition_statistics(&self, partition: Option<usize>) -> Result<Statistics> {
let mut stats = self.input.partition_statistics(partition)?;
let ratio = self.upper_bound - self.lower_bound;
// Scale statistics by sampling ratio (inexact due to randomness)
stats.num_rows = stats
.num_rows
.map(|n| (n as f64 * ratio) as usize)
.to_inexact();
stats.total_byte_size = stats
.total_byte_size
.map(|n| (n as f64 * ratio) as usize)
.to_inexact();
Ok(stats)
}
}
/// Bernoulli sampler: includes each row with probability `(upper - lower)`.
/// This is sampling **without replacement** - each row appears at most once.
struct BernoulliSampler {
lower_bound: f64,
upper_bound: f64,
rng: StdRng,
}
impl BernoulliSampler {
fn new(lower_bound: f64, upper_bound: f64, seed: u64) -> Self {
Self {
lower_bound,
upper_bound,
rng: StdRng::seed_from_u64(seed),
}
}
fn sample(&mut self, batch: &RecordBatch) -> Result<RecordBatch> {
let range = self.upper_bound - self.lower_bound;
if range <= 0.0 {
return Ok(RecordBatch::new_empty(batch.schema()));
}
// Select rows where random value falls in [lower, upper)
let indices: Vec<u32> = (0..batch.num_rows())
.filter(|_| {
let r: f64 = self.rng.random();
r >= self.lower_bound && r < self.upper_bound
})
.map(|i| i as u32)
.collect();
if indices.is_empty() {
return Ok(RecordBatch::new_empty(batch.schema()));
}
compute::take_record_batch(batch, &UInt32Array::from(indices))
.map_err(DataFusionError::from)
}
}
/// Stream adapter that applies sampling to each batch.
struct SampleStream {
input: SendableRecordBatchStream,
sampler: BernoulliSampler,
metrics: BaselineMetrics,
}
impl Stream for SampleStream {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
match ready!(self.input.poll_next_unpin(cx)) {
Some(Ok(batch)) => {
let elapsed = self.metrics.elapsed_compute().clone();
let _timer = elapsed.timer();
let result = self.sampler.sample(&batch);
Poll::Ready(Some(result.record_output(&self.metrics)))
}
Some(Err(e)) => Poll::Ready(Some(Err(e))),
None => Poll::Ready(None),
}
}
}
impl RecordBatchStream for SampleStream {
fn schema(&self) -> SchemaRef {
self.input.schema()
}
}