Home - Waterfall Grid T-Grid Console Builders Recent Builds Buildslaves Changesources - JSON API - About

Console View


Categories: connectors experimental galera main
Legend:   Passed Failed Warnings Failed Again Running Exception Offline No data

connectors experimental galera main
Rex Johnston
MDEV-39492 PQ: a GROUP BY column the WHERE binds to a constant is a group column

TPC-DS Q66 ran three times slower with eight workers than without, and
the workers never ran. Each UNION branch groups by the warehouse
columns and d_year under d_year = 2000. The gate asked before the plan
(pwt_query_shape_allows_workers) admitted the branch, so the search
costed date_dim as a parallel driver and chose it, at cost 26 against
the serial plan's. The gate asked after the plan refused the same
branch: "a select list item reads a column outside an aggregate that
GROUP BY does not name". The plan then ran serially in the shape
chosen for the workers, date_dim first with the fact table looked up
per date, 1015 ms against 321.

The two gates disagreed because they read different group lists. The
first sees the GROUP BY as written, with d_year in it. By the time the
second asks, remove_const() has dropped d_year from join->group_list
and from the aggregation table's key as having one value everywhere,
and the select list's d_year is no longer named by either. The column
is a group column all the same: bound to a constant by the WHERE, it
has the one value in every group, which is what the check exists to
establish.

Pwt_group_checker now accepts a column that the join's multiple
equalities bind to a constant, looked up through the COND_EQUAL both
gates are given, whether or not the group list names it. The two gates
agree again, and the branch runs divided. A query cannot be refused on
this ground after the plan if it was admitted before it, which is the
property the pre-plan gate was introduced to provide: a parallel plan
the workers will not run must never be chosen.

main.parallel_query_why gains the shape: a GROUP BY column bound to a
constant, read by the select list, with no refusal and the driving
table divided.

This commit was prepared with Claude Code (Fable 5.1), which traced the
Q66 refusal to the trimmed group list, implemented the check through
the multiple equalities, wrote the test case and ran the parallel-query
tests in both protocols and the main suite.
Rex Johnston
MDEV-39492 PQ: choose the divided driving table as a plan, not by its scan alone

TPC-DS Q29 ran at twice its serial time with eight workers. Serially the
optimizer starts at date_dim d2, whose WHERE keeps 122 of 73049 rows,
and reaches store_returns through the returned-date index: 16700
lookups into store_sales. With workers it started at store_returns
instead, divided its 287514 rows eight ways, and applied the d2 filter
only after the store_sales lookup, so each worker did 36000 of those
lookups. Dividing d2 and keeping the serial order under it costs 24
against the chosen plan's 58 and the serial plan's 61, and the search
never saw it.

best_access_path() priced the driving table's scan both ways and kept
the cheaper reading on the spot. For d2 the parallel reading is the
dearer: one eighth of a 12.5 scan plus 2 ms of setup for each of eight
tables comes to 17.6, so the serial reading was kept and the plan with
d2 divided was never extended. What that comparison leaves out is the
join under the driving table, which the division cuts eight ways too
and which is where the cost is. The scan of a table like d2 can never
repay the setup on its own; the join under it repays it many times
over.

The search now offers the driving position every candidate twice. After
get_costs_for_tables() has costed each table with its scan read
serially, add_parallel_driver_candidates() costs it again with
JOIN::parallel_driver_costing set, under which best_access_path()
prices a full or range scan as one worker's share plus the setup
(parallel_scan_cost() no longer judges the reading), and appends the
result as a further candidate when the parallel scan is what
best_access_path() chose. Both readings are extended, and the complete
plans compete on cost. optimize_straight_join() costs the fixed order
twice in the same way and keeps the cheaper. The sort space in
make_join_statistics() grows by two POSITIONs per table for the extra
candidates.

Two more things had to change for the search to be honest about it.

The pruning heuristic keeps parallel prefixes apart from serial ones so
that a divided big table is not dropped next to a tiny driver. With
every table now offered as a parallel candidate, the tiny driver's
parallel reading landed in the parallel family too -- one row, next to
no cost -- and dropped every prefix that does spread its rows, which
is what the family exists to protect. A candidate whose divisor is 1
spreads nothing over the workers and is compared with the serial
prefixes, where it loses to its serial twin by the setup it is charged.

And the divisor itself credited a table with a division the workers
cannot make. With the local comparison gone, TPC-H Q5 chose NATION as
its driving table: 25 rows, 5 surviving, costed as spreading the whole
join under it over four workers at cost 230 against the ORDERS-first
plan's 297. NATION is a single InnoDB page, which the partitioner
cannot cut, so one worker ran the whole join at serial speed. The
handler now says how many pieces a scan of its table can be cut into
(parallel_scan_pieces(): for InnoDB the leaf pages of the clustered
index, which bounds the chunks the partitioner can make), scaled by
the share of the table a range reads, and the rows that survive the
driving table's WHERE are spread over no more workers than that. They
are also spread as the busiest worker sees them: R rows over W workers
put ceil(R/W) on one of them, so the divisor is R / ceil(R/W), which
makes five rows over four workers a division by 2.5 and one row a
division by 1. The scan's own cost is still divided by N: a scan the
engine cannot cut is at most a couple of pages, worth nothing next to
the setup, and dividing it is what lets the parallel-query tests, whose
tables are that small, run the workers with the setup cost at 0.

Measured on TPC-DS SF1 with eight workers, Q29: serial 34-46 ms, before
78-90 ms with store_returns divided, after 33-35 ms with d2 divided.
The two workers that receive the 122 qualifying dates, contiguous in
the primary key, do most of the join, so the gain over serial is
small; the loss is gone. Q93 and Q32 stay serial, as they should. On
TPC-H SF1 with four workers the plans of Q1, Q3, Q5, Q7, Q10, Q11 and
Q12 and their times are as the costing commit measured them, Q5 at
165 ms with ORDERS divided.

main.parallel_query_costing gains a 2000-row dimension with 200 rows
matching and 100 fact rows under each: its scan alone cannot repay the
default setup, and it drives the join divided all the same, with and
without STRAIGHT_JOIN.

This commit was prepared with Claude Code (Fable 5.1), which found the
local comparison in the optimizer trace of Q29, implemented the second
candidate, the divisor-keyed pruning family, the pieces estimate and
the busiest-worker divisor, found the Q5 regression and the pruning
regression by measuring TPC-H and re-running the costing test, wrote
the new test section, and ran the parallel-query tests in both
protocols and the main suite.
Rex Johnston
MDEV-42318 followup for parallel query tests
Andrzej Jarzabek
MDEV-31956: Fix extended buffer pool crashes, leaks and test flakiness

Fix several problems in the extended buffer pool (EBP) that showed up
on buildbot:

- IORequest::write_complete() crashed with a sux_lock assertion when an
  EBP write completed after its tablespace was dropped: it called
  x_unlock() on a U-latched page and skipped the rest of the
  completion. The new buf_page_ext_write_discard() releases the
  write-fix and U-latch, returns the EBP page to the free list and tries
  to evict the page.

- buf_page_write_complete() leaked the EBP page slot when the write
  failed, and when the page could not be evicted after a successful
  write (so the copy was never registered in buf_pool.page_hash). Both
  cases now return the slot to the free list. free_ext_page() resets the
  debug in_page_hash flag, because such slots are freed without having
  been inserted into page_hash.

- On Windows the EBP file was opened through mysys create_temp_file(),
  without FILE_FLAG_OVERLAPPED and without being bound to
  srv_thread_pool, so the first asynchronous EBP write crashed in
  StartThreadpoolIo(). create_ext_file() now creates the file with
  CreateFile(FILE_FLAG_OVERLAPPED | FILE_FLAG_DELETE_ON_CLOSE) and binds
  it. The new close_ext_file() closes the file the right way on each
  platform and is also used when setting the file size fails.

- buf_flush_LRU_list_batch() counted a page in n->evicted without
  having evicted it when the write to the EBP could not be started. It
  invoked buf_LRU_free_page() while the page was still U-latched, so
  can_relocate() was false and the call silently did nothing, leaving
  the page in the buffer pool. Release the U-latch before the call, like
  the path that handles a tablespace that is stopping writes.

- The debug variable innodb_force_LRU_eviction returned before the
  forced eviction had finished: it waited for two done_flush_list
  signals, which other flushing can also send, and did not wait for the
  asynchronous writes. It now waits until two page cleaner LRU batches
  (counted by the new debug-only buf_pool.n_LRU_batches) have completed
  with the flag set, and then for all pending writes. This fixes the
  wrong counts seen in innodb.ext_buf_pool and
  innodb.ext_buf_pool_admission_pct.

  That wait could never end when no page cleaner is running, because
  only buf_flush_page_cleaner() increments n_LRU_batches and srv_start()
  only starts it when !srv_read_only_mode, which innodb_force_recovery=6
  implies as well. The update function now does nothing in read only
  mode, and stops waiting if the page cleaner is no longer running; the
  page cleaner clears buf_page_cleaner_is_active and broadcasts
  done_flush_list while holding buf_pool.flush_list_mutex, so the
  transition cannot be missed. The wait also no longer holds
  LOCK_global_system_variables, like the other InnoDB update functions
  that wait, so that it cannot keep other connections from being
  established.

- The debug flag ib_ext_bp_disable_LRU_eviction_for_t never skipped
  anything, because its continue statement applied to the
  do ... while (0) of DBUG_EXECUTE_IF() and not to the page loop. Set a
  variable inside the DBUG_EXECUTE_IF() and act on it after the macro,
  so that the pages of test/t are really left alone while
  innodb.ext_buf_pool and innodb.ext_buf_pool_admission_pct are still
  filling the table. Without this, those pages can be admitted to the
  EBP and evicted while the tests are inserting, and the exact counts
  that the tests expect after the forced eviction depend on how the page
  cleaner happened to be scheduled.

Add a case to innodb.ext_buf_pool for the n->evicted fix. The new debug
flag ib_ext_bp_alloc_fail makes every EBP page allocation fail, so that
buf_page_t::flush(space, true) returns false with the page still
U-latched.

Also re-record sys_vars.sysvars_innodb,32bit for
innodb_extended_buffer_pool_size and
rocksdb.innodb_i_s_tables_disabled for the new
INNODB_BUFFER_POOL_STATS columns.
Rex Johnston
MDEV-39492 PQ: a plan chosen for the workers must reach them, through
the split-materialized reoptimization and a reduced GROUP BY

TPC-DS Q68 with eight workers chose, for its grouped derived table, the
plan with store_sales divided among the workers and every other table
looked up by eq_ref, and then ran that plan serially: a full scan of
2,880,404 rows with four lookups each, 1.7 s against 0.3 s for the
serial plan that starts from the 72 matching dates. Two gate defects,
each enough on its own, turned the chosen parallel plan into a serial
one in the shape the workers would have run.

The first is in the post-plan check that every select-list column
outside an aggregate is a group column. The query groups by
ss_ticket_number, ss_customer_sk, ss_addr_sk and ca_city, and selects
ca_city. The plan reads customer_address by eq_ref on ss_addr_sk, a
grouped column, so remove_const() drops ca_city from the plan's GROUP
BY (eq_ref_table(): every row of a group reads the one same
customer_address row), and the aggregation table is keyed by what is
left. The check, asked with that key, found ca_city unnamed and
refused. And the pre-plan form of the same check, which is asked again
by the full gate, read the query's GROUP BY from join->group_list,
which remove_const() had reduced in place -- relinking the select's
own ORDER nodes, so select_lex->group_list was reduced with it -- and
refused for the same reason.

Pwt_group_checker now also accepts a column of a table the plan reads
by eq_ref through columns that are themselves grouped, constant or
determined the same way, which is remove_const()'s own reasoning and
leaves the column with one value per group; it is asked only of a
finished plan, with the plan to read. And pwt_query_shape_allows_workers()
copies the query's GROUP BY the first time it is asked, before the plan
(choose_plan()), into JOIN::parallel_query_group, and answers from the
copy afterwards.

The second is in what survives a reoptimization. The outer query joins
the derived table by a key on ss_customer_sk, so opt_split.cc tries
splitting it: it saves the plan, runs choose_plan() again with the outer
equality pushed in, and restores the saved plan when the split loses, as
it does here with 100,000 customers to run it for. choose_plan() sets
JOIN::parallel_plan_chosen for the plan it finds, so the restored plan
-- the divided one -- came back with the flag the losing split had left,
false, and parallel_join_check() declined it as "costed cheaper read
serially". The flag is a property of the plan and now travels with it:
Join_plan_state carries it, save_query_plan() takes it and
restore_query_plan() puts it back.

With both, the derived table runs in the workers: 0.76 s with eight,
Parallel_queries_executed counting it. That is still slower than the
0.30 s serial plan, which the costing values at 514 against the divided
plan's 395. The gap is not in the gate. The forced store_sales-first
plan takes 1.61 s serially, 1.10 s with two workers, 0.78 s with four,
0.70 s with eight and 0.73 s with twelve, and ANALYZE puts the time in
the 2,880,404 eq_ref lookups of date_dim: 0.35 us each serially, 1.6 us
each in a worker when eight of them look up the same 73,049-row table
at once, while the scan of store_sales divides cleanly. The costing
divides lookups by the number of workers as it divides the scan, and
for lookups into a small hot table the engine does not. That is a
separate matter, left for its own change.

Tests. main.parallel_query_why: a GROUP BY column of a table read by
eq_ref through a grouped column, dropped from the plan's key, no longer
a reason. main.parallel_query_costing: a grouped derived table joined by
a key on its group column from an outer query too wide for the split to
win, which runs in the workers.

This commit was prepared with Claude Code (Fable 5.1), which traced the
two refusals on a copy of the TPC-DS data, found the reduced GROUP BY
and the flag lost across the restored plan, wrote the fixes and the
tests, rebuilt the worktree, measured the forced plan's scaling by
worker count, and ran the parallel_query tests in both protocols and
the main suite.
Rex Johnston
MDEV-39492 PQ: spread the driving rows over no more workers than the pieces they fill

The rows that survive the driving table's WHERE were spread, in the
costing, over as many workers as the engine could cut the table into.
Where in the table they lie was not asked, and for the tables an
analytic query filters most often it is not spread at all: the 366
rows of date_dim for one year are four of its 671 pages, next to each
other in the primary key, and the 122 returned dates of TPC-DS Q29 are
two. The partitioner hands out a chunk per page, so those rows reach
four workers of eight, or two, and the join under them runs at the
pace of the busiest while the costing credited an eighth of it to each
worker.

parallel_scan_cost() now takes the surviving rows to lie together:
R rows of a T-row table of P pieces fill ceil(R * P / T) of them, and
the rows reach no more workers than that. For rows spread evenly
through the table this is pessimistic, and it only bites when the
survivors are fewer than N pieces' worth; for rows that do lie
together it is what the workers will find, and a plan chosen on a
division the workers cannot make costs more than a division not made.
The busiest worker's share then follows as before, R / ceil(R / W).

On TPC-DS Q66 the divisor for date_dim drops from 8 to 4, which is
what the workers achieve, and the plan is still chosen at cost 114
against the serial plan's 168. It still loses, 457 ms against 315,
because the worker holding the fourth quarter does half the work:
sales peak before the holidays, and how much of the join each driving
row carries is not something the statistics describe. Q29's divided
plan is unchanged at divisor 2 and runs as before, and the TPC-H plans
and times are as the costing commit measured them.

The cap moved a second kind of plan into the wrong pruning family. A
large fact table of which one percent survives, scanned in parallel
with a dimension looked up per surviving row, now has a divisor of 1
-- its 200 rows fill one page -- and the pruning heuristic compared it
with the serial prefixes, where the five-row dimension beats it on
rows and on cost and drops it, although its scan alone, divided four
ways, repays the setup several times over. The parallel family is
therefore for a parallel candidate with something to gain by the
division, either in the join under it (parallel_divisor > 1) or in the
scan itself (the new POSITION::parallel_scan_pays, the divided reading
costing less than the serial one); a candidate with neither is one of
the serial prefixes but for the setup, as before.

main.parallel_query_costing's 2000-row dimension becomes a 20000-row
one whose first 2000 rows match, four pages that four workers can
divide, and the sections it supports read the same.

This commit was prepared with Claude Code (Fable 5.1), which measured
the per-worker row counts of Q66 and Q29 against the divisor the
costing had assumed, implemented the cap, adapted the test, and ran
the parallel-query tests in both protocols and the main suite.
Rex Johnston
MDEV-39492 PQ: charge a parallel plan for every row the workers ship

The cost of a parallel plan was the workers' share of the join plus the
setup, and nothing for the result: the manager receives every row the
workers ship, by itself, and a plan whose output is a large share of
what it reads handed it as many rows as the join produced at no cost.
A cross join of 1000 x 2000 rows was costed cheaper in the workers and
ran there 15 times slower than serially, the time going into writing
two million rows into the workers' containers and draining them.

The join-order search now adds the cost of shipping to a parallel plan
when the plan is complete, which is the first point its row count is
known: at the leaf of best_extension_by_limited_search() and at the end
of cost_straight_join(), as parallel_ship_cost(). A partial plan carries
no estimate of it, which is a lower bound, so the pruning by cost above
the leaf is unchanged.

What is shipped depends on the query's shape, decided once per
optimization by parallel_estimate_shipped_groups() into
JOIN::parallel_groups. A query that does not aggregate ships every
joined row. One that aggregates over everything it reads ships a partial
per worker, which is charged nothing. A grouped one ships a partial per
group per worker, and the number of groups is estimated as the product
of the GROUP BY columns' distinct values from the engine-independent
statistics, capped by the joined rows; without statistics the estimate
is one group, the optimistic side, which leaves such a query costed as
before rather than charged for every joined row.

A row costs optimizer_parallel_row_cost, a new session variable, while
the worker's container is in memory: 0.03 us by default, measured on a
1,000,000-row scan shipping two INT columns. A container is a temporary
table that starts as a HEAP table of at most min(tmp_memory_table_size,
max_heap_table_size) bytes and is converted to Aria when that is
exceeded, after which every row goes through the page cache: the same
scan shipping a VARCHAR(30) as well took 630 ms in the workers against
65 ms serially, 0.6 us a row. So the rows past what the containers hold
in memory, the busiest worker holding rows / parallel_divisor of them
and each container one HEAP table's worth, cost DISK_TEMPTABLE_LOOKUP_COST
more. The row width is the plan's tables' used field lengths at their
declared length, which is how HEAP stores a VARCHAR, not capped at the
engine's mean row length as the join buffer's estimate is. Set to 0 the
variable switches the charge off, the disk tier included.

On the scratch server, with four workers: the two-INT-column scan of a
million rows stays divided (43 ms against 61), the VARCHAR one is read
serially (93 ms, where the divided reading took 630), and the TPC-H
plans are unchanged. The estimate is the optimizer's: a filter it
cannot see through, such as b % 10 = 0, is costed as shipping every row.

Tests. main.parallel_query_costing: a join that ships every joined row
is divided at the default charge and serial at a large one, and a
grouped query at the same charge stays divided, with the trace's
parallel_rows_shipped for each. main.parallel_query_join, _sort and
_spill switch the charge off beside the setup cost, as what they ship
and spill is what they test, not what it costs. The variable is added
to the sysvars, optimizer_costs, opt_context_replay and mysqld--help
results.

This commit was prepared with Claude Code (Fable 5.1), which measured
the per-row shipping cost in memory and after a spill and found the
spill to be the ten-fold difference, wrote the estimate and the cost,
adapted the tests, rebuilt the worktree and ran the parallel_query tests
in both protocols and the main suite.
Rex Johnston
MDEV-42165 Selectivity of a multiple equality with an earlier table is never applied

During optimization, when a table is joined onto the tables already in the
plan, table_multi_eq_cond_selectivity() is meant to account for the
multiple equalities tying its columns to theirs that the chosen access
method does not already use: for each such equality, the largest
avg_frequency/rows over its fields on the earlier tables, multiplied
together across equalities.

It never did. The accumulator starts at 1.0 and is only ever raised:

      double eq_fld_sel= 1.0;
      ...
        if (curr_eq_fld_sel < 1.0)
          set_if_bigger(eq_fld_sel, curr_eq_fld_sel);

Every candidate is below 1.0, so eq_fld_sel stays 1.0 and the function
returns 1.0 for every table in every plan. This has been so since the
function was added (fc1c8ffdadf, the MWL#253 pilot patch).

The effect is visible whenever a table is joined on a column without an
index, so that the join runs through a join buffer: the rows the join
condition rejects are counted as surviving, and every table joined after
it is costed for that many loops. In the test, one of 20 dimension rows
survives its filter and one twentieth of the fact rows joins it, but the
fact table is estimated at filtered 100 and the lookup table under it at
2000 loops where 100 happen. TPC-DS Q93 shows the same shape at scale:
store_returns joined to reason on an unindexed sr_reason_sk, 287514
store_sales lookups estimated where 3710 happen, and a serial plan costed
at 360 that runs in 43 ms.

Make the accumulator do what the comment describes: the largest selectivity
among the fields of the earlier tables, 1.0 only when there is none. The
fact table is then estimated at filtered 5 and the lookup table at 100
loops.

Two things the no-op had been hiding had to change with it.

A column without statistics has an average frequency of 0, which the
accumulator would have taken as "no row matches" and the plan as a
zero-row join. Such a field says nothing and is skipped.

table_after_join_selectivity() multiplied the factor into pos->records_out,
the smallest row count any access method considered for the table had
estimated. That estimate often comes from a ref access on the very
equality the factor accounts for -- a scan whose row count was capped by
the estimate of a ref on the join column, or a ref on one key capped by a
ref on another -- so multiplying counted the equality twice: supplier
after nation in the dbt3 Q9 plan came out at 0.44% where 4% is right. The
factor is now applied to the access method's own estimate (records_init
with the ref discounts for a ref access, records_read for a scan) and the
smaller of that and pos->records_out is kept. This also makes the function
idempotent, which optimize_wo_join_buffering() relies on when it re-costs
a semi-join range from positions that already carry the factor.

Eleven result files change: filtered values where an equality with an
earlier table now counts, and a few join orders in tests on tiny tables
where the estimates moved.

This commit was prepared with Claude Code (Fable 5.1), which found the
no-op while tracing why the parallel plan for Q93 was preferred, confirmed
it with the test here, found the two consequences above from the main
suite's result changes, and wrote the fix, the result updates and this
message.
Rex Johnston
MDEV-39492 PQ: cost the parallel scan in the join-order search

Until now the join order was chosen by the serial optimizer and the
driving table it settled on was then handed to the workers whenever the
gate admitted the query. On TPC-H that split REGION in Q5 and NATION in
Q11: five- and twenty-five-row tables of which one row survives the
WHERE, so the whole join under them ran on one worker and the query paid
the setup of the workers for nothing. The plan that would actually
divide -- ORDERS first in Q5, split four ways with the lookups below it
spread evenly -- costs 1917 against the chosen plan's 873 when read
serially, and the serial optimizer had no way to know that read by four
workers it costs about 490.

best_access_path() now prices the driving table's scan both ways and
keeps the cheaper (parallel_scan_cost): serially, or as one worker's
share of the scan plus optimizer_parallel_setup_cost per table in the
join, with the rows surviving the table's own WHERE spread over
min(N, rows_out) workers. The join-order search divides every later
position's cost by that divisor (position_cost_in_plan), since each
worker joins only its share of the driving rows and the plan's cost is
one worker's. A large table can therefore win the driving position it
loses serially, while a tiny driver gains nothing from the division
and is charged the setup, so it stays serial. parallel_join_check()
runs the workers only for a plan chosen that way.

Three things are needed for the search to find such a plan honestly.
The pruning heuristic drops a prefix that is worse on both rows and
cost than the best at its depth, which is always true of a big-table
prefix next to a five-row one; prefixes under a parallel driver are now
compared only with each other. The tables under a parallel driver are
costed as a worker runs them, a plain nested loop with no join buffer,
hash join or rowid filter, and no covering-index or rowid-filtered scan
is offered as a driver, because the gate refuses all of these and a
plan chosen on their cost would run serially. And the refusals the gate
can make without a plan -- limits, DISTINCT, HAVING, outer joins,
window functions, aggregates whose partials do not merge, a GROUP BY
on an expression, a select-list column GROUP BY does not name, an item
a worker cannot evaluate -- are asked before the search as well
(pwt_query_shape_allows_workers), so that a query the workers will
refuse is costed as the serial plan it will run. Q7's GROUP BY on
extract(year ...) is the case that showed why: chosen for LINEITEM
first on the discount, refused after the plan, and run serially in
that shape at five times its serial time.

The setup cost is a session variable, optimizer_parallel_setup_cost,
in microseconds, default 2000 per table. It was measured on this
branch at about 2 ms for a single-table scan and about 8 ms for a
three-table join, dominated by creating the worker threads with a THD
each, opening every table once per worker, and building and draining
the result containers. The parallel-query tests set it to 0, since
their tables are far too small to repay it, and
main.parallel_query_costing pins the three behaviours on a five-row
dimension and a 20000-row fact table.

Measured on TPC-H SF1 with histograms, four workers against serial:
Q5 490 -> 164 ms, Q3 623 -> 188 ms, Q10 341 -> 139 ms, Q12 615 -> 191
ms, Q15 1225 -> 396 ms, Q1 3966 -> 1160 ms; Q11 and Q7 unchanged.

This commit was prepared with Claude Code (Fable 5.1), which diagnosed
the REGION/NATION splits and the Q7 regression on a scratch copy of the
TPC-H data, implemented the costing, the two-family pruning, the
worker-shaped costing of the parallel chain and the pre-plan gate,
wrote the costing test, updated the existing tests, and ran the
parallel-query tests in both protocols and the main suite.
Kristian Nielsen
Change CONCURRENT syntax in BACKUP SERVER

A follow-up patch, proposing to make the CONCURRENT option for BACKUP SERVER
be one of a comma-separated list of options following the OPTIONS keyword
instead of having special syntax for CONCURRENT.

For example, now the syntax is this:

  BACKUP SERVER TO 'file' OPTIONS CONCURRENT=4

instead of this:

  BACKUP SERVER TO 'file' 4 CONCURRENT

Signed-off-by: Kristian Nielsen <[email protected]>
Rex Johnston
MDEV-39492 PQ: run a FirstMatch semijoin in the workers

The gate refused every semijoin duplicate-elimination strategy, on the
grounds that a worker's nested loop implements none of them. For
FirstMatch that was not true. FirstMatch is the nested loop backing out
early: when the last inner table of the semijoin nest matches, the
executor sets join->return_tab to the outer table the nest follows
(JOIN_TAB::do_firstmatch) and sub_select() unwinds to it rather than
looking for further matches that would only duplicate the row. A worker
runs sub_select() over its own JOIN and its own JOIN_TABs, so it does
the same -- provided its copy of do_firstmatch names a tab of its own
array, since return_tab is only ever compared with the tabs of the
array being walked. setup_worker_jointabs() now remaps do_firstmatch,
first_sj_inner_tab and last_sj_inner_tab from the manager's array onto
the worker's, and the gate admits SJ_OPT_FIRST_MATCH, refusing a nest
whose return tab is a const table, which no worker holds. LooseScan and
DuplicateWeedout keep state that no copy carries -- a match flag, a
weed-out table -- and stay refused, as does materialization.

This is the second half of what TPC-H Q21 needed: its EXISTS over
LINEITEM is flattened to a FirstMatch nest after NATION, and with its
NOT EXISTS left to the manager by the previous commit, the plan the
optimizer had costed as a parallel scan of ORDERS now runs in the
workers.

main.parallel_query_firstmatch runs an EXISTS flattened to FirstMatch
under whole-table aggregation, GROUP BY and a manager-side sort, with
two matching inner rows per outer row so that a nested loop without the
early return would double every count, and shows DuplicateWeedout still
refused.

This commit was prepared with Claude Code (Fable 5.1), which read what
sub_select() and evaluate_join_record() consult for FirstMatch, wrote
the remap and the gate change, and wrote the test.
Rex Johnston
MDEV-39492 PQ: spread the driving rows over no more workers than the pieces they fill

The rows that survive the driving table's WHERE were spread, in the
costing, over as many workers as the engine could cut the table into.
Where in the table they lie was not asked, and for the tables an
analytic query filters most often it is not spread at all: the 366
rows of date_dim for one year are four of its 671 pages, next to each
other in the primary key, and the 122 returned dates of TPC-DS Q29 are
two. The partitioner hands out a chunk per page, so those rows reach
four workers of eight, or two, and the join under them runs at the
pace of the busiest while the costing credited an eighth of it to each
worker.

parallel_scan_cost() now takes the surviving rows to lie together:
R rows of a T-row table of P pieces fill ceil(R * P / T) of them, and
the rows reach no more workers than that. For rows spread evenly
through the table this is pessimistic, and it only bites when the
survivors are fewer than N pieces' worth; for rows that do lie
together it is what the workers will find, and a plan chosen on a
division the workers cannot make costs more than a division not made.
The busiest worker's share then follows as before, R / ceil(R / W).

On TPC-DS Q66 the divisor for date_dim drops from 8 to 4, which is
what the workers achieve, and the plan is still chosen at cost 114
against the serial plan's 168. It still loses, 457 ms against 315,
because the worker holding the fourth quarter does half the work:
sales peak before the holidays, and how much of the join each driving
row carries is not something the statistics describe. Q29's divided
plan is unchanged at divisor 2 and runs as before, and the TPC-H plans
and times are as the costing commit measured them.

The cap moved a second kind of plan into the wrong pruning family. A
large fact table of which one percent survives, scanned in parallel
with a dimension looked up per surviving row, now has a divisor of 1
-- its 200 rows fill one page -- and the pruning heuristic compared it
with the serial prefixes, where the five-row dimension beats it on
rows and on cost and drops it, although its scan alone, divided four
ways, repays the setup several times over. The parallel family is
therefore for a parallel candidate with something to gain by the
division, either in the join under it (parallel_divisor > 1) or in the
scan itself (the new POSITION::parallel_scan_pays, the divided reading
costing less than the serial one); a candidate with neither is one of
the serial prefixes but for the setup, as before.

main.parallel_query_costing's 2000-row dimension becomes a 20000-row
one whose first 2000 rows match, four pages that four workers can
divide, and the sections it supports read the same.

This commit was prepared with Claude Code (Fable 5.1), which measured
the per-worker row counts of Q66 and Q29 against the divisor the
costing had assumed, implemented the cap, adapted the test, and ran
the parallel-query tests in both protocols and the main suite.
Sergei Golubchik
MDEV-42070 handlersocket crashes after open_index with huge number of return fields

alloca() sizes in do_exec_on_index() and cmd_find_internal() depend
on client-controlled counts (return fields, filters) bounded only by
the request line length.

* make DENA_ALLOCA_ALLOCATE always use malloc
* free key_buf/filter_buf on the early "filterblob" return

Also, a huge statement id in open_index or IN list length in exec
resized a vector to 4G elements, aborting on std::bad_alloc.
Limit both to 1024.

Assisted-by: Claude:claude-opus-5-5
Rex Johnston
MDEV-39492 PQ: a LIKE is clonable, so a worker can evaluate it

The gate asks whether every expression a worker would evaluate can be
deep-copied without the copy sharing a node with the original, because the
copy's Item_field leaves are repointed at the worker's own tables and a
shared node would move the manager's item with them. Item_func_like failed
that test: its escape is a child it keeps outside args, and
Item_func_or_sum::deep_copy() clones args only, so the copy still pointed at
the original's escape item. Every LIKE was therefore left to the manager as
a residual condition, which for a LIKE on the driving table ships every row
of the scan to be filtered serially -- TPC-H Q14's CASE WHEN p_type LIKE
'PROMO%' was declined outright, as an aggregate argument a worker cannot
evaluate.

Item_func_like::deep_copy() now clones the escape item as well. The TurboBM
shift tables and the pattern are read-only, allocated on the statement's
mem_root by fix_fields() and never freed by cleanup(), so the copy keeps
pointing at them.

Q14 on the SF1 scratch data: 566 ms serially, 180 ms with four workers and
113 ms with eight, with the same result.

This commit was prepared with Claude Code (Fable 5.1), which found the LIKE
in the gate's trace as the manager-evaluated share of a Q14 probe, wrote the
deep_copy() override and the test, and measured the query.
Rex Johnston
MDEV-42318 InnoDB range estimate doubled for ranges wider than 9 leaf pages

Prior to the MDEV-21136, the old records_in_range estimator undercounted
tall trees because it sampled only around the borders.  A compensation
doubled the estimate.

  if (root_height > divergence_height && !is_n_rows_exact)
    /* In trees whose height is > 1 our algorithm tends to underestimate:
    multiply the estimate by 2: */
    n_rows*= 2;

After MDEV-21136, this compensation is no longer needed.  This commit
removes the above lines.
Rex Johnston
MDEV-42364 PQ: a worker's join buffers are allocated on the worker's thread

In a debug build main.parallel_query_join aborted in the worker THD's
destructor: status_var.local_memory_used was not zero, and safemalloc
reported the join buffer and its field descriptors as freed by a worker
thread but allocated by the query thread.

The manager built each worker's JOIN_CACHE in setup_worker_jointabs() and
called init() there, on the query thread. init() allocates the buffer with
my_malloc(MY_THREAD_SPECIFIC) and the field descriptors on the cache's
JOIN's THD, the worker's. A thread-specific allocation is charged to
current_thd at the time, the manager's THD, while the free -- the buffer in
pwt_worker::close_tables(), the descriptors when the worker THD's mem_root
is torn down -- is credited to the worker's THD on the worker's thread. Each
THD's count ended up off by the buffer in opposite directions, and ~THD
asserts on a non-zero count.

The cache object is still built by the manager, on the statement's
mem_root, with the previous tab chained and the trackers attached. init()
now runs at the start of pwt_worker::execute_and_handoff(), on the worker's
thread, in tab order, before anything is locked, so a failure has nothing
to undo and is reported as out of memory through the worker's error path.
The allocation and the free are then made by the same thread and charged
to the same THD.

This commit was prepared with Claude Code (Fable 5.1), which reproduced the
assertion under mtr, resolved the safemalloc allocation stacks to
JOIN_CACHE::init() called from setup_worker_jointabs(), moved the init()
call to the worker thread, and verified the 24 parallel_query tests pass in
both protocols on the debug build.
Rex Johnston
MDEV-42364 PQ: each worker runs a join buffer of its own

A plan that read a table through a join buffer was refused by the gate
(101a4ccc724), and the join-order search costed the tables under a
parallel driver without one so as not to choose such a plan. That kept
the workers out of every plan where a buffer is the right join method:
a cross join, a small dimension scanned under the divided driver
(TPC-DS Q66's ship_mode, which the gate refused on that ground), any
join without a usable index. Before 101a4ccc724 the worker stripped the buffer off its copy of
the tab and joined a row at a time, scanning the inner table once per
driving row instead of once per buffer-full, which is where the order of
magnitude went on

  SELECT * FROM s1 JOIN s2 ON (1)    -- 1000 x 2000 rows

Now a worker runs a buffer of its own. The saving a buffer gives is fewer
scans of the inner table, and a buffer per worker gets the same saving: a
worker with a quarter of the driving rows fills it a quarter as often, so
the inner table is scanned about as often in total as serially, at most
one extra partial-buffer scan per worker, and those scans run
concurrently. There is nothing to share between the workers.

setup_worker_jointabs() builds, for a tab the manager reads through a
BNL or BNLH cache, a new JOIN_CACHE of the same kind over the worker's
own JOIN and tabs, chained to the previous tab's the way the manager's
is, and calls init() on it. init() walks the worker's tabs up to this one
and takes the fields of the worker's table copies, and it sizes and
allocates the buffer through the worker's THD, which carries the
session's join_buffer_size, so each worker gets a buffer of the session's
size. The tab before it is pointed at sub_select_cache(), which fills
the buffer and flushes it when full and on the end-of-records call the
worker's driver already makes. The buffer is freed with the worker's
tables (pwt_worker::close_tables()).

A buffer evaluates two conditions the nested loop does not, and both
needed a home on the worker's tab. The scan filter in cache_select is
applied to each row of the inner table as the buffer scans it
(JOIN_TAB_SCAN::next()), and remove_redundant_bnl_scan_conds() has taken
its conjuncts out of select_cond, so the worker's tab gets an SQL_SELECT
holding a clone of it, rebound to the worker's tables. The remainder is
evaluated by JOIN_CACHE::check_match() through select->cond rather than
select_cond, so a cached tab gets a second SQL_SELECT over the cloned
select_cond; neither carries a quick. The gate checks the scan filter is
worker-safe whole: it is applied before any prefix row is matched, so
the manager cannot take a conjunct of it the way pwt_split_table_cond()
takes one of a table condition.

A hashed buffer (BNLH) keys the buffered rows by the tab's ref, which
for a hash join is keyed by a KEY create_hj_key_for_table() built for
the manager's table, with key parts naming the manager's fields.
pwt_clone_hj_key() makes the same descriptor over the worker's fields,
clone_table_ref() takes the KEY rather than deriving it from the table,
and the gate and the inert assertions admit JT_HASH.

BKA and BKAH are not run: they read the inner table through multi-range
read on the handler. The gate refuses them, and so that the costing never
chooses a plan the gate refuses, check_join_cache_usage_for_tables()
caps a plan chosen for the workers at join_cache_level 4, where a level
that serially means BKA means BNLH. best_access_path() prices a ref
access the same with or without a BKA buffer, so the plan runs in the
shape it was costed in either way.

The join-order search costs the tables under a parallel driver with join
buffers and hash joins (parallel_chain in best_access_path() now
withholds only the rowid filter).

The worker's hand-built JOIN gets the manager's tables_list, read only:
next_linear_tab() ends its walk at exec_join_tab_cnt(), which is zero
for a JOIN without one, and JOIN_CACHE::calc_record_fields() walked past
the end of the worker's array.

ANALYZE: the worker gets its own three buffer counters, summed into the
manager's tab trackers by quiesce_workers() like the table counters.
Exec_time_tracker gains add() and reset_counts() for that.

Measured on the cross join above with four workers: ANALYZE shows s2
scanned twice, once per worker that got rows, where the stripped worker
scanned it a thousand times. The join is no longer the cost of that
query in the workers; what remains is every joined row being written to
the worker's sink and drained by the manager, which the costing does not
price and which no buffer can help. TPC-H SF1 plans and times (Q3, Q5,
Q10, Q12) are as before this commit.

Tests. main.parallel_query_join: the BNL case now runs in the workers,
plus a BNLH case, the level-6 case (BKA serially, BNLH in the workers)
and the cross join above. main.parallel_query_why: a buffered inner
table is no longer a reason. main.parallel_query_costing gains a small
table scanned under the divided driver, which takes its BNL buffer in
the serial and the parallel plan alike and runs in the workers.

This commit was prepared with Claude Code (Fable 5.1), which traced what
a JOIN_CACHE reads from its JOIN and tabs, wrote the worker-side cache
construction, condition and hash-key cloning, the gate and costing
changes and the tracker merge, updated the tests, rebuilt the worktree,
ran the parallel_query tests in both protocols and the main suite, and
timed the cross join and TPC-H on a scratch server.
Rex Johnston
MDEV-42165 Selectivity of a multiple equality with an earlier table is never applied

During optimization, when a table is joined onto the tables already in the
plan, table_multi_eq_cond_selectivity() is meant to account for the
multiple equalities tying its columns to theirs that the chosen access
method does not already use: for each such equality, the largest
avg_frequency/rows over its fields on the earlier tables, multiplied
together across equalities.

It never did. The accumulator starts at 1.0 and is only ever raised:

      double eq_fld_sel= 1.0;
      ...
        if (curr_eq_fld_sel < 1.0)
          set_if_bigger(eq_fld_sel, curr_eq_fld_sel);

Every candidate is below 1.0, so eq_fld_sel stays 1.0 and the function
returns 1.0 for every table in every plan. This has been so since the
function was added (fc1c8ffdadf, the MWL#253 pilot patch).

The effect is visible whenever a table is joined on a column without an
index, so that the join runs through a join buffer: the rows the join
condition rejects are counted as surviving, and every table joined after
it is costed for that many loops. In the test, one of 20 dimension rows
survives its filter and one twentieth of the fact rows joins it, but the
fact table is estimated at filtered 100 and the lookup table under it at
2000 loops where 100 happen. TPC-DS Q93 shows the same shape at scale:
store_returns joined to reason on an unindexed sr_reason_sk, 287514
store_sales lookups estimated where 3710 happen, and a serial plan costed
at 360 that runs in 43 ms.

Make the accumulator do what the comment describes: the largest selectivity
among the fields of the earlier tables, 1.0 only when there is none. The
fact table is then estimated at filtered 5 and the lookup table at 100
loops.

Two things the no-op had been hiding had to change with it.

A column without statistics has an average frequency of 0, which the
accumulator would have taken as "no row matches" and the plan as a
zero-row join. Such a field says nothing and is skipped.

table_after_join_selectivity() multiplied the factor into pos->records_out,
the smallest row count any access method considered for the table had
estimated. That estimate often comes from a ref access on the very
equality the factor accounts for -- a scan whose row count was capped by
the estimate of a ref on the join column, or a ref on one key capped by a
ref on another -- so multiplying counted the equality twice: supplier
after nation in the dbt3 Q9 plan came out at 0.44% where 4% is right. The
factor is now applied to the access method's own estimate (records_init
with the ref discounts for a ref access, records_read for a scan) and the
smaller of that and pos->records_out is kept. This also makes the function
idempotent, which optimize_wo_join_buffering() relies on when it re-costs
a semi-join range from positions that already carry the factor.

Eleven result files change: filtered values where an equality with an
earlier table now counts, and a few join orders in tests on tiny tables
where the estimates moved.

This commit was prepared with Claude Code (Fable 5.1), which found the
no-op while tracing why the parallel plan for Q93 was preferred, confirmed
it with the test here, found the two consequences above from the main
suite's result changes, and wrote the fix, the result updates and this
message.
Rex Johnston
MDEV-42364 PQ: a worker's join buffers are allocated on the worker's thread

In a debug build main.parallel_query_join aborted in the worker THD's
destructor: status_var.local_memory_used was not zero, and safemalloc
reported the join buffer and its field descriptors as freed by a worker
thread but allocated by the query thread.

The manager built each worker's JOIN_CACHE in setup_worker_jointabs() and
called init() there, on the query thread. init() allocates the buffer with
my_malloc(MY_THREAD_SPECIFIC) and the field descriptors on the cache's
JOIN's THD, the worker's. A thread-specific allocation is charged to
current_thd at the time, the manager's THD, while the free -- the buffer in
pwt_worker::close_tables(), the descriptors when the worker THD's mem_root
is torn down -- is credited to the worker's THD on the worker's thread. Each
THD's count ended up off by the buffer in opposite directions, and ~THD
asserts on a non-zero count.

The cache object is still built by the manager, on the statement's
mem_root, with the previous tab chained and the trackers attached. init()
now runs at the start of pwt_worker::execute_and_handoff(), on the worker's
thread, in tab order, before anything is locked, so a failure has nothing
to undo and is reported as out of memory through the worker's error path.
The allocation and the free are then made by the same thread and charged
to the same THD.

This commit was prepared with Claude Code (Fable 5.1), which reproduced the
assertion under mtr, resolved the safemalloc allocation stacks to
JOIN_CACHE::init() called from setup_worker_jointabs(), moved the init()
call to the worker thread, and verified the 24 parallel_query tests pass in
both protocols on the debug build.
Rex Johnston
MDEV-39492 PQ: key lookups under a divided driver are credited with
the square root of the division

TPC-DS Q68's grouped derived table, with eight workers, was costed
cheaper with store_sales divided among them and date_dim, store,
customer_address and household_demographics looked up by eq_ref under
it -- 395 against 514 for the serial plan that starts from the 72
matching dates -- and ran in 0.70 s where the serial plan runs in
0.24 s.

The join-order search divided every position under a parallel driver
by the driver's parallel_divisor, as if W workers did W times the work
of one. A scan does: each worker reads its own pages at the serial
rate, store_sales at 0.14 us a row per worker against 0.12 serially.
Key lookups do not. The 2,880,404 eq_ref probes of date_dim took
0.35 us each serially and 1.6 us each per worker with eight workers
probing the same index at once, and the plan as a whole ran 1.5 times
faster with two workers, 2.1 with four and 2.3 with eight.

position_cost_in_plan() now divides a ref, eq_ref or ref_or_null
position by the square root of the divisor. That fits the two- and
four-worker measurements and is still generous at eight; it is also
enough to make Q68's divided plan lose at eight workers, and the query
runs the serial plan in 0.32 s. A BNL or hashed join buffer scans the
inner table and divides like a scan, so it is left at the full
division.

What else it moves was checked: TPC-DS Q29 and Q66 keep their divided
plans at four and eight workers, and TPC-H Q1, Q3, Q5, Q10 and Q12 keep
theirs at four with their times unchanged (Q7 and Q11 serial as
before). The dimension lookups under a divided fact table are few next
to the rows scanned, and the discount on them does not reach the
decision.

main.parallel_query_costing: the grouped case's trace lists one complete
parallel plan fewer, the search having pruned the other sooner.

This commit was prepared with Claude Code (Fable 5.1), which measured
the forced plan's scaling by worker count and the per-probe cost from
ANALYZE, wrote the rule, and re-ran the TPC-DS and TPC-H queries, the
parallel_query tests in both protocols and the main suite.
Rex Johnston
MDEV-40012  Documentation update
Rex Johnston
MDEV-39492 PQ: a plan chosen for the workers must reach them, through
the split-materialized reoptimization and a reduced GROUP BY

TPC-DS Q68 with eight workers chose, for its grouped derived table, the
plan with store_sales divided among the workers and every other table
looked up by eq_ref, and then ran that plan serially: a full scan of
2,880,404 rows with four lookups each, 1.7 s against 0.3 s for the
serial plan that starts from the 72 matching dates. Two gate defects,
each enough on its own, turned the chosen parallel plan into a serial
one in the shape the workers would have run.

The first is in the post-plan check that every select-list column
outside an aggregate is a group column. The query groups by
ss_ticket_number, ss_customer_sk, ss_addr_sk and ca_city, and selects
ca_city. The plan reads customer_address by eq_ref on ss_addr_sk, a
grouped column, so remove_const() drops ca_city from the plan's GROUP
BY (eq_ref_table(): every row of a group reads the one same
customer_address row), and the aggregation table is keyed by what is
left. The check, asked with that key, found ca_city unnamed and
refused. And the pre-plan form of the same check, which is asked again
by the full gate, read the query's GROUP BY from join->group_list,
which remove_const() had reduced in place -- relinking the select's
own ORDER nodes, so select_lex->group_list was reduced with it -- and
refused for the same reason.

Pwt_group_checker now also accepts a column of a table the plan reads
by eq_ref through columns that are themselves grouped, constant or
determined the same way, which is remove_const()'s own reasoning and
leaves the column with one value per group; it is asked only of a
finished plan, with the plan to read. And pwt_query_shape_allows_workers()
copies the query's GROUP BY the first time it is asked, before the plan
(choose_plan()), into JOIN::parallel_query_group, and answers from the
copy afterwards.

The second is in what survives a reoptimization. The outer query joins
the derived table by a key on ss_customer_sk, so opt_split.cc tries
splitting it: it saves the plan, runs choose_plan() again with the outer
equality pushed in, and restores the saved plan when the split loses, as
it does here with 100,000 customers to run it for. choose_plan() sets
JOIN::parallel_plan_chosen for the plan it finds, so the restored plan
-- the divided one -- came back with the flag the losing split had left,
false, and parallel_join_check() declined it as "costed cheaper read
serially". The flag is a property of the plan and now travels with it:
Join_plan_state carries it, save_query_plan() takes it and
restore_query_plan() puts it back.

With both, the derived table runs in the workers: 0.76 s with eight,
Parallel_queries_executed counting it. That is still slower than the
0.30 s serial plan, which the costing values at 514 against the divided
plan's 395. The gap is not in the gate. The forced store_sales-first
plan takes 1.61 s serially, 1.10 s with two workers, 0.78 s with four,
0.70 s with eight and 0.73 s with twelve, and ANALYZE puts the time in
the 2,880,404 eq_ref lookups of date_dim: 0.35 us each serially, 1.6 us
each in a worker when eight of them look up the same 73,049-row table
at once, while the scan of store_sales divides cleanly. The costing
divides lookups by the number of workers as it divides the scan, and
for lookups into a small hot table the engine does not. That is a
separate matter, left for its own change.

Tests. main.parallel_query_why: a GROUP BY column of a table read by
eq_ref through a grouped column, dropped from the plan's key, no longer
a reason. main.parallel_query_costing: a grouped derived table joined by
a key on its group column from an outer query too wide for the split to
win, which runs in the workers.

This commit was prepared with Claude Code (Fable 5.1), which traced the
two refusals on a copy of the TPC-DS data, found the reduced GROUP BY
and the flag lost across the restored plan, wrote the fixes and the
tests, rebuilt the worktree, measured the forced plan's scaling by
worker count, and ran the parallel_query tests in both protocols and
the main suite.
Rex Johnston
MDEV-39492 PQ: a GROUP BY column the WHERE binds to a constant is a group column

TPC-DS Q66 ran three times slower with eight workers than without, and
the workers never ran. Each UNION branch groups by the warehouse
columns and d_year under d_year = 2000. The gate asked before the plan
(pwt_query_shape_allows_workers) admitted the branch, so the search
costed date_dim as a parallel driver and chose it, at cost 26 against
the serial plan's. The gate asked after the plan refused the same
branch: "a select list item reads a column outside an aggregate that
GROUP BY does not name". The plan then ran serially in the shape
chosen for the workers, date_dim first with the fact table looked up
per date, 1015 ms against 321.

The two gates disagreed because they read different group lists. The
first sees the GROUP BY as written, with d_year in it. By the time the
second asks, remove_const() has dropped d_year from join->group_list
and from the aggregation table's key as having one value everywhere,
and the select list's d_year is no longer named by either. The column
is a group column all the same: bound to a constant by the WHERE, it
has the one value in every group, which is what the check exists to
establish.

Pwt_group_checker now accepts a column that the join's multiple
equalities bind to a constant, looked up through the COND_EQUAL both
gates are given, whether or not the group list names it. The two gates
agree again, and the branch runs divided. A query cannot be refused on
this ground after the plan if it was admitted before it, which is the
property the pre-plan gate was introduced to provide: a parallel plan
the workers will not run must never be chosen.

main.parallel_query_why gains the shape: a GROUP BY column bound to a
constant, read by the select list, with no refusal and the driving
table divided.

This commit was prepared with Claude Code (Fable 5.1), which traced the
Q66 refusal to the trimmed group list, implemented the check through
the multiple equalities, wrote the test case and ran the parallel-query
tests in both protocols and the main suite.
Rex Johnston
MDEV-39492 PQ: charge a parallel plan for every row the workers ship

The cost of a parallel plan was the workers' share of the join plus the
setup, and nothing for the result: the manager receives every row the
workers ship, by itself, and a plan whose output is a large share of
what it reads handed it as many rows as the join produced at no cost.
A cross join of 1000 x 2000 rows was costed cheaper in the workers and
ran there 15 times slower than serially, the time going into writing
two million rows into the workers' containers and draining them.

The join-order search now adds the cost of shipping to a parallel plan
when the plan is complete, which is the first point its row count is
known: at the leaf of best_extension_by_limited_search() and at the end
of cost_straight_join(), as parallel_ship_cost(). A partial plan carries
no estimate of it, which is a lower bound, so the pruning by cost above
the leaf is unchanged.

What is shipped depends on the query's shape, decided once per
optimization by parallel_estimate_shipped_groups() into
JOIN::parallel_groups. A query that does not aggregate ships every
joined row. One that aggregates over everything it reads ships a partial
per worker, which is charged nothing. A grouped one ships a partial per
group per worker, and the number of groups is estimated as the product
of the GROUP BY columns' distinct values from the engine-independent
statistics, capped by the joined rows; without statistics the estimate
is one group, the optimistic side, which leaves such a query costed as
before rather than charged for every joined row.

A row costs optimizer_parallel_row_cost, a new session variable, while
the worker's container is in memory: 0.03 us by default, measured on a
1,000,000-row scan shipping two INT columns. A container is a temporary
table that starts as a HEAP table of at most min(tmp_memory_table_size,
max_heap_table_size) bytes and is converted to Aria when that is
exceeded, after which every row goes through the page cache: the same
scan shipping a VARCHAR(30) as well took 630 ms in the workers against
65 ms serially, 0.6 us a row. So the rows past what the containers hold
in memory, the busiest worker holding rows / parallel_divisor of them
and each container one HEAP table's worth, cost DISK_TEMPTABLE_LOOKUP_COST
more. The row width is the plan's tables' used field lengths at their
declared length, which is how HEAP stores a VARCHAR, not capped at the
engine's mean row length as the join buffer's estimate is. Set to 0 the
variable switches the charge off, the disk tier included.

On the scratch server, with four workers: the two-INT-column scan of a
million rows stays divided (43 ms against 61), the VARCHAR one is read
serially (93 ms, where the divided reading took 630), and the TPC-H
plans are unchanged. The estimate is the optimizer's: a filter it
cannot see through, such as b % 10 = 0, is costed as shipping every row.

Tests. main.parallel_query_costing: a join that ships every joined row
is divided at the default charge and serial at a large one, and a
grouped query at the same charge stays divided, with the trace's
parallel_rows_shipped for each. main.parallel_query_join, _sort and
_spill switch the charge off beside the setup cost, as what they ship
and spill is what they test, not what it costs. The variable is added
to the sysvars, optimizer_costs, opt_context_replay and mysqld--help
results.

This commit was prepared with Claude Code (Fable 5.1), which measured
the per-row shipping cost in memory and after a spill and found the
spill to be the ten-fold difference, wrote the estimate and the cost,
adapted the tests, rebuilt the worktree and ran the parallel_query tests
in both protocols and the main suite.
Rex Johnston
MDEV-40012  Documentation update
Rex Johnston
MDEV-39492 PQ: run a FirstMatch semijoin in the workers

The gate refused every semijoin duplicate-elimination strategy, on the
grounds that a worker's nested loop implements none of them. For
FirstMatch that was not true. FirstMatch is the nested loop backing out
early: when the last inner table of the semijoin nest matches, the
executor sets join->return_tab to the outer table the nest follows
(JOIN_TAB::do_firstmatch) and sub_select() unwinds to it rather than
looking for further matches that would only duplicate the row. A worker
runs sub_select() over its own JOIN and its own JOIN_TABs, so it does
the same -- provided its copy of do_firstmatch names a tab of its own
array, since return_tab is only ever compared with the tabs of the
array being walked. setup_worker_jointabs() now remaps do_firstmatch,
first_sj_inner_tab and last_sj_inner_tab from the manager's array onto
the worker's, and the gate admits SJ_OPT_FIRST_MATCH, refusing a nest
whose return tab is a const table, which no worker holds. LooseScan and
DuplicateWeedout keep state that no copy carries -- a match flag, a
weed-out table -- and stay refused, as does materialization.

This is the second half of what TPC-H Q21 needed: its EXISTS over
LINEITEM is flattened to a FirstMatch nest after NATION, and with its
NOT EXISTS left to the manager by the previous commit, the plan the
optimizer had costed as a parallel scan of ORDERS now runs in the
workers.

main.parallel_query_firstmatch runs an EXISTS flattened to FirstMatch
under whole-table aggregation, GROUP BY and a manager-side sort, with
two matching inner rows per outer row so that a nested loop without the
early return would double every count, and shows DuplicateWeedout still
refused.

This commit was prepared with Claude Code (Fable 5.1), which read what
sub_select() and evaluate_join_record() consult for FirstMatch, wrote
the remap and the gate change, and wrote the test.
Rex Johnston
MDEV-40012  Documentation
Rex Johnston
MDEV-42318 InnoDB range estimate doubled for ranges wider than 9 leaf pages

Prior to the MDEV-21136, the old records_in_range estimator undercounted
tall trees because it sampled only around the borders.  A compensation
doubled the estimate.

  if (root_height > divergence_height && !is_n_rows_exact)
    /* In trees whose height is > 1 our algorithm tends to underestimate:
    multiply the estimate by 2: */
    n_rows*= 2;

After MDEV-21136, this compensation is no longer needed.  This commit
removes the above lines.
Andrzej Jarzabek
MDEV-31956: Fix extended buffer pool crashes, leaks and test flakiness

Fix several problems in the extended buffer pool (EBP) that showed up
on buildbot:

- IORequest::write_complete() crashed with a sux_lock assertion when an
  EBP write completed after its tablespace was dropped: it called
  x_unlock() on a U-latched page and skipped the rest of the
  completion. The new buf_page_ext_write_discard() releases the
  write-fix and U-latch, returns the EBP page to the free list and tries
  to evict the page.

- buf_page_write_complete() leaked the EBP page slot when the write
  failed, and when the page could not be evicted after a successful
  write (so the copy was never registered in buf_pool.page_hash). Both
  cases now return the slot to the free list. free_ext_page() resets the
  debug in_page_hash flag, because such slots are freed without having
  been inserted into page_hash.

- On Windows the EBP file was opened through mysys create_temp_file(),
  without FILE_FLAG_OVERLAPPED and without being bound to
  srv_thread_pool, so the first asynchronous EBP write crashed in
  StartThreadpoolIo(). create_ext_file() now creates the file with
  CreateFile(FILE_FLAG_OVERLAPPED | FILE_FLAG_DELETE_ON_CLOSE) and binds
  it. The new close_ext_file() closes the file the right way on each
  platform and is also used when setting the file size fails.

- buf_flush_LRU_list_batch() counted a page in n->evicted without
  having evicted it when the write to the EBP could not be started. It
  invoked buf_LRU_free_page() while the page was still U-latched, so
  can_relocate() was false and the call silently did nothing, leaving
  the page in the buffer pool. Release the U-latch before the call, like
  the path that handles a tablespace that is stopping writes.

- The debug variable innodb_force_LRU_eviction returned before the
  forced eviction had finished: it waited for two done_flush_list
  signals, which other flushing can also send, and did not wait for the
  asynchronous writes. It now waits until two page cleaner LRU batches
  (counted by the new debug-only buf_pool.n_LRU_batches) have completed
  with the flag set, and then for all pending writes. This fixes the
  wrong counts seen in innodb.ext_buf_pool and
  innodb.ext_buf_pool_admission_pct.

  That wait could never end when no page cleaner is running, because
  only buf_flush_page_cleaner() increments n_LRU_batches and srv_start()
  only starts it when !srv_read_only_mode, which innodb_force_recovery=6
  implies as well. The update function now does nothing in read only
  mode, and stops waiting if the page cleaner is no longer running; the
  page cleaner clears buf_page_cleaner_is_active and broadcasts
  done_flush_list while holding buf_pool.flush_list_mutex, so the
  transition cannot be missed. The wait also no longer holds
  LOCK_global_system_variables, like the other InnoDB update functions
  that wait, so that it cannot keep other connections from being
  established.

- Remove the debug flag ib_ext_bp_disable_LRU_eviction_for_t. Its
  continue statement applied to the do ... while (0) of
  DBUG_EXECUTE_IF() and not to the page loop, so the flag never skipped
  anything. Removing it and the SET DEBUG_DBUG statements that enabled
  it leaves the recorded output of innodb.ext_buf_pool and
  innodb.ext_buf_pool_admission_pct unchanged.

Add a case to innodb.ext_buf_pool for the n->evicted fix. The new debug
flag ib_ext_bp_alloc_fail makes every EBP page allocation fail, so that
buf_page_t::flush(space, true) returns false with the page still
U-latched.

Also re-record sys_vars.sysvars_innodb,32bit for
innodb_extended_buffer_pool_size and
rocksdb.innodb_i_s_tables_disabled for the new
INNODB_BUFFER_POOL_STATS columns.
Rex Johnston
MDEV-39492 PQ: cost the parallel scan in the join-order search

Until now the join order was chosen by the serial optimizer and the
driving table it settled on was then handed to the workers whenever the
gate admitted the query. On TPC-H that split REGION in Q5 and NATION in
Q11: five- and twenty-five-row tables of which one row survives the
WHERE, so the whole join under them ran on one worker and the query paid
the setup of the workers for nothing. The plan that would actually
divide -- ORDERS first in Q5, split four ways with the lookups below it
spread evenly -- costs 1917 against the chosen plan's 873 when read
serially, and the serial optimizer had no way to know that read by four
workers it costs about 490.

best_access_path() now prices the driving table's scan both ways and
keeps the cheaper (parallel_scan_cost): serially, or as one worker's
share of the scan plus optimizer_parallel_setup_cost per table in the
join, with the rows surviving the table's own WHERE spread over
min(N, rows_out) workers. The join-order search divides every later
position's cost by that divisor (position_cost_in_plan), since each
worker joins only its share of the driving rows and the plan's cost is
one worker's. A large table can therefore win the driving position it
loses serially, while a tiny driver gains nothing from the division
and is charged the setup, so it stays serial. parallel_join_check()
runs the workers only for a plan chosen that way.

Three things are needed for the search to find such a plan honestly.
The pruning heuristic drops a prefix that is worse on both rows and
cost than the best at its depth, which is always true of a big-table
prefix next to a five-row one; prefixes under a parallel driver are now
compared only with each other. The tables under a parallel driver are
costed as a worker runs them, a plain nested loop with no join buffer,
hash join or rowid filter, and no covering-index or rowid-filtered scan
is offered as a driver, because the gate refuses all of these and a
plan chosen on their cost would run serially. And the refusals the gate
can make without a plan -- limits, DISTINCT, HAVING, outer joins,
window functions, aggregates whose partials do not merge, a GROUP BY
on an expression, a select-list column GROUP BY does not name, an item
a worker cannot evaluate -- are asked before the search as well
(pwt_query_shape_allows_workers), so that a query the workers will
refuse is costed as the serial plan it will run. Q7's GROUP BY on
extract(year ...) is the case that showed why: chosen for LINEITEM
first on the discount, refused after the plan, and run serially in
that shape at five times its serial time.

The setup cost is a session variable, optimizer_parallel_setup_cost,
in microseconds, default 2000 per table. It was measured on this
branch at about 2 ms for a single-table scan and about 8 ms for a
three-table join, dominated by creating the worker threads with a THD
each, opening every table once per worker, and building and draining
the result containers. The parallel-query tests set it to 0, since
their tables are far too small to repay it, and
main.parallel_query_costing pins the three behaviours on a five-row
dimension and a 20000-row fact table.

Measured on TPC-H SF1 with histograms, four workers against serial:
Q5 490 -> 164 ms, Q3 623 -> 188 ms, Q10 341 -> 139 ms, Q12 615 -> 191
ms, Q15 1225 -> 396 ms, Q1 3966 -> 1160 ms; Q11 and Q7 unchanged.

This commit was prepared with Claude Code (Fable 5.1), which diagnosed
the REGION/NATION splits and the Q7 regression on a scratch copy of the
TPC-H data, implemented the costing, the two-family pruning, the
worker-shaped costing of the parallel chain and the pre-plan gate,
wrote the costing test, updated the existing tests, and ran the
parallel-query tests in both protocols and the main suite.
Rex Johnston
MDEV-42318 followup for parallel query tests
Rex Johnston
MDEV-40012  Documentation
Rex Johnston
MDEV-39492 PQ: leave a condition the workers cannot evaluate to the manager

A conjunct of a table's condition that no worker can evaluate kept the
whole query serial. The common one is a correlated subquery: its JOIN
belongs to the manager's thread, so there is no clone of it to hand a
worker, and TPC-H Q21's NOT EXISTS over LINEITEM was enough to refuse a
plan whose driving table the optimizer had already costed as a parallel
scan.

The gate now divides each table's condition instead of refusing it
(pwt_split_table_cond). The conjuncts a worker can evaluate stay with the
table, as the worker's select_cond, and the rest are ANDed into
JOIN::parallel_residual_cond for the manager to apply to every row it
drains, after copy_back_row() has put the shipped columns back into the
manager's own records, where the residual's items already look. A
correlated subquery among them runs on the manager's thread through the
manager's own handlers exactly as it would have run serially. A conjunct
of an inner join may be applied anywhere after its tables have been
read, so the answer is the same; what changes is the number of rows it
is asked of, which is the finished join's rather than this table's.

For the residual to be answerable from a drained row, every field it
reads from a join table has to be a shipped column, which
pwt_row_layout::build() takes from the read_set. The split checks that,
walking into subqueries for their outer references, and refuses the plan
if a conjunct can be evaluated on neither side. The split is taken by
the gate and taken again by init_parallel_workers() from the plan as it
stands when the workers are built (pwt_split_plan_conditions), because it
names the plan's own items.

A plan with a residual ships joined rows rather than pre-aggregating:
the filter has to run before any grouping, so pwt_row_layout::build()
takes a ship_rows argument that keeps 'grouped' off while
'plan_aggregates' stays on, which is the fall-back shape the drain
already handles, with the plan's own terminal grouping what the manager
lets through. The non-aggregating drain applies the residual before
sending a row, and before collecting it when the sort is the manager's.
The optimizer trace records the manager's share under
parallel_scan_manager_evaluates.

On TPC-H SF1 Q21 the serial plan evaluates the NOT EXISTS once per late
LINEITEM row of a finished order, 1.8M times, and the manager once per
row of the finished join, 77k times, since the NATION filter has run by
then. With a FirstMatch semijoin admitted to the workers in the next
commit, Q21 goes from 2.9 s serially to 0.85 s with four workers and
0.68 s with eight, with the same result.

main.parallel_query_residual pins the four shapes: whole-table
aggregation, GROUP BY, a plain select, and a select whose sort the
manager performs, each with a correlated subquery in the WHERE clause,
each run in the workers and each giving the serial answer.

This commit was prepared with Claude Code (Fable 5.1), which diagnosed
the refusal from the optimizer trace, measured that applying the
subqueries after the join was cheaper even serially, designed and wrote
the split, the layout change and the drain-side filter, and wrote the
test.
Rex Johnston
MDEV-39492 PQ: leave a condition the workers cannot evaluate to the manager

A conjunct of a table's condition that no worker can evaluate kept the
whole query serial. The common one is a correlated subquery: its JOIN
belongs to the manager's thread, so there is no clone of it to hand a
worker, and TPC-H Q21's NOT EXISTS over LINEITEM was enough to refuse a
plan whose driving table the optimizer had already costed as a parallel
scan.

The gate now divides each table's condition instead of refusing it
(pwt_split_table_cond). The conjuncts a worker can evaluate stay with the
table, as the worker's select_cond, and the rest are ANDed into
JOIN::parallel_residual_cond for the manager to apply to every row it
drains, after copy_back_row() has put the shipped columns back into the
manager's own records, where the residual's items already look. A
correlated subquery among them runs on the manager's thread through the
manager's own handlers exactly as it would have run serially. A conjunct
of an inner join may be applied anywhere after its tables have been
read, so the answer is the same; what changes is the number of rows it
is asked of, which is the finished join's rather than this table's.

For the residual to be answerable from a drained row, every field it
reads from a join table has to be a shipped column, which
pwt_row_layout::build() takes from the read_set. The split checks that,
walking into subqueries for their outer references, and refuses the plan
if a conjunct can be evaluated on neither side. The split is taken by
the gate and taken again by init_parallel_workers() from the plan as it
stands when the workers are built (pwt_split_plan_conditions), because it
names the plan's own items.

A plan with a residual ships joined rows rather than pre-aggregating:
the filter has to run before any grouping, so pwt_row_layout::build()
takes a ship_rows argument that keeps 'grouped' off while
'plan_aggregates' stays on, which is the fall-back shape the drain
already handles, with the plan's own terminal grouping what the manager
lets through. The non-aggregating drain applies the residual before
sending a row, and before collecting it when the sort is the manager's.
The optimizer trace records the manager's share under
parallel_scan_manager_evaluates.

On TPC-H SF1 Q21 the serial plan evaluates the NOT EXISTS once per late
LINEITEM row of a finished order, 1.8M times, and the manager once per
row of the finished join, 77k times, since the NATION filter has run by
then. With a FirstMatch semijoin admitted to the workers in the next
commit, Q21 goes from 2.9 s serially to 0.85 s with four workers and
0.68 s with eight, with the same result.

main.parallel_query_residual pins the four shapes: whole-table
aggregation, GROUP BY, a plain select, and a select whose sort the
manager performs, each with a correlated subquery in the WHERE clause,
each run in the workers and each giving the serial answer.

This commit was prepared with Claude Code (Fable 5.1), which diagnosed
the refusal from the optimizer trace, measured that applying the
subqueries after the join was cheaper even serially, designed and wrote
the split, the layout change and the drain-side filter, and wrote the
test.
Rex Johnston
MDEV-39492 PQ: a LIKE is clonable, so a worker can evaluate it

The gate asks whether every expression a worker would evaluate can be
deep-copied without the copy sharing a node with the original, because the
copy's Item_field leaves are repointed at the worker's own tables and a
shared node would move the manager's item with them. Item_func_like failed
that test: its escape is a child it keeps outside args, and
Item_func_or_sum::deep_copy() clones args only, so the copy still pointed at
the original's escape item. Every LIKE was therefore left to the manager as
a residual condition, which for a LIKE on the driving table ships every row
of the scan to be filtered serially -- TPC-H Q14's CASE WHEN p_type LIKE
'PROMO%' was declined outright, as an aggregate argument a worker cannot
evaluate.

Item_func_like::deep_copy() now clones the escape item as well. The TurboBM
shift tables and the pattern are read-only, allocated on the statement's
mem_root by fix_fields() and never freed by cleanup(), so the copy keeps
pointing at them.

Q14 on the SF1 scratch data: 566 ms serially, 180 ms with four workers and
113 ms with eight, with the same result.

This commit was prepared with Claude Code (Fable 5.1), which found the LIKE
in the gate's trace as the manager-evaluated share of a Q14 probe, wrote the
deep_copy() override and the test, and measured the query.
Rex Johnston
MDEV-39492 PQ: key lookups under a divided driver are credited with
the square root of the division

TPC-DS Q68's grouped derived table, with eight workers, was costed
cheaper with store_sales divided among them and date_dim, store,
customer_address and household_demographics looked up by eq_ref under
it -- 395 against 514 for the serial plan that starts from the 72
matching dates -- and ran in 0.70 s where the serial plan runs in
0.24 s.

The join-order search divided every position under a parallel driver
by the driver's parallel_divisor, as if W workers did W times the work
of one. A scan does: each worker reads its own pages at the serial
rate, store_sales at 0.14 us a row per worker against 0.12 serially.
Key lookups do not. The 2,880,404 eq_ref probes of date_dim took
0.35 us each serially and 1.6 us each per worker with eight workers
probing the same index at once, and the plan as a whole ran 1.5 times
faster with two workers, 2.1 with four and 2.3 with eight.

position_cost_in_plan() now divides a ref, eq_ref or ref_or_null
position by the square root of the divisor. That fits the two- and
four-worker measurements and is still generous at eight; it is also
enough to make Q68's divided plan lose at eight workers, and the query
runs the serial plan in 0.32 s. A BNL or hashed join buffer scans the
inner table and divides like a scan, so it is left at the full
division.

What else it moves was checked: TPC-DS Q29 and Q66 keep their divided
plans at four and eight workers, and TPC-H Q1, Q3, Q5, Q10 and Q12 keep
theirs at four with their times unchanged (Q7 and Q11 serial as
before). The dimension lookups under a divided fact table are few next
to the rows scanned, and the discount on them does not reach the
decision.

main.parallel_query_costing: the grouped case's trace lists one complete
parallel plan fewer, the search having pruned the other sooner.

This commit was prepared with Claude Code (Fable 5.1), which measured
the forced plan's scaling by worker count and the per-probe cost from
ANALYZE, wrote the rule, and re-ran the TPC-DS and TPC-H queries, the
parallel_query tests in both protocols and the main suite.
Rex Johnston
MDEV-42364 PQ: each worker runs a join buffer of its own

A plan that read a table through a join buffer was refused by the gate
(101a4ccc724), and the join-order search costed the tables under a
parallel driver without one so as not to choose such a plan. That kept
the workers out of every plan where a buffer is the right join method:
a cross join, a small dimension scanned under the divided driver
(TPC-DS Q66's ship_mode, which the gate refused on that ground), any
join without a usable index. Before 101a4ccc724 the worker stripped the buffer off its copy of
the tab and joined a row at a time, scanning the inner table once per
driving row instead of once per buffer-full, which is where the order of
magnitude went on

  SELECT * FROM s1 JOIN s2 ON (1)    -- 1000 x 2000 rows

Now a worker runs a buffer of its own. The saving a buffer gives is fewer
scans of the inner table, and a buffer per worker gets the same saving: a
worker with a quarter of the driving rows fills it a quarter as often, so
the inner table is scanned about as often in total as serially, at most
one extra partial-buffer scan per worker, and those scans run
concurrently. There is nothing to share between the workers.

setup_worker_jointabs() builds, for a tab the manager reads through a
BNL or BNLH cache, a new JOIN_CACHE of the same kind over the worker's
own JOIN and tabs, chained to the previous tab's the way the manager's
is, and calls init() on it. init() walks the worker's tabs up to this one
and takes the fields of the worker's table copies, and it sizes and
allocates the buffer through the worker's THD, which carries the
session's join_buffer_size, so each worker gets a buffer of the session's
size. The tab before it is pointed at sub_select_cache(), which fills
the buffer and flushes it when full and on the end-of-records call the
worker's driver already makes. The buffer is freed with the worker's
tables (pwt_worker::close_tables()).

A buffer evaluates two conditions the nested loop does not, and both
needed a home on the worker's tab. The scan filter in cache_select is
applied to each row of the inner table as the buffer scans it
(JOIN_TAB_SCAN::next()), and remove_redundant_bnl_scan_conds() has taken
its conjuncts out of select_cond, so the worker's tab gets an SQL_SELECT
holding a clone of it, rebound to the worker's tables. The remainder is
evaluated by JOIN_CACHE::check_match() through select->cond rather than
select_cond, so a cached tab gets a second SQL_SELECT over the cloned
select_cond; neither carries a quick. The gate checks the scan filter is
worker-safe whole: it is applied before any prefix row is matched, so
the manager cannot take a conjunct of it the way pwt_split_table_cond()
takes one of a table condition.

A hashed buffer (BNLH) keys the buffered rows by the tab's ref, which
for a hash join is keyed by a KEY create_hj_key_for_table() built for
the manager's table, with key parts naming the manager's fields.
pwt_clone_hj_key() makes the same descriptor over the worker's fields,
clone_table_ref() takes the KEY rather than deriving it from the table,
and the gate and the inert assertions admit JT_HASH.

BKA and BKAH are not run: they read the inner table through multi-range
read on the handler. The gate refuses them, and so that the costing never
chooses a plan the gate refuses, check_join_cache_usage_for_tables()
caps a plan chosen for the workers at join_cache_level 4, where a level
that serially means BKA means BNLH. best_access_path() prices a ref
access the same with or without a BKA buffer, so the plan runs in the
shape it was costed in either way.

The join-order search costs the tables under a parallel driver with join
buffers and hash joins (parallel_chain in best_access_path() now
withholds only the rowid filter).

The worker's hand-built JOIN gets the manager's tables_list, read only:
next_linear_tab() ends its walk at exec_join_tab_cnt(), which is zero
for a JOIN without one, and JOIN_CACHE::calc_record_fields() walked past
the end of the worker's array.

ANALYZE: the worker gets its own three buffer counters, summed into the
manager's tab trackers by quiesce_workers() like the table counters.
Exec_time_tracker gains add() and reset_counts() for that.

Measured on the cross join above with four workers: ANALYZE shows s2
scanned twice, once per worker that got rows, where the stripped worker
scanned it a thousand times. The join is no longer the cost of that
query in the workers; what remains is every joined row being written to
the worker's sink and drained by the manager, which the costing does not
price and which no buffer can help. TPC-H SF1 plans and times (Q3, Q5,
Q10, Q12) are as before this commit.

Tests. main.parallel_query_join: the BNL case now runs in the workers,
plus a BNLH case, the level-6 case (BKA serially, BNLH in the workers)
and the cross join above. main.parallel_query_why: a buffered inner
table is no longer a reason. main.parallel_query_costing gains a small
table scanned under the divided driver, which takes its BNL buffer in
the serial and the parallel plan alike and runs in the workers.

This commit was prepared with Claude Code (Fable 5.1), which traced what
a JOIN_CACHE reads from its JOIN and tabs, wrote the worker-side cache
construction, condition and hash-key cloning, the gate and costing
changes and the tracker merge, updated the tests, rebuilt the worktree,
ran the parallel_query tests in both protocols and the main suite, and
timed the cross join and TPC-H on a scratch server.
Rex Johnston
MDEV-39492 PQ: choose the divided driving table as a plan, not by its scan alone

TPC-DS Q29 ran at twice its serial time with eight workers. Serially the
optimizer starts at date_dim d2, whose WHERE keeps 122 of 73049 rows,
and reaches store_returns through the returned-date index: 16700
lookups into store_sales. With workers it started at store_returns
instead, divided its 287514 rows eight ways, and applied the d2 filter
only after the store_sales lookup, so each worker did 36000 of those
lookups. Dividing d2 and keeping the serial order under it costs 24
against the chosen plan's 58 and the serial plan's 61, and the search
never saw it.

best_access_path() priced the driving table's scan both ways and kept
the cheaper reading on the spot. For d2 the parallel reading is the
dearer: one eighth of a 12.5 scan plus 2 ms of setup for each of eight
tables comes to 17.6, so the serial reading was kept and the plan with
d2 divided was never extended. What that comparison leaves out is the
join under the driving table, which the division cuts eight ways too
and which is where the cost is. The scan of a table like d2 can never
repay the setup on its own; the join under it repays it many times
over.

The search now offers the driving position every candidate twice. After
get_costs_for_tables() has costed each table with its scan read
serially, add_parallel_driver_candidates() costs it again with
JOIN::parallel_driver_costing set, under which best_access_path()
prices a full or range scan as one worker's share plus the setup
(parallel_scan_cost() no longer judges the reading), and appends the
result as a further candidate when the parallel scan is what
best_access_path() chose. Both readings are extended, and the complete
plans compete on cost. optimize_straight_join() costs the fixed order
twice in the same way and keeps the cheaper. The sort space in
make_join_statistics() grows by two POSITIONs per table for the extra
candidates.

Two more things had to change for the search to be honest about it.

The pruning heuristic keeps parallel prefixes apart from serial ones so
that a divided big table is not dropped next to a tiny driver. With
every table now offered as a parallel candidate, the tiny driver's
parallel reading landed in the parallel family too -- one row, next to
no cost -- and dropped every prefix that does spread its rows, which
is what the family exists to protect. A candidate whose divisor is 1
spreads nothing over the workers and is compared with the serial
prefixes, where it loses to its serial twin by the setup it is charged.

And the divisor itself credited a table with a division the workers
cannot make. With the local comparison gone, TPC-H Q5 chose NATION as
its driving table: 25 rows, 5 surviving, costed as spreading the whole
join under it over four workers at cost 230 against the ORDERS-first
plan's 297. NATION is a single InnoDB page, which the partitioner
cannot cut, so one worker ran the whole join at serial speed. The
handler now says how many pieces a scan of its table can be cut into
(parallel_scan_pieces(): for InnoDB the leaf pages of the clustered
index, which bounds the chunks the partitioner can make), scaled by
the share of the table a range reads, and the rows that survive the
driving table's WHERE are spread over no more workers than that. They
are also spread as the busiest worker sees them: R rows over W workers
put ceil(R/W) on one of them, so the divisor is R / ceil(R/W), which
makes five rows over four workers a division by 2.5 and one row a
division by 1. The scan's own cost is still divided by N: a scan the
engine cannot cut is at most a couple of pages, worth nothing next to
the setup, and dividing it is what lets the parallel-query tests, whose
tables are that small, run the workers with the setup cost at 0.

Measured on TPC-DS SF1 with eight workers, Q29: serial 34-46 ms, before
78-90 ms with store_returns divided, after 33-35 ms with d2 divided.
The two workers that receive the 122 qualifying dates, contiguous in
the primary key, do most of the join, so the gain over serial is
small; the loss is gone. Q93 and Q32 stay serial, as they should. On
TPC-H SF1 with four workers the plans of Q1, Q3, Q5, Q7, Q10, Q11 and
Q12 and their times are as the costing commit measured them, Q5 at
165 ms with ORDERS divided.

main.parallel_query_costing gains a 2000-row dimension with 200 rows
matching and 100 fact rows under each: its scan alone cannot repay the
default setup, and it drives the join divided all the same, with and
without STRAIGHT_JOIN.

This commit was prepared with Claude Code (Fable 5.1), which found the
local comparison in the optimizer trace of Q29, implemented the second
candidate, the divisor-keyed pruning family, the pieces estimate and
the busiest-worker divisor, found the Q5 regression and the pruning
regression by measuring TPC-H and re-running the costing test, wrote
the new test section, and ran the parallel-query tests in both
protocols and the main suite.
Sergei Golubchik
MDEV-42324 CONNECTION of a MULTIPLE table is used as a format string

For ODBC tables with MULTIPLE=1 TDBODBC::GetFile() replaced the DBQ
value in CONNECTION with "%s" and TDBODBC::SetFile() passed the result
to snprintf() as the format string.

Store the parts of CONNECTION before and after the file name as two
strings and concatenate them with the file name.

Assisted-by: Claude:claude-opus-5-5
Kristian Nielsen
Binlog options for BACKUP SERVER

Extends the backup syntax with options for how to backup binlogs:

  BACKUP SERVER TO xxx OPTIONS BINLOG=FULL|MINIMAL|NONE
  BACKUP SERVER WITH xxx OPTIONS BINLOG=FULL|MINIMAL|NONE

BINLOG=FULL    All engine binlogs included in backup, default
BINLOG=MINIMAL Only actively used binlog files are included
BINLOG=NONE    Binlogs are not included in the backup.

The syntax is intended to take a list of options, eg.

  BACKUP SERVER ... OPTIONS BINLOG=MINIMAL, SOMEOPT=42, ...

A follow-up patch will propose changing the CONCURRENT syntax to be included
in the OPTIONS list.

Signed-off-by: Kristian Nielsen <[email protected]>