Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
813160c
bench: per-query pprof flamegraphs (DF_PPROF) and plan statistics (DF…
andygrove Dec 3, 2026
f604f65
build: patch arrow/parquet to arrow-rs polars-gap branch (bounded mas…
andygrove Dec 3, 2026
beeabee
parquet: merge row filter conjuncts into one predicate (DF_ROWFILTER_…
andygrove Dec 3, 2026
09ed71a
perf: stop hash-table lookups in dynamic filters that keep >90% of rows
andygrove Dec 3, 2026
ccd110e
stats: estimate scan rows after pushed filters, 10% string equality d…
andygrove Dec 3, 2026
33d9e29
perf: keep partial aggregate tables cache sized, growing while they r…
andygrove Dec 3, 2026
b09ff56
perf: compute repeated aggregating/joining subplans once via Material…
andygrove Dec 3, 2026
f671207
parquet: DF_PUSHDOWN_MODE=auto pushes static filters only when the sc…
andygrove Dec 3, 2026
ba5c423
chore: clippy fixes
andygrove Dec 3, 2026
d269863
perf: DF_JOIN_SWAP=rows picks the hash join build side by estimated rows
andygrove Dec 3, 2026
294c6ee
stats: each literal character of a LIKE pattern with wildcards lowers…
andygrove Dec 3, 2026
fa4e57d
perf: move join keys on aggregate results into the join filter so dyn…
andygrove Dec 3, 2026
baeebc1
perf: make the polars-gap experiments the defaults (pushdown_filters=…
andygrove Dec 3, 2026
5124d73
docs: TPC-H SF100 DataFusion vs Polars/qe2 gap report and benchmark s…
andygrove Dec 3, 2026
0672ca6
build: take the arrow-rs patch from the andygrove/arrow-rs polars-gap…
andygrove Dec 3, 2026
7c78b7a
docs: compare against Polars only; require HOST in sync.sh
andygrove Dec 3, 2026
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
348 changes: 292 additions & 56 deletions Cargo.lock

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,23 @@ incremental = false
[profile.ci-bench]
inherits = "ci"
opt-level = 1

[patch.crates-io]
arrow = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-arith = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-array = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-avro = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-buffer = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-cast = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-cmp = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-csv = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-data = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-flight = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-ipc = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-json = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-ord = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-row = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-schema = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-select = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
arrow-string = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
parquet = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" }
1 change: 1 addition & 0 deletions benchmarks/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ datafusion = { workspace = true, default-features = true }
datafusion-common = { workspace = true, default-features = true }
datafusion-common-runtime = { workspace = true }
env_logger = { workspace = true }
pprof = { version = "0.15", features = ["flamegraph"] }
futures = { workspace = true }
libmimalloc-sys = { version = "0.1", optional = true }
log = { workspace = true }
Expand Down
251 changes: 251 additions & 0 deletions benchmarks/polars-gap/REPORT.md

Large diffs are not rendered by default.

13 changes: 13 additions & 0 deletions benchmarks/polars-gap/scripts/diffprof.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import collections,sys,re
def load(p):
s=collections.Counter(); t=0
for line in open(p):
st,_,c=line.rstrip().rpartition(" "); c=int(c); t+=c
f=st.split(";")[-1]
f=re.sub(r"\{closure#\d+\}","{c}",f)
s[f[:140]]+=c
return s,t
a,ta=load(sys.argv[1]); b,tb=load(sys.argv[2])
print(f"total samples A={ta} B={tb}")
keys=sorted(set(a)|set(b), key=lambda k: -(a[k]+b[k]))[:int(sys.argv[3]) if len(sys.argv)>3 else 30]
for k in keys: print(f"{a[k]:7d} {b[k]:7d} {k}")
9 changes: 9 additions & 0 deletions benchmarks/polars-gap/scripts/matrix.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# usage: matrix.sh BIN "tag|env|args" ... runs sequentially; writes ~/pg/matrix.done when finished
B=$1; shift
rm -f ~/pg/matrix.done
for spec in "$@"; do
IFS='|' read -r tag envs args <<< "$spec"
env $envs ~/pg/run_df.sh $B $tag all $args > ~/pg/results/$tag.log 2>&1
done
touch ~/pg/matrix.done
18 changes: 18 additions & 0 deletions benchmarks/polars-gap/scripts/planx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import re,sys
# condense a dfbench --debug metrics plan
txt=open(sys.argv[1]).read()
sec=txt.split("=== Physical plan with metrics ===")[1].split("\n\n")[0]
for line in sec.splitlines():
m=re.match(r"^(\s*)(\w+Exec)(.*)$",line)
if not m: continue
ind,name,rest=m.groups()
def g(k):
mm=re.search(k+r"=([^,\]]+)",rest); return mm.group(1) if mm else None
head=re.sub(r"file_groups=\{[^}]*\}","",rest)
head=re.sub(r", metrics=\[.*","",head)
head=re.sub(r"pruning_predicate=.*?required_guarantees=\[[^\]]*\]","",head)
extra=[]
for k in ["output_rows","elapsed_compute","build_time","join_time","build_input_rows","input_rows","selectivity","pushdown_rows_pruned","pushdown_rows_matched","row_groups_pruned_statistics","skipped_aggregation_rows","time_calculating_group_ids","probe_hit_rate","avg_fanout"]:
v=g(k)
if v: extra.append(f"{k}={v}")
print(f"{ind}{name}{head[:int(sys.argv[2]) if len(sys.argv)>2 else 200]}\n{ind} [{' '.join(extra)}]")
6 changes: 6 additions & 0 deletions benchmarks/polars-gap/scripts/run_df.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/bin/bash
# usage: run_df.sh BIN TAG [QUERY] [extra dfbench args...] -> ~/pg/results/TAG.json
BIN=$1; TAG=$2; Q=$3; shift 3
mkdir -p ~/pg/results
cd ~/git/apache/datafusion-polars-gap; QA=""; [ -n "$Q" ] && [ "$Q" != all ] && QA="--query $Q"
flock ~/pg/bench.lock $BIN tpch --iterations ${ITERS:-3} --path /mnt/bigdata/tpcgen4/tpch/sf${SF:-100} --format parquet --scale-factor ${SF:-100} $QA -o ~/pg/results/$TAG.json "$@" 2>&1 | grep -E "Query .* (avg|iteration)|failed|rror"
35 changes: 35 additions & 0 deletions benchmarks/polars-gap/scripts/summarize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import json,sys,glob,os
# usage: summarize.py tag1 tag2 ... (DF json in ~/pg/results, polars jsonl tags start with polars:)
def load_df(tag):
d=json.load(open(os.path.expanduser(f"~/pg/results/{tag}.json")))
out={}
for q in d["queries"]:
n=int(q["query"].split()[-1]); its=[i["elapsed"] for i in q["iterations"]]
if its: out[n]=min(its)
return out
def load_polars(tag):
out={}
for f in glob.glob(os.path.expanduser(f"~/git/polars-2.0-benchmark/results/{tag}/*.json")):
r=json.load(open(f))
if r.get("status")!="ok": continue
n=int(r["query"].lstrip("q")); out[n]=min(out.get(n,1e18),r["wall_time_s"]*1000)
return out
def load_qe2(pat):
out={}
for f in glob.glob(os.path.expanduser(pat)):
for line in open(f):
p=line.split()
if len(p)>3 and p[0].startswith("q") and p[1]=="ok":
n=int(p[0][1:]); out[n]=min(out.get(n,1e18),float(p[2]))
return out
cols=[]
for a in sys.argv[1:]:
name,_,src=a.partition("=")
cols.append((name, load_polars(src[2:]) if src.startswith("p:") else load_qe2(src[2:]) if src.startswith("q:") else load_df(src or name)))
print("query "+" ".join(f"{n:>12}" for n,_ in cols))
tot=[0]*len(cols)
for q in range(1,23):
vals=[c.get(q) for _,c in cols]
print(f"q{q:<4} "+" ".join(f"{v:12.0f}" if v else f"{'-':>12}" for v in vals))
for i,v in enumerate(vals): tot[i]+= v or 0
print("total "+" ".join(f"{v:12.0f}" for v in tot))
15 changes: 15 additions & 0 deletions benchmarks/polars-gap/scripts/sync.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash
# usage: sync.sh NAME
# Applies this worktree's diff against BASE to a checkout on HOST, builds
# dfbench (release-nonlto) there and copies it to ~/pg/bin/NAME.
set -e
HOST=${HOST:?set HOST to the benchmark machine}
BASE=${BASE:-05b6de3e4}
REMOTE_REPO=${REMOTE_REPO:-'~/git/apache/datafusion-polars-gap'}
cd "$(git rev-parse --show-toplevel)"
DIFF=$(mktemp)
git add -N . >/dev/null 2>&1 || true
git diff "$BASE" > "$DIFF"
scp -q "$DIFF" "$HOST":pg/pg.diff
rm -f "$DIFF"
ssh "$HOST" "cd $REMOTE_REPO && git reset -q --hard $BASE && git clean -fdq datafusion benchmarks && (test ! -s ~/pg/pg.diff || git apply ~/pg/pg.diff) && export PATH=\$HOME/.cargo/bin:\$PATH && cargo build --profile release-nonlto --bin dfbench -p datafusion-benchmarks 2>&1 | grep -E '^(error|warning)' -A5; cp target/release-nonlto/dfbench ~/pg/bin/$1 && echo built $1"
13 changes: 13 additions & 0 deletions benchmarks/polars-gap/scripts/top.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import collections,sys
# usage: top.py folded [N] [filter-substring-for-inclusive]
self_=collections.Counter(); incl=collections.Counter(); tot=0
for line in open(sys.argv[1]):
st,_,c=line.rstrip().rpartition(" "); c=int(c); tot+=c
fr=st.split(";"); self_[fr[-1]]+=c
for f in set(fr): incl[f]+=c
N=int(sys.argv[2]) if len(sys.argv)>2 else 25
print("--- self"); [print(f"{100*c/tot:5.1f}% {f[:170]}") for f,c in self_.most_common(N)]
if len(sys.argv)>3:
print("--- inclusive matching", sys.argv[3])
for f,c in incl.most_common(4000):
if sys.argv[3] in f: print(f"{100*c/tot:5.1f}% {f[:170]}")
30 changes: 29 additions & 1 deletion benchmarks/src/tpch/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,33 @@ impl RunOpt {

for query_id in query_range {
benchmark_run.start_new_case(&format!("Query {query_id}"));
let guard = std::env::var("DF_PPROF").ok().map(|dir| {
let g = pprof::ProfilerGuardBuilder::default()
.frequency(499)
.blocklist(&["libc", "libgcc", "pthread", "vdso"])
.build()
.unwrap();
(dir, g)
});
let query_run = self.benchmark_query(query_id, scale_factor, &ctx).await;
if let Some((dir, g)) = guard
&& let Ok(report) = g.report().build()
{
let f = std::fs::File::create(format!("{dir}/q{query_id}.svg")).unwrap();
report.flamegraph(f).unwrap();
use std::io::Write;
let mut folded =
std::fs::File::create(format!("{dir}/q{query_id}.folded")).unwrap();
for (frames, count) in report.data.iter() {
let names: Vec<String> = frames
.frames
.iter()
.rev()
.map(|f| f.first().map(|s| s.name()).unwrap_or_default())
.collect();
writeln!(folded, "{} {count}", names.join(";")).unwrap();
}
}
match query_run {
Ok(query_results) => {
for iter in query_results {
Expand Down Expand Up @@ -219,7 +245,9 @@ impl RunOpt {
if debug {
println!(
"=== Physical plan ===\n{}\n",
displayable(physical_plan.as_ref()).indent(true)
displayable(physical_plan.as_ref())
.set_show_statistics(std::env::var("DF_SHOW_STATS").is_ok())
.indent(true)
);
}
let result = collect(physical_plan.clone(), state.task_ctx()).await?;
Expand Down
6 changes: 3 additions & 3 deletions datafusion/common/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::parquet_config::{
DFTimeUnit, RowGroupRangeAssignment,
};
use crate::parsers::{CompressionTypeVariant, CsvQuoteStyle};
use crate::utils::get_available_parallelism;
use crate::utils::{get_available_parallelism, get_physical_parallelism};
use crate::{DataFusionError, Result};
#[cfg(feature = "parquet_encryption")]
use hex;
Expand Down Expand Up @@ -889,7 +889,7 @@ config_namespace! {
/// concurrency.
///
/// Defaults to the number of CPU cores on the system
pub target_partitions: usize, transform = ExecutionOptions::normalized_parallelism, default = get_available_parallelism()
pub target_partitions: usize, transform = ExecutionOptions::normalized_parallelism, default = get_physical_parallelism()

/// The default time zone
///
Expand Down Expand Up @@ -1309,7 +1309,7 @@ config_namespace! {

/// (reading) If true, filter expressions are be applied during the parquet decoding operation to
/// reduce the number of rows decoded. This optimization is sometimes called "late materialization".
pub pushdown_filters: bool, default = false
pub pushdown_filters: bool, default = true

/// (reading) If true, filter expressions evaluated during the parquet decoding operation
/// will be reordered heuristically to minimize the cost of evaluation. If false,
Expand Down
38 changes: 38 additions & 0 deletions datafusion/common/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,44 @@ pub fn get_available_parallelism() -> usize {
*PARALLELISM
}

/// Returns [`get_available_parallelism`] divided by the number of hardware
/// threads per physical core, when that is known (Linux with SMT active).
///
/// Running more partitions than physical cores makes the sibling hardware
/// threads share one core's caches, which slows down cache-sensitive
/// operators such as hash aggregation and hash joins.
pub fn get_physical_parallelism() -> usize {
static PARALLELISM: LazyLock<usize> = LazyLock::new(|| {
let logical = get_available_parallelism();
if std::env::var("DF_PHYSICAL_PARTITIONS").is_ok_and(|v| v == "0") {
return logical;
}
(logical / threads_per_core().unwrap_or(1)).max(1)
});
*PARALLELISM
}

fn threads_per_core() -> Option<usize> {
let smt = std::fs::read_to_string("/sys/devices/system/cpu/smt/active").ok()?;
if smt.trim() != "1" {
return None;
}
let siblings = std::fs::read_to_string(
"/sys/devices/system/cpu/cpu0/topology/thread_siblings_list",
)
.ok()?;
let mut count = 0;
for part in siblings.trim().split(',') {
count += match part.split_once('-') {
Some((start, end)) => {
end.parse::<usize>().ok()? - start.parse::<usize>().ok()? + 1
}
None => 1,
};
}
(count > 0).then_some(count)
}

/// Converts a collection of function arguments into a fixed-size array of length N
/// producing a reasonable error message in case of unexpected number of arguments.
///
Expand Down
6 changes: 6 additions & 0 deletions datafusion/datasource-parquet/src/opener/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,8 @@ pub(super) struct ParquetMorselizer {
/// Should the filters be evaluated during the parquet scan using
/// [`DatafusionArrowPredicate`](crate::row_filter::DatafusionArrowPredicate)?
pub pushdown_filters: bool,
/// Should conjuncts without a dynamic filter become row filters?
pub push_static_filters: bool,
/// Should the filters be reordered to optimize the scan?
pub reorder_filters: bool,
/// Should we force the reader to use RowSelections for filtering
Expand Down Expand Up @@ -457,6 +459,7 @@ struct PreparedParquetOpen {
virtual_state: Option<Arc<VirtualColumnsState>>,
reorder_predicates: bool,
pushdown_filters: bool,
push_static_filters: bool,
force_filter_selections: bool,
enable_page_index: bool,
enable_bloom_filter: bool,
Expand Down Expand Up @@ -569,6 +572,7 @@ impl DecoderReadPlans {
prepared.reorder_predicates,
prepared.file_metrics.clone(),
prepared.max_predicate_cache_size,
prepared.push_static_filters,
)
});
Ok(Self {
Expand Down Expand Up @@ -985,6 +989,7 @@ impl ParquetMorselizer {
virtual_state: self.virtual_state.as_ref().map(Arc::clone),
reorder_predicates: self.reorder_filters,
pushdown_filters: self.pushdown_filters,
push_static_filters: self.push_static_filters,
force_filter_selections: self.force_filter_selections,
enable_page_index: self.enable_page_index,
enable_bloom_filter: self.enable_bloom_filter,
Expand Down Expand Up @@ -2693,6 +2698,7 @@ mod test {
}),
schema_provider: None,
pushdown_filters: self.pushdown_filters,
push_static_filters: true,
reorder_filters: self.reorder_filters,
force_filter_selections: self.force_filter_selections,
enable_page_index: self.enable_page_index,
Expand Down
2 changes: 2 additions & 0 deletions datafusion/datasource-parquet/src/push_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,11 +371,13 @@ impl RowFilterContext {
reorder_predicates: bool,
file_metrics: ParquetFileMetrics,
max_predicate_cache_size: Option<usize>,
push_static_filters: bool,
) -> Option<Self> {
match prebuild_row_filter_candidates(
predicate,
physical_file_schema,
file_metadata.as_ref(),
push_static_filters,
) {
Ok(Some(prebuilt)) => Some(Self {
prebuilt: PrebuiltRowFilterCandidateList::new(prebuilt),
Expand Down
Loading
Loading