Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion datafusion/core/tests/dataframe/dataframe_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ use datafusion_common::test_util::batches_to_string;
use datafusion_common::{DFSchema, ScalarValue};
use datafusion_expr::expr::Alias;
use datafusion_expr::{ExprSchemable, LogicalPlanBuilder, table_scan};
use datafusion_functions_aggregate::expr_fn::{approx_median, approx_percentile_cont};
use datafusion_functions_aggregate::expr_fn::{
approx_median, approx_percentile_cont, approx_top_k,
};
use datafusion_functions_nested::map::map;
use insta::assert_snapshot;

Expand Down Expand Up @@ -396,6 +398,27 @@ async fn test_fn_approx_median() -> Result<()> {
Ok(())
}

#[tokio::test]
async fn test_fn_approx_top_k() -> Result<()> {
// Column b has values [1, 10, 10, 100] -- 10 appears twice, others once.
let expr = approx_top_k(col("b"), lit(1));

let df = create_test_table().await?;
let batches = df.aggregate(vec![], vec![expr]).unwrap().collect().await?;

assert_snapshot!(
batches_to_string(&batches),
@r"
+-------------------------------+
| approx_top_k(test.b,Int32(1)) |
+-------------------------------+
| [{value: 10, count: 2}] |
+-------------------------------+
");

Ok(())
}

#[tokio::test]
async fn test_fn_approx_percentile_cont() -> Result<()> {
let expr = approx_percentile_cont(col("b").sort(true, false), lit(0.5), None);
Expand Down
4 changes: 4 additions & 0 deletions datafusion/functions-aggregate/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ name = "min_max_bytes"
name = "approx_distinct"
harness = false

[[bench]]
name = "approx_top_k"
harness = false

[[bench]]
name = "first_last"
harness = false
Expand Down
303 changes: 303 additions & 0 deletions datafusion/functions-aggregate/benches/approx_top_k.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,303 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use std::hint::black_box;
use std::sync::Arc;

use arrow::array::{ArrayRef, StringArray};
use arrow::datatypes::{DataType, Field, Schema};
use criterion::measurement::WallTime;
use criterion::{
BatchSize, BenchmarkGroup, Criterion, Throughput, criterion_group, criterion_main,
};
use datafusion_expr::function::AccumulatorArgs;
use datafusion_expr::{Accumulator, AggregateUDFImpl, EmitTo, GroupsAccumulator};
use datafusion_functions_aggregate::approx_top_k::ApproxTopK;
use datafusion_physical_expr::expressions::{col, lit};

const ROWS: usize = 100_000;
const GROUPS: usize = 25_000;
const CHURN_GROUPS: usize = 1_000;

fn with_accumulator_args<T>(
data_type: DataType,
k: i64,
build: impl FnOnce(&ApproxTopK, AccumulatorArgs<'_>) -> T,
) -> T {
let schema = Arc::new(Schema::new(vec![Field::new(
"value",
data_type.clone(),
true,
)]));
let exprs = [col("value", &schema).unwrap(), lit(k)];
let expr_fields = exprs
.iter()
.map(|expr| expr.return_field(&schema).unwrap())
.collect::<Vec<_>>();
let function = ApproxTopK::new();
let return_type = function.return_type(&[data_type, DataType::Int64]).unwrap();
build(
&function,
AccumulatorArgs {
return_field: Arc::new(Field::new("result", return_type, true)),
schema: &schema,
expr_fields: &expr_fields,
ignore_nulls: false,
order_bys: &[],
is_reversed: false,
name: "approx_top_k(value, k)",
is_distinct: false,
exprs: &exprs,
},
)
}

fn prepare_accumulator(data_type: DataType, k: i64) -> Box<dyn Accumulator> {
with_accumulator_args(data_type, k, |f, args| f.accumulator(args).unwrap())
}

fn prepare_groups_accumulator(data_type: DataType, k: i64) -> Box<dyn GroupsAccumulator> {
with_accumulator_args(data_type, k, |f, args| {
f.create_groups_accumulator(args).unwrap()
})
}

fn high_cardinality_values(offset: usize) -> ArrayRef {
Arc::new(StringArray::from_iter_values(
(offset..offset + ROWS).map(|row| format!("value_{row:08}")),
))
}

/// Skewed workload like top URL paths or top error codes: 90% of rows come
/// from 300 hot values (heavily skewed toward the first few) and 10% are
/// distinct tail values. At `k=1000` and `k=10000` all hot values fit in the
/// summary (~90% hits); at `k=10` (capacity 30) the tracked values cover
/// roughly 42% of rows.
fn skewed_values() -> ArrayRef {
const HOT_VALUES: f64 = 300.0;
let mut rng = 0x9e37_79b9_7f4a_7c15u64;
Arc::new(StringArray::from_iter_values((0..ROWS).map(|row| {
rng = rng
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
let random = rng >> 11;
if random.is_multiple_of(10) {
format!("value_{:08}", 1_000 + row)
} else {
let uniform = (random >> 4) as f64 / (1u64 << 49) as f64;
let hot = (uniform * uniform * uniform * HOT_VALUES) as usize;
format!("value_{hot:08}")
}
})))
}

fn bench_update_and_evaluate(
group: &mut BenchmarkGroup<'_, WallTime>,
values: &ArrayRef,
k: i64,
) {
group.bench_function(format!("update and evaluate utf8 k={k}"), |b| {
b.iter_batched(
|| prepare_accumulator(DataType::Utf8, k),
|mut accumulator| {
accumulator
.update_batch(std::slice::from_ref(values))
.unwrap();
let result = accumulator.evaluate().unwrap();
black_box((result, accumulator))
},
BatchSize::PerIteration,
);
});
}

fn bench_grouped(
group: &mut BenchmarkGroup<'_, WallTime>,
values: &ArrayRef,
total_groups: usize,
k: i64,
) {
let groups: Vec<usize> = (0..ROWS).map(|row| row % total_groups).collect();
group.bench_function(format!("utf8 {total_groups} groups k={k}"), |b| {
b.iter_batched(
|| prepare_groups_accumulator(DataType::Utf8, k),
|mut accumulator| {
accumulator
.update_batch(
std::slice::from_ref(values),
&groups,
None,
total_groups,
)
.unwrap();
let result = accumulator.evaluate(EmitTo::All).unwrap();
black_box((result, accumulator))
},
BatchSize::PerIteration,
);
});
}

fn approx_top_k_benchmark(c: &mut Criterion) {
let values = high_cardinality_values(0);
let other_values = high_cardinality_values(ROWS / 2);
let mut group = c.benchmark_group("approx_top_k_high_cardinality");
group.sample_size(10);
group.throughput(Throughput::Elements(ROWS as u64));
for k in [10, 1_000, 10_000] {
bench_update_and_evaluate(&mut group, &values, k);
group.bench_function(format!("update only utf8 k={k}"), |b| {
b.iter_batched(
|| prepare_accumulator(DataType::Utf8, k),
|mut accumulator| {
accumulator
.update_batch(std::slice::from_ref(&values))
.unwrap();
black_box(accumulator)
},
BatchSize::PerIteration,
);
});
}
group.finish();

let mut group = c.benchmark_group("approx_top_k_grouped");
group.sample_size(10);
group.throughput(Throughput::Elements(ROWS as u64));
for (total_groups, k) in [
(ROWS, 10),
(GROUPS, 10),
(CHURN_GROUPS, 10),
(CHURN_GROUPS, 10_000),
] {
bench_grouped(&mut group, &values, total_groups, k);
}
// Final stage after partial aggregation was skipped: one state per row.
let groups: Vec<usize> = (0..ROWS).map(|row| row % CHURN_GROUPS).collect();
for k in [10, 10_000] {
let states = prepare_groups_accumulator(DataType::Utf8, k)
.convert_to_state(std::slice::from_ref(&values), None)
.unwrap();
group.bench_function(
format!("merge converted utf8 {CHURN_GROUPS} groups k={k}"),
|b| {
b.iter_batched(
|| prepare_groups_accumulator(DataType::Utf8, k),
|mut accumulator| {
accumulator
.merge_batch(&states, &groups, CHURN_GROUPS)
.unwrap();
let result = accumulator.evaluate(EmitTo::All).unwrap();
black_box((result, accumulator))
},
BatchSize::PerIteration,
);
},
);
}
group.finish();

let skewed = skewed_values();
let mut group = c.benchmark_group("approx_top_k_skewed");
group.sample_size(10);
group.throughput(Throughput::Elements(ROWS as u64));
for k in [10, 1_000, 10_000] {
bench_update_and_evaluate(&mut group, &skewed, k);
}
for (total_groups, k) in [(GROUPS, 10), (CHURN_GROUPS, 10), (CHURN_GROUPS, 10_000)] {
bench_grouped(&mut group, &skewed, total_groups, k);
}
group.finish();

let mut group = c.benchmark_group("approx_top_k_state");
group.sample_size(10);
let converter = prepare_groups_accumulator(DataType::Utf8, 10);
group.bench_function("convert_to_state utf8", |b| {
b.iter_batched(
|| (),
|_| {
converter
.convert_to_state(std::slice::from_ref(&values), None)
.unwrap()
},
BatchSize::PerIteration,
);
});
for k in [1_000, 10_000] {
let populated = |input: &ArrayRef| {
let mut accumulator = prepare_accumulator(DataType::Utf8, k);
accumulator
.update_batch(std::slice::from_ref(input))
.unwrap();
accumulator
};
let mut accumulator = populated(&values);
group.bench_function(format!("state utf8 k={k}"), |b| {
b.iter_batched(
|| (),
|_| accumulator.state().unwrap(),
BatchSize::PerIteration,
);
});

let state = populated(&other_values)
.state()
.unwrap()
.iter()
.map(|state| state.to_array().unwrap())
.collect::<Vec<_>>();
group.bench_function(format!("merge state into nonempty utf8 k={k}"), |b| {
b.iter_batched(
|| populated(&values),
|mut accumulator| {
accumulator.merge_batch(&state).unwrap();
black_box(accumulator)
},
BatchSize::PerIteration,
);
});
}
for (total_groups, k) in [(GROUPS, 10), (CHURN_GROUPS, 10)] {
let groups: Vec<usize> = (0..ROWS).map(|row| row % total_groups).collect();
let state_groups: Vec<usize> = (0..total_groups).collect();
let populated = || {
let mut accumulator = prepare_groups_accumulator(DataType::Utf8, k);
accumulator
.update_batch(std::slice::from_ref(&values), &groups, None, total_groups)
.unwrap();
accumulator
};
group.bench_function(format!("state utf8 {total_groups} groups k={k}"), |b| {
b.iter_batched(
populated,
|mut accumulator| {
let state = accumulator.state(EmitTo::All).unwrap();
black_box((state, accumulator))
},
BatchSize::PerIteration,
);
});

let state = populated().state(EmitTo::All).unwrap();
group.bench_function(
format!("merge state utf8 {total_groups} groups k={k}"),
|b| {
b.iter_batched(
|| prepare_groups_accumulator(DataType::Utf8, k),
|mut accumulator| {
accumulator
.merge_batch(&state, &state_groups, total_groups)
.unwrap();
black_box(accumulator)
},
BatchSize::PerIteration,
);
},
);
}
group.finish();
}

criterion_group!(benches, approx_top_k_benchmark);
criterion_main!(benches);
Loading