Skip to content

fix: keep volatile predicates in place when simplifying filters - #27742

Open
vishalkotak wants to merge 2 commits into
apache:mainfrom
vishalkotak:fix-volatile-predicate-order
Open

vishalkotak wants to merge 2 commits into
apache:mainfrom
vishalkotak:fix-volatile-predicate-order

Conversation

@vishalkotak

@vishalkotak vishalkotak commented Nov 25, 2026 •

Copy link
Copy Markdown

Which issue does this PR close?

Rationale for this change

Adding a redundant comparison to a filter could change how often a volatile function like random() runs. When the optimizer merged the comparisons, it moved the volatile call to the front, so it ran on every row instead of only the rows the earlier comparisons kept.

What changes are included in this PR?

Merged comparisons now stay where the first of them was written, and every other predicate keeps its place. A merged comparison is at least
as strict as the ones it replaces, so nothing after it sees more rows than before.

What is the testing strategy for this PR?

Added the example from the issue, which counts how often the volatile function runs, and plan tests for the other cases the issue lists. Two existing plan tests change order: predicates now follow the query instead of being grouped by column.

Are there any user-facing changes?

No.

Removing a redundant comparison could move a volatile call like random()
in front of the comparisons written before it, so it ran on more rows.
Simplified comparisons now stay where the first one was written, and
everything else keeps its place.

Closes apache#27683
@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Nov 25, 2026
@mbutrovich
mbutrovich self-requested a review November 25, 2026 19:45

@mbutrovich mbutrovich left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @vishalkotak for picking this up. The new tests fail on main and pass with this change.

The fork's "verify benchmark results" job fails on TPC-H Q16 (run). Its expected plan in q16.slt.part and line 69 still starts with p_size IN (...), but the plan now starts with p_brand != Brand#45, which is where the query writes it. The old order came from p_brand being moved behind the other conjuncts and reorder_predicates then putting the cheap IN first. Could you regenerate the TPC-H plans? The sqllogictest README describes how to generate the data and run them with INCLUDE_TPCH=true.

Comment on lines +256 to +272
/// A predicate kept as is, or the place of a column's simplified predicates.
enum Slot {
Other(Expr),
Column(Column),
}

fn push_column_predicate(
column_predicates: &mut BTreeMap<Column, Vec<Expr>>,
slots: &mut Vec<Slot>,
col: Column,
predicate: Expr,
) {
if !column_predicates.contains_key(&col) {
slots.push(Slot::Column(col.clone()));
}
column_predicates.entry(col).or_default().push(predicate);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we do this without Slot? If the first pass keeps the predicates in a Vec<Vec<Expr>> in output order, with a BTreeMap<Column, usize> from each column to its group, every predicate is already in its final place. The second pass then only simplifies the column groups in place and flattens. The expect on line 240 goes away too, because there's no second map to keep in sync with the slots:

    let mut groups: Vec<Vec<Expr>> = Vec::with_capacity(predicates.len());
    let mut column_groups: BTreeMap<Column, usize> = BTreeMap::new();

    // the loop is unchanged, except `slots.push(Slot::Other(pred))` becomes
    // `groups.push(vec![pred])` and the helper takes `&mut column_groups, &mut groups`

    for i in column_groups.into_values() {
        let preds = std::mem::take(&mut groups[i]);
        let simplified = match simplify_column_predicates(preds.clone()) {
            Ok(simplified) => simplified,
            Err(_) => preds,
        };
        if simplified.iter().any(is_false) {
            return Ok(always_false());
        }
        groups[i] = simplified;
    }

    Ok(groups.into_iter().flatten().collect())
}

fn push_column_predicate(
    column_groups: &mut BTreeMap<Column, usize>,
    groups: &mut Vec<Vec<Expr>>,
    col: Column,
    predicate: Expr,
) {
    let i = *column_groups.entry(col).or_insert_with(|| {
        groups.push(vec![]);
        groups.len() - 1
    });
    groups[i].push(predicate);
}

The cost is one single-element Vec per conjunct that isn't a column comparison, once per filter at plan time.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, will spend time on this now. Appreciate the feedback.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, that's simpler. Thank you.

@vishalkotak

Copy link
Copy Markdown
Author

Thank you for the review. I regenerated the TPC-H plans. Only Q16 changed, and its filter now follows the order the query is written in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PushDownFilter moves volatile conjuncts ahead of the comparisons it simplifies

2 participants