Debian Codegraph @

storage/innobase/ddl/ddl0par-scan.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2020, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file ddl/ddl0par-scan.cc
29 DDL cluster index parallel scan implementation.
30 Created 2020-11-01 by Sunny Bains. */
31
32 #include "ddl0impl-builder.h"
33 #include "ddl0impl-cursor.h"
34 #include "row0pread.h"
35 #include "row0row.h"
36 #include "ut0stage.h"
37
38 #ifdef UNIV_DEBUG
39 #include <current_thd.h>
40 #endif /* UNIV_DEBUG */
41
42 namespace ddl {
43
44 /** Cursor used for parallel reads. */
45 struct Parallel_cursor : public Cursor {
46 /** Constructor.
47 @param[in,out] ctx DDL context. */
48 explicit Parallel_cursor(ddl::Context &ctx) noexcept
49 : Cursor(ctx),
50 m_index(const_cast<dict_index_t *>(m_ctx.index())),
51 m_single_threaded_mode(m_ctx.has_virtual_columns() ||
52 m_ctx.has_fts_indexes()) {}
53
54 /** Destructor. */
55 ~Parallel_cursor() noexcept override = default;
56
57 /** Open the cursor. */
58 void open() noexcept override {}
59
60 /** @return the index being iterated over. */
61 [[nodiscard]] dict_index_t *index() noexcept override { return m_index; }
62
63 /** Reads clustered index of the table and create temporary files
64 containing the index entries for the indexes to be built.
65 @param[in,out] builders Merge buffers to use for reading.
66 @return DB_SUCCESS or error code. */
67 [[nodiscard]] dberr_t scan(Builders &builders) noexcept override;
68
69 /** Copy the row data, by default only the pointers are copied.
70 @param[in] thread_id Scan thread ID.
71 @param[in,out] row Row to copy.
72 @return DB_SUCCESS or error code. */
73 [[nodiscard]] virtual dberr_t copy_row(size_t thread_id,
74 Row &row) noexcept override;
75
76 /** @return true if EOF reached. */
77 [[nodiscard]] virtual bool eof() const noexcept override { return m_eof; }
78
79 private:
80 using Heaps = std::vector<mem_heap_t *, ut::allocator<mem_heap_t *>>;
81
82 /** If true then no more rows to scan. */
83 bool m_eof{};
84
85 /** Heap per thread. */
86 Heaps m_heaps{};
87
88 /** Index to iterate over. */
89 dict_index_t *m_index{};
90
91 /** true if scan should be in single threaded mode. */
92 bool m_single_threaded_mode{};
93 };
94
95 dberr_t Parallel_cursor::scan(Builders &builders) noexcept {
96 ut_a(!builders.empty());
97
98 ut_a(!m_ctx.m_online || m_ctx.m_trx->isolation_level ==
99 trx_t::isolation_level_t::REPEATABLE_READ);
100
101 size_t n_threads{};
102
103 if (!m_single_threaded_mode) {
104 auto use_n_threads = thd_parallel_read_threads(m_ctx.m_trx->mysql_thd);
105
106 if (use_n_threads > 1) {
107 for (auto &builder : builders) {
108 if (builder->is_skip_file_sort() || builder->is_spatial_index()) {
109 /* Note: Parallel scan will break the order. If in the future we
110 decide to force a parallel scan then we will need to force a file
111 sort later. Or, figure out how to "stitch" the lists together after
112 the dumping the rows from the scan. */
113 m_single_threaded_mode = true;
114 break;
115 }
116 }
117
118 if (!m_single_threaded_mode) {
119 /* Check how many threads can actually be allocated. */
120 n_threads = Parallel_reader::available_threads(use_n_threads, false);
121
122 /* May as well do a synchronous read. */
123 if (n_threads == 1) {
124 Parallel_reader::release_threads(n_threads);
125 n_threads = 0;
126 }
127 }
128 }
129 }
130
131 const auto use_n_threads = n_threads == 0 ? 1 : n_threads;
132
133 Builders batch_insert{};
134
135 for (auto &builder : builders) {
136 auto err = builder->init(*this, use_n_threads);
137 if (err != DB_SUCCESS) {
138 return err;
139 }
140
141 if (builder->is_spatial_index()) {
142 batch_insert.push_back(builder);
143 }
144 }
145
146 using Rows = std::vector<Row, ut::allocator<Row>>;
147 using Row_counters = std::vector<size_t, ut::allocator<size_t>>;
148
149 /* Each thread has its own row instance and row count instance. */
150 Rows rows{};
151 Row_counters n_rows{};
152
153 ut_a(m_heaps.empty());
154
155 rows.resize(use_n_threads);
156 n_rows.resize(rows.size());
157
158 /* Delete the per thread heaps. */
159 auto cleanup = [](Heaps &heaps, dberr_t err) {
160 for (auto heap : heaps) {
161 if (heap != nullptr) {
162 mem_heap_free(heap);
163 }
164 }
165 heaps.clear();
166 return err == DB_END_OF_INDEX ? DB_SUCCESS : err;
167 };
168
169 /* Create the per thread heap for transient memory allocations. */
170 for (size_t i = 0; i < use_n_threads; ++i) {
171 m_heaps.push_back(mem_heap_create(1024, UT_LOCATION_HERE));
172
173 if (m_heaps.back() == nullptr) {
174 return cleanup(m_heaps, DB_OUT_OF_MEMORY);
175 }
176
177 if (m_ctx.m_dtuple_heap != nullptr) {
178 rows[i].m_add_cols = m_ctx.create_add_cols();
179 if (rows[i].m_add_cols == nullptr) {
180 return cleanup(m_heaps, DB_OUT_OF_MEMORY);
181 }
182 }
183 }
184
185 Parallel_reader reader{n_threads};
186
187 const Parallel_reader::Scan_range FULL_SCAN;
188
189 using Thread_ctx = Parallel_reader::Thread_ctx;
190
191 auto batch_inserter = [&](Thread_ctx *thread_ctx) {
192 size_t i{};
193 bool latches_released{};
194 dberr_t err{DB_SUCCESS};
195 const auto thread_id = thread_ctx->m_thread_id;
196
197 /* End of page scan. */
198 for (auto builder : batch_insert) {
199 /* Do a batch insert of the cached rows, instead of one by one. */
200 err = builder->batch_insert(thread_id, [&]() {
201 if (!latches_released) {
202 /* We are going to commit the mini-transaction, this will release
203 the latches and so we must do a deep copy of the rows before we
204 can commit the mini-transaction. */
205 for (size_t j = i + 1; j < batch_insert.size(); ++j) {
206 batch_insert[j]->batch_insert_deep_copy_tuples(thread_id);
207 }
208 thread_ctx->save_previous_user_record_as_last_processed();
209 latches_released = true;
210 DEBUG_SYNC_C("ddl_batch_inserter_latches_released");
211 }
212 return DB_SUCCESS;
213 });
214
215 if (err != DB_SUCCESS && err != DB_END_OF_INDEX) {
216 return err;
217 }
218
219 ++i;
220 }
221
222 if (latches_released) {
223 /* Resume from the savepoint (above). */
224 thread_ctx->restore_to_first_unprocessed();
225 }
226
227 return DB_SUCCESS;
228 };
229
230 /* Handle the case when the bulk loader wants to do an mtr commit. The
231 log_free_checks require that the caller can't be holding any latches. */
232 auto bulk_inserter = [&](Thread_ctx *thread_ctx, Row &row) {
233 bool latches_released{};
234 const auto thread_id = thread_ctx->m_thread_id;
235
236 for (auto builder : builders) {
237 const auto err = builder->add_row(*this, row, thread_id, [&]() {
238 if (!latches_released &&
239 thread_ctx->get_state() != Parallel_reader::State::THREAD) {
240 thread_ctx->save_current_user_record_as_last_processed();
241 latches_released = true;
242 DEBUG_SYNC_C("ddl_bulk_inserter_latches_released");
243 }
244 return DB_SUCCESS;
245 });
246
247 if (err != DB_SUCCESS && err != DB_END_OF_INDEX) {
248 return err;
249 }
250 }
251
252 if (latches_released) {
253 ut_a(row.m_ptr != nullptr);
254 /* Resume from the savepoint (above). */
255 thread_ctx->restore_to_last_processed_user_record();
256 }
257
258 return DB_SUCCESS;
259 };
260
261 size_t nr{};
262
263 /* current_thread is a thread local variable. Set current_thd it
264 to the user thread's THD instance so that the debug sync calls
265 will trigger for the spawned threads too. */
266 IF_DEBUG(reader.set_start_callback([&](Thread_ctx *thread_ctx) {
267 if (thread_ctx->get_state() == Parallel_reader::State::THREAD) {
268 current_thd = m_ctx.thd();
269 }
270 return DB_SUCCESS;
271 });)
272
273 /* Called when a thread finishes traversing a page and when it completes. */
274 reader.set_finish_callback([&](Thread_ctx *thread_ctx) {
275 if (reader.is_error_set()) {
276 return reader.get_error_state();
277 }
278
279 dberr_t err{DB_SUCCESS};
280 const auto thread_id = thread_ctx->m_thread_id;
281
282 switch (thread_ctx->get_state()) {
283 case Parallel_reader::State::PAGE:
284 if (!batch_insert.empty()) {
285 err = batch_inserter(thread_ctx);
286 }
287
288 /* Reset the heap. Note: row.m_offsets and row.m_ptr are invalid now. */
289 mem_heap_empty(m_heaps[thread_id]);
290
291 nr += n_rows[thread_id];
292
293 for (auto &builder : builders) {
294 if (builder->stage() != nullptr) {
295 builder->stage()->n_pk_recs_inc(n_rows[thread_id]);
296 builder->stage()->inc(1);
297 }
298 }
299
300 n_rows[thread_id] = 0;
301
302 /* End of page counter. */
303 return err;
304
305 case Parallel_reader::State::THREAD: {
306 ut_a(n_rows[thread_id] == 0);
307
308 /* End of index scan. */
309 auto &row = rows[thread_id];
310
311 row.m_ptr = nullptr;
312
313 m_eof = true;
314
315 return bulk_inserter(thread_ctx, row);
316 }
317
318 case Parallel_reader::State::CTX:
319 return DB_SUCCESS;
320
321 case Parallel_reader::State::UNKNOWN:
322 ut_error;
323 }
324 return DB_ERROR;
325 });
326
327 Parallel_reader::Config config(FULL_SCAN, index());
328
329 /* Called for each row during the scan. */
330 auto err = reader.add_scan(
331 /* Ignore read views for non-online scans. */
332 m_ctx.m_online ? m_ctx.m_trx : nullptr, config,
333 [&](const Parallel_reader::Ctx *read_ctx) {
334 const auto thread_id = read_ctx->thread_id();
335
336 auto &row = rows[thread_id];
337 auto heap = m_heaps[thread_id];
338
339 row.m_rec = read_ctx->m_rec;
340
341 row.m_offsets =
342 rec_get_offsets(row.m_rec, index(), nullptr, ULINT_UNDEFINED,
343 UT_LOCATION_HERE, &heap);
344
345 #ifdef UNIV_DEBUG
346 {
347 const auto rec = row.m_rec;
348 const auto is_comp = dict_table_is_comp(m_ctx.m_old_table);
349
350 ut_ad(!rec_get_deleted_flag(rec, is_comp));
351
352 /* When !online, we are holding a lock on old_table, preventing
353 any inserts that could have written a record 'stub' before
354 writing out off-page columns. */
355 ut_ad(m_ctx.m_online ||
356 !rec_offs_any_null_extern(index(), rec, row.m_offsets));
357 }
358 #endif /* UNIV_DEBUG */
359
360 /* We only need to copy the data when the heap is emptied.
361 @see Parallel_cursor::copy_row */
362 auto err = row.build(m_ctx, m_index, heap, ROW_COPY_POINTERS);
363
364 if (err != DB_SUCCESS) {
365 return err;
366 }
367
368 err = bulk_inserter(read_ctx->thread_ctx(), row);
369
370 ++n_rows[thread_id];
371
372 return err;
373 });
374
375 if (err == DB_SUCCESS) {
376 err = reader.run(n_threads);
377
378 if (err == DB_OUT_OF_RESOURCES) {
379 ut_a(!m_single_threaded_mode);
380
381 ib::warn(ER_INNODB_OUT_OF_RESOURCES)
382 << "Resource not available to create threads for parallel scan."
383 << " Falling back to single thread mode.";
384
385 /* No need to for the extra thread states, release them. */
386 for (auto builder : builders) {
387 builder->fallback_to_single_thread();
388 }
389
390 err = reader.run(0);
391 }
392 }
393
394 /* We completed reading the PK, now we can call its end
395 in order to calculate metrics based on it. */
396 for (auto &builder : builders) {
397 if (builder->stage() != nullptr) {
398 builder->stage()->end_phase_read_pk();
399 }
400 }
401 return cleanup(m_heaps, err);
402 }
403
404 dberr_t Parallel_cursor::copy_row(size_t thread_id, Row &row) noexcept {
405 ut_a(!eof());
406
407 auto heap = m_heaps[thread_id];
408
409 row.m_offsets = rec_get_offsets(row.m_rec, index(), nullptr, ULINT_UNDEFINED,
410 UT_LOCATION_HERE, &heap);
411
412 return row.build(m_ctx, index(), heap, ROW_COPY_DATA);
413 }
414
415 Cursor *Cursor::create_cursor(ddl::Context &ctx) noexcept {
416 return ut::new_withkey<Parallel_cursor>(ut::make_psi_memory_key(mem_key_ddl),
417 ctx);
418 }
419
420 } // namespace ddl