Include residual predicates in join estimates
Describe the bug
The join estimator receives equality keys but no residual filter expression. With exact scan counts, adding a cross-table inequality roughly halves actual output without changing the estimate.
To Reproduce
From the repository root, with the CLI fix from PR #25570 applied:
cargo build --profile ci --locked -p datafusion-benchmarks --bin dfbench
cargo install tpchgen-cli --version 1.1.1 --locked # if not already installed
repro_dir=$(mktemp -d)
tpchgen-cli --scale-factor 1 --format parquet \
--parquet-compression 'ZSTD(1)' --parts 1 --output-dir "$repro_dir/data"
cat > "$repro_dir/repro.sql" <<'SQL'
SET datafusion.execution.target_partitions = 1;
SET datafusion.optimizer.enable_dynamic_filter_pushdown = false;
SELECT l_orderkey FROM lineitem JOIN part ON l_partkey = p_partkey;
SELECT l_orderkey FROM lineitem JOIN part ON l_partkey = p_partkey AND l_quantity < p_size;
SQL
target/ci/dfbench statistics \
--path "$repro_dir/data" --query_path "$repro_dir/repro.sql"
Observed with tpchgen-cli 1.1.1 at
6c320561b5.
Inspect the SELECT reports; ignore the empty SET reports.
| SELECT | HashJoinExec node | Estimated rows | Actual rows |
|---|---|---|---|
| Equality only | 0 |
6,001,215 | 6,001,215 |
Add l_quantity < p_size |
0 |
6,001,215 | 2,932,286 |
Expected behavior
Estimate residual predicates from mapped input statistics. Treat inner join pair counts and semi/anti matching probabilities separately.
Additional context
The first join estimate is accurate, so the second query isolates new error rather than inherited filter or NDV error.
Part of #25610.
I’ll investigate the join cardinality estimation path and propose an approach for accounting for residual predicates.
take
Investigation update: I reproduced the issue exactly.
- Equality-only join:
- Estimated rows:
6,001,215 - Actual rows:
6,001,215
- Estimated rows:
- Join with
l_quantity < p_size:- Estimated rows:
6,001,215 - Actual rows:
2,932,286 - Q-error:
2.05x
- Estimated rows:
I traced the missing statistics edge to HashJoinExec::statistics_from_inputs. HashJoinExec owns self.filter, but the call to estimate_join_statistics does not pass it.
I also tested the existing FilterExec interval analyzer with two columns whose ranges are both [1, 50].
- Predicate:
column_0 < column_1 - Expression supported: yes
- Refined ranges:
column_0:[1, 49]column_1:[2, 50]
- Selectivity returned:
0.9604 - Estimated rows from
10,000:9,604
The interval analyzer multiplies the two marginal range reductions:
(49 / 50) × (49 / 50) = 0.9604
For independent uniform discrete values, however, the pair probability is:
P(column_0 < column_1) = 1,225 / 2,500 = 0.49
Applying the current interval estimate to the reproduced join would produce approximately 5,763,567 estimated rows, which would barely improve the current error. Applying 0.49 would produce approximately 2,940,596 rows, close to the actual 2,932,286.
Therefore, directly reusing the current interval-product selectivity would recognize the expression but would not adequately fix the reported estimation error.
My proposed first scope is:
- Pass the optional
JoinFilterinto join statistics estimation. - Map
JoinFilter::column_indicesinto compact column statistics. - Recognize direct numeric column-to-column comparisons such as
<,<=,>, and>=. - Estimate their pair-survival probability using a specialized uniform-range model.
- Apply the resulting selectivity to equality candidate pairs for inner joins.
- Mark the resulting row estimate as inexact.
- Preserve current estimates when:
- There is no residual filter.
- The expression is unsupported.
- Required statistics are missing.
- The join is outer, semi, anti, or mark.
I propose leaving outer and semi/anti residual estimation unchanged initially because pair selectivity is not sufficient for those joins.
- Outer joins must estimate whether every candidate for a preserved row fails the residual predicate.
- Semi/anti joins need the probability that at least one candidate survives.
- Both require a match-multiplicity or preserved-row probability model.
The reproduced comparison also involves different input types:
l_quantity:Decimal128(15, 2)p_size:Int32
The initial implementation would therefore need to handle compatible numeric coercion or the cast expression introduced during physical planning.
For supported inner joins, the intended flow would be:
- Estimate equality candidate pairs using the existing logic.
- Map the residual filter columns into the compact
JoinFilterschema. - Read and normalize the mapped min/max statistics.
- Estimate the residual comparison probability.
- Apply it with
Precision::with_estimated_selectivity. - Continue through the existing projection and fetch adjustments.
For unsupported expressions or insufficient statistics, the estimator would return no new selectivity and retain the previous join estimate rather than applying a hard-coded default.
Given the ongoing expression-level statistics work in #21122:
@asolimando, would you recommend implementing the column-comparison probability estimator within that expression-level framework, or keeping it join-local for an initial inner-join-only PR?
I would also appreciate guidance on whether preserving existing estimates for outer and semi/anti joins is an acceptable first scope.
Thanks @rgbuilds for the ping and for looking into this.
Quick meta point first: I understand the topic is complex and there is a lot to discuss, but the message was too long and I had to use an LLM to go through it in reasonable time, I’d appreciate if you did that summarization on your end next time (it's not that long but extremely dense, not a "good" summary).
Missing residual filter: estimate_join_statistics doesn’t take the residual filter, that’s a known limitation stated in the doc, I think we can improve it, especially since adding that param is not a breaking change.
On the estimator: I agree that multiplying the ranges from interval analyzer is not what we want, that only works for single-column predicates (like a < 10), we need a pair-probability estimator, and this will need to be called wherever we can reference predicates (WHERE, JOIN etc.). I’d put it in expr-common/src/interval_arithmetic.rs as a pure function, something like comparison_selectivity(op, left: &Interval, right: &Interval), with no join concepts in the signature: that's the piece that is the same no matter where it is called from, and PhysicalExpr will reference it from the comparison branch when the expression-level support comes.
But if you want to support the repro in this issue, you also need to handle the cast, which is exactly the “navigation” the expression-level framework would give you for free, if you wait for it. Again, you can put that in a pure function somewhere, but you see the pattern, we are creating a lot of ad-hoc pieces to compensate for a missing framework, that’s why I am OK adding some support now (comparison_selectivity in this case, as that will be re-used as-is), but supporting more complex cases needs a lot of special-casing that will later go away, for that it’s worth waiting for the expression-level framework.
Side note: what you propose with min/max is good, the expression-level support with extended statistics will allow even more precise estimations, if you have quantile sketches for the involved columns, for instance. (you can peek into the branch mentioned here to see how sketches and advanced custom stats could be used).
In summary, for a first PR I’d keep it simple with what we won’t need to remove later:
- the
comparison_selectivityhelper on intervals, - the filter parameter addition,
- column mapping to the filter’s intermediate schema stats,
- apply the selectivity for inner joins (column vs column only, no cast handling),
- fall back to the current estimate otherwise,
- inner-join only, the rest needs a more complex treatment that needs a separate PR
On the repro itself you’ll still hit the fallback because of the cast, that’s expected and it will only partially close this issue. Add a test on a cast-free column-vs-column join asserting the pair probability (0.49 on [1, 50] vs [1, 50]), and one on the repro documenting the gap, that one will improve once the expression-level estimator is in.
Does this make sense to you?
Thanks @asolimando — this makes sense. I’ll keep future updates shorter and focused on the decision needed.
I’ll scope the first PR to:
- add a pure
comparison_selectivity(op, left, right)helper inexpr-common, - pass the residual filter into join statistics estimation,
- map input statistics into the filter’s intermediate schema,
- support cast-free column-vs-column comparisons for inner joins,
- and preserve the current estimate for casts, unsupported predicates, missing statistics, and other join types.
@gabotechs, does this incremental scope align with your expectation for the issue, given that the original TPC-H reproduction will require later expression-level cast navigation?