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
Sergei Golubchik
fixup
Sergei Petrunia
In TABLE::init(), set opt_range_condition_rows=HA_ERR_END_OF_FILE, not 0.

If we neglect to set it, it's better to have very large value.
Setting it to 0 would mean a very optimistic estimate that "we expect
that no rows will match".
Yuchen Pei
MDEV-25848 A JSON column needs CHECK (json_valid(<the column itself>))

dc0b0388e96b983b472c7a347c6f5340ee019198 added a json type, and

CREATE TABLE t1 (
  j json
);

translates to

CREATE TABLE t1 (
  j LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
    CHECK (json_valid(j))
);

The check of the CHECK constraint was too lax: it did not check that
the argument of json_valid was the column itself. In this commit we
fix this hole
Marko Mäkelä
MDEV-39091 BACKUP SERVER of ENGINE=RocksDB

RocksDB is based on log structured merge trees (LSM trees)
that are immutable files. A consistent point-in-time snapshot
is obtained at BACKUP_LOCK_COMMIT cheaply via rdb_create_checkpoint(),
which is also what mariadb-backup is invoking via
SET GLOBAL rocksdb_create_checkpoint.

Under BACKUP_LOCK_COMMIT, a backup snapshot is created in #rocksdb under
rocksdb_datadir (by default, #rocksdb/#rocksdb in the server datadir).
This snapshot will be made available in #rocksdb subdirectory of the
backup target. The default rocksdb_datadir="./#rocksdb" makes restore
transparent: just point datadir to the backup directory or a restored
copy of it.

The transfer of the snapshot is deferred to BACKUP_FINISHED, after the
backup lock has been released, and finally the checkpoint is removed
from rocksdb_datadir.

Co-developed by: Thirunarayanan Balathandayuthapani
Reviewed by: Alessandro Vetere
Assisted-by: Claude:claude-opus-5-5
Alexey Yurchenko
MDEV-42499 don't enclose handlerton members in #ifdef WITH_WSREP

Even if the member is used by wsrep only, the handlerton structure
is shared between embedded server compiled without WITH_WSREP and
plugins compiled normally.
Monty
Removed compiler warning in ha_perfschema.cc
Sergei Petrunia
tmp
bsrikanth-mariadb
MDEV-38303: Address review comments
Sergei Petrunia
Address review input: fix comments.
Monty
MDEV-39938 JSON_TABLE ignores negative indexes and 'last' in paths

The row path and NESTED PATH of JSON_TABLE gave no rows for paths
like $[-1], $[last] and $[1 to last], because
Json_table_nested_path::scan_next() passed no array sizes to
json_path_compare().

Fixed by counting the array sizes during the scan when the path has
negative indexes or 'last', in the same way as JSON_EXTRACT() does.

This also fixes the code from the MDEV-39972 that was only needed
as a temporary workaround for this issue.

Reviewed by: Alexey Botchkov <[email protected]>
Sergei Petrunia
Refactoring: simplify code in estimate_table_group_cardinality()

Should work exactly the same as before.

Do not search in join->join_tab array to find the table by its table_map
bit. Get it from the Item_field object and Field that refers to that table.

(This is preparation for fix for MDEV-37732)
Monty
Updated sql-bench to benchmark json functions

Other things:
- Added compare-result --adjust to compare benchmark with different
  query/row count
- Have different configure options for MySQL and MariaDB
- Use highrest timers for tests for more accurate results
Rucha Deodhar
MDEV-42069: mem_root_dynamic_array_resize_and_set_val does not allow to set
values for fixed-size dynamic arrays

Analysis:
The functions returned failure for any MY_BUFFER_NO_RESIZE array before
checking the index, so in-bounds values were never stored. Callers using
fixed buffers (e.g. ColumnStore via json_normalize) then read unset data
and crashed.

Fix:
Check MY_BUFFER_NO_RESIZE only when the index is beyond max_element, in both
resize_and_set_val and resize_and_get_val.
Alexey Yurchenko
MDEV-42499 don't enclose handlerton members in #ifdef WITH_WSREP

Even if the member is used by wsrep only, the handlerton structure
is shared between embedded server compiled without WITH_WSREP and
plugins compiled normally.
DerZc
MDEV-41091 Avoid MBR-disjoint ranges for exact ST_Disjoint

MBR disjointness is sufficient but not necessary for exact geometric
disjointness. Using an MBR_DISJOINT range for ST_Disjoint can therefore
discard matching geometries whose bounding rectangles overlap.

Distinguish the existing MBR and precise relation classes when building
this range. Keep MBRDisjoint range optimization and decline the unsafe
range for the exact predicate.

MyISAM and Aria reject MBR_DISJOINT range estimates; InnoDB accepts the
range, which explains why the missing rows appear with InnoDB.

Add the regression to main.gis-rt-precise.
Monty
MDEV-39972 Incorrect result of $[last] of JSON

MDEV-40971 JSON Path Array Index 32-bit Integer Truncation Wraparound
( [ 2 3 2 + n ] ≡ [2 3 2+n]≡[n])
MDEV-40986 JSON edit functions' array-index 32-bit wraparound
(edit variant of M4 — modifies the wrong position)

- has_negative_path has to be set for every row. Before, it was only
  set when the path was parsed. If the path argument is a constant,
  c_path->parsed stays set after the first row and the path is not
  parsed again, but we still have to set has_negative_path if needed.
- Setting c_path->p.types_used= JSON_PATH_KEY_NULL in the loop was wrong
  as it reset the JSON_PATH_NEGATIVE_INDEX bit of constant paths. The
  reset is not needed, as json_path_setup() resets it.
- A range with only positive bounds no longer depends on the array sizes.
- Ensure we do not get integer overflow when calculating array indexes in
  json_path_setup(). An index that does not fit in an int is now a path
  syntax error.

Reviewed by: Alexey Botchkov <[email protected]>
bsrikanth-mariadb
MDEV-38303: Stop scan early when aggregate HAVING cannot become true

For a query without GROUP BY, such as

  SELECT COUNT(*) FROM t1 HAVING COUNT(*) < 10

the whole table was read even after the count reached 10 and the
condition could no longer be true.

Add Item_sum::is_having_shortcut_cmp(op, c), which tells whether a
HAVING condition "aggregate op constant", once false, stays false as
more rows are added. Item_sum_count implements it for COUNT(..) < c,
COUNT(..) <= c and COUNT(..) = 0. Other aggregates return false, so
they are read in full as before.

JOIN::setup_having_shortcut_conds() collects such AND-parts of HAVING
in a List at the end of JOIN::make_aggr_tables_info(), in the
optimizer. An error there is returned to the caller. When the list is
not empty, setup_end_select_func() uses check_having_shortcut_conds()
instead of end_send_group(), so other queries pay nothing. It calls
end_send_group(), then checks the conditions after each row and returns
NESTED_LOOP_QUERY_LIMIT, the same way LIMIT stops a scan, once one is
false. The end-of-records step still runs, so HAVING is checked on the
final state.

Only used when it is safe:
- implicit grouping, with no temporary table, ROLLUP, window functions,
  PROCEDURE, loose index scan, optimized-away GROUP BY or correlated
  HAVING
- COUNT(DISTINCT) is excluded, as its value is known only at the end
- the comparison must be numeric. COUNT compared with a DATE is not
  monotonic, so it is not used
- the constant must be a non-NULL numeric literal, a bound PS
  parameter, or a constant expression (5+5, ABS(0)) with no user
  variables, stored functions or subqueries. A user variable changed by
  a stored function during the scan would give a wrong result.
  String constants are not used, as evaluating them for every row
  would raise a warning for every row.
- a NULL result does not stop the scan

Like LIMIT, stopping early means the remaining rows are not read, so
errors and side effects from them no longer happen.

The code is in the new file sql/opt_having_shortcut.cc. Since the
decision is made at optimization time, it is also reported:
- EXPLAIN FORMAT=JSON shows "having_shortcut": true
- tabular EXPLAIN shows "Using having_shortcut" in the Extra column
  of the first table
- the optimizer trace has a "having_shortcut" object with the
  stop_conditions

The plan only says the scan may stop. The tests also cover queries where
the plan shows the shortcut, but the scan is not stopped, or is stopped
late.
Yuchen Pei
MDEV-25848 Fix CHECK check required for a json field type

CREATE TABLE t1 (
  j json
);

translates to

CREATE TABLE t1 (
  j LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
    CHECK (json_valid(j))
);

The check of the CHECK constraint was too lax: it did not check that
the argument of json_valid was the column itself. In this commit we
fix this hole
Marko Mäkelä
MDEV-39091 BACKUP SERVER of ENGINE=RocksDB

RocksDB is based on log structured merge trees (LSM trees)
that are immutable files. A consistent point-in-time snapshot
is obtained at BACKUP_LOCK_COMMIT cheaply via rdb_create_checkpoint(),
which is also what mariadb-backup is invoking via
SET GLOBAL rocksdb_create_checkpoint.

Under BACKUP_LOCK_COMMIT, a backup snapshot is created in #rocksdb under
rocksdb_datadir (by default, #rocksdb/#rocksdb in the server datadir).
This snapshot will be made available in #rocksdb subdirectory of the
backup target. The default rocksdb_datadir="./#rocksdb" makes restore
transparent: just point datadir to the backup directory or a restored
copy of it.

The transfer of the snapshot is deferred to BACKUP_FINISHED, after the
backup lock has been released, and finally the checkpoint is removed
from rocksdb_datadir.

Co-developed by: Thirunarayanan Balathandayuthapani
Reviewed by: Alessandro Vetere
Assisted-by: Claude:claude-opus-5-5
Mohammad Tafzeel Shams
MDEV-39647: Deleted Virtual secondary records might never get purged

Virtual column values are not stored in the clustered index. To check
whether a secondary index record that includes a virtual column can be
purged, row_purge_vc_matches_cluster() and row_vers_build_cur_vrow_low()
read those values from the undo log by invoking
trx_undo_prev_version_build() with TRX_UNDO_PREV_IN_PURGE.

Since MDEV-24402, this read was skipped if purge_sys.end_view saw the
transaction. That happens as soon as a purge batch has ended inside the
undo log of the transaction, even though the remaining undo log records
of the transaction have not been freed. With no values to compare,
row_purge_vc_matches_cluster() assumed a match, row_purge_is_unsafe()
returned true, and the delete-marked secondary index record was never
removed. CHECK TABLE...EXTENDED reported "Clustered index record not
found".

Changes:

- trx_undo_prev_version_build(): For TRX_UNDO_PREV_IN_PURGE, always read
the undo log record, using purge_sys_t::view_guard::PURGE. Only purge
tasks set this flag. The callers never read past the undo log record
being purged, and purge only frees undo log records before purge_sys.head.

- innodb.purge_secondary updates an indexed virtual column several
times in one transaction, with innodb_purge_batch_size=1 so that its
undo log is purged across several batches. CHECK TABLE...EXTENDED
must not report any leftover secondary index records.
Marko Mäkelä
MDEV-14992/MDEV-38362/MDEV-39092 BACKUP SERVER

The following SQL statements will be introduced:

BACKUP SERVER TO '/path/to/directory' [ OPTIONS backup_options ]
BACKUP SERVER WITH 'command' [ OPTIONS backup_options ];

The backup_options is a comma-separated list of the following:
CONCURRENT=1: number of concurrent threads to use
BINLOG=NONE: omit any innodb_storage_engine=innodb files
BINLOG=MINIMAL: include the necessary innodb_storage_engine=innodb files
BINLOG=FULL: include all available innodb_storage_engine=innodb files

In place of the 1, any positive number of threads may be specified.
For the first variant, '/path/to' must exist and '/path/to/directory'
must not exist; that is where the backup will be written to.

In BACKUP SERVER TO, when innodb_undo_directory or binlog_directory
differ from the datadir, the undo* or *.ibb files will be placed
directly in the backup target directory. The user can move them
to the appropriate place after restoring the backup, as appropriate.

For BACKUP SERVER WITH, the string mariadb-backup-
will be prepended to the specified command and quoted.
Path separators or quotes are not allowed in command.
We expect the mariadb-backup-command to be in the
search PATH of the mariadbd process.
For now, we distribute no such script or program;
the user has to write one, something like this:

zstdmt|exec ssh [email protected] "exec cat > $1.tar.zstd"

The standard input of that command will be in a format compatible with
GNU tar --format=oldgnu (and also BSD tar variants that are also part of
Microsoft Windows and Apple macOS). The command is expected to optionally
compress and encrypt the stream and redirect it to a file on a local or
a remote server. The BACKUP SERVER WITH will append an additional argument,
a positive base-ten number in ASCII, starting with 1, to identify the
current thread. In this way, there can be multiple concurrent streams.
The InnoDB write-ahead log will be streamed near the end, because
the stream format requires the file sizes to be declared upfront.

In BACKUP SERVER TO ... OPTIONS CONCURRENT=2 or more, one thread will be
responsible for copying the InnoDB write-ahead log from the beginning
of the backup, running InnoDB_backup::log_track(). Other files will be
copied by other threads.

Note: In single-threaded BACKUP SERVER TO, the parameter
innodb_log_recovery_start that is written out to backup.cnf is
STRICTLY NECESSARY TO AVOID CORRUPTION during recovery! By default,
InnoDB crash recovery starts from the latest available log
checkpoint. However, for restoring a backup, recovery must start from
the checkpoint that was the latest when the backup was
started. Starting recovery from a possible later checkpoint will
result in a corrupted database!

The backup or the first stream will contain a file backup.cnf, which
includes parameters needed for restoring the backup. Currently,
these are innodb_log_recovery_start and innodb_log_recovery_target.
If innodb_log_recovery_target>0, InnoDB will be in read-only mode,
not allowing any writes to persistent files other than via the log
application.

To restore a streaming backup made with BACKUP SERVER WITH, an empty
directory needs to be created and all streams be extracted there using
the standard tar utility of the operating system, optionally after
undoing any encryption or compression that had been added by the
backup command. Then, the backup is prepared or MariaDB server started
up on the extracted directory, similar to as if the BACKUP SERVER TO
statement had been used.

The following will be implemented separately:

MDEV-39061 mariadb-backup compatible wrapper script for BACKUP SERVER
MDEV-40163 Partial backup and restore
MDEV-39091 Back up ENGINE=RocksDB
MDEV-40333 Concurrent DDL for Aria tables in BACKUP SERVER
MDEV-39987 Improve BACKUP SERVER performance for ENGINE=Aria

The implementation introduces a basic multi-threaded driver
Sql_cmd_backup, storage engine interfaces, and basic copying of the
storage engines InnoDB, Aria, MyISAM, MERGE (MyISAM), Archive, CSV.

backup_target: A target directory and a set of operations,
such as backup_target::create_file().
On Microsoft Windows, we must use directory paths because there is
no variant of CopyFileEx() that would work on file handles.

backup_sink: Per-thread storage engine context and output stream,
and a set of operations such as backup_sink::create_file() that
are valid if an output stream exists. The member "id" identifies
the thread, between 0 and CONCURRENT-1.

backup_context: Process-wide BACKUP SERVER context.
Handles the directory traversal and copying of
files for built-in storage engines that do not
implement this backup interface.

backup_target_stage: Wrap backup_context.

backup_target_stage::step(), backup_context::step(): Process a file
from a directory scan, or by invoking handlerton::backup_step().

handlerton::backup_start(), handlerton::backup_end(): Invoked at the
start or end of a backup phase, in the thread that executes a
BACKUP SERVER statement.

handlerton::backup_step(): A backup step that can be invoked from
multiple threads concurrently, between the execution of the corresponding
handlerton::backup_start() and handlerton::backup_end() of the same
phase.

my_clone_file_range(): A wrapper for Linux block-cloning ioctl(2)
FICLONERANGE, which may fail depending on the parameters
and thus require a fallback to my_copy_file_range().

my_allocate_file(): A wrapper for Linux FALLOC_FL_ZERO_RANGE.
This is a best-effort attempt to pre-allocate file space before
invoking my_copy_file_range(). We ignore EINVAL in case the
request is incompatible with the file system block size
(which it likely is for other than block-oriented files).

my_copy_file_range(): A partial or sparse file-copying service.
On FreeBSD, this simply wraps copy_file_range(2).
On Linux, for small files we attempt copy_file_range(2) before
falling back to specialised a pread/pwrite loop, which turned out
to be the fastest way to copy large files. Even though sendfile(2)
would work for copying between files, it as well as
copy_file_range(2) can be much slower than the alternatives.
For large files on Linux, we always invoke a pread/pwrite loop
with special cache control. It is also needed as a fallback,
because the Linux copy_file_range(2) can fail depending on the
file system.

On Windows, my_copy_file_range() is not usable on files that have
been opened for asynchronous I/O, such as InnoDB data files.
Such files have to be copied via backup::copy(), which uses the
native_file_handle wrapper of HANDLE.

my_copy_file(): Copy files between two POSIX file descriptors.
On Microsoft Windows, my_copy() or CopyFileEx() should be used instead.
On Linux, we attempt the ioctl(2) FICLONE before falling back to
my_copy_file_range().

my_copy(): Make use of CopyFileEx() on Microsoft Windows.

my_evict_prepare(), my_evict(): Try to write back and evict
data from the file system cache.

backup::copy(): Wraps my_copy_file_range() or the
Windows native_file_handle based copied outside mysys.

backup::copy_or_stream(): Copy or stream a file.

backup_sink::append(): The streaming streaming equivalent of backup::copy().

backup_sink::append_async(): A variant of backup_sink::append()
where the source file region is guaranteed to be immutable after the
call returns. Zero-copy Linux sendfile(2) is inherently risky for copying
data files that may be modified in place, because it could introduce
a race condition between a page write that runs concurrently with a
child process that is reading the data from the pipe. This could be
improved with io_uring later.

backup_sink::zeropad(): Zero-pad the last tar block if needed.

backup_sink::write(): Write to a stream or a file, with a retry
mechanism in case a partial write occurred.

pread_write(): Allocate a buffer of up to 4 MiB.
This is the "slow path" of copying or streaming files.
For InnoDB data files, BACKUP SERVER TO invokes this on output that
has been opened in unbuffered I/O (O_DIRECT) mode, to avoid polluting
the Linux file system cache (block cache). For the InnoDB log,
regular buffered I/O performed best in our tests.

maria_backup_start(): The entry point for ENGINE=Aria.
Currently, the directory traversal is single-threaded and a memory hog.
This could be improved in MDEV-39987. The Aria log and data file
copying were implemented by Michael 'Monty' Widenius and
Alessandro Vetere.

mariadb_backup_end(): Determine the last written LSN, which must be
included in the backup. For this we invoke the new function
translog_get_end() that adjusts translog_get_horizon() for the case
that the last write completely filled a block.

maria_backup_log_tail(): Copy the necessary part of the last
ENGINE=Aria log until the end LSN, by my_clone_file_range() or
my_copy_file_range().
The copy will be trimmed to the logical end of the backup.
The logic was developed by Alessandro Vetere.

InnoDB_backup::init(): Wait for a possible previous BACKUP SERVER
operation to reach the very end of InnoDB_backup::context::cleanup()
so that the context can be safely reused.

InnoDB_backup::queue: Collection of tablespace IDs and payload sizes
at the start of the backup, and the log_sys.first_lsn of log files
that have to be included in the backup. In the BACKUP_FINISHED stage,
this identifies the binlog_storage_engine=innodb files that are to
be copied. If any data file is created or extended while the backup
is executing, we must have the corresponding write-ahead-log entries
that we are copying since the latest checkpoint that was completed when
the backup started. If any tablespaces are deleted during the backup,
we may or may not copy them, and the application of a FILE_DELETE record
will remove them. Similarly, applying FILE_RENAME or FILE_CREATE records
will rename or create files during recovery as needed.

InnoDB_backup::context::tracked: Log file queue for the dedicated
log-copying task InnoDB_backup::log_track().

innodb_backup_log_tracking(): Determine if log-tracking backup is
active, which blocks concurrent changes of innodb_log_file_buffering
and innodb_log_file_write_through.

log_sys.backup: Whether BACKUP SERVER is in progress. The purpose of this
is to make BACKUP SERVER prevent the concurrent execution of
SET GLOBAL innodb_log_archive=OFF or SET GLOBAL innodb_log_file_size
when innodb_log_archive=OFF.

log_sys.archived_checkpoint: Keep track of the earliest available
checkpoint, corresponding to log_sys.archived_lsn. This reflects
SET GLOBAL innodb_log_recovery_start (which is settable now), for
incremental backup.

fil_system.have_all_spaces: Whether all tablespace metadata is guaranteed
to be known. To speed up startup, InnoDB does not normally open
all tablespace files.

fil_space_t::create_lsn: Change to Atomic_relaxed and use this to
indicate tablespace creation LSN, in addition to indicate undo
tablespace rebuild LSN.

fil_space_t::backup_end: The first page number that is not being backed up
(by default 0, to indicate that no backup is in progress).

fil_space_t::BACKUP_BATCH_SIZE: The number of preceding pages that will be
covered by fil_space_t::backup_end. This is the unit of "page range locking"
during InnoDB backup.

fil_node_t::backup_name: A snapshot of the file name, sampled in
InnoDB_backup::init(). For backing up any files that were created before
the backup start checkpoint LSN, these names will be written to the backup.
On restore, the files will be renamed or deleted as needed, by
applying FILE_RENAME or FILE_DELETE records.

fil_node_t::rename(), fil_node_t::set_backup_name(),
fil_node_t::get_backup_name(), fil_node_t::~fil_node_t(),
fil_node_t::clear_backup_name(): Deal with fil_node_t::backup_name.

buf_page_t::write_fix_try(), buf_page_t::write_unfix_try(): Try to set
or unset a fake "write fix" on a page, to prevent concurrent flush()
during a backup batch. The atomic operations may run concurrently with
set_reinit() and set_freed(). The fake "write fix" does not prevent
any concurrent read or write of the page data in the buffer pool; it
only blocks writes to the underlying data file.

buf_page_t::flush(): Atomically test and set write fix, and
skip the operation if the fake "write fix" was set.

buf_page_t::set_freed(), buf_page_t::set_reinit(): Employ a
compare-and-exchange loop to accommodate for the "write fix".

innodb_backup_batch_wait(): Look up any pages that we are about to
back up. For any dirty pages, invoke buf_page_t::write_fix_try() to
try to set a fake "write fix" lock-free. If the page is currently
write-fixed between buf_page_t::flush() and
buf_page_t::write_complete(), acquire and release a page U-latch to
wait for the conflicting write to complete.

InnoDB_backup::backup_batch_start(),
InnoDB_backup::backup_batch_stop(): Adjust fil_space_t::backup_end and
fake "write fix" of dirty pages to protect the copying of a range of
pages from the underlying file.

InnoDB_backup::commit(): Enqueue the remaining log to be copied.

InnoDB_backup::checkpoint_complete(): If backup is running and
commit() has not been called, add each completed innodb_archive_log=ON
file to the queue. Else, skip or delete, as appropriate.

InnoDB_backup::archive_create(), innodb_backup_archive_create():
Hook for log_t::archive_create().

log_t::backup_start(): If we were running with innodb_log_archive=ON,
ensure that the latest file is a valid recovery starting point.
That is, wait for the latest log checkpoint to be within the file.

buf_flush_list_space(): Check for concurrent backup before writing each
page. This is inefficient, but this function may be invoked from multiple
threads concurrently, and it cannot be changed easily, especially for
fil_crypt_thread().

fil_ibd_create(): Set fil_space_t::create_lsn after the file has been
created.

dict_load_tablespaces(): Determine the size of each file if
upgrade==true. Backup depends on that.

buf_dblwr_t::begin(), buf_dblwr_t::end(), buf_dblwr_t::size():
Accessors to allow BACKUP SERVER to skip the contents of the
doublewrite buffer in the system tablespace. It is only useful for
crash recovery in case a data page had been incompletely written by
the time the server was killed. If the server is killed during a
backup, the backup will be incomplete and unusable anyway.
Furthermore, the page range locking makes page writes and backup
mutually exclusive.

Tested by: Matthias Leich
Tested by: Saahil Alam
Tested by: Rahul Raj
Co-authored by: Michael 'Monty' Widenius (mysys and ENGINE=Aria changes)
Co-authored by: Alessandro Vetere (ENGINE=Aria changes)
Co-authored by: Kristian Nielsen (syntax, binlog_storage_engine=innodb)
Reviewed by: Thirunarayanan Balathandayuthapani (the ENGINE=InnoDB part)
Sergei Petrunia
Introduce TABLE::matching_rows_in_table() and use it in DupsWeedout code
Marko Mäkelä
MDEV-14992/MDEV-38362/MDEV-39092 BACKUP SERVER

The following SQL statements will be introduced:

BACKUP SERVER TO '/path/to/directory' [ OPTIONS backup_options ]
BACKUP SERVER WITH 'command' [ OPTIONS backup_options ];

The backup_options is a comma-separated list of the following:
CONCURRENT=1: number of concurrent threads to use
BINLOG=NONE: omit any innodb_storage_engine=innodb files
BINLOG=MINIMAL: include the necessary innodb_storage_engine=innodb files
BINLOG=FULL: include all available innodb_storage_engine=innodb files

In place of the 1, any positive number of threads may be specified.
For the first variant, '/path/to' must exist and '/path/to/directory'
must not exist; that is where the backup will be written to.

In BACKUP SERVER TO, when innodb_undo_directory or binlog_directory
differ from the datadir, the undo* or *.ibb files will be placed
directly in the backup target directory. The user can move them
to the appropriate place after restoring the backup, as appropriate.

For BACKUP SERVER WITH, the string mariadb-backup-
will be prepended to the specified command and quoted.
Path separators or quotes are not allowed in the user-specified command.
We expect the mariadb-backup-command to be in the
search PATH of the mariadbd process.
For now, we distribute no such script or program;
the user has to write one, containing something like this:

zstdmt|exec ssh [email protected] "exec cat > $1.tar.zstd"

The standard input of that command will be in a format compatible with
GNU tar --format=oldgnu (and also BSD tar variants that are also part of
Microsoft Windows and Apple macOS). The command is expected to optionally
compress and encrypt the stream and redirect it to a file on a local or
a remote server. The BACKUP SERVER WITH will append an additional argument,
a positive base-ten number in ASCII, starting with 1, to identify the
current thread. In this way, there can be multiple concurrent streams.
The InnoDB write-ahead log will be streamed near the end, because
the stream format requires the file sizes to be declared upfront.

In BACKUP SERVER TO ... OPTIONS CONCURRENT=2 or more, one thread will be
responsible for copying the InnoDB write-ahead log from the beginning
of the backup, running InnoDB_backup::log_track(). Other files will be
copied by other threads.

Note: In single-threaded BACKUP SERVER TO, the parameter
innodb_log_recovery_start that is written out to backup.cnf is
STRICTLY NECESSARY TO AVOID CORRUPTION during recovery! By default,
InnoDB crash recovery starts from the latest available log
checkpoint. However, for restoring a backup, recovery must start from
the checkpoint that was the latest when the backup was
started. Starting recovery from a possible later checkpoint will
result in a corrupted database!

The backup or the first stream will contain a file backup.cnf, which
includes parameters needed for restoring the backup. Currently,
these are innodb_log_recovery_start and innodb_log_recovery_target.
If innodb_log_recovery_target>0, InnoDB will be in read-only mode,
not allowing any writes to persistent files other than via the log
application.

To restore a streaming backup made with BACKUP SERVER WITH, an empty
directory needs to be created and all streams be extracted there using
the standard tar utility of the operating system, optionally after
undoing any encryption or compression that had been added by the
backup command. Then, the backup is prepared or MariaDB server started
up on the extracted directory, similar to as if the BACKUP SERVER TO
statement had been used.

The following will be implemented separately:

MDEV-39061 mariadb-backup compatible wrapper script for BACKUP SERVER
MDEV-40163 Partial backup and restore
MDEV-39091 Back up ENGINE=RocksDB
MDEV-40333 Concurrent DDL for Aria tables in BACKUP SERVER
MDEV-39987 Improve BACKUP SERVER performance for ENGINE=Aria

The implementation introduces a basic multi-threaded driver
Sql_cmd_backup, storage engine interfaces, and basic copying of the
storage engines InnoDB, Aria, MyISAM, MERGE (MyISAM), Archive, CSV.

backup_target: A target directory and a set of operations,
such as backup_target::create_file().
On Microsoft Windows, we must use directory paths because there is
no variant of CopyFileEx() that would work on file handles.

backup_sink: Per-thread storage engine context and output stream,
and a set of operations such as backup_sink::create_file() that
are valid if an output stream exists. The member "id" identifies
the thread, between 0 and CONCURRENT-1.

backup_context: Process-wide BACKUP SERVER context.
Handles the directory traversal and copying of
files for built-in storage engines that do not
implement this backup interface.

backup_target_stage: Wrap backup_context.

backup_target_stage::step(), backup_context::step(): Process a file
from a directory scan, or by invoking handlerton::backup_step().

handlerton::backup_start(), handlerton::backup_end(): Invoked at the
start or end of a backup phase, in the thread that executes a
BACKUP SERVER statement.

handlerton::backup_step(): A backup step that can be invoked from
multiple threads concurrently, between the execution of the corresponding
handlerton::backup_start() and handlerton::backup_end() of the same
phase.

my_clone_file_range(): A wrapper for Linux block-cloning ioctl(2)
FICLONERANGE, which may fail depending on the parameters
and thus require a fallback to my_copy_file_range().

my_allocate_file(): A wrapper for Linux FALLOC_FL_ZERO_RANGE.
This is a best-effort attempt to pre-allocate file space before
invoking my_copy_file_range(). We ignore EINVAL in case the
request is incompatible with the file system block size
(which it likely is for other than block-oriented files).

my_copy_file_range(): A partial or sparse file-copying service.
On FreeBSD, this simply wraps copy_file_range(2).
On Linux, for small files we attempt copy_file_range(2) before
falling back to specialised a pread/pwrite loop, which turned out
to be the fastest way to copy large files. Even though sendfile(2)
would work for copying between files, it as well as
copy_file_range(2) can be much slower than the alternatives.
For large files on Linux, we always invoke a pread/pwrite loop
with special cache control. It is also needed as a fallback,
because the Linux copy_file_range(2) can fail depending on the
file system.

On Windows, my_copy_file_range() is not usable on files that have
been opened for asynchronous I/O, such as InnoDB data files.
Such files have to be copied via backup::copy(), which uses the
native_file_handle wrapper of HANDLE.

my_copy_file(): Copy files between two POSIX file descriptors.
On Microsoft Windows, my_copy() or CopyFileEx() should be used instead.
On Linux, we attempt the ioctl(2) FICLONE before falling back to
my_copy_file_range().

my_copy(): Make use of CopyFileEx() on Microsoft Windows.

my_evict_prepare(), my_evict(): Try to write back and evict
data from the file system cache.

backup::copy(): Wraps my_copy_file_range() or the
Windows native_file_handle based copied outside mysys.

backup::copy_or_stream(): Copy or stream a file.

backup_sink::append(): The streaming streaming equivalent of backup::copy().

backup_sink::append_async(): A variant of backup_sink::append()
where the source file region is guaranteed to be immutable after the
call returns. Zero-copy Linux sendfile(2) is inherently risky for copying
data files that may be modified in place, because it could introduce
a race condition between a page write that runs concurrently with a
child process that is reading the data from the pipe. This could be
improved with io_uring later.

backup_sink::zeropad(): Zero-pad the last tar block if needed.

backup_sink::write(): Write to a stream or a file, with a retry
mechanism in case a partial write occurred.

pread_write(): Allocate a buffer of up to 4 MiB.
This is the "slow path" of copying or streaming files.
For InnoDB data files, BACKUP SERVER TO invokes this on output that
has been opened in unbuffered I/O (O_DIRECT) mode, to avoid polluting
the Linux file system cache (block cache). For the InnoDB log,
regular buffered I/O performed best in our tests.

maria_backup_start(): The entry point for ENGINE=Aria.
Currently, the directory traversal is single-threaded and a memory hog.
This could be improved in MDEV-39987. The Aria log and data file
copying were implemented by Michael 'Monty' Widenius and
Alessandro Vetere.

mariadb_backup_end(): Determine the last written LSN, which must be
included in the backup. For this we invoke the new function
translog_get_end() that adjusts translog_get_horizon() for the case
that the last write completely filled a block.

maria_backup_log_tail(): Copy the necessary part of the last
ENGINE=Aria log until the end LSN, by my_clone_file_range() or
my_copy_file_range().
The copy will be trimmed to the logical end of the backup.
The logic was developed by Alessandro Vetere.

InnoDB_backup::init(): Wait for a possible previous BACKUP SERVER
operation to reach the very end of InnoDB_backup::context::cleanup()
so that the context can be safely reused.

InnoDB_backup::queue: Collection of tablespace IDs and payload sizes
at the start of the backup, and the log_sys.first_lsn of log files
that have to be included in the backup. In the BACKUP_FINISHED stage,
this identifies the binlog_storage_engine=innodb files that are to
be copied. If any data file is created or extended while the backup
is executing, we must have the corresponding write-ahead-log entries
that we are copying since the latest checkpoint that was completed when
the backup started. If any tablespaces are deleted during the backup,
we may or may not copy them, and the application of a FILE_DELETE record
will remove them. Similarly, applying FILE_RENAME or FILE_CREATE records
will rename or create files during recovery as needed.

InnoDB_backup::context::tracked: Log file queue for the dedicated
log-copying task InnoDB_backup::log_track().

innodb_backup_log_tracking(): Determine if log-tracking backup is
active, which blocks concurrent changes of innodb_log_file_buffering
and innodb_log_file_write_through.

log_sys.backup: Whether BACKUP SERVER is in progress. The purpose of this
is to make BACKUP SERVER prevent the concurrent execution of
SET GLOBAL innodb_log_archive=OFF or SET GLOBAL innodb_log_file_size
when innodb_log_archive=OFF.

log_sys.archived_checkpoint: Keep track of the earliest available
checkpoint, corresponding to log_sys.archived_lsn. This reflects
SET GLOBAL innodb_log_recovery_start (which is settable now), for
incremental backup.

fil_system.have_all_spaces: Whether all tablespace metadata is guaranteed
to be known. To speed up startup, InnoDB does not normally open
all tablespace files.

fil_space_t::create_lsn: Change to Atomic_relaxed and use this to
indicate tablespace creation LSN, in addition to indicate undo
tablespace rebuild LSN.

fil_space_t::backup_end: The first page number that is not being backed up
(by default 0, to indicate that no backup is in progress).

fil_space_t::BACKUP_BATCH_SIZE: The number of preceding pages that will be
covered by fil_space_t::backup_end. This is the unit of "page range locking"
during InnoDB backup.

fil_node_t::backup_name: A snapshot of the file name, sampled in
InnoDB_backup::init(). For backing up any files that were created before
the backup start checkpoint LSN, these names will be written to the backup.
On restore, the files will be renamed or deleted as needed, by
applying FILE_RENAME or FILE_DELETE records.

fil_node_t::rename(), fil_node_t::set_backup_name(),
fil_node_t::get_backup_name(), fil_node_t::~fil_node_t(),
fil_node_t::clear_backup_name(): Deal with fil_node_t::backup_name.

buf_page_t::write_fix_try(), buf_page_t::write_unfix_try(): Try to set
or unset a fake "write fix" on a page, to prevent concurrent flush()
during a backup batch. The atomic operations may run concurrently with
set_reinit() and set_freed(). The fake "write fix" does not prevent
any concurrent read or write of the page data in the buffer pool; it
only blocks writes to the underlying data file.

buf_page_t::flush(): Atomically test and set write fix, and
skip the operation if the fake "write fix" was set.

buf_page_t::set_freed(), buf_page_t::set_reinit(): Employ a
compare-and-exchange loop to accommodate for the "write fix".

innodb_backup_batch_wait(): Look up any pages that we are about to
back up. For any dirty pages, invoke buf_page_t::write_fix_try() to
try to set a fake "write fix" lock-free. If the page is currently
write-fixed between buf_page_t::flush() and
buf_page_t::write_complete(), acquire and release a page U-latch to
wait for the conflicting write to complete.

InnoDB_backup::backup_batch_start(),
InnoDB_backup::backup_batch_stop(): Adjust fil_space_t::backup_end and
fake "write fix" of dirty pages to protect the copying of a range of
pages from the underlying file.

InnoDB_backup::commit(): Enqueue the remaining log to be copied.

InnoDB_backup::checkpoint_complete(): If backup is running and
commit() has not been called, add each completed innodb_archive_log=ON
file to the queue. Else, skip or delete, as appropriate.

InnoDB_backup::archive_create(), innodb_backup_archive_create():
Hook for log_t::archive_create().

log_t::backup_start(): If we were running with innodb_log_archive=ON,
ensure that the latest file is a valid recovery starting point.
That is, wait for the latest log checkpoint to be within the file.

buf_flush_list_space(): Check for concurrent backup before writing each
page. This is inefficient, but this function may be invoked from multiple
threads concurrently, and it cannot be changed easily, especially for
fil_crypt_thread().

fil_ibd_create(): Set fil_space_t::create_lsn after the file has been
created.

dict_load_tablespaces(): Determine the size of each file if
upgrade==true. Backup depends on that.

buf_dblwr_t::begin(), buf_dblwr_t::end(), buf_dblwr_t::size():
Accessors to allow BACKUP SERVER to skip the contents of the
doublewrite buffer in the system tablespace. It is only useful for
crash recovery in case a data page had been incompletely written by
the time the server was killed. If the server is killed during a
backup, the backup will be incomplete and unusable anyway.
Furthermore, the page range locking makes page writes and backup
mutually exclusive.

Tested by: Matthias Leich
Tested by: Saahil Alam
Tested by: Rahul Raj
Co-authored by: Michael 'Monty' Widenius (mysys and ENGINE=Aria changes)
Co-authored by: Alessandro Vetere (ENGINE=Aria changes)
Co-authored by: Kristian Nielsen (syntax, binlog_storage_engine=innodb)
Reviewed by: Thirunarayanan Balathandayuthapani (the ENGINE=InnoDB part)
Marko Mäkelä
MDEV-39061 mariadb-backup compatible wrapper for BACKUP SERVER

This adds a shell script that lets users keep using their existing
mariadb-backup commands while the real work is done by the new
server-side BACKUP SERVER command. The goal is "drop-in": users
should not have to change their backup scripts.

mariadb-backup-server.sh : Understands the usual mariadb-backup
modes and translates each one.

mbstream-server.sh : lets streamed backups be unpacked by
pipelines that expect the mbstream CLI

mariadb-backup-pipe.sh is the stream sink that
BACKUP SERVER itself runs.

All three are documented in README.md.

--backup
========
Connects with the mariadb client and runs
"BACKUP SERVER TO '<dir>'".

Connection options (--user, --host, --port, --socket,
--defaults-file, ssl, ...) are passed through to the client.

--parallel=N becomes "OPTIONS CONCURRENT=<N+1>": mariadb-backup
runs a dedicated log_copying_thread() besides its N data-copy
threads, while CONCURRENT counts every BACKUP SERVER worker.
The result is clamped to the 1..256 the parser accepts,
and to a minimum of 2.

After the backup it writes backup-prepare.cnf into the backup
directory, recording what --prepare needs later:
  - where mariadbd lives
  - InnoDB parameters (page size, data file path, undo tablespaces,
                      checksum algorithm, log file size)
  - If the server is encrypted then how to reload the
    encryption key plugin (the file_key_management variables),
    so an encrypted backup can be prepared without extra input.
  - every active provider_* compression plugin, with plugin-dir.

The providers matter because --prepare runs "mariadbd --bootstrap
--defaults-file=backup-prepare.cnf", which suppresses the
/etc/my.cnf.d snippet that normally enables a provider. Recovery has
to decompress a PAGE_COMPRESSED page before it can apply redo to it,
so without the provider it aborts with "Unable to apply log to
corrupted page". mariadb-backup carries the same plugins through
backup-my.cnf (encryption_plugin.cc QUERY_PLUGIN collects the
ENCRYPTION plugin and the provider_* DAEMON plugins together), so
this is parity with it rather than a new capability.

--backup --stream
=================
Runs "BACKUP SERVER WITH 'pipe'".
The server only accepts a bare command name, which it resolves
n the PATH of the mariadbd process after prepending mariadb-backup-,
so uses the installed mariadb-backup-pipe instead.

mariadb-backup-pipe writes the tar into
.mariadb-backup-pipe-<stream>.tar, a named pipe the wrapper
created in the server @@datadir and is already draining to
its own stdout.

The backup therefore reaches the consumer as it is produced and
never lands on local disk. The wrapper appends backup-prepare.cnf
as a final tar afterwards; the server's tar carries no
end-of-archive marker, so that trailing archive supplies the
only one and the whole stream extracts with a plain "tar -x".
The trailing archive is written with "tar -b 1" so that nothing
follows its end-of-archive marker. At the default blocking factor tar
pads the archive to 10240 bytes; the reader stops at the marker and
exits with the padding still unwritten, which on a small pipe is a
short write. tar treats a short write as fatal, so a backup that had
in fact completed was reported as failed.

--parallel is ignored here, with a warning.

Four properties follow from how BACKUP SERVER streams,
all differing from mariadb-backup:
- local: the stream command runs inside the server,
so the wrapper must share its filesystem;
- fifo lives in @@datadir, because mariadb-backup-pipe resolves it
relative to the working directory of mariadbd, so --stream needs
write access there;
- tar only: any --stream=<format> yields tar;
- single-threaded: one worker, so no parallel read either.
--target-dir is optional in stream mode;

mbstream-server.sh maps the mbstream CLI onto a plain
"tar -x"/"tar -c", so existing "mbstream -x"/"-c" pipelines
keep working on the wrapper's stream.

mbstream-only flags (-p/--parallel, ...) are accepted and
ignored; any other unknown option is rejected.

Environment overrides:
MARIADB (client),
MARIADBD (the --prepare bootstrap server) and
TAR (the tar implementation, e.g. TAR=bsdtar) can each be overridden.

To run the bootstrap under rr, put it in MARIADBD and
let rr's own _RR_TRACE_DIR choose the trace location, e.g.
  _RR_TRACE_DIR=/dev/shm/rr MARIADBD='rr record mariadbd'

--prepare
=========
Starts "mariadbd --bootstrap" on the backup directory using
backup-prepare.cnf as its defaults file, replays the archived redo
log between the start and target LSN read from backup.cnf,
then builds a fresh ib_logfile0 so a normal server can start
on the directory.

mariadbd is taken from the path recorded in backup-prepare.cnf
if that binary exists, otherwise by searching
/libexec, /sbin, /bin and the configured install directories.

PATH is not searched; set MARIADBD to point elsewhere.
User --defaults-file/-extra-file and encryption options are
layered onto the bootstrap.

--copy-back / --move-back
=========================
Copy or move a prepared backup into the datadir. The datadir
is created if missing, a non-empty datadir is refused unless
--force-non-empty-directories is given, and a chown
reminder is printed.

If --aria-log-dir-path is given, the Aria logs (aria_log_control,
aria_log.*) are relocated into that directory.

Packaging
=========
The wrapper is not installed by default and never replaces the
real mariadb-backup / mbstream binaries.
1. cmake -DWITH_MARIABACKUP_WRAPPER=ON (default OFF) controls it.
2. When ON, the scripts install as /usr/bin/mariadb-backup-server,
/usr/bin/mbstream-server and /usr/bin/mariadb-backup-pipe, tagged
COMPONENT Backup so they ship in the mariadb-backup package.
mariadb-backup-pipe must end up in the PATH of the mariadbd
process, not merely in the PATH of whoever runs the wrapper.
  mariadb-backup-pipe is generated unconditionally, because the
  mariabackup test suite needs it on the server's PATH even when the
  wrapper is not installed; only its install rule is gated.
3. RPM: nothing extra to do. the component handles it.
4. DEB: not wired. debian/rules uses --fail-missing and does not
enable the option, so the -server binaries are not listed.
To ship via DEB, make a paired change: add
-DWITH_MARIABACKUP_WRAPPER=ON in debian/rules and list all three of
usr/bin/mariadb-backup-server, usr/bin/mbstream-server and
usr/bin/mariadb-backup-pipe in debian/mariadb-backup.install together.
5. The real mariadb-backup/mbstream binaries and the
mariabackup symlink are left untouched; opt in via an alias or a
symlink early in PATH.

Limitations (not supported yet)
===============================
1) Incremental backup & prepare (--incremental-basedir,
  --incremental-dir, --apply-log-only)
2) --rollback-xa
3) --binlog (for binlog_storage_engine=innodb)
4) Partial backup (--databases, --tables, --tables-file)
5) Output compression and encryption (--compress, --encrypt)
6) --export is accepted but only warns and runs a plain recovery
7) --extra-lsndir is ignored
8) --parallel is ignored with --stream
9) Windows: POSIX sh only, not installed on Windows

Behaviour differences from native mariadb-backup
================================================
- The wrapper needs the mariadb client on PATH for --backup;
--prepare needs mariadbd recorded in backup-prepare.cnf, in a
standard install directory, or named by MARIADBD
- BACKUP SERVER refuses an already-existing target directory
- BACKUP SERVER does copy the data file as raw pages without
checksum validation, so a corrupted table is not detected
at backup time
- --prepare only works on a wrapper-made backup: it
needs backup-prepare.cnf
- --stream is tar, not xbstream, local-only and single-threaded,
and needs write access to @@datadir for the fifo

Tests
=====
include/have_mariabackup_wrapper.inc redirects $XTRABACKUP to
mariadb-backup-server.sh and $XBSTREAM to mbstream-server.sh,
skipping when a wrapper or the mariadb client is unavailable.

include/have_mariabackup_combination.inc runs a test under both the
[CLIENT] mariadb-backup binary and the [SERVER] wrapper.

suite/mariabackup/suite.pm prepends the directory holding
mariadb-backup-pipe to PATH. BACKUP SERVER resolves the command in the
PATH of the mariadbd process, which mtr starts from the suite's
environment, so it has to be set there rather than with a --let at
--exec time. have_mariabackup_wrapper.inc skips the [SERVER]
combination when the helper is not on PATH.

Co-authored by: Thirunarayanan Balathandayuthapani
Assisted-by: Claude:claude-opus-5-5
Sergei Golubchik
fixup
Sergei Petrunia
In optimize_semijoin_nests(), count selectivity in materialized table size

In optimize_semijoin_nests(), properly count table condition selectivity
when estimating the size of materialized table.

This is preparation for fix for MDEV-37732.

Author: Monty Widenius
Monty
MDEV-26448 CAST(expr AS JSON)

Until we have a true JSON TYPE, the definition of CAST(X to JSON) will be
IDENTICAL to:

IF X IS NULL
  RETURN NULL
ELSE IF X is of type temporal
  RETURN "X"    # Tagged as a JSON OBJECT. This matches MySQL 8.0
ELSE IF JSON_VALID(X)
  RETURN X      # Tagged as JSON object
ELSE
  GIVE_ERROR
FI

Reviewed by: Alexey Botchkov <[email protected]>
Marko Mäkelä
MDEV-39061 mariadb-backup compatible wrapper for BACKUP SERVER

This adds a shell script that lets users keep using their existing
mariadb-backup commands while the real work is done by the new
server-side BACKUP SERVER command. The goal is "drop-in": users
should not have to change their backup scripts.

mariadb-backup-server.sh : Understands the usual mariadb-backup
modes and translates each one.

mbstream-server.sh : lets streamed backups be unpacked by
pipelines that expect the mbstream CLI

mariadb-backup-pipe.sh is the stream sink that
BACKUP SERVER itself runs.

All three are documented in README.md.

--backup
========
Connects with the mariadb client and runs
"BACKUP SERVER TO '<dir>'".

Connection options (--user, --host, --port, --socket,
--defaults-file, ssl, ...) are passed through to the client.

--parallel=N becomes "OPTIONS CONCURRENT=<N+1>": mariadb-backup
runs a dedicated log_copying_thread() besides its N data-copy
threads, while CONCURRENT counts every BACKUP SERVER worker.
The result is clamped to the 1..256 the parser accepts,
and to a minimum of 2.

After the backup it writes backup-prepare.cnf into the backup
directory, recording what --prepare needs later:
  - where mariadbd lives
  - InnoDB parameters (page size, data file path, undo tablespaces,
                      checksum algorithm, log file size)
  - If the server is encrypted then how to reload the
    encryption key plugin (the file_key_management variables),
    so an encrypted backup can be prepared without extra input.
  - every active provider_* compression plugin, with plugin-dir.

The providers matter because --prepare runs "mariadbd --bootstrap
--defaults-file=backup-prepare.cnf", which suppresses the
/etc/my.cnf.d snippet that normally enables a provider. Recovery has
to decompress a PAGE_COMPRESSED page before it can apply redo to it,
so without the provider it aborts with "Unable to apply log to
corrupted page". mariadb-backup carries the same plugins through
backup-my.cnf (encryption_plugin.cc QUERY_PLUGIN collects the
ENCRYPTION plugin and the provider_* DAEMON plugins together), so
this is parity with it rather than a new capability.

--backup --stream
=================
Runs "BACKUP SERVER WITH 'pipe'".
The server only accepts a bare command name, which it resolves
n the PATH of the mariadbd process after prepending mariadb-backup-,
so uses the installed mariadb-backup-pipe instead.

mariadb-backup-pipe writes the tar into
.mariadb-backup-pipe-<stream>.tar, a named pipe the wrapper
created in the server @@datadir and is already draining to
its own stdout.

The backup therefore reaches the consumer as it is produced and
never lands on local disk. The wrapper appends backup-prepare.cnf
as a final tar afterwards; the server's tar carries no
end-of-archive marker, so that trailing archive supplies the
only one and the whole stream extracts with a plain "tar -x".
The trailing archive is written with "tar -b 1" so that nothing
follows its end-of-archive marker. At the default blocking factor tar
pads the archive to 10240 bytes; the reader stops at the marker and
exits with the padding still unwritten, which on a small pipe is a
short write. tar treats a short write as fatal, so a backup that had
in fact completed was reported as failed.

--parallel is ignored here, with a warning.

Four properties follow from how BACKUP SERVER streams,
all differing from mariadb-backup:
- local: the stream command runs inside the server,
so the wrapper must share its filesystem;
- fifo lives in @@datadir, because mariadb-backup-pipe resolves it
relative to the working directory of mariadbd, so --stream needs
write access there;
- tar only: any --stream=<format> yields tar;
- single-threaded: one worker, so no parallel read either.
--target-dir is optional in stream mode;

mbstream-server.sh maps the mbstream CLI onto a plain
"tar -x"/"tar -c", so existing "mbstream -x"/"-c" pipelines
keep working on the wrapper's stream.

mbstream-only flags (-p/--parallel, ...) are accepted and
ignored; any other unknown option is rejected.

Environment overrides:
MARIADB (client),
MARIADBD (the --prepare bootstrap server) and
TAR (the tar implementation, e.g. TAR=bsdtar) can each be overridden.

To run the bootstrap under rr, put it in MARIADBD and
let rr's own _RR_TRACE_DIR choose the trace location, e.g.
  _RR_TRACE_DIR=/dev/shm/rr MARIADBD='rr record mariadbd'

--prepare
=========
Starts "mariadbd --bootstrap" on the backup directory using
backup-prepare.cnf as its defaults file, replays the archived redo
log between the start and target LSN read from backup.cnf,
then builds a fresh ib_logfile0 so a normal server can start
on the directory.

mariadbd is taken from the path recorded in backup-prepare.cnf
if that binary exists, otherwise by searching
/libexec, /sbin, /bin and the configured install directories.

PATH is not searched; set MARIADBD to point elsewhere.
User --defaults-file/-extra-file and encryption options are
layered onto the bootstrap.

--copy-back / --move-back
=========================
Copy or move a prepared backup into the datadir. The datadir
is created if missing, a non-empty datadir is refused unless
--force-non-empty-directories is given, and a chown
reminder is printed.

If --aria-log-dir-path is given, the Aria logs (aria_log_control,
aria_log.*) are relocated into that directory.

Packaging
=========
The wrapper is not installed by default and never replaces the
real mariadb-backup / mbstream binaries.
1. cmake -DWITH_MARIABACKUP_WRAPPER=ON (default OFF) controls it.
2. When ON, the scripts install as /usr/bin/mariadb-backup-server,
/usr/bin/mbstream-server and /usr/bin/mariadb-backup-pipe, tagged
COMPONENT Backup so they ship in the mariadb-backup package.
mariadb-backup-pipe must end up in the PATH of the mariadbd
process, not merely in the PATH of whoever runs the wrapper.
  mariadb-backup-pipe is generated unconditionally, because the
  mariabackup test suite needs it on the server's PATH even when the
  wrapper is not installed; only its install rule is gated.
3. RPM: nothing extra to do. the component handles it.
4. DEB: not wired. debian/rules uses --fail-missing and does not
enable the option, so the -server binaries are not listed.
To ship via DEB, make a paired change: add
-DWITH_MARIABACKUP_WRAPPER=ON in debian/rules and list all three of
usr/bin/mariadb-backup-server, usr/bin/mbstream-server and
usr/bin/mariadb-backup-pipe in debian/mariadb-backup.install together.
5. The real mariadb-backup/mbstream binaries and the
mariabackup symlink are left untouched; opt in via an alias or a
symlink early in PATH.

Limitations (not supported yet)
===============================
1) Incremental backup & prepare (--incremental-basedir,
  --incremental-dir, --apply-log-only)
2) --rollback-xa
3) --binlog (for binlog_storage_engine=innodb)
4) Partial backup (--databases, --tables, --tables-file)
5) Output compression and encryption (--compress, --encrypt)
6) --export is accepted but only warns and runs a plain recovery
7) --extra-lsndir is ignored
8) --parallel is ignored with --stream
9) Windows: POSIX sh only, not installed on Windows

Behaviour differences from native mariadb-backup
================================================
- The wrapper needs the mariadb client on PATH for --backup;
--prepare needs mariadbd recorded in backup-prepare.cnf, in a
standard install directory, or named by MARIADBD
- BACKUP SERVER refuses an already-existing target directory
- BACKUP SERVER does copy the data file as raw pages without
checksum validation, so a corrupted table is not detected
at backup time
- --prepare only works on a wrapper-made backup: it
needs backup-prepare.cnf
- --stream is tar, not xbstream, local-only and single-threaded,
and needs write access to @@datadir for the fifo

Tests
=====
include/have_mariabackup_wrapper.inc redirects $XTRABACKUP to
mariadb-backup-server.sh and $XBSTREAM to mbstream-server.sh,
skipping when a wrapper or the mariadb client is unavailable.

include/have_mariabackup_combination.inc runs a test under both the
[CLIENT] mariadb-backup binary and the [SERVER] wrapper.

suite/mariabackup/suite.pm prepends the directory holding
mariadb-backup-pipe to PATH. BACKUP SERVER resolves the command in the
PATH of the mariadbd process, which mtr starts from the suite's
environment, so it has to be set there rather than with a --let at
--exec time. have_mariabackup_wrapper.inc skips the [SERVER]
combination when the helper is not on PATH.

Co-authored by: Thirunarayanan Balathandayuthapani
Assisted-by: Claude:claude-opus-5-5
Sergei Petrunia
MDEV-37732: TPROC-H, Query 21 is much slower in 11.4 than in 10.11

The problem was in Duplicate_weedout_picker::check_qep(). It computes
updated record_count - the number of record combinations left after the
strategy removes the subquery's duplicates. The logic was incorrect.
Consider EXAMPLE-1:

  select * from t1 where t1.col1 in (select col2 from t2 where corr_cond)

  and the join order of
    t2, full scan rows=1M
    t1, ref access on t1.col1=t2.col2, rows=10

Here, it would compute updated record_count=10, based on #rows in t1's
access method. This number is much smaller than real estimate.

Rewrote the computation logic to use two approaches:

== 1. Use Subquery Fanout ==
Compute "Subquery Fanout" - how many (duplicate) matches the subquery
will generate for a record combination of outer tables. (Like everywhere
else in the code, we assume that any value has a match). For example, for

  ... IN (SELECT o_customer FROM orders WHERE ...)

the Subquery Fanout is average number of orders per one customer.
Then, after Duplicate Elimination is applied, we will have:
  updated_record_count = record_count / subquery_fanout.

Applying this to EXAMPLE-1, one gets:
  if (n_distinct(t2.col2) is known) then
    subquery_fanout= #rows(t2) / n_distinct(t2.col2);
  else
    subquery_fanout= 1.0;
  updated_record_count= 1M * 10 / subquery_fanout;

== 2. Collect fanout of outer tables in the join prefix ==

Done as follows:
  outer_fanout=1.0;
  for each table T in join prefix {
    if (T is not from subquery) {
      // This table's fanout will not be removed
      if (access to T doesn't depend on subquery tables)
        outer_fanout *= T->records_out;
      else
        outer_fanout *= T->table->stat_records() *
                        T->table->cond_selectivity;
    }
  }
  updated_record_count= outer_fanout;

The formula "stat_records()*cond_selectivity" estimates the fanout
that table T would have if it used an "independent" access method.

When we apply this to the join order of EXAMPLE-1:
  t2, full scan rows=1M  -- subquery table, ignore
  t1, ref access on t1.col1=t2.col2, rows=10 -- outer table, but the
access depends on the subquery table, so use
  t1->stat_records() * t1->cond_selectivity.

== Putting it together ==
Both approaches can give poor estimates in different cases, so we pick
the one providing smaller estimate.

The fix is controlled by @@new_mode='FIX_SEMIJOIN_DUPS_WEEDOUT_CHECK'
and is OFF by default in this patch.
bsrikanth-mariadb
MDEV-38303: Address mreview comments

- Do not use the HAVING shortcut when COUNT(..) is compared with a
  string constant using < or <=, not only =. This avoids a
  "Truncated incorrect DECIMAL value" warning for every scanned row.
  The numeric-constant check is now done once in is_aggr_cmp_const().
- Do not use the shortcut with loose index scan (precomputed_group_by).
- EXPLAIN: print "Using having_shortcut" to match JSON and trace, and
  clear the flag after the first table like using_tmp/using_fs.
  Remove the default value of print_explain() using_having_shortcut.
- Fix comments.
- Add tests: string constants with < and <=, IN subquery with a
  cached constant, COUNT(*)=0 with join buffer, and stored procedure
  re-execution.