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: 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-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-41251 Wrong result with split materialized query

A query like

  SELECT * FROM t0 WHERE t0.b IN
    (SELECT t.n2 FROM t1, (SELECT n1, n2 FROM t1 GROUP BY n1, n2) t
      WHERE t.n1 = t1.n1 AND t1.c1 = 'a' UNION SELECT -1)

returned only the row of t0 that was read first, when the derived table t
was split-materialized.

The IN->EXISTS transformation wraps t0.b in an Item_cache owned by the
Item_in_optimizer, and injects t.n2 = <cache>(t0.b) into the subquery. The
optimizer then pushes an equality on n2 into the derived table, so that
the table only has to be filled with the matching rows.
TABLE::add_splitting_info_for_key_field() built the right side of that
equality as a deep copy of <cache>(t0.b). A copy of a cache is a second
cache: it read t0.b for the first row of t0 and kept that value, because
only the Item_in_optimizer stores new values, and it stores them into the
original cache. Every later refill of the derived table was filtered on
the first row's value.

The right side is an expression of the outer select used inside the select
that specifies the derived table. Add a copy hierarchy for that purpose.
Item::new_select_copy_with_checks(thd, item_select) returns a copy for use
in a select nested in item_select, the select the item belongs to. In the
nested select the copy is an outer reference to item_select:

- An Item_field is copied and its depended_from set to item_select. This is
  what add_splitting_info_for_key_field() did before with
  set_fields_as_dependent_processor, except that depended_from now names
  the select the column belongs to instead of the nested select.
- An Item_direct_view_ref, a column of a merged view or derived table, is
  also copied like a column: the copy refers to a new_select_copy() of the
  item the view column stands for. A constant view column keeps its constant
  underlying item, which keeps a column of a constant NULL-complemented
  table constant in the pushed equality (the MDEV-30081 test in
  main.derived_cond_pushdown still shows ref "const" for its LATERAL DERIVED
  table). If the copy still depends on a table of item_select, which happens
  for a constant column of a view on the NULL-complemented side of an outer
  join, since used_tables() then names that table, the copy gets its
  depended_from set as well.
- Any other item that depends on tables of item_select is not copied. The
  copy is an Item_direct_ref to the original item, with depended_from set
  to item_select. So the nested select reads the cache, aggregate or
  subquery that its owner keeps up to date, instead of a copy of it that
  nobody refreshes. Item_default_value, Item_insert_value and
  Item_trigger_field are treated this way too, as they are not plain
  columns.
- An item that depends on no table of item_select is shared. This includes
  items whose deep_copy() returns nullptr, such as stored routine
  variables, which therefore no longer prevent splitting.

The copy is fixed, and only refers to tables outside the select it is used
in, which the wrapper asserts. add_splitting_info_for_key_field() now uses
it for the right side of the pushed equality, and no longer walks the copy
with set_fields_as_dependent_processor or calls update_used_tables() on
it.

A second test, taken from Dave Gosselin's MDEV-41251 commit, pushes a
comparison, dt.a <=> (t1.b = 1), and its row form. The deep copy of the
comparison was never fixed again. Its Arg_comparator still pointed at the
original, which sets null_value of the original, and a copied row
comparison had comparators set to NULL. The row of t1 with a NULL b was
missing from the result, and the row form crashed in
Arg_comparator::compare_row(). Now the comparison is not copied: the right
side refers to the original.

A third test pushes dt.a <=> v.one where v is a merged view with the
constant column one, on the NULL-complemented side of an outer join. It
covers the view column copy that depends on a table only through its
NULL-complemented table.

This commit was prepared with Claude Code (Opus 5), which designed and
wrote the new_select_copy() hierarchy, switched the split equality to it,
wrote the three-row test from the earlier rr analysis, added the
comparison test, confirmed in a build of the parent commit that both tests
fail without the change, and ran main and the SQL-layer suites in normal
and --ps-protocol mode. Claude Code (Fable 5.1) then reviewed the commit,
found and reproduced the NULL-complemented view column case, wrote its fix
and test, and reran the derived and SQL-layer tests.
Rex Johnston
PQ:  Code tidy ups and fixups of tidyups.

parallel_query_aggregate.test: fix statistics
impersonalize language in can_parallel_scan_jointab_access()
remove dead code (trace_parallel_scan_options)
add an assert to ensure we do not use Item_sum_avg without two packed fields
minor comment fixups
remove enum element NESTED_LOOP_DECLINED and use a local bool instead
fix silly code in pwt_row_layout::build_aggregates (throwing away a pointer
  then searching for it again later); 'one' starts as nullptr, because GCC
  cannot see that whole_table is unchanged between the two blocks and warns
  -Wmaybe-uninitialized in an ASAN build
tidy up Parallel_scan_partitioner::Scan_ctx::create_chunks to use
  create_chunks_unsplit

The 'one= nullptr' initialisation was added with Claude Code (Opus 5.5),
which traced the -Wmaybe-uninitialized warning to this change and folded
the fix in here.

Fixup for our scan only prototype, and a test.
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-40012 PQ: refuse DEFAULT() in an expression a worker evaluates

DEFAULT(col) was evaluated against the worker's row. Item_default_value is
an Item_field whose field is a private copy made by make_default_field(),
reading the share's default_values but carrying the column's own table.
Its deep_copy() shares that field, and Pwt_field_rebinder, seeing the
manager's table, repointed it at the worker's real column. DEFAULT(col)
then read the current row's value, and for an expression default
calculate() called set_default() and wrote the default into the row --
wrong results in a release build, a marked_for_write assertion in a debug
one. It shows only when the expression also names the column some other
way; alone, DEFAULT(col) is table-independent and evaluated at optimize
time.

The gate now refuses any expression holding a DEFAULT(), found with
check_func_default_processor, which only Item_default_value answers.

Found by running the main suite with --parallel-worker-threads=4, where
type_temporal_innodb lost a "Truncated incorrect BOOLEAN value" warning
because the worker's WHERE evaluated to NULL. parallel_query_clone covers
a lost row, a gained row and the expression default that crashed, and
checks that none of them ran in the workers.

This commit was prepared with Claude Code (Opus 5.5), which traced the
wrong result from a main-suite sweep with workers enabled to the rebinder,
wrote the gate refusal and the test, confirmed the test fails without the
refusal, and ran the parallel_query tests in normal and --ps-protocol
modes.
Rex Johnston
MDEV-40012 PQ: a worker must not end its container's scan after handing it over

A pre-aggregating worker accumulates into its own container, a temporary
table, and hands that container to the manager with sink->flush(). Just
before the hand-off, execute_and_handoff() closes the container's index,
because the manager starts its own scan of the container immediately after
the hand-off.

The tidy-up at exec_exit then closed the container a second time. Its
comment said this was only for the paths that reach exec_exit without a
hand-off, but the code ran on every path, including the path with a
successful hand-off. By that point the container may already belong to the
manager: claim_next_result() has seen it marked as done, and
pwt_tmp_table_source::next_row() has rebound it to the manager's thread and
called ha_rnd_init() on it. The worker's ha_index_or_rnd_end() therefore
ends the manager's scan. The manager's next ha_rnd_next() then fails
"inited == RND" in a debug build, and in a release build it reads from a
table with a closed scan.

The window between the flush and the second close is only a few
instructions wide, so the failure is rare: main.ps_3innodb hit it once in a
main-suite run with --parallel-worker-threads=4, on
SELECT ... UNION DISTINCT SELECT sum(a) ... GROUP BY b. The second close now
runs only on the paths that skipped the first close, as recorded by a flag
set next to the first one.

parallel_query_handoff makes the race certain. With pwt_handoff_sync set, a
worker that has handed over its container waits until the manager reaches
the new sync point pwt_manager_scanning_container, and the manager keeps its
scan open until the worker has finished its tidy-up. The test uses one
worker, so there is a single container and no risk of crossed signals. It
checks the rows and that the query ran in the worker. Without the fix it
fails the inited == RND assertion on every run.

This commit was prepared with Claude Code (Opus 5.5), which found the crash
in a main-suite sweep with workers enabled, traced it from the core dump to
the second close, wrote the fix, the sync points and the test, and confirmed
that the test fails without the fix in five runs out of five and passes with
it in normal and --ps-protocol modes.
Rex Johnston
MDEV-40012 PQ: merge AVG, MIN and MAX partials after the manager's table spills

The manager merges a worker's partial for a group through the plan's own
terminal. direct_add() hands the partial to each aggregate, and
end_update() either opens the group with reset_field() or folds the
partial into it with update_field(). Once the aggregation table spills
from HEAP to disk, the terminal becomes end_unique_update(), which calls
reset_field() for every row, before the write shows whether the group is
new. For a group already in the table it then restores the stored row
and calls update_field() with the same partial.

reset_field() consumes the partial, so update_field() has to find it
again. Item_sum_sum and Item_sum_count keep their direct values for that
case and mark it with direct_reseted_field. Two aggregates lacked that:

- Item_sum_avg::reset_field() zeroed direct_count, so update_field()
  added the partial's sum with a count of zero, and the average of such a
  group came out too high.
- Item_sum_min_max::reset_field() cleared direct_added and had no
  direct_reseted_field, so update_field() compared the stored value with
  args[0], the manager's own argument over a base-table row the manager
  never fills, instead of with the partial.

Item_sum_avg::reset_field() now leaves direct_count for update_field(),
which already clears it. Item_sum_min_max gains direct_reseted_field, set
by reset_field() and read and cleared by update_field(). A directly added
item also bypasses the FILTER test in update_field(), as in
Item_sum_sum, since the partial already reflects the filter. A serial
plan never sets direct_added, so it never reaches the new branches.

The grouped case already in main.parallel_query_spill has one row per
group, so each group gets a single partial and the branch for a group
already in the table never ran. The new case groups 20000 rows into 3000
groups, so each worker sends a partial for nearly every group, and the
64K heap limit makes the manager's table spill. Without either of the two
changes, its parallel answer differs from the serial one.

This commit was prepared with Claude Code (Opus 5.5), which found the
wrong averages while letting the workers pre-aggregate on a wide GROUP BY
column, traced them and the wrong MIN and MAX values to the reset_field()
and update_field() pair under end_unique_update(), and showed with the new
test that the AVG change and the MIN/MAX change each fix a failure of
their own.
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-40012  Documentation
Rex Johnston
MDEV-41632 UPPER(key_col) IN (constant subquery) does not use the index

Item_func_in::varchar_upper_cmp_transformer() rewrites
UPPER(key_col) IN (const, ...) into key_col IN (const, ...).

It needs a copy of the IN predicate to put the new first argument into,
it used deep_copy_with_checks(). A deep copy copies every node of the tree and
refuses as a whole if any node cannot be copied, so an IN list holding an
uncorrelated scalar subquery, which is constant but has no copy, silently
lost the rewrite: UPPER(a) IN ((SELECT MAX(c) FROM t2),'A-2') read the whole
table instead of using a range on the index on a. The rows returned were
correct; the symptom is the plan. After copying, the rewrite walked the copy
with cleanup_excluding_const_fields_processor and re-fixed it, which would
also have cleaned up a subquery had one been copied.

A copy for use in the same SELECT_LEX does not need to copy what can be
shared there. We add a separate copy hierarchy for that purpose.

Item::same_select_copy_with_checks() calls the protected virtual
Item::same_select_copy(), and cleans up every node it actually copied, so
that the caller only has to call fix_fields() on the result. fix_fields()
re-fixes the copied nodes and skips the shared ones, which are still fixed.
It does not use deep_copy() at any level; the only other copy function it
calls is shallow_copy() on the node being copied. It returns nullptr on out
of memory, and when a copied node's shallow_copy() returns nullptr; every
Item_func subclass whose shallow_copy() returns nullptr therefore overrides
same_select_copy() to share the item, and a future class in that position
must do the same or callers silently lose their rewrite.

Item default is to share the item.

Item_func, Item_cond and Item_row copy their node and recurse into their
arguments.

Item_func copies an argument that occurs more than once in args[] only once.
Item_bool_rowready_func2, Item_func_case_simple and Item_func_in detach the
comparators and value array they would otherwise share with the original,
as their deep_copy() overrides do. Item_func_interval points its row member
at the copied args[0], which it aliases.

Fields, references, constants, parameters, caches, subqueries, aggregate and
window functions are shared because they don't derive from Item_func.

Some Item_func subclasses cannot safely be copied, so they override
same_select_copy() to share the original instead:

- Functions that own memory or handles, which the copy would free a
  second time in cleanup() or its destructor: the regex functions, UDFs,
  stored functions, the JSON functions that build hashes, VEC_FromText,
  and the geometry functions with Gcalc state.
- Functions that their SELECT_LEX keeps a pointer to, so a copy would not
  be the item the SELECT_LEX uses: MATCH, ROWNUM and Item_equal.
- Functions whose copy would behave differently: RAND would restart its
  random sequence, and SET @var would assign the variable twice.
- TO_NUMBER, which refuses to be copied at all.
- Functions whose arguments point at each other: NULLIF uses args[0] a
  second time as args[2] and hides it from arg_count until cleanup(), and
  Item_in_optimizer's cache belongs to its subquery.

The rewrite now uses same_select_copy_with_checks() and no longer walks the
copy with a cleanup processor.

TABLE::add_splitting_info_for_key_field() uses it too, for the left side of
the equality it pushes into a split-materialized derived table: the item of
the derived table's select list, used in the WHERE condition of the same
select. Its real item is always a column, so the copy is the select list
item itself, where the deep copy made a second Item_field for it. Sharing
one item between the select list and the WHERE clause of a select is
intended here: state that condition processing sets on the item, such as
Item_field::item_equal, describes the same column in the same select. The
equality is fixed when it is injected.

This commit was prepared with Claude Code (Opus 5), which found the
subquery case that lost the rewrite and confirmed that the new test fails
without the change, designed and wrote the same_select_copy() hierarchy
and the list of shared Item_func classes, switched the casefold rewrite to
it, and ran main and the SQL-layer suites in normal and --ps-protocol mode.
Claude Code (Fable 5.1) then reviewed the commit, corrected the commit
message, kept Item_func_case_simple::shallow_copy() protected, added the
Item_func_interval override and the nullptr note, and re-ran the tests.
Razvan-Liviu Varzaru
MDEV-41266 Add missing procps dependency to the server RPM

The RPM packaging declares no dependency on procps, although several
things shipped in MariaDB-server need it:

  - mariadbd-safe runs ps(1): scripts/CMakeLists.txt substitutes
    @FIND_PROC@ into it, and every platform variant of that string is a
    "ps" invocation. mysqld_safe.sh additionally runs "ps xaww" to reap
    hung mariadbd processes before a restart
  - wsrep_sst_common.sh, wsrep_sst_rsync.sh and wsrep_sst_mariabackup.sh
    poll "ps -p $pid" to check whether the SST parent is still alive
  - mysql.server and mini-benchmark use pgrep(1)

rpm's automatic dependency generation only covers ELF sonames, script
interpreters and perl/python modules, so a command invoked inside a
shell script is never picked up. The Debian packaging has declared
procps for mariadb-server all along (debian/control).

procps is part of the base install on RHEL, Fedora and SLES, so this
goes unnoticed on a normal system; it bites in minimal containers and
chroots, where "ps -p $pid" failing because ps is absent is
indistinguishable from "the process is gone".

Declare it on the server package only, mirroring Debian, where
mariadb-server-galera picks it up transitively via its dependency on
mariadb-server. Depend on the file /usr/bin/ps rather than on a package
name, to avoid the procps-ng (Fedora/RHEL) versus procps (SLES)
difference; pgrep comes from the same package.

Co-Authored-By: Claude Opus 5 <[email protected]>
Rex Johnston
MDEV-40012 PQ: let the workers pre-aggregate on a GROUP BY column too wide for an on-disk key

The gate refused a grouped plan with a GROUP BY column too wide to be a
key part, or with a key too long in total, on the grounds that
create_tmp_table() would key the aggregation table by a unique
constraint, a hash of the row with nothing to look a group up in. Since
MDEV-38975 that holds only for a table that starts on disk: a HEAP table
indexes a wide or blob key part, and Create_tmp_table::start() skips the
fallback when it expects HEAP. Such a plan writes through end_update(),
so pwt_plan_group_key() finds its key, and the gate then refused it on
the per-column prediction alone.

Both predictions are now out of the gate. A plan whose aggregation table
starts on disk still has a unique constraint and no end_update()
terminal, and the gate still refuses it, with the reason it already gave
for that shape. Otherwise the containers are built the way the plan's own
table was, and pwt_row_layout::build() checks the finished container for
a group index, with plain rows shipped in place of partials if it has
none.

A worker container with a wide key fills sooner, and a worker that
rebuilds it on disk inside end_update() exposed a fault in how memory
moves between threads. The container's own MEM_ROOT was thread-specific,
so whatever a worker allocated in it was charged to the worker and freed
by the manager. pwt_end_send() moved the charge by bracketing
put_record() and handing the whole change in the worker's
local_memory_used to the manager. But that change also holds memory that
stays with the worker: ha_maria::enable_indexes() allocates its HA_CHECK
from thd->mem_root, the worker's own root, which ~THD frees later on the
worker's thread. With that block counted against the manager, the
worker's counter went negative in ~THD:

  Assertion `(longlong) thd->status_var.local_memory_used >= 0 ||
  !debug_assert_on_not_freed_memory' failed.
    THD::~THD
    destroy_background_thd
    pwt_thread::init_and_run_thread_func

A table one thread writes and another frees is not thread-specific
memory, which is what HA_OPEN_GLOBAL_TMP_TABLE already says to its
engines. Create_tmp_table::start() now gives a cross-thread table a root
without MY_THREAD_SPECIFIC, and with nothing left to hand over, the
hand-over code is removed: the bracket in pwt_end_send(), the same
accounting in pwt_tmp_table_sink::emit_row() and cleanup(), and
account_spilled_memory().

Tests:
- main.parallel_query_why now asks for the on-disk shape
  (tmp_memory_table_size=0), which keeps the unique-constraint reason. At
  the default size the same query runs in the workers.
- main.parallel_query_aggregate shows a VARCHAR(4000) GROUP BY that stays
  in HEAP and pre-aggregates in the workers, with fewer than 1000
  tmp-table writes for 20000 rows and the serial answer. Its note on the
  no-group-index fallback no longer claims a gate refusal for wide keys.
- main.parallel_query_spill shows the same kind of key at a 16M heap
  limit, where the workers rebuild their containers on disk part way
  through. Without the memory change it fails on the assertion above.

A comment that still named accumulate_group(), long since replaced by
end_update(), is corrected too.

This commit was prepared with Claude Code (Opus 5.5), which traced the
changed refusal reason to MDEV-38975, removed the two predictions, found
the negative memory counter with the new spill case and located the
HA_CHECK allocation with an rr recording, moved the container's root off
thread-specific memory, and showed by reverting the memory change on its
own that the new spill case fails on the assertion without it.
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-40012 PQ: refuse a plan that reads a table through a join buffer

A worker has no join buffer. setup_worker_jointabs() stripped the cache off
every worker JOIN_TAB and joined a row at a time, and pwt_table_conds() handed
the worker the buffer's scan filter (cache_select->cond) as well as
select_cond so that it still rejected what the buffer would have. The result
was correct, but it was not the plan the optimizer costed: BNL, BNLH, BKA and
BKAH were chosen for scanning the inner table once per buffer-full of outer
rows, and a worker scanned it once per driving row instead. For a full-scan
inner table that can be orders of magnitude more work than the serial plan
the parallel one is meant to beat.

So the gate now refuses the plan, as the prototype did. The check sits in
can_run_query_in_workers() beside the other per-table refusals, on
tab->cache or tab->use_join_cache, both of which make_join_readinfo() has
settled by the time parallel_join_check() runs in optimize_stage2(). The
refusal names the table in the optimizer trace.

The worker-side handling of a buffered table goes with it:

- pwt_table_conds() becomes pwt_table_cond() and no longer reports
  cache_select->cond. remove_redundant_bnl_scan_conds() only moves conjuncts
  out of select_cond when the tab has a BNL/BNLH cache, so for every tab the
  gate now admits select_cond is already the whole condition. A tab can still
  carry a cache_select without a buffer, because make_join_select() builds the
  scan filter before check_join_cache_usage() decides, but its cond is then a
  copy of conjuncts select_cond still holds. The gate no longer asks whether
  that copy is worker-safe, since no worker evaluates it.
- pwt_clone_table_conds(), which cloned both halves and ANDed them, is gone;
  setup_worker_jointabs() clones the one condition with pwt_clone_rebind().
- setup_worker_jointabs() no longer clears cache, use_join_cache and
  jbuf_tracker on the worker's copy; pwt_assert_tab_inert() asserts that the
  manager's tab has no cache instead. The copy's cache_select is still
  cleared, as it can be set on a tab without a buffer.

parallel_query_join: the BNL case now expects the query to run serially,
with the same rows. The full-scan inner table case (d3) was getting a BNL
buffer under the default join_cache_level, so it runs with
join_cache_level=0 to keep covering a worker-side full scan of an inner
table. parallel_query_why pins the new refusal reason.

This commit was prepared with Claude Code (Opus 5.5), which wrote the gate
check, removed the worker-side join buffer handling it made unreachable,
updated the tests, reconfigured and rebuilt the worktree, and ran the
parallel_query tests in normal and --ps-protocol modes.
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-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.
mariadb-PranavTiwari
MDEV-41151 SF erroneously caches an anchored return data type
Do not keep the result field of a stored function between statements.
Create it again on each fix, so RETURNS TYPE OF is resolved against
the current table definition.
This reverts the caching added by the MDEV-26115 fix. It is safe now
because MDEV-37563 gives each FOR loop instruction its own items.
Rex Johnston
MDEV-40012  Documentation update
Rex Johnston
MDEV-42318 followup for parallel query tests
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-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.
Marko Mäkelä
Merge 13.2 into main
Rex Johnston
MDEV-42318 followup for parallel query tests
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.
Yuchen Pei
MDEV-25848 Call set_optimizer_costs for the hlindex table

This fixes msan uninitialised value failures for MVI
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: 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.
Sergei Petrunia
MDEV-25848: record/replay hlindex records_in_range() in optimizer context

check_quick_select_array() now goes through hook_hl_records_in_range(),
which records or replaces both the row estimate and the cost
(record_hl_records_in_range / infuse_hl_records_in_range). The calls are
stored in a new per-table "hl_records_in_range_calls" array.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Yuchen Pei
MDEV-25848 Returns unrestricted SEL_ARG leaf for mvi_col IS [NOT] NULL

This allows "js IS [NOT] NULL AND <JSON_SARGABLE_PREDICATE on js>" to
use range access of the latter:

Before the change, Item_func_null_predicate::get_mm_leaf returns a
non-NULL SEL_ARG leaf, which cannot be combined with a SEL_ARG_ARRAY
in key_and.

After the change, Item_func_null_predicate::get_mm_leaf returns NULL,
which gives the array's SEL arg when combined in key_and.
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: 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-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 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-39492 PQ: parallel query tests under --view-protocol

The view protocol runs each SELECT as CREATE VIEW mysqltest_tmp_v AS
<query> on mysqltest's utility connection, then SELECT * FROM
mysqltest_tmp_v. Four tests broke on that, none of them because of
parallel query:

- parallel_query_why, parallel_query_firstmatch, parallel_query_join read
  the optimizer trace. Through the view, list_has_optimizer_trace_table()
  sees only the view and not information_schema.optimizer_trace behind
  it, so a read of the trace is itself traced and replaces the trace a
  second read sees. A query with aggregates or LIMIT becomes a
  materialized derived table whose outer SELECT adds refusals of its own
  to $**.parallel_scan_declined_because, and shifts the subquery
  numbering. A merged view drops STRAIGHT_JOIN, so the join order, and
  with it the costing, changes. View protocol is disabled for the whole
  of parallel_query_why, every case of which reads the trace, and around
  the trace sections of the other two.

- parallel_query_session hung. FLUSH STATUS commits implicitly, so after
  SET AUTOCOMMIT=0; START TRANSACTION; FLUSH STATUS mysqltest sees no
  open transaction and wraps the next SELECT in a view; with autocommit
  off that SELECT opens a transaction holding the view's metadata lock,
  and mysqltest's DROP VIEW waits on it. FLUSH STATUS now comes before
  the transaction is started, which also makes the SELECT run inside the
  transaction the test opened, as it intended.

parallel_query_join also checked that a CREATE ... SELECT was chosen for
the workers by reading the trace after it. CREATE TABLE is not a command
the optimizer trace records (sql_command_can_be_traced()), so the check
read the trace of the SELECT before it and proved nothing. It is now an
INSERT ... SELECT, which is traced: chosen by the optimizer, then run
serially because InnoDB declines the locking read
(Parallel_queries_executed 0), with every row inserted.

This commit was prepared with Claude Code (Opus 5.5), which ran the tests
under --view-protocol, traced each difference to its cause with scratch
tests (which statement's trace a read sees, EXPLAIN of a STRAIGHT_JOIN
view, the general log of the hung run), made the test changes, and ran
the parallel_query tests in normal, --ps-protocol and --view-protocol
modes.
Rex Johnston
MDEV-40012 PQ: end a worker's parallel scan before close() frees m_prebuilt

A worker's handler was destroyed with its parallel scan still open.
exec() and scan_only() jump to their exit labels when
parallel_init_worker() fails, and the commonest failure is
HA_ERR_END_OF_FILE: no chunk was left for this worker, which happens all
the time on small tables. InnoDB has allocated m_pscan_worker by then, so
the scan was left for ~ha_innobase() -> parallel_scan_free(), which runs
after close() has freed m_prebuilt. parallel_scan_free() says it drops the
worker without end() for exactly that reason, but ~Parallel_scan_worker()
called end() anyway, and end() writes m_prebuilt->pscan_chunk_clamp: a
heap-use-after-free that ASAN reports on every such worker. In a build
without ASAN the write lands in freed memory, and it is the likely cause of
the intermittent SIGSEGV in free() inside pthread_create() when a later
worker reused a cached thread stack whose DTV had been overwritten.

Three changes close it. Both workers now end the scan at their exit label
instead of after the loop, so every way out ends it while the handler is
still open; ending a scan that was never begun is harmless.
ha_innobase::close() ends any worker or coordinator scan still open before
row_prebuilt_free(), so a path that misses it is ended properly rather than
left for the destructor; with the SQL layer put back as it was, this alone
keeps ASAN clean. And ~Parallel_scan_worker() no longer calls end(), so
parallel_scan_free(), now reached only for a handler destroyed without
close(), cannot write through m_prebuilt either. The close() hook and the
single call site are taken from a patch by a co-worker.

Two debug assertions state the rule the defect broke, so it no longer
takes ASAN to see it. ha_innobase::close() asserts that the SQL layer has
already ended a worker's scan, and parallel_scan_free() asserts that no
worker survives close(). The injection pwt_leave_scan_for_close makes the
SQL layer leave the scan of a worker that holds no cursor -- one handed no
chunk -- for close() to end, so the backstop is exercised on purpose and
the first assertion is told to allow it. pwt_end_worker_scan() holds the
injection and ends the scan at both exit labels.

parallel_query_no_chunk (debug only) runs a full scan and a range scan of a
one-page table with four workers, so three of them get no chunk, twice
each, through the normal and the scan-only path, with and without the
injection, checking the rows and that the workers ran every query. In a
plain debug build, removing the exit-label calls fails the first assertion
and removing the close() backstop fails the second.
~Parallel_scan_worker() no longer calling end() is defence for release
builds and is not reachable while the backstop is there.

This commit was prepared with Claude Code (Opus 5.5), which reproduced the
pthread_create() crash under ASAN and traced it, wrote the fix, folded in
the co-worker's close() hook and single call site, added the debug
assertions, the injection and the test, confirmed in a plain debug build
that the test fails with each of the two fixes removed, and ran the
parallel_query tests in normal and --ps-protocol modes and the main suite
with --parallel-worker-threads=4 under ASAN.
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.
Yuchen Pei
MDEV-25848 bound range optimizer work for many ARRAY index points

With one range slot per ARRAY index, the number of points in a
SEL_ARG_ARRAY is no longer bounded by MAX_KEY, and a JSON_OVERLAPS or
JSON_CONTAINS constant with N elements cost (see the TODOs):

* N records_in_range() index dives, one per leaf, even when the
  estimate is never used;
* O(N^2) work in key_or_array(), which copied both point lists into a
  new SEL_ARG_ARRAY on every OR and deduplicated with a linear scan.

Now:

* key_or_array() appends the smaller point list to the larger
  SEL_ARG_ARRAY in place, or to a copy of it if it is shared
  (use_count > 0), without sorting or deduplicating.
* SEL_ARG_ARRAY::normalize() sorts and deduplicates the points once,
  when they are needed: estimates, quick select, optimizer trace.
* SEL_ARG_ARRAY::estimate() computes rows and cost lazily, on first
  use (key_and() or check_quick_select_array()). With
  eq_range_index_dive_limit or more points it dives on that many
  points spread over the sorted list and extrapolates.
* JSON_CONTAINS skips duplicate elements of the constant and uses at
  most eq_range_index_dive_limit distinct ones for the range, since
  each AND costs a dive and fewer conjuncts give a superset.

Points are now read in sorted order, so the order of rows from an
ARRAY index range scan may differ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

MDEV-25848 deduplicate JSON_OVERLAPS/JSON_CONTAINS elements when parsing

Skip duplicate elements of the constant in json_get_range_elements(),
using a hash on the element's JSON text, instead of in
json_get_func_mm_tree() for JSON_CONTAINS only. Duplicates now never
become Items, SEL_ARG_ARRAY leaves or make_key() calls, for
JSON_OVERLAPS as well, and json_get_func_mm_tree() only counts the
distinct elements against eq_range_index_dive_limit.

The text includes the quotes of strings, so "1" and 1 are different.
Equal values with different text, such as 1 and 1.0, are still
deduplicated later by SEL_ARG_ARRAY::normalize().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rex Johnston
MDEV-40012  Documentation update
Sergei Petrunia
MDEV-25848: record/replay hlindex records_in_range() in optimizer context

check_quick_select_array() now goes through hook_hl_records_in_range(),
which records or replaces both the row estimate and the cost
(record_hl_records_in_range / infuse_hl_records_in_range). The calls are
stored in a new per-table "hl_records_in_range_calls" array.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>