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
support AND/OR ranges over spatial indexes

* remove the code that unconditionally disabled indexes when GEOM_FLAG
  was present on ranges
* instead, treat two spatial ranges as two _separate index scans_,
  unlike normal indexes, two spatial ranges cannot be combined.
  Optimizer later picks one with the better selectivity.
* this means there can be up to MAX_KEY ranges (SEL_TREE) even if the
  table has only one or two indexes - limit all arrays by MAX_KEY, not
  by param->keys.
* the KEY_PART is cloned as needed to create separate spatial ranges
Yuchen Pei
Fix crash caused by incorrectly assigning MULTIPLE to an ARRAY key when adding an index to a table with an existing ARRAY INDEX

Missing ARRAY key type causes hliton to not be assigned in
mysql_prepare_create_table_finalize. This further causes the ARRAY key
not to be placed at the end of the key list, which it should be.

Later in TABLE_SHARE::init_from_binary_frm_image it still assumes the
last key is an hlindex key. When it is not, this non-hlindex last key
has NULL hliton, causing options() to access field of the NULL t
argument passed to it by the caller thus crash.
Sergei Golubchik
cleanup: KEY::type() and KEY::is_hlindex() methods
Marko Mäkelä
MDEV-42354 SET GLOBAL innodb_log_file_size=OFF may break recovery

log_t::set_archive(): Enforce the strictest checkpoint_age_max() limit
before switching to innodb_log_archive=OFF.

Assisted-by: Claude:claude-opus-5-5
Sergei Golubchik
cleanup: is_local_field() -> get_local_field()

removes the need for a separate cast after the check,
and guarantees that the correct item is used as Item_field
(and not something else was mistakenly cast due to a typo)
Yuchen Pei
MDEV-25848 Fix a compiling failure
Sergei Golubchik
fix fulltext.test to break ties (rows with the same relevance)
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]>
Sergei Golubchik
cleanup: move mhnsw behind the hlindex interface

* new hlindex home: sql/index/
* API classes:
  * hlindexton - singleton, global methods. it creates
  * hlindex_share - a physical index (like TABLE_SHARE), it creates
  * hlindex - one index cursor (like handler or TABLE)
* TABLE stores hlindex, TABLE_SHARE stores hlindex_share, no more void*
* move vector_hnsw.h to its new home sql/index, added sql/index/hlindex.h
* MHNSW_Share is stored in mhnsw_share, Search_context in mhnsw_index
* KEY::options() method
Sergei Golubchik
cleanup: remove dead code
Sergei Golubchik
return vector extended metadata
Yuchen Pei
MDEV-25848 Fix a compiling failure
Sergei Golubchik
HA_ERR_NULL_IN_SPATIAL should be ignorable error

index or column that accepts only certain values is like an implicit
CHECK constraint and should behave similarly. It even can be shielded
with, say, `CHECK (length(gis_col)>0)` which will make the error
ignorable. So it should be ignorable without `CHECK` too.
Sergei Golubchik
MDEV-25848 Support for Multi-Valued Indexes

* New type of high-level indexes - JSON ARRAY
* sql/index/json.{h,cc}
  * table structure (value varbinary(255), tref varbinary(N), PK(value,tref))
  * insert/update/delete/search works, search uses keyread
  * on insert json array is parsed, values are inserted
    * prefixed by the type tag, only simple types are supported
  * records_in_range works, but only for equalities (MEMBER OF)
* MySQL-compatible syntax `INDEX ((CAST(col AS type ARRAY)))`, but
  * col is a bare name, not an expression, expressions are part of MDEV-35853
  * type is ignored, not stored, also part of MDEV-35853
  * thus `'[1, 0.2, true, "foo", null]'` works fine, type not enforced
  * thus SHOW CREATE TABLE prints `... AS JSON ARRAY`
* `const MEMBER OF (col)` uses index, via
  * range optimizer, QUICK_RANGE_SELECT_ARRAY
  * Item_func_member_of::get_mm_tree()/etc
Sergei Golubchik
MDEV-25848 Support for Multi-Valued Indexes

* New type of high-level indexes - JSON ARRAY
* sql/index/json.{h,cc}
  * table structure (value varbinary(255), tref varbinary(N), PK(value,tref))
  * insert/update/delete/search works, search uses keyread
  * on insert json array is parsed, values are inserted
    * prefixed by the type tag, only simple types are supported
  * records_in_range works, but only for equalities (MEMBER OF)
* MySQL-compatible syntax `INDEX ((CAST(col AS type ARRAY)))`, but
  * col is a bare name, not an expression, expressions are part of MDEV-35853
  * type is ignored, not stored, also part of MDEV-35853
  * thus `'[1, 0.2, true, "foo", null]'` works fine, type not enforced
  * thus SHOW CREATE TABLE prints `... AS JSON ARRAY`
* `const MEMBER OF (col)` uses index, via
  * range optimizer, QUICK_RANGE_SELECT_ARRAY
  * Item_func_member_of::get_mm_tree()/etc
Sergei Golubchik
MDEV-25848 use xxh3 hash of string values, not actual values

That is, keep 8-byte prefix of the original string value and xxh3
hash of the tail. Prefix keeps strings generally sorted, otherwise
the performance pathologically decreases (compared to btree or
non-hashed variant) when keys are accessed in a predictable order.

Keys that are shorter than 17 bytes are stored as is.

Benchmark: single threaded. 1,000,000 random 256-byte strings.
stored then retrieved. As '["string"]' json and directly
as varchar(256) in a normal btree index.

MyISAM:
* btree 02:07
* json  02:04
* xxh3  01:54

Note that MyISAM prefix compresses keys, which helps to put
a lot more long strings on one page, reducing benefits of short keys.

InnoDB:
* btree 04:51
* json  04:53
* xxh3  03:25
Marko Mäkelä
Merge 13.2 into main
Sergei Golubchik
cleanup: remove obsolete code
Sergei Golubchik
cleanup: extract duplicated no_part_keypart() check
Sergei Golubchik
cleanup: const, spaces, comments
Sergei Golubchik
skip hlindex update if its columns aren't in the write_set
Yuchen Pei
Fix crash caused by incorrectly assigning MULTIPLE to an ARRAY key when adding an index to a table with an existing ARRAY INDEX

Missing ARRAY key type causes hliton to not be assigned in
mysql_prepare_create_table_finalize. This further causes the ARRAY key
not to be placed at the end of the key list, which it should be.

Later in TABLE_SHARE::init_from_binary_frm_image it still assumes the
last key is an hlindex key. When it is not, this non-hlindex last key
has NULL hliton, causing options() to access field of the NULL t
argument passed to it by the caller thus crash.
Yuchen Pei
MDEV-25848 Call set_optimizer_costs for the hlindex table

This fixes msan uninitialised value failures for MVI
Sergei Golubchik
skip hlindex update if its columns aren't in the write_set
Sergei Golubchik
MDEV-25848 use xxh3 hash of string values, not actual values

That is, keep 8-byte prefix of the original string value and xxh3
hash of the tail. Prefix keeps strings generally sorted, otherwise
the performance pathologically decreases (compared to btree or
non-hashed variant) when keys are accessed in a predictable order.

Keys that are shorter than 17 bytes are stored as is.

Benchmark: single threaded. 1,000,000 random 256-byte strings.
stored then retrieved. As '["string"]' json and directly
as varchar(256) in a normal btree index.

MyISAM:
* btree 02:07
* json  02:04
* xxh3  01:54

Note that MyISAM prefix compresses keys, which helps to put
a lot more long strings on one page, reducing benefits of short keys.

InnoDB:
* btree 04:51
* json  04:53
* xxh3  03:25
Thirunarayanan Balathandayuthapani
MDEV-42382 ALTER IGNORE TABLE ADD PRIMARY KEY removes every row of a duplicate group, not just the extra rows

Problem:
========
ALTER IGNORE TABLE ... ALGORITHM=COPY (IGNORE_UNDO mode) keeps only
the latest insert undo log record. When an insert fails,
row_insert_for_mysql() rolls back to savept=0 to remove that
surviving record, assuming it belongs to the failed row.

That holds for a duplicate in a secondary index, which is reported
after the clustered index record and its undo log record were
written. A duplicate in the clustered index is detected before any
undo log record is written for the failed row. The surviving
record then belongs to the previous row, and rolling it back
deletes a row that must be kept.

Solution:
=========
In IGNORE_UNDO mode, row_insert_for_mysql() rolls back to savept=0
only if trx->error_info is not the clustered index. For a
clustered index duplicate nothing is rolled back, because the
failed row left no undo log record.
Yuchen Pei
MDEV-25848 Call set_optimizer_costs for the hlindex table

This fixes msan uninitialised value failures for MVI
Sergei Golubchik
generalize HA_ERR_NULL_IN_SPATIAL

* make it mean "tthe index rejects this field value"
* rename to HA_ERR_BAD_FIELD_VALUE (not user-visible)
* change handler::print_error() to provide a more helpful error message

-Warning 1416 Cannot get geometry object from data you send to the GEOMETRY field
+Warning 1366 Incorrect geometry value: '' for column `test`.`t1`.`b` at row 2

  at least for cases when get_dup_key() returns a valid affected key,
  otherwise fallback to the old error message.
bsrikanth-mariadb
MDEV-38303: Stop scanning early when an 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::having_false_is_final(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_stop_conds() collects such AND-parts of HAVING (at
most 4) at the end of JOIN::make_aggr_tables_info(), in the optimizer.
end_send_group() checks them 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
  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 literal or a cached value. A user variable
  changed by a stored function during the scan is not used.
- 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
- 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.
sjaakola
MDEV-42420 Use two applier threads in tests that pause the applier

Galera periodically delivers a COMMIT_CUT action. It has only a local
seqno and must pass the local monitor in an applier thread. Tests that
paused the only applier of a node, and then waited for a local
transaction on that node to certify or reach a later sync point, could
hang until timeout when a COMMIT_CUT was ordered before the local
transaction. These hangs are sporadic because a COMMIT_CUT comes only
about every 128 transactions.

Fix the affected tests in the same way as galera_sr.mysql-wsrep#215:
set wsrep_slave_threads = 2 on the paused node for the duration of the
test, so the second applier can process the COMMIT_CUT. At the end,
restore the original value and run a DDL from the other node. The
extra applier exits only after it applies a writeset, and that DDL
brings the applier count back down before the next test.

Fixed tests:
  galera.MDEV-29512
  galera.galera_MDEV-29512
  galera.MW-292
  galera.galera_as_slave_replay
  galera.galera_ddl_fk_conflict
  galera.galera_insert_bulk
  galera.galera_savepoint_replay
  galera.galera_sequences_bf_kill
  galera.galera_sequences_bf_kill_sr
  galera.galera_slave_replay
  galera.galera_sp_bf_abort
  galera.galera_transaction_replay
  galera.mysql-wsrep-bugs-607
  galera_sr.MDEV-25717
  galera_sr.galera_sr_bf_abort

In galera.MW-292, also replace the 3 second sleep and the
TIMEDIFF(SYSDATE(), NOW()) < 2 check with two consecutive NOW(6)
reads. A stuck timestamp returns the same value in both, so the test
no longer needs to wait.

Assisted By: Claude Opus 5.5
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
cleanup: change mhnsw_read_first() API to take the value not Item*
Sergei Golubchik
cleanup: remove redundant function
Sergei Golubchik
Tree<> - a typesafe wrapper for TREE
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.

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_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.

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.

maria_backup_log_tail(): Copy the necessary part of the last
ENGINE=Aria log, 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 (some ENGINE=Aria changes)
Co-authored by: Kristian Nielsen (the binlog_storage_engine=innodb part)
Reviewed by: Thirunarayanan Balathandayuthapani (the ENGINE=InnoDB part)
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]>
Sergei Golubchik
JSON data type pre-feature

pretend better that JSON is a proper data type:

* SHOW CREATE shows JSON for LONGTEXT CHARSET utf8mb4_bin
  CHECK(IS_JSON_VALID()) columns.
* CAST(... AS JSON) is accepted (casts to TEXT CHARSET utf8mb4_bin, with
  no real JSON validation)

These two placeholders will be fully correct when MDEV-38740 is pushed.
Marko Mäkelä
MDEV-42350 fixup: innodb_log_recovery_target blocks writes