1
0
mirror of https://github.com/MariaDB/server.git synced 2025-08-07 00:04:31 +03:00

Changing all cost calculation to be given in milliseconds

This makes it easier to compare different costs and also allows
the optimizer to optimizer different storage engines more reliably.

- Added tests/check_costs.pl, a tool to verify optimizer cost calculations.
  - Most engine costs has been found with this program. All steps to
    calculate the new costs are documented in Docs/optimizer_costs.txt

- User optimizer_cost variables are given in microseconds (as individual
  costs can be very small). Internally they are stored in ms.
- Changed DISK_READ_COST (was DISK_SEEK_BASE_COST) from a hard disk cost
  (9 ms) to common SSD cost (400MB/sec).
- Removed cost calculations for hard disks (rotation etc).
- Changed the following handler functions to return IO_AND_CPU_COST.
  This makes it easy to apply different cost modifiers in ha_..time()
  functions for io and cpu costs.
  - scan_time()
  - rnd_pos_time() & rnd_pos_call_time()
  - keyread_time()
- Enhanched keyread_time() to calculate the full cost of reading of a set
  of keys with a given number of ranges and optional number of blocks that
  need to be accessed.
- Removed read_time() as keyread_time() + rnd_pos_time() can do the same
  thing and more.
- Tuned cost for: heap, myisam, Aria, InnoDB, archive and MyRocks.
  Used heap table costs for json_table. The rest are using default engine
  costs.
- Added the following new optimizer variables:
  - optimizer_disk_read_ratio
  - optimizer_disk_read_cost
  - optimizer_key_lookup_cost
  - optimizer_row_lookup_cost
  - optimizer_row_next_find_cost
  - optimizer_scan_cost
- Moved all engine specific cost to OPTIMIZER_COSTS structure.
- Changed costs to use 'records_out' instead of 'records_read' when
  recalculating costs.
- Split optimizer_costs.h to optimizer_costs.h and optimizer_defaults.h.
  This allows one to change costs without having to compile a lot of
  files.
- Updated costs for filter lookup.
- Use a better cost estimate in best_extension_by_limited_search()
  for the sorting cost.
- Fixed previous issues with 'filtered' explain column as we are now
  using 'records_out' (min rows seen for table) to calculate filtering.
  This greatly simplifies the filtering code in
  JOIN_TAB::save_explain_data().

This change caused a lot of queries to be optimized differently than
before, which exposed different issues in the optimizer that needs to
be fixed.  These fixes are in the following commits.  To not have to
change the same test case over and over again, the changes in the test
cases are done in a single commit after all the critical change sets
are done.

InnoDB changes:
- Updated InnoDB to not divide big range cost with 2.
- Added cost for InnoDB (innobase_update_optimizer_costs()).
- Don't mark clustered primary key with HA_KEYREAD_ONLY. This will
  prevent that the optimizer is trying to use index-only scans on
  the clustered key.
- Disabled ha_innobase::scan_time() and ha_innobase::read_time() and
  ha_innobase::rnd_pos_time() as the default engine cost functions now
  works good for InnoDB.

Other things:
- Added  --show-query-costs (\Q) option to mysql.cc to show the query
  cost after each query (good when working with query costs).
- Extended my_getopt with GET_ADJUSTED_VALUE which allows one to adjust
  the value that user is given. This is used to change cost from
  microseconds (user input) to milliseconds (what the server is
  internally using).
- Added include/my_tracker.h  ; Useful include file to quickly test
  costs of a function.
- Use handler::set_table() in all places instead of 'table= arg'.
- Added SHOW_OPTIMIZER_COSTS to sys variables. These are input and
  shown in microseconds for the user but stored as milliseconds.
  This is to make the numbers easier to read for the user (less
  pre-zeros).  Implemented in 'Sys_var_optimizer_cost' class.
- In test_quick_select() do not use index scans if 'no_keyread' is set
  for the table. This is what we do in other places of the server.
- Added THD parameter to Unique::get_use_cost() and
  check_index_intersect_extension() and similar functions to be able
  to provide costs to called functions.
- Changed 'records' to 'rows' in optimizer_trace.
- Write more information to optimizer_trace.
- Added INDEX_BLOCK_FILL_FACTOR_MUL (4) and INDEX_BLOCK_FILL_FACTOR_DIV (3)
  to calculate usage space of keys in b-trees. (Before we used numeric
  constants).
- Removed code that assumed that b-trees has similar costs as binary
  trees. Replaced with engine calls that returns the cost.
- Added Bitmap::find_first_bit()
- Added timings to join_cache for ANALYZE table (patch by Sergei Petrunia).
- Added records_init and records_after_filter to POSITION to remember
  more of what best_access_patch() calculates.
- table_after_join_selectivity() changed to recalculate 'records_out'
  based on the new fields from best_access_patch()

Bug fixes:
- Some queries did not update last_query_cost (was 0). Fixed by moving
  setting thd->...last_query_cost in JOIN::optimize().
- Write '0' as number of rows for const tables with a matching row.

Some internals:
- Engine cost are stored in OPTIMIZER_COSTS structure.  When a
  handlerton is created, we also created a new cost variable for the
  handlerton. We also create a new variable if the user changes a
  optimizer cost for a not yet loaded handlerton either with command
  line arguments or with SET
  @@global.engine.optimizer_cost_variable=xx.
- There are 3 global OPTIMIZER_COSTS variables:
  default_optimizer_costs   The default costs + changes from the
                            command line without an engine specifier.
  heap_optimizer_costs      Heap table costs, used for temporary tables
  tmp_table_optimizer_costs The cost for the default on disk internal
                            temporary table (MyISAM or Aria)
- The engine cost for a table is stored in table_share. To speed up
  accesses the handler has a pointer to this. The cost is copied
  to the table on first access. If one wants to change the cost one
  must first update the global engine cost and then do a FLUSH TABLES.
  This was done to be able to access the costs for an open table
  without any locks.
- When a handlerton is created, the cost are updated the following way:
  See sql/keycaches.cc for details:
  - Use 'default_optimizer_costs' as a base
  - Call hton->update_optimizer_costs() to override with the engines
    default costs.
  - Override the costs that the user has specified for the engine.
  - One handler open, copy the engine cost from handlerton to TABLE_SHARE.
  - Call handler::update_optimizer_costs() to allow the engine to update
    cost for this particular table.
  - There are two costs stored in THD. These are copied to the handler
    when the table is used in a query:
    - optimizer_where_cost
    - optimizer_scan_setup_cost
- Simply code in best_access_path() by storing all cost result in a
  structure. (Idea/Suggestion by Igor)
This commit is contained in:
Monty
2022-08-11 13:05:23 +03:00
committed by Sergei Petrunia
parent 590416e21c
commit b66cdbd1ea
110 changed files with 5373 additions and 1537 deletions

View File

@@ -26,9 +26,9 @@
#endif
#include "sql_const.h"
#include "optimizer_costs.h"
#include "sql_basic_types.h"
#include "mysqld.h" /* server_id */
#include "optimizer_costs.h"
#include "sql_plugin.h" /* plugin_ref, st_plugin_int, plugin */
#include "thr_lock.h" /* thr_lock_type, THR_LOCK_DATA */
#include "sql_cache.h"
@@ -36,6 +36,7 @@
#include "sql_array.h" /* Dynamic_array<> */
#include "mdl.h"
#include "vers_string.h"
#include "optimizer_costs.h"
#include "sql_analyze_stmt.h" // for Exec_time_tracker
@@ -1046,6 +1047,7 @@ enum enum_schema_tables
SCH_KEY_CACHES,
SCH_KEY_COLUMN_USAGE,
SCH_OPEN_TABLES,
SCH_OPTIMIZER_COSTS,
SCH_OPT_TRACE,
SCH_PARAMETERS,
SCH_PARTITIONS,
@@ -1496,6 +1498,10 @@ struct handlerton
/* Called for all storage handlers after ddl recovery is done */
void (*signal_ddl_recovery_done)(handlerton *hton);
/* Called at startup to update default engine costs */
void (*update_optimizer_costs)(OPTIMIZER_COSTS *costs);
void *optimizer_costs; /* Costs are stored here */
/*
Optional clauses in the CREATE/ALTER TABLE
*/
@@ -3085,6 +3091,21 @@ enum class Compare_keys : uint32_t
NotEqual
};
/* Cost for reading a row through an index */
struct INDEX_READ_COST
{
double read_cost;
double index_only_cost;
};
/* Separated costs for IO and CPU. For handler::keyread_time() */
struct IO_AND_CPU_COST
{
double io;
double cpu;
};
/**
The handler class is the interface for dynamically loadable
storage engines. Do not add ifdefs and take care when adding or
@@ -3145,9 +3166,10 @@ protected:
ha_rows estimation_rows_to_insert;
handler *lookup_handler;
public:
handlerton *ht; /* storage engine of this handler */
uchar *ref; /* Pointer to current row */
uchar *dup_ref; /* Pointer to duplicate row */
handlerton *ht; /* storage engine of this handler */
OPTIMIZER_COSTS *costs; /* Points to table->share->costs */
uchar *ref; /* Pointer to current row */
uchar *dup_ref; /* Pointer to duplicate row */
uchar *lookup_buffer;
ha_statistics stats;
@@ -3220,15 +3242,6 @@ public:
ulonglong rows_changed;
/* One bigger than needed to avoid to test if key == MAX_KEY */
ulonglong index_rows_read[MAX_KEY+1];
/*
Cost of using key/record cache: (100-cache_hit_ratio)/100
Updated from THD in open_tables()
*/
double optimizer_cache_cost;
double optimizer_key_next_find_cost;
double optimizer_row_copy_cost, optimizer_key_copy_cost;
double optimizer_where_cost, optimizer_key_cmp_cost;
ha_copy_info copy_info;
private:
@@ -3347,13 +3360,15 @@ private:
For non partitioned handlers this is &TABLE_SHARE::ha_share.
*/
Handler_share **ha_share;
double optimizer_where_cost; // Copy of THD->...optimzer_where_cost
double optimizer_scan_setup_cost; // Copy of THD->...optimzer_scan_...
public:
handler(handlerton *ht_arg, TABLE_SHARE *share_arg)
:table_share(share_arg), table(0),
estimation_rows_to_insert(0),
lookup_handler(this),
ht(ht_arg), ref(0), lookup_buffer(NULL), end_range(NULL),
ht(ht_arg), costs(0), ref(0), lookup_buffer(NULL), end_range(NULL),
implicit_emptied(0),
mark_trx_read_write_done(0),
check_table_binlog_row_based_done(0),
@@ -3364,7 +3379,6 @@ public:
ref_length(sizeof(my_off_t)),
ft_handler(0), inited(NONE), pre_inited(NONE),
pushed_cond(0), next_insert_id(0), insert_id_for_cur_row(0),
optimizer_cache_cost((100-DEFAULT_CACHE_HIT_RATIO)/100.0),
tracker(NULL),
pushed_idx_cond(NULL),
pushed_idx_cond_keyno(MAX_KEY),
@@ -3378,12 +3392,19 @@ public:
m_psi_numrows(0),
m_psi_locker(NULL),
row_logging(0), row_logging_init(0),
m_lock_type(F_UNLCK), ha_share(NULL)
m_lock_type(F_UNLCK), ha_share(NULL), optimizer_where_cost(0),
optimizer_scan_setup_cost(0)
{
DBUG_PRINT("info",
("handler created F_UNLCK %d F_RDLCK %d F_WRLCK %d",
F_UNLCK, F_RDLCK, F_WRLCK));
reset_statistics();
/*
The following variables should be updated in set_optimizer_costs()
which is to be run as part of setting up the table for the query
*/
MEM_UNDEFINED(&optimizer_where_cost, sizeof(optimizer_where_cost));
MEM_UNDEFINED(&optimizer_scan_setup_cost, sizeof(optimizer_scan_setup_cost));
}
virtual ~handler(void)
{
@@ -3584,22 +3605,22 @@ public:
bzero(&copy_info, sizeof(copy_info));
reset_copy_info();
}
virtual void change_table_ptr(TABLE *table_arg, TABLE_SHARE *share)
{
table= table_arg;
table_share= share;
reset_statistics();
}
virtual void change_table_ptr(TABLE *table_arg, TABLE_SHARE *share);
/*
Time for a full table data scan. To be overrided by engines, should not
be used by the sql level.
*/
protected:
virtual double scan_time()
virtual IO_AND_CPU_COST scan_time()
{
return (((ulonglong2double(stats.data_file_length) / stats.block_size)) *
avg_io_cost());
IO_AND_CPU_COST cost;
ulonglong length= stats.data_file_length;
cost.io= (double) (length / IO_SIZE) * avg_io_cost();
cost.cpu= (!stats.block_size ? 0.0 :
(double) ((length + stats.block_size-1)/stats.block_size) *
INDEX_BLOCK_COPY_COST);
return cost;
}
public:
@@ -3615,147 +3636,149 @@ public:
a few rows and the extra cost has no practical effect.
*/
inline double ha_scan_time()
inline double ha_scan_time(ha_rows rows)
{
return (scan_time() * optimizer_cache_cost +
TABLE_SCAN_SETUP_COST * avg_io_cost());
IO_AND_CPU_COST cost= scan_time();
return (cost.io * DISK_READ_RATIO +
cost.cpu + TABLE_SCAN_SETUP_COST +
(double) rows * (ROW_NEXT_FIND_COST + ROW_COPY_COST));
}
/*
Time for a full table scan, fetching the rows from the table and comparing
the row with the where clause
Time for a full table scan, fetching the rows from the table and comparing
the row with the where clause
*/
inline double ha_scan_and_compare_time(ha_rows records)
inline double ha_scan_and_compare_time(ha_rows rows)
{
return (ha_scan_time() +
(double) records * (ROW_COPY_COST + WHERE_COST));
return ha_scan_time(rows) + (double) rows * WHERE_COST;
}
/* Cost of (random) reading a block of IO_SIZE */
virtual double avg_io_cost()
{
return 1.0;
return DISK_READ_COST;
}
/*
Update table->share optimizer costs for this particular table.
Called once when table is opened the first time.
*/
virtual void update_optimizer_costs(OPTIMIZER_COSTS *costs) {}
/*
Set handler optimizer cost variables.
Called for each table used by the statment
This is virtual mainly for the partition engine.
*/
virtual void set_optimizer_costs(THD *thd);
/*
Set cost for finding a row in the engine cache
This allows the handler to override the cost if there is no
caching of rows, like in heap or federatedx.
*/
virtual void set_optimizer_cache_cost(double cost)
{
optimizer_cache_cost= cost;
}
/**
The cost of reading a set of ranges from the table using an index
to access it.
@param index The index number.
@param ranges The number of ranges to be read. If 0, it means that
we calculate separately the cost of reading the key.
@param rows Total number of rows to be read.
This method can be used to calculate the total cost of scanning a table
using an index by calling it using read_time(index, 1, table_size).
This function is to be reimplemented by engines (if needed). The sql_level
should call ha_read_time(), ha_read_and_copy_time() or
ha_read_and_compare_time().
*/
protected:
virtual double read_time(uint index, uint ranges, ha_rows rows)
/*
Cost of reading 'rows' number of rows with a rowid
*/
virtual IO_AND_CPU_COST rnd_pos_time(ha_rows rows)
{
return ((rows2double(rows) * ROW_LOOKUP_COST +
rows2double(ranges) * KEY_LOOKUP_COST) * avg_io_cost());
double r= rows2double(rows);
return
{
r * avg_io_cost() * stats.block_size/IO_SIZE, // Blocks read
r * INDEX_BLOCK_COPY_COST // Copy block from cache
};
}
public:
/* Same as above, but take into account CACHE_COST */
inline double ha_read_time(uint index, uint ranges, ha_rows rows)
{
return read_time(index, ranges, rows) * optimizer_cache_cost;
}
/* Same as above, but take into account also copying of the row to 'record' */
inline double ha_read_and_copy_time(uint index, uint ranges, ha_rows rows)
{
return (ha_read_time(index, ranges, rows) +
rows2double(rows) * ROW_COPY_COST);
}
/* Same as above, but take into account also copying and comparing the row */
inline double ha_read_and_compare_time(uint index, uint ranges, ha_rows rows)
{
return (ha_read_time(index, ranges, rows) +
rows2double(rows) * (ROW_COPY_COST + WHERE_COST));
}
/* Cost of reading a row with rowid */
protected:
virtual double rnd_pos_time(ha_rows rows)
{
return rows2double(rows) * ROW_LOOKUP_COST * avg_io_cost();
}
public:
/*
Same as above, but take into account cache_cost and copying of the row
to 'record'.
Note that this should normally be same as ha_read_time(some_key, 0, rows)
Time for doing and internal rnd_pos() inside the engine. For some
engine, this is more efficient than the SQL layer calling
rnd_pos() as there is no overhead in converting/checking the
rnd_pos_value. This is used when calculating the cost of fetching
a key+row in one go (like when scanning an index and fetching the
row).
*/
inline double ha_rnd_pos_time(ha_rows rows)
{
return (rnd_pos_time(rows) * optimizer_cache_cost +
rows2double(rows) * ROW_COPY_COST);
IO_AND_CPU_COST cost= rnd_pos_time(rows);
return (cost.io * DISK_READ_RATIO +
cost.cpu + rows2double(rows) * (ROW_LOOKUP_COST + ROW_COPY_COST));
}
/*
This cost if when we are calling rnd_pos() explict in the call
For the moment this function is identical to ha_rnd_pos time,
but that may change in the future after we do more cost checks for
more engines.
*/
inline double ha_rnd_pos_call_time(ha_rows rows)
{
IO_AND_CPU_COST cost= rnd_pos_time(rows);
return (cost.io * DISK_READ_RATIO +
cost.cpu + rows2double(rows) * (ROW_LOOKUP_COST + ROW_COPY_COST));
}
inline double ha_rnd_pos_call_and_compare_time(ha_rows rows)
{
return (ha_rnd_pos_call_time(rows) + rows2double(rows) * WHERE_COST);
}
/**
Calculate cost of 'index_only' scan for given index and number of records.
Calculate cost of 'index_only' scan for given index, a number of reanges
and number of records.
@param index Index to read
@param flag If flag == 1 then the function returns the cost of
index only scan by index 'index' of one range containing
'rows' key entries.
If flag == 0 then function returns only the cost of copying
those key entries into the engine buffers.
@param rows #of records to read
@param index Index to read
@param rows #of records to read
@param blocks Number of IO blocks that needs to be accessed.
0 if not known (in which case it's calculated)
*/
protected:
virtual double keyread_time(uint index, uint flag, ha_rows rows);
virtual IO_AND_CPU_COST keyread_time(uint index, ulong ranges, ha_rows rows,
ulonglong blocks);
public:
/*
Calculate cost of 'keyread' scan for given index and number of records
including fetching the key to the 'record' buffer.
*/
inline double ha_keyread_time(uint index, uint flag, ha_rows rows)
{
return (keyread_time(index, flag, rows) * optimizer_cache_cost);
}
double ha_keyread_time(uint index, ulong ranges, ha_rows rows,
ulonglong blocks);
/* Same as above, but take into account copying the key the the SQL layer */
inline double ha_keyread_and_copy_time(uint index, uint flag, ha_rows rows)
inline double ha_keyread_and_copy_time(uint index, ulong ranges,
ha_rows rows, ulonglong blocks)
{
return ha_keyread_time(index, flag, rows) + (double) rows * KEY_COPY_COST;
return (ha_keyread_time(index, ranges, rows, blocks) +
(double) rows * KEY_COPY_COST);
}
inline double ha_keyread_and_compare_time(uint index, ulong ranges,
ha_rows rows, ulonglong blocks)
{
return (ha_keyread_time(index, ranges, rows, blocks) +
(double) rows * (KEY_COPY_COST + WHERE_COST));
}
double ha_keyread_clustered_and_copy_time(uint index, ulong ranges,
ha_rows rows,
ulonglong blocks);
/*
Time for a full table index scan (without copy or compare cost).
To be overrided by engines, sql level should use ha_key_scan_time().
Note that IO_AND_CPU_COST does not include avg_io_cost() !
*/
protected:
virtual double key_scan_time(uint index)
virtual IO_AND_CPU_COST key_scan_time(uint index, ha_rows rows)
{
return keyread_time(index, 1, records());
return keyread_time(index, 1, MY_MAX(rows, 1), 0);
}
public:
/* Cost of doing a full index scan */
inline double ha_key_scan_time(uint index)
inline double ha_key_scan_time(uint index, ha_rows rows)
{
return (key_scan_time(index) * optimizer_cache_cost);
IO_AND_CPU_COST cost= key_scan_time(index, rows);
return (cost.io * DISK_READ_RATIO +
cost.cpu + INDEX_SCAN_SETUP_COST + KEY_LOOKUP_COST +
(double) rows * (KEY_NEXT_FIND_COST + KEY_COPY_COST));
}
/*
@@ -3764,8 +3787,7 @@ public:
*/
inline double ha_key_scan_and_compare_time(uint index, ha_rows rows)
{
return (ha_key_scan_time(index) +
(double) rows * (KEY_COPY_COST + WHERE_COST));
return ha_key_scan_time(index, rows) + (double) rows * WHERE_COST;
}
virtual const key_map *keys_to_use_for_scanning() { return &key_map_empty; }
@@ -5218,7 +5240,7 @@ public:
ha_share= arg_ha_share;
return false;
}
void set_table(TABLE* table_arg) { table= table_arg; }
inline void set_table(TABLE* table_arg);
int get_lock_type() const { return m_lock_type; }
public:
/* XXX to be removed, see ha_partition::partition_ht() */
@@ -5292,7 +5314,7 @@ protected:
void unlock_shared_ha_data();
/*
Mroonga needs to call read_time() directly for it's internal handler
Mroonga needs to call some xxx_time() directly for it's internal handler
methods
*/
friend class ha_mroonga;