Skip to content

Commit bb39e8b

Browse files
committed
perf: Route remaining literal CASE branches in one pass
1 parent 24a553d commit bb39e8b

4 files changed

Lines changed: 600 additions & 3 deletions

File tree

‎datafusion/physical-expr/benches/case_when.rs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ fn criterion_benchmark(c: &mut Criterion) {
9494
run_benchmarks(c, &make_batch(8192, 100));
9595

9696
benchmark_lookup_table_case_when(c, 8192);
97+
benchmark_literal_when_expressions(c);
9798
benchmark_divide_by_zero_protection(c, 8192);
9899
}
99100

@@ -599,3 +600,51 @@ fn benchmark_divide_by_zero_protection(c: &mut Criterion, batch_size: usize) {
599600

600601
criterion_group!(benches, criterion_benchmark);
601602
criterion_main!(benches);
603+
604+
fn benchmark_literal_when_expressions(c: &mut Criterion) {
605+
let mut group = c.benchmark_group("literal_when_expressions");
606+
for branches in [2, 8, 16, 32, 128] {
607+
for distribution in [
608+
"uniform",
609+
"first",
610+
"first_two",
611+
"mostly_first",
612+
"miss_constant",
613+
"miss_varied",
614+
] {
615+
let keys: ArrayRef = Arc::new(Int32Array::from_iter_values((0..8192).map(
616+
|i| match distribution {
617+
"first" => 0,
618+
"first_two" => i % 2,
619+
"mostly_first" if i % 16 != 0 => 0,
620+
"mostly_first" => (i / 16) % branches,
621+
"miss_constant" => branches,
622+
"miss_varied" => branches + i,
623+
_ => i % branches,
624+
},
625+
)));
626+
let values: ArrayRef = Arc::new(Int32Array::from_iter_values(0..8192));
627+
let batch =
628+
RecordBatch::try_from_iter(vec![("category", keys), ("value", values)])
629+
.unwrap();
630+
let key = col("category", &batch.schema()).unwrap();
631+
let value = col("value", &batch.schema()).unwrap();
632+
let expr = case(
633+
Some(key),
634+
(0..branches)
635+
.map(|i| (lit(i), make_x_cmp_y(&value, Operator::Gt, i)))
636+
.collect(),
637+
Some(lit(false)),
638+
)
639+
.unwrap();
640+
group.bench_with_input(
641+
BenchmarkId::new(distribution, branches),
642+
&batch,
643+
|b, batch| {
644+
b.iter(|| black_box(expr.evaluate(black_box(batch)).unwrap()));
645+
},
646+
);
647+
}
648+
}
649+
group.finish();
650+
}

‎datafusion/physical-expr/src/expressions/case.rs‎

Lines changed: 131 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ enum EvalMethod {
6464
/// [ELSE result]
6565
/// END
6666
WithExpression(ProjectedCaseBody),
67+
/// Route remaining literal WHEN matches after evaluating the leading branches.
68+
WithLiteralWhen(ProjectedCaseBody, LiteralLookupTable),
6769
/// This is a specialization for a specific use case where we can take a fast path
6870
/// for expressions that are infallible and can be cheaply computed for the entire
6971
/// record batch rather than just for the rows where the predicate is true.
@@ -128,6 +130,108 @@ struct CaseBody {
128130
}
129131

130132
impl CaseBody {
133+
fn literal_branch_lookup(&self) -> Option<LiteralLookupTable> {
134+
// For short CASE expressions, sequential comparisons avoid lookup/gather setup.
135+
if self.when_then_expr.len() <= 8 {
136+
return None;
137+
}
138+
// Map keys to original branch indices using the existing first-match/NULL rules.
139+
let count = u32::try_from(self.when_then_expr.len()).ok()?;
140+
let body = Self {
141+
expr: self.expr.clone(),
142+
when_then_expr: self
143+
.when_then_expr
144+
.iter()
145+
.zip(0..count)
146+
.map(|((when, _), index)| (Arc::clone(when), lit(index)))
147+
.collect(),
148+
else_expr: Some(lit(count)),
149+
};
150+
LiteralLookupTable::maybe_new(&body)
151+
}
152+
153+
fn case_when_literal_branches(
154+
&self,
155+
batch: &RecordBatch,
156+
keys: &ArrayRef,
157+
return_type: &DataType,
158+
lookup: &LiteralLookupTable,
159+
) -> Result<ColumnarValue> {
160+
let row_count = batch.num_rows();
161+
let count = u32::try_from(row_count).map_err(|_| {
162+
internal_datafusion_err!("CASE batch exceeds row index limit")
163+
})?;
164+
let branch_expr = |branch: usize| -> Result<Option<Arc<dyn PhysicalExpr>>> {
165+
if let Some((_, then)) = self.when_then_expr.get(branch) {
166+
Ok(Some(Arc::clone(then)))
167+
} else {
168+
self.else_expr
169+
.as_ref()
170+
.map(|otherwise| {
171+
try_cast(
172+
Arc::clone(otherwise),
173+
&batch.schema(),
174+
return_type.clone(),
175+
)
176+
})
177+
.transpose()
178+
}
179+
};
180+
let mut result = ResultBuilder::new(return_type, row_count);
181+
if row_count == 0 {
182+
return result.finish();
183+
}
184+
// A constant batch needs one lookup and no gathers, including a batch of NULLs.
185+
let first = keys.slice(0, 1);
186+
let same_key = if keys.logical_null_count() == row_count {
187+
true
188+
} else {
189+
let value = ScalarValue::try_from_array(keys, 0)?.to_scalar()?;
190+
let equal = compare_with_eq(&value, keys, keys.data_type().is_nested())?;
191+
equal.null_count() == 0 && !equal.has_false()
192+
};
193+
if same_key {
194+
let index = lookup.map_keys_to_values(&first)?;
195+
let branch = index.as_primitive::<UInt32Type>().value(0) as usize;
196+
return match branch_expr(branch)? {
197+
Some(expr) => expr.evaluate(batch),
198+
None => result.finish(),
199+
};
200+
}
201+
let branches = lookup.map_keys_to_values(keys)?;
202+
let mut selections = vec![Vec::new(); self.when_then_expr.len() + 1];
203+
for (row, branch) in
204+
(0..count).zip(branches.as_primitive::<UInt32Type>().values())
205+
{
206+
selections[*branch as usize].push(row);
207+
}
208+
for (branch, rows) in selections.into_iter().enumerate() {
209+
if rows.is_empty() {
210+
continue;
211+
}
212+
let Some(expr) = branch_expr(branch)? else {
213+
continue;
214+
};
215+
if rows.len() == row_count {
216+
return expr.evaluate(batch);
217+
}
218+
let indices: ArrayRef = Arc::new(UInt32Array::from(rows));
219+
let columns = batch
220+
.columns()
221+
.iter()
222+
.map(|column| arrow::compute::take(column, &indices, None))
223+
.collect::<std::result::Result<Vec<_>, ArrowError>>()?;
224+
// Expressions without column references still need the selected row count.
225+
let selected = RecordBatch::try_new_with_options(
226+
batch.schema(),
227+
columns,
228+
&RecordBatchOptions::new().with_row_count(Some(indices.len())),
229+
)?;
230+
result.add_branch_result(&indices, expr.evaluate(&selected)?)?;
231+
}
232+
result.finish()
233+
}
234+
131235
/// Derives a [ProjectedCaseBody] from this [CaseBody].
132236
fn project(&self) -> Result<ProjectedCaseBody> {
133237
// Determine the set of columns that are used in all the expressions of the case body.
@@ -685,6 +789,9 @@ impl CaseExpr {
685789
return Ok(EvalMethod::WithExprScalarLookupTable(mapping));
686790
}
687791

792+
if let Some(mapping) = body.literal_branch_lookup() {
793+
return Ok(EvalMethod::WithLiteralWhen(body.project()?, mapping));
794+
}
688795
return Ok(EvalMethod::WithExpression(body.project()?));
689796
}
690797

@@ -750,6 +857,7 @@ impl CaseBody {
750857
&self,
751858
batch: &RecordBatch,
752859
return_type: &DataType,
860+
lookup: Option<&LiteralLookupTable>,
753861
) -> Result<ColumnarValue> {
754862
let mut result_builder = ResultBuilder::new(return_type, batch.num_rows());
755863

@@ -817,6 +925,19 @@ impl CaseBody {
817925
let base_value_is_nested = base_values.data_type().is_nested();
818926

819927
for i in 0..self.when_then_expr.len() {
928+
// Preserve early exits for common leading branches before paying for routing.
929+
if i == 2
930+
&& let Some(lookup) = lookup
931+
{
932+
let value = self.case_when_literal_branches(
933+
&remainder_batch,
934+
&base_values,
935+
return_type,
936+
lookup,
937+
)?;
938+
result_builder.add_branch_result(&remainder_rows, value)?;
939+
return result_builder.finish();
940+
}
820941
// Evaluate the 'when' predicate for the remainder batch
821942
// This results in a boolean array with the same length as the remaining number of rows
822943
let when_expr = &self.when_then_expr[i].0;
@@ -1047,6 +1168,7 @@ impl CaseExpr {
10471168
&self,
10481169
batch: &RecordBatch,
10491170
projected: &ProjectedCaseBody,
1171+
lookup: Option<&LiteralLookupTable>,
10501172
) -> Result<ColumnarValue> {
10511173
let return_type = self.data_type(&batch.schema())?;
10521174
// projected.projection may include indexes of lambda variables not available on this batch
@@ -1060,9 +1182,9 @@ impl CaseExpr {
10601182
let projected_batch = batch.project(&projection)?;
10611183
projected
10621184
.body
1063-
.case_when_with_expr(&projected_batch, &return_type)
1185+
.case_when_with_expr(&projected_batch, &return_type, lookup)
10641186
} else {
1065-
self.body.case_when_with_expr(batch, &return_type)
1187+
self.body.case_when_with_expr(batch, &return_type, lookup)
10661188
}
10671189
}
10681190

@@ -1326,7 +1448,10 @@ impl PhysicalExpr for CaseExpr {
13261448
EvalMethod::WithExpression(p) => {
13271449
// this use case evaluates "expr" and then compares the values with the "when"
13281450
// values
1329-
self.case_when_with_expr(batch, p)
1451+
self.case_when_with_expr(batch, p, None)
1452+
}
1453+
EvalMethod::WithLiteralWhen(p, lookup) => {
1454+
self.case_when_with_expr(batch, p, Some(lookup))
13301455
}
13311456
EvalMethod::NoExpression(p) => {
13321457
// The "when" conditions all evaluate to boolean in this use case and can be
@@ -3524,3 +3649,6 @@ mod proto_tests {
35243649
assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 2")));
35253650
}
35263651
}
3652+
3653+
#[cfg(test)]
3654+
mod literal_branches_tests;

0 commit comments

Comments
 (0)