Skip to content

WIP: MDEV-40439 Evaluate cheap subconditions before expensive ones in WHER… - #6066

Open
Olernov wants to merge 1 commit into
mainfrom
13.2-MDEV-40439-rearr-cond
Open

Olernov wants to merge 1 commit into
mainfrom
13.2-MDEV-40439-rearr-cond

Conversation

@Olernov

@Olernov Olernov commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

…E and ON conditions

The arguments of AND and OR are evaluated left to right with short-circuiting, in the order written in the query. An expensive subcondition written first is therefore evaluated even for rows that a cheap one would reject (AND) or accept (OR).

Reorder the arguments of each AND/OR so that the expensive ones come after the cheap ones, keeping the relative order within each group. The walk goes down into nested AND/OR and into trigger conditions. A subcondition is expensive if it contains a subquery, a stored function call, or an item that marks itself as expensive through is_expensive_processor() (a UDF, MATCH()).

The reordering is applied to:

  • the conditions attached to tables (select_cond, select->cond, on_precond), at the end of make_join_select() and before the attached_conditions_summary trace, so the trace shows the final order;
  • BNL/BNLH scan filters, in make_scan_filter(). They are built from the original WHERE/ON, and check_join_cache_usage() may build them after make_join_select();
  • outer_ref_cond and pseudo_bits_cond, the conditions a subquery checks once per execution before running its join. The steps that later build new conditions from these (index condition pushdown, removal of duplicate BNL conditions) take subsets and keep the order.

Not covered yet: HAVING, exec_const_cond, terms added after make_join_select() (the index condition remainder rejected by an engine, HAVING moved to a table's condition), and SLEEP()/GET_LOCK(), which do not mark themselves as expensive through
is_expensive_processor().

@Olernov
Olernov requested a review from spetrunia November 3, 2026 10:27
@spetrunia

Copy link
Copy Markdown
Member

Fails for embedded server builds: https://buildbot.mariadb.org/#/builders/719/builds/20922/steps/6/logs/stdio

@spetrunia

Copy link
Copy Markdown
Member
    thd->change_item_tree(write_iter.ref(), expensive[i]);

Do we really need this?

As far as I know, AND/OR items at top level are transient.
They either are created during this optimization phase, or they are [parts of] the original WHERE/ ON which has been saved like this:

    sel->prep_where= conds ? conds->copy_andor_structure(thd) : 0;

and will be restored for the next execution.

@Olernov
Olernov force-pushed the 13.2-MDEV-40439-rearr-cond branch from 2f17175 to 0c1b771 Compare November 3, 2026 14:13
@Olernov

Olernov commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@spetrunia , agree on the unnecessary change_item_tree, direct rewrite is enough. Force-pushed and fixed cond_reorder.test failures too.

@spetrunia

spetrunia commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Note to self: Item_func_is_not_null_test is not affected.
It is used like this:

    (l1, l2, l3) IN (SELECT v1, v2, v3 ... HAVING having)
    =>
    EXISTS (SELECT ... HAVING having and
                              (l1 = v1 or is null v1) and
                              (l2 = v2 or is null v2) and
                              (l3 = v3 or is null v3) and
                              is_not_null_test(v1) and
                              is_not_null_test(v2) and
                              is_not_null_test(v3))

The item is put into HAVING, which is not processed.

If it was processed, would that be harmful? Suppose a part of having is moved to be after the is_not_null_test ...
The is_not_null test could record that a NULL was present in the output, even if having condition would have filtered it out... Looks like a possibility of a wrong query result?

EDIT: there is also Item_ref_null_helper which is similar: seems dangerous to move it, but AFAIU current patch won't do that.

@spetrunia spetrunia left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Consider also this:

create table t1 ( a int , b int);
insert into t1 select seq, seq from seq_1_to_10;
create table t2 ( a int , b int);
insert into t2 select seq, seq from seq_1_to_100;
explain format=json 
select * from t1 
where t1.a >= (select max(t2.a) from t2 where t2.b=t1.b) and rand()<0.5;

with the patch this gives:

          "attached_condition": "rand() < 0.5 and t1.a >= (subquery#2)"

That is, the "coin toss" or "rand<0.5" is done before checking the subquery.

At first glance, this reordering looks like it might affect some users in a way that's not desirable. What do you think?

Comment thread sql/sql_select.cc Outdated
is_expensive_processor() (a UDF, MATCH() and so on).
*/

static bool is_expensive_cond(Item *cond)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We need another name for this function to avoid confusion.
First proposal to get the ball rolling: is_cond_to_be_checked_last()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I decided to inline it, so there is no confusion with the name any more.

Comment thread sql/sql_select.cc Outdated
{
Item_func::Functype sp_func= Item_func::FUNC_SP;
return cond->with_subquery() ||
cond->walk(&Item::is_expensive_processor, NULL, 0) ||

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should this be

cond->walk(&Item::is_expensive_processor, NULL, 0) 

or just

cond->is_expensive()

?
They seem to have some overlapping meaning. Are there any known reasons to prefer one over the other?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agree, cond->is_expensive() covers almost everything besides some corner cases that can be probably ignored.

Comment thread sql/sql_select.cc Outdated
Item_func::Functype sp_func= Item_func::FUNC_SP;
return cond->with_subquery() ||
cond->walk(&Item::is_expensive_processor, NULL, 0) ||
cond->walk(&Item::find_function_processor, &sp_func, 0);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm wondering if we should check for Item_func_get_user_var and Item_func_set_user_var also ...

@Olernov
Olernov force-pushed the 13.2-MDEV-40439-rearr-cond branch 2 times, most recently from f6ee5df to f008d56 Compare November 6, 2026 17:50
@Olernov

Olernov commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@spetrunia, I addressed your concern about RAND(): an AND/OR that has a non-deterministic argument (one with RAND_TABLE_BIT) is not reordered to prevent unwanted change of behavior. But its arguments (nested AND/OR) are still processed.

RAND_TABLE_BIT covers RAND(), UUID_SHORT(), SLEEP(), GET_LOCK(), reads of a user variable, subqueries containing RAND(), NOT DETERMINISTIC stored functions and UDFs. Stored functions are NOT DETERMINISTIC by default, so unless they are declared DETERMINISTIC, they are not reordered.

A read of a variable that the statement also assigns has RAND_TABLE_BIT (Item_func_get_user_var::used_tables() returns it unless const_item() is set). So @cnt:= @cnt + 1 makes its AND/OR keep its order. Not covered: an assignment of a constant, like @x:= 5, which reads nothing and has no RAND_TABLE_BIT.

I also mentioned in the commit message that processing HAVING will need care with Item_is_not_null_test and Item_ref_null_helper.

@mariadb-RexJohnston

Copy link
Copy Markdown
Member

f008d56 (Evaluate cheap subconditions before expensive ones) causes a plan regression. A query that used index_merge for every outer row before the commit now does a full scan of the inner table for every outer row. The cause: move_expensive_args_last() changes which imerge the range optimizer keeps when range-checked-for-each-record re-analyses the reordered select->cond.

Reproducer

The only plan change is in the last row: with the parent build it is 4 rows read (index_merge), with f008d56 it is 4006 (full scan).

--source include/have_sequence.inc
CREATE TABLE t_one (k INT);
INSERT INTO t_one VALUES (7);
CREATE TABLE t1 (x INT);
INSERT INTO t1 VALUES (5),(6);
CREATE TABLE t2 (a INT, b INT, c INT, d INT, e INT DEFAULT 0,
                 filler CHAR(200) DEFAULT 'x',
                 KEY(a), KEY(b), KEY(c), KEY(d), KEY(e));
INSERT INTO t2 (a,b,c,d)
  SELECT seq, seq, IF(seq <= 10, 100, 0), seq FROM seq_1_to_2000;
ANALYZE TABLE t1, t2, t_one PERSISTENT FOR ALL;
SET join_cache_level=0;

FLUSH STATUS;
SELECT STRAIGHT_JOIN COUNT(*) FROM t1, t2
WHERE (((t2.a = (SELECT MAX(k) FROM t_one) OR t2.b = 2)
AND (t2.c < 10 OR t2.d = 1)) OR t2.c > t1.x)
AND t2.e <= t1.x;
SHOW STATUS LIKE 'Handler_read_rnd_next';

EXPLAIN shows range-checked-for-each-record on t2 in both builds. t2.e <= t1.x is only there to put a key that depends on t1 alone into tab->keys, which range-checked-for-each-record needs.

Query Parent f03e902 f008d56
Literal a = 7, written order (a=7 OR b=2) AND (c<10 OR d=1) 3 3
Same literal, (c<10 OR d=1) written first 4005 4005
a = (subquery) OR b = 2 OR c > t1.x, no inner AND 4 4
The query above, subquery conjunct written first 4 4006

Numbers are Handler_read_rnd_next. Rows 1 and 2 show that index merge already depended on conjunct order before the commit. Row 3 shows that a = (subquery) gives a range inside range-checked-for-each-record. Row 4 is the regression: the commit makes the same swap as row 2.

Why it happens

When an AND of ORs is itself ORed with something else, the range optimizer keeps only the first imerge. The reorder changes which imerge is first.

  1. Item_cond_and::get_mm_tree builds one imerge per OR-conjunct, in conjunct order, and tree_and concatenates them with imerge_list_and_list.

  2. When that tree is ORed with c > t1.x, tree_or takes only merges.head(), and so does imerge_list_or_list (sql/opt_range.cc). opt_range.h documents this: "the choice of read plan may depend on the order of conjuncts/disjuncts in WHERE".

  3. In written order the head is (a = subq OR b = 2). ORed with c > x it gives a selective union over a, b and c, which is chosen.

  4. After move_expensive_args_last() the head is the cheap (c < 10 OR d = 1). ORing c < 10 with c > 5 merges into the range (NULL) < (c), which covers all 2000 rows (seen in the optimizer trace). The c+d union then loses to a table scan on cost.

Only range analysis that runs after make_join_select() sees the reordered condition:

  • range-checked-for-each-record, through test_if_quick_select(), every time the outer row changes;

  • test_if_skip_sort_order(), which reads select->cond or pre_idx_push_select_cond. Both are reordered, because index condition pushdown keeps the order.

The range analysis at optimize time runs on join->conds, which the reorder never touches, because make_cond_for_table copies AND/OR nodes. So EXPLAIN describes a plan chosen from the written order, while execution re-plans from the reordered one. The commit message says that later steps "take subsets and keep the order". That is true for index condition pushdown, but these range re-analyses read the reordered order, and for them the order matters.

Suggested fix

I suggest keeping an original-order copy of the condition for range re-analysis, the same way pre_idx_push_select_cond is kept, and evaluating rows with the reordered one.

  • Original-order copy for range-checked-for-each-record and test_if_skip_sort_order(): the smallest change, and the range optimizer is not touched.

  • Do not reorder an AND that has two or more OR arguments able to produce imerges: crude, and gives up the speedup exactly in those cases.

  • Remove the head-only limit in imerge_list_or_list() and tree_or(): fixes the underlying order dependence, but is a much larger change.

Whichever way you go, the query above could be added to cond_reorder.test, checking Handler_read_rnd_next, as the regression test.

@mariadb-RexJohnston

Copy link
Copy Markdown
Member

Also: cached constant subqueries count as expensive. (subq) still reports with_subquery(), so it gets moved to the end, as in derived_cond_pushdown.result:10553 and the trigcond(... or t4.d is null) cases in subselect4.result. After the first evaluation it's effectively a constant, so in an OR it would short-circuit cheaply if left first. This isn't harmful, but checking const_item() first would be more accurate.

The outer_ref_cond call ignores errors on the spot. The call at the add_cond_and_fix(... outer_ref_cond) site doesn't check thd->is_error() itself.

@spetrunia

Copy link
Copy Markdown
Member

Original-order copy for range-checked-for-each-record and test_if_skip_sort_order(): the smallest change, and the range optimizer is not touched.

@mariadb-RexJohnston , thanks for the input.

How to handle index_merge differences... In my opinion, we should either
A. Keep and use the original-order copy (as quoted above).
B. Do nothing

Rationale for B: the order of conditions in the WHERE is essentially random, there is no accepted practice that one should "write conditions that index merge should use first" (Note that one may argue that in some databases the "shape" of the WHERE, (a OR b) AND (c OR d) dictates the way it would be computed. But a AND b and b AND a are normally the same thing.
If one wants to force use of a certain variant of index_merge, they do so with hints.

Rationale for A: In some cases, MariaDB optimizer runs the range analyzer multiple times and we expect to get the same output every time... This has shown to have exceptions in edge cases, but should we add to the list..

@spetrunia

Copy link
Copy Markdown
Member

constant subqueries can still be expensive to compute...

@Olernov

Olernov commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

It's an interesting case with RCFER (range checked for every record). If I manually rewrite the query and disable move_expensive_args_last:

SELECT STRAIGHT_JOIN COUNT(*) FROM t1, t2
WHERE (((t2.c < 10 OR t2.d = 1) AND (t2.a = (SELECT MAX(k) FROM t_one) OR t2.b = 2))
       OR t2.c > t1.x)
  AND t2.e <= t1.x;

I get Handler_read_rnd_next = 4006 (same as for the regression). So, we already don't guarantee the best imerge combination, that makes me incline to option B which will allow to keep things simple.

Regarding the point about constant subqueries, I agree with @spetrunia that even a single computation may be expensive, and moving them to the tail may avoid that. And the short-circuited evaluation (getting the cached value) should be comparable to a simple condition check in terms of execution time.
Another point to consider: if we don't move constant subqueries, won't it automatically solve the RCFER issue above?

And regarding the missing error check - I agree, worth adding.

@Olernov
Olernov force-pushed the 13.2-MDEV-40439-rearr-cond branch from f008d56 to 5cb80af Compare November 24, 2026 16:12
@spetrunia

Copy link
Copy Markdown
Member

Is this optimization used for single-table UPDATE/DELETEs ? I didn't check but looking at the code I suppose not. Should we enable it there too?

Comment thread sql/sql_select.cc Outdated
if (move_expensive_args_last(thd, item))
{
if (!expensive &&
!(expensive= thd->alloc<Item *>(args->elements)))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

To show that the storage is temporary, please switch to using my_alloca/ my_afree.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Turns out to be not that trivial. Plain my_alloca doesn't have a size limit, so a generated query with 50K subconditions can allocate 50K * (pointer size 8 bytes) = 400K while the default stack size is 292K per thread.
The other option is my_safe_alloca which falls back to my_malloc for large allocations. However, for multiple recursions we are still not guaranteed from stack overflow, so check_stack_overrun guard would be needed. And a my_safe_afree call will be needed.

@spetrunia

Copy link
Copy Markdown
Member

Let's try to not put more things into sql_select.cc, please move the new function move_expensive_args_last() into sql/opt_plan_refinement.cc

@spetrunia

Copy link
Copy Markdown
Member

We can have this done unconditionally in the main branch.
We should put this under a @@new_mode switch in 11.8+.
(The reason for choosing 11.8 is that the customer will need this there)

…E and ON conditions

The arguments of AND and OR are evaluated left to right with
short-circuiting, in the order written in the query. An expensive
subcondition written first is therefore evaluated even for rows that
a cheap one would reject (AND) or accept (OR).

Reorder the arguments of each AND/OR so that the expensive ones come
after the cheap ones, keeping the relative order within each group.
The walk goes down into nested AND/OR and into trigger conditions.
A subcondition is expensive if it contains a subquery, a stored
function call, or an item that marks itself as expensive through
is_expensive_processor() (a UDF, MATCH()).

An AND/OR that has a non-deterministic argument (one with RAND_TABLE_BIT)
keeps its order, to prevent unwanted change of behavior. Nested lists
are still reordered.

The reordering is applied to:
- the conditions attached to tables (select_cond, select->cond,
  on_precond), at the end of make_join_select() and before the
  attached_conditions_summary trace, so the trace shows the final
  order;
- BNL/BNLH scan filters, in make_scan_filter(). They are built from
  the original WHERE/ON, and check_join_cache_usage() may build them
  after make_join_select();
- outer_ref_cond and pseudo_bits_cond, the conditions a subquery
  checks once per execution before running its join.
The steps that later build new conditions from these (index condition
pushdown, removal of duplicate BNL conditions) take subsets and keep
the order.

Not covered yet: HAVING, exec_const_cond, terms added after
make_join_select() (the index condition remainder rejected by an
engine, HAVING moved to a table's condition). Reordering HAVING would
need care with Item_is_not_null_test and Item_ref_null_helper, which
record NULLs for IN->EXISTS.
@Olernov
Olernov force-pushed the 13.2-MDEV-40439-rearr-cond branch from 5cb80af to ae81dcc Compare November 25, 2026 16:19
@Olernov Olernov changed the title MDEV-40439 Evaluate cheap subconditions before expensive ones in WHER… WIP: MDEV-40439 Evaluate cheap subconditions before expensive ones in WHER… Nov 26, 2026
@Olernov

Olernov commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

It was decided to implement the feature in 11.8 with protection by @new_mode flag (see #6241). I am keeping this PR open as it might be useful when merging the patch from 11.8 upstream, when the @new_mode protection will be removed, and existing tests will start failing.
Here the feature is not protected, so failing tests are already re-recorded.

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

Development

Successfully merging this pull request may close these issues.

4 participants