Debian Codegraph @

storage/innobase/ddl/ddl0merge.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/ddl0merge.cc
29 DDL merge sort implementation.
30 Created 2020-11-01 by Sunny Bains. */
31
32 #include "ddl0impl-buffer.h"
33 #include "ddl0impl-builder.h"
34 #include "ddl0impl-merge.h"
35 #include "trx0trx.h"
36 #include "ut0stage.h"
37
38 namespace ddl {
39
40 /** Cursor for merging blocks from the same file. */
41 struct Merge_file_sort::Cursor : private ut::Non_copyable {
42 /** Constructor.
43 @param[in,out] builder Index builder instance.
44 @param[in] file File to iterate over.
45 @param[in,out] dup For reporting duplicates.
46 @param[in,out] stage PFS staging. */
47 Cursor(Builder *builder, file_t *file, Dup *dup, Alter_stage *stage) noexcept
48 : m_file(file), m_cursor(builder, dup, stage) {
49 ut_a(m_file->m_size > 0);
50 ut_a(m_file->m_n_recs > 0);
51 #ifdef POSIX_FADV_SEQUENTIAL
52 /* The input file will be read sequentially, starting from the
53 beginning and the middle. In Linux, the POSIX_FADV_SEQUENTIAL
54 affects the entire file. Each block will be read exactly once. */
55 {
56 const auto flags = POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE;
57 posix_fadvise(m_file->m_file.get(), 0, 0, flags);
58 }
59 #endif /* POSIX_FADV_SEQUENTIAL */
60 }
61
62 /** Prepare the cursor for reading.
63 @param[in] ranges Ranges to merge in a pass.
64 @param[in] buffer_size IO Buffer size to use for reading.
65 @return DB_SUCCESS or error code. */
66 [[nodiscard]] dberr_t prepare(const Ranges &ranges,
67 size_t buffer_size) noexcept;
68
69 /** Fetch the next record.
70 @param[out] mrec Row read from the file.
71 @param[out] offsets Column offsets inside mrec.
72 @return DB_SUCCESS or error code. */
73 [[nodiscard]] dberr_t fetch(const mrec_t *&mrec, ulint *&offsets) noexcept;
74
75 /** Move to the next record.
76 @return DB_SUCCESS, DB_END_OF_INDEX or error code. */
77 [[nodiscard]] dberr_t next() noexcept;
78
79 /** Move the cursor to the start of the new records lists to merge.
80 @param[in] range Seek to these offsets.
81 @return DB_SUCCESS or error code. */
82 [[nodiscard]] dberr_t seek(const Ranges &range) noexcept;
83
84 /** @return the number of active readers. */
85 [[nodiscard]] size_t size() const noexcept { return m_cursor.size(); }
86
87 private:
88 /** File to iterate over. */
89 file_t *m_file{};
90
91 /** Cursor to use for the merge. */
92 Merge_cursor m_cursor;
93 };
94
95 /** For writing out the merged rows. */
96 struct Merge_file_sort::Output_file : private ut::Non_copyable {
97 /** The transaction interrupted check is expensive, we check after this
98 many page writes. */
99 static constexpr uint64_t TRX_INTERRUPTED_CHECK = 64;
100
101 /** Constructor.
102 @param[in,out] ctx DDL context.
103 @param[in] file File to write to.
104 @param[in] io_buffer Buffer to store records and write to file. */
105 Output_file(ddl::Context &ctx, const Unique_os_file_descriptor &file,
106 IO_buffer io_buffer) noexcept
107 : m_ctx(ctx), m_file(file), m_buffer(io_buffer), m_ptr(m_buffer.first) {}
108
109 /** Destructor. */
110 ~Output_file() = default;
111
112 /** Initialize the duplicate check infrastructure.
113 @param[in] index DDL index. */
114 void init(const dict_index_t *index) noexcept {
115 const auto n_fields = dict_index_get_n_fields(index);
116 const auto i = 1 + REC_OFFS_HEADER_SIZE + n_fields;
117
118 ut_a(m_offsets.empty());
119
120 m_offsets.resize(i);
121
122 m_offsets[0] = i;
123 m_offsets[1] = n_fields;
124 }
125
126 /** Write the row to the buffer. If the buffer fills up write the
127 buffer to the output file.
128 @param[in] mrec Row to write.
129 @param[in] offsets Column offsets in row.
130 @param[in,out] dup For duplicate checks.
131 @return DB_SUCCESS or error code. */
132 [[nodiscard]] dberr_t write(const mrec_t *mrec, const ulint *offsets,
133 Dup *dup) noexcept;
134
135 /** Write end of block marker and flush buffer to disk.
136 @return DB_SUCCESS or error code. */
137 [[nodiscard]] dberr_t flush() noexcept;
138
139 /** @return the current size of the output file in bytes. */
140 [[nodiscard]] os_offset_t get_size() const { return m_offset; }
141
142 /** @return number of rows in the output file. */
143 [[nodiscard]] uint64_t get_n_rows() const noexcept { return m_n_rows; }
144
145 private:
146 /** @return the number of bytes copied so far. */
147 [[nodiscard]] size_t copied() const noexcept {
148 return std::ptrdiff_t(m_ptr - m_buffer.first);
149 }
150
151 /** Do a duplicate check against the incoming record.
152 @param[in] mrec Row to write.
153 @param[in] offsets Column offsets in row.
154 @param[in,out] dup For duplicate checks. */
155 void duplicate_check(const mrec_t *mrec, const ulint *offsets,
156 Dup *dup) noexcept;
157
158 private:
159 /** Limit is [start, end]. */
160 using Offsets = std::vector<ulint, ut::allocator<ulint>>;
161
162 /** DDL context. */
163 ddl::Context &m_ctx;
164
165 /** File to write to. */
166 const Unique_os_file_descriptor &m_file;
167
168 /** Buffer to write to (output buffer). */
169 IO_buffer m_buffer;
170
171 /** Start writing new bytes at this offset. */
172 byte *m_ptr{};
173
174 /** Total number of bytes written. */
175 os_offset_t m_offset{};
176
177 /** Offsets of the last inserted row. */
178 Offsets m_offsets{};
179
180 /** Pointer to last record in the output buffer. */
181 mrec_t *m_last_mrec{};
182
183 /** Number of rows read/written. */
184 uint64_t m_n_rows{};
185
186 /** Counter for checking trx_is_interrupted. */
187 uint64_t m_interrupt_check{};
188 };
189
190 dberr_t Merge_file_sort::Cursor::prepare(const Ranges &ranges,
191 size_t buffer_size) noexcept {
192 for (size_t i = 0; i < ranges.size() - 1; ++i) {
193 if (const auto err =
194 m_cursor.add_file(*m_file, buffer_size, {ranges[i], ranges[i + 1]});
195 err != DB_SUCCESS && err != DB_END_OF_INDEX) {
196 return err;
197 }
198 }
199 return m_cursor.open();
200 }
201
202 dberr_t Merge_file_sort::Cursor::fetch(const mrec_t *&mrec,
203 ulint *&offsets) noexcept {
204 return m_cursor.fetch(mrec, offsets);
205 }
206
207 dberr_t Merge_file_sort::Cursor::next() noexcept { return m_cursor.next(); }
208
209 dberr_t Merge_file_sort::Cursor::seek(const Ranges &ranges) noexcept {
210 auto file_readers = m_cursor.file_readers();
211 ut_a(file_readers.size() == N_WAY_MERGE);
212 ut_a(ranges.size() == N_WAY_MERGE + 1);
213
214 dberr_t err{DB_ERROR_UNSET};
215 bool can_seek = false;
216
217 for (size_t i = 0; i < ranges.size() - 1; ++i) {
218 if (ranges[i] == m_file->m_size) {
219 err = DB_END_OF_INDEX;
220 } else {
221 err = file_readers[i]->read({ranges[i], ranges[i + 1]});
222 if (err == DB_SUCCESS) {
223 can_seek = true;
224 }
225 }
226 }
227
228 if (can_seek) {
229 m_cursor.clear_eof();
230 err = DB_SUCCESS;
231 }
232
233 return err;
234 }
235
236 void Merge_file_sort::Output_file::duplicate_check(const mrec_t *mrec,
237 const ulint *offsets,
238 Dup *dup) noexcept {
239 if (m_offsets.empty()) {
240 const auto n_fields = dict_index_get_n_fields(dup->m_index);
241 const auto n = 1 + REC_OFFS_HEADER_SIZE + n_fields;
242
243 m_offsets.resize(n);
244
245 m_offsets[0] = n;
246 m_offsets[1] = n_fields;
247
248 } else if (m_last_mrec != nullptr && m_offsets[2] != 0) {
249 auto last_mrec = m_last_mrec;
250 size_t extra_size = *last_mrec++;
251
252 if (extra_size >= 0x80) {
253 extra_size = (extra_size & 0x7f) << 8;
254 extra_size |= *last_mrec++;
255 }
256
257 /* Normalize extra_size. Above, value 0 signals "end of list". */
258 --extra_size;
259
260 last_mrec += extra_size;
261
262 auto cmp = cmp_rec_rec_simple(mrec, last_mrec, offsets, &m_offsets[0],
263 dup->m_index, dup->m_table);
264
265 if (cmp <= 0) {
266 ut_a(cmp == 0);
267 dup->report(mrec, offsets);
268 }
269 }
270
271 memcpy(&m_offsets[2], &offsets[2], (m_offsets.size() - 2) * sizeof(*offsets));
272 }
273
274 dberr_t Merge_file_sort::Output_file::write(const mrec_t *mrec,
275 const ulint *offsets,
276 Dup *dup) noexcept {
277 if (unlikely(dup != nullptr)) {
278 duplicate_check(mrec, offsets, dup);
279 }
280
281 ++m_n_rows;
282
283 size_t need;
284 char prefix[sizeof(uint16_t)];
285
286 /* Normalize extra_size. Value 0 signals "end of list". */
287 const auto extra_size = rec_offs_extra_size(offsets);
288 const auto nes = extra_size + 1;
289
290 if (likely(nes < 0x80)) {
291 need = 1;
292 prefix[0] = (byte)nes;
293 } else {
294 need = 2;
295 prefix[0] = (byte)(0x80 | (nes >> 8));
296 prefix[1] = (byte)nes;
297 }
298
299 const auto rec_size = extra_size + rec_offs_data_size(offsets);
300 ut_ad(rec_size == rec_offs_size(offsets));
301
302 if (unlikely(m_ptr + rec_size + need >= m_buffer.first + m_buffer.second)) {
303 const size_t n_write = m_ptr - m_buffer.first;
304 const auto len = ut_uint64_align_down(n_write, IO_BLOCK_SIZE);
305 if (len != 0) {
306 auto err = ddl::pwrite(m_file.get(), m_buffer.first, len, m_offset);
307
308 if (err != DB_SUCCESS) {
309 return err;
310 }
311
312 ut_a(n_write >= len);
313 const auto n_move = n_write - len;
314
315 m_ptr = m_buffer.first;
316 memmove(m_ptr, m_ptr + len, n_move);
317 m_ptr += n_move;
318
319 m_offset += len;
320 }
321
322 if (unlikely(m_ptr + rec_size + need >= m_buffer.first + m_buffer.second)) {
323 // Should be caught earlier
324 ut_d(ut_error);
325 ut_o(return DB_TOO_BIG_RECORD);
326 }
327 }
328
329 m_last_mrec = m_ptr;
330
331 memcpy(m_ptr, prefix, need);
332 m_ptr += need;
333
334 ut_a(m_ptr + rec_size <= m_buffer.first + m_buffer.second);
335
336 memcpy(m_ptr, mrec - extra_size, rec_size);
337 m_ptr += rec_size;
338
339 return DB_SUCCESS;
340 }
341
342 dberr_t Merge_file_sort::Output_file::flush() noexcept {
343 /* There must always be room to write the end of list marker. */
344 ut_a(copied() < m_buffer.second);
345
346 /* End of the block marker */
347 *m_ptr++ = 0;
348
349 /* Reset the duplicate checks because we are going to start merging
350 a new range after the flush. */
351 m_last_mrec = nullptr;
352
353 if (!m_offsets.empty()) {
354 memset(&m_offsets[2], 0x0, (m_offsets.size() - 2) * sizeof(m_offsets[0]));
355 }
356
357 const auto len = ut_uint64_align_up(m_ptr - m_buffer.first, IO_BLOCK_SIZE);
358 const auto err = ddl::pwrite(m_file.get(), m_buffer.first, len, m_offset);
359
360 m_offset += len;
361
362 /* Start writing the next page from the start. */
363 m_ptr = m_buffer.first;
364
365 #ifdef UNIV_DEBUG
366 if (Sync_point::enabled(m_ctx.thd(), "ddl_merge_sort_interrupt")) {
367 ut_a(err == DB_SUCCESS);
368 m_interrupt_check = TRX_INTERRUPTED_CHECK;
369 }
370 #endif
371
372 if (err == DB_SUCCESS && !(m_interrupt_check++ % TRX_INTERRUPTED_CHECK) &&
373 m_ctx.is_interrupted()) {
374 return DB_INTERRUPTED;
375 } else {
376 return err;
377 }
378 }
379
380 Merge_file_sort::Ranges Merge_file_sort::next_ranges(
381 Merge_offsets &offsets) noexcept {
382 Ranges ranges(N_WAY_MERGE + 1, m_merge_ctx->m_file->m_size);
383 for (size_t i = 0; i < N_WAY_MERGE; i++) {
384 if (!offsets.empty()) {
385 ranges[i] = offsets.front();
386 offsets.pop_front();
387 }
388 }
389
390 if (!offsets.empty()) {
391 ranges.back() = offsets.front();
392 }
393
394 return ranges;
395 }
396
397 dberr_t Merge_file_sort::merge_rows(Cursor &cursor,
398 Output_file &output_file) noexcept {
399 dberr_t err;
400 ulint *offsets{};
401 const mrec_t *mrec{};
402
403 while ((err = cursor.fetch(mrec, offsets)) == DB_SUCCESS) {
404 /* If we are simply appending from a single partition then enable duplicate
405 key checking for the write phase. */
406 auto dup = cursor.size() == 0 ? m_merge_ctx->m_dup : nullptr;
407
408 err = output_file.write(mrec, offsets, dup);
409
410 if (unlikely(err != DB_SUCCESS)) {
411 break;
412 }
413
414 err = cursor.next();
415
416 if (unlikely(err != DB_SUCCESS)) {
417 break;
418 }
419 }
420
421 return err;
422 }
423
424 dberr_t Merge_file_sort::merge_ranges(Cursor &cursor, Merge_offsets &offsets,
425 Output_file &output_file,
426 size_t buffer_size) noexcept {
427 auto ranges = next_ranges(offsets);
428 auto err = cursor.prepare(ranges, buffer_size);
429
430 if (err != DB_SUCCESS) {
431 return err;
432 }
433
434 m_next_offsets.push_back(output_file.get_size());
435
436 do {
437 err = merge_rows(cursor, output_file);
438
439 if (unlikely(err == DB_END_OF_INDEX)) {
440 err = output_file.flush();
441 m_next_offsets.push_back(output_file.get_size());
442 }
443
444 if (unlikely(err != DB_SUCCESS)) {
445 return err;
446 }
447
448 if (unlikely(m_merge_ctx->m_dup != nullptr &&
449 m_merge_ctx->m_dup->m_n_dup > 0)) {
450 return DB_DUPLICATE_KEY;
451 }
452
453 ranges = next_ranges(offsets);
454
455 /* Reposition the merge cursor on the new range to merge next. */
456 } while ((err = cursor.seek(ranges)) == DB_SUCCESS);
457
458 m_next_offsets.pop_back();
459
460 return err == DB_END_OF_INDEX ? DB_SUCCESS : err;
461 }
462
463 dberr_t Merge_file_sort::sort(Builder *builder,
464 Merge_offsets &offsets) noexcept {
465 ut_a(m_merge_ctx->m_dup != nullptr);
466
467 auto &ctx = builder->ctx();
468 auto file = m_merge_ctx->m_file;
469 const auto n_buffers = (m_merge_ctx->m_n_threads * N_WAY_MERGE) + 1;
470 const auto io_buffer_size = ctx.merge_io_buffer_size(n_buffers);
471
472 ut::unique_ptr_aligned<byte[]> aligned_buffer =
473 ut::make_unique_aligned<byte[]>(ut::make_psi_memory_key(mem_key_ddl),
474 UNIV_SECTOR_SIZE, io_buffer_size);
475
476 if (!aligned_buffer) {
477 return DB_OUT_OF_MEMORY;
478 }
479
480 /* Buffer for writing the merged rows to the output file. */
481 IO_buffer io_buffer{aligned_buffer.get(), io_buffer_size};
482
483 /* This is the output file for the first pass. */
484 auto tmpfd = ddl::file_create_low(builder->tmpdir());
485
486 if (tmpfd.is_open()) {
487 MONITOR_ATOMIC_INC(MONITOR_ALTER_TABLE_SORT_FILES);
488 } else {
489 return DB_OUT_OF_RESOURCES;
490 }
491
492 dberr_t err{DB_SUCCESS};
493
494 /* Merge until there is a single list of rows in the file. */
495 while (offsets.size() > 1) {
496 Output_file output_file(ctx, tmpfd, io_buffer);
497 Cursor cursor{builder, file, m_merge_ctx->m_dup, m_merge_ctx->m_stage};
498
499 err = merge_ranges(cursor, offsets, output_file, io_buffer_size);
500
501 m_n_rows = output_file.get_n_rows();
502
503 if (unlikely(err != DB_SUCCESS)) {
504 break;
505 }
506
507 #ifdef UNIV_DEBUG
508 ib::info() << " Merge sort pass completed. Input file: "
509 << file->m_file.get() << " Output file: " << tmpfd.get()
510 << " New offsets: " << m_next_offsets.size()
511 << " thread_id: " << std::this_thread::get_id();
512 #endif /* UNIV_DEBUG */
513
514 /* Swap the input file with the output file and repeat. */
515 tmpfd.swap(file->m_file);
516 std::swap(offsets, m_next_offsets);
517
518 ut_a(m_next_offsets.empty());
519
520 if (!offsets.empty()) {
521 file->m_size = output_file.get_size();
522 }
523 }
524
525 ut_a(err != DB_SUCCESS || file->m_n_recs == m_n_rows);
526
527 return err;
528 }
529
530 } // namespace ddl