-
Notifications
You must be signed in to change notification settings - Fork 409
/
DeltaMergeStore.cpp
1787 lines (1574 loc) · 71.7 KB
/
DeltaMergeStore.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Common/Exception.h>
#include <Common/FailPoint.h>
#include <Common/FmtUtils.h>
#include <Common/Logger.h>
#include <Common/Stopwatch.h>
#include <Common/SyncPoint/SyncPoint.h>
#include <Common/TiFlashMetrics.h>
#include <Common/assert_cast.h>
#include <Core/SortDescription.h>
#include <Flash/Coprocessor/DAGContext.h>
#include <Functions/FunctionsConversion.h>
#include <Interpreters/Context.h>
#include <Interpreters/SharedContexts/Disagg.h>
#include <Interpreters/sortBlock.h>
#include <Operators/UnorderedSourceOp.h>
#include <Poco/Exception.h>
#include <Storages/DeltaMerge/DMContext.h>
#include <Storages/DeltaMerge/DMSegmentThreadInputStream.h>
#include <Storages/DeltaMerge/DeltaMergeHelpers.h>
#include <Storages/DeltaMerge/DeltaMergeStore.h>
#include <Storages/DeltaMerge/File/DMFile.h>
#include <Storages/DeltaMerge/Filter/PushDownFilter.h>
#include <Storages/DeltaMerge/Filter/RSOperator.h>
#include <Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.h>
#include <Storages/DeltaMerge/ReadThread/UnorderedInputStream.h>
#include <Storages/DeltaMerge/Remote/DisaggSnapshot.h>
#include <Storages/DeltaMerge/SchemaUpdate.h>
#include <Storages/DeltaMerge/Segment.h>
#include <Storages/DeltaMerge/SegmentReadTaskPool.h>
#include <Storages/DeltaMerge/WriteBatchesImpl.h>
#include <Storages/Page/PageStorage.h>
#include <Storages/Page/V2/VersionSet/PageEntriesVersionSetWithDelta.h>
#include <Storages/PathPool.h>
#include <Storages/Transaction/TMTContext.h>
#include <Storages/Transaction/Types.h>
#include <common/logger_useful.h>
#include <atomic>
#include <ext/scope_guard.h>
#include <magic_enum.hpp>
#include <memory>
namespace ProfileEvents
{
extern const Event DMWriteBlock;
extern const Event DMWriteBlockNS;
extern const Event DMWriteFile;
extern const Event DMWriteFileNS;
extern const Event DMDeleteRange;
extern const Event DMDeleteRangeNS;
extern const Event DMAppendDeltaCommitDisk;
extern const Event DMAppendDeltaCommitDiskNS;
extern const Event DMAppendDeltaCleanUp;
extern const Event DMAppendDeltaCleanUpNS;
} // namespace ProfileEvents
namespace CurrentMetrics
{
extern const Metric DT_DeltaMergeTotalBytes;
extern const Metric DT_DeltaMergeTotalRows;
extern const Metric DT_SnapshotOfRead;
extern const Metric DT_SnapshotOfReadRaw;
extern const Metric DT_SnapshotOfPlaceIndex;
} // namespace CurrentMetrics
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
} // namespace ErrorCodes
namespace FailPoints
{
extern const char skip_check_segment_update[];
extern const char pause_when_writing_to_dt_store[];
extern const char pause_when_altering_dt_store[];
extern const char force_triggle_background_merge_delta[];
extern const char force_triggle_foreground_flush[];
extern const char random_exception_after_dt_write_done[];
extern const char force_slow_page_storage_snapshot_release[];
extern const char exception_before_drop_segment[];
extern const char exception_after_drop_segment[];
} // namespace FailPoints
namespace DM
{
// ================================================
// MergeDeltaTaskPool
// ================================================
std::pair<bool, bool> DeltaMergeStore::MergeDeltaTaskPool::tryAddTask(const BackgroundTask & task, const ThreadType & whom, const size_t max_task_num, const LoggerPtr & log_)
{
std::scoped_lock lock(mutex);
if (light_tasks.size() + heavy_tasks.size() >= max_task_num)
return std::make_pair(false, false);
bool is_heavy = false;
switch (task.type)
{
case TaskType::Split:
case TaskType::MergeDelta:
is_heavy = true;
// reserve some task space for light tasks
if (max_task_num > 1 && heavy_tasks.size() >= static_cast<size_t>(max_task_num * 0.9))
return std::make_pair(false, is_heavy);
heavy_tasks.push(task);
break;
case TaskType::Compact:
case TaskType::Flush:
case TaskType::PlaceIndex:
is_heavy = false;
// reserve some task space for heavy tasks
if (max_task_num > 1 && light_tasks.size() >= static_cast<size_t>(max_task_num * 0.9))
return std::make_pair(false, is_heavy);
light_tasks.push(task);
break;
default:
throw Exception(fmt::format("Unsupported task type: {}", magic_enum::enum_name(task.type)));
}
LOG_DEBUG(
log_,
"Segment task add to background task pool, segment={} task={} by_whom={}",
task.segment->simpleInfo(),
magic_enum::enum_name(task.type),
magic_enum::enum_name(whom));
return std::make_pair(true, is_heavy);
}
DeltaMergeStore::BackgroundTask DeltaMergeStore::MergeDeltaTaskPool::nextTask(bool is_heavy, const LoggerPtr & log_)
{
std::scoped_lock lock(mutex);
auto & tasks = is_heavy ? heavy_tasks : light_tasks;
if (tasks.empty())
return {};
auto task = tasks.front();
tasks.pop();
LOG_DEBUG(log_, "Segment task pop from background task pool, segment={} task={}", task.segment->simpleInfo(), magic_enum::enum_name(task.type));
return task;
}
// ================================================
// DeltaMergeStore
// ================================================
namespace
{
// Actually we will always store a column of `_tidb_rowid`, no matter it
// exist in `table_columns` or not.
ColumnDefinesPtr generateStoreColumns(const ColumnDefines & table_columns, bool is_common_handle)
{
auto columns = std::make_shared<ColumnDefines>();
// First three columns are always _tidb_rowid, _INTERNAL_VERSION, _INTERNAL_DELMARK
columns->emplace_back(getExtraHandleColumnDefine(is_common_handle));
columns->emplace_back(getVersionColumnDefine());
columns->emplace_back(getTagColumnDefine());
// Add other columns
for (const auto & col : table_columns)
{
if (col.name != EXTRA_HANDLE_COLUMN_NAME && col.name != VERSION_COLUMN_NAME && col.name != TAG_COLUMN_NAME)
columns->emplace_back(col);
}
return columns;
}
} // namespace
DeltaMergeStore::Settings DeltaMergeStore::EMPTY_SETTINGS = DeltaMergeStore::Settings{.not_compress_columns = NotCompress{}};
DeltaMergeStore::DeltaMergeStore(Context & db_context,
bool data_path_contains_database_name,
const String & db_name_,
const String & table_name_,
KeyspaceID keyspace_id_,
TableID physical_table_id_,
bool has_replica,
const ColumnDefines & columns,
const ColumnDefine & handle,
bool is_common_handle_,
size_t rowkey_column_size_,
const Settings & settings_,
ThreadPool * thread_pool)
: global_context(db_context.getGlobalContext())
, path_pool(std::make_shared<StoragePathPool>(global_context.getPathPool().withTable(db_name_, table_name_, data_path_contains_database_name)))
, settings(settings_)
, db_name(db_name_)
, table_name(table_name_)
, keyspace_id(keyspace_id_)
, physical_table_id(physical_table_id_)
, is_common_handle(is_common_handle_)
, rowkey_column_size(rowkey_column_size_)
, original_table_handle_define(handle)
, background_pool(db_context.getBackgroundPool())
, blockable_background_pool(db_context.getBlockableBackgroundPool())
, next_gc_check_key(is_common_handle ? RowKeyValue::COMMON_HANDLE_MIN_KEY : RowKeyValue::INT_HANDLE_MIN_KEY)
, log(Logger::get(fmt::format("keyspace_id={} table_id={}", keyspace_id_, physical_table_id_)))
{
replica_exist.store(has_replica);
// for mock test, table_id_ should be DB::InvalidTableID
NamespaceID ns_id = physical_table_id == DB::InvalidTableID ? TEST_NAMESPACE_ID : physical_table_id;
LOG_INFO(log, "Restore DeltaMerge Store start");
storage_pool = std::make_shared<StoragePool>(global_context,
keyspace_id,
ns_id,
*path_pool,
db_name_ + "." + table_name_);
// Restore existing dm files.
// Should be done before any background task setup.
restoreStableFiles();
original_table_columns.emplace_back(original_table_handle_define);
original_table_columns.emplace_back(getVersionColumnDefine());
original_table_columns.emplace_back(getTagColumnDefine());
for (const auto & col : columns)
{
if (col.id != original_table_handle_define.id && col.id != VERSION_COLUMN_ID && col.id != TAG_COLUMN_ID)
original_table_columns.emplace_back(col);
}
original_table_header = std::make_shared<Block>(toEmptyBlock(original_table_columns));
store_columns = generateStoreColumns(original_table_columns, is_common_handle);
auto dm_context = newDMContext(db_context, db_context.getSettingsRef());
PageStorageRunMode page_storage_run_mode;
try
{
page_storage_run_mode = storage_pool->restore(); // restore from disk
if (const auto first_segment_entry = storage_pool->metaReader()->getPageEntry(DELTA_MERGE_FIRST_SEGMENT_ID);
!first_segment_entry.isValid())
{
auto segment_id = storage_pool->newMetaPageId();
if (segment_id != DELTA_MERGE_FIRST_SEGMENT_ID)
{
RUNTIME_CHECK_MSG(
page_storage_run_mode != PageStorageRunMode::ONLY_V2,
"The first segment id should be {}, but get {}, run_mode={}",
DELTA_MERGE_FIRST_SEGMENT_ID,
segment_id,
magic_enum::enum_name(page_storage_run_mode));
// In ONLY_V3 or MIX_MODE, If create a new DeltaMergeStore
// Should used fixed DELTA_MERGE_FIRST_SEGMENT_ID to create first segment
segment_id = DELTA_MERGE_FIRST_SEGMENT_ID;
}
LOG_INFO(log, "creating the first segment with segment_id={}", segment_id);
auto first_segment = Segment::newSegment( //
log,
*dm_context,
store_columns,
RowKeyRange::newAll(is_common_handle, rowkey_column_size),
segment_id,
0);
segments.emplace(first_segment->getRowKeyRange().getEnd(), first_segment);
id_to_segment.emplace(segment_id, first_segment);
}
else
{
auto segment_id = DELTA_MERGE_FIRST_SEGMENT_ID;
// parallel restore segment to speed up
if (thread_pool)
{
auto wait_group = thread_pool->waitGroup();
auto segment_ids = Segment::getAllSegmentIds(*dm_context, segment_id);
for (auto & segment_id : segment_ids)
{
auto task = [this, dm_context, segment_id] {
auto segment = Segment::restoreSegment(log, *dm_context, segment_id);
std::lock_guard lock(read_write_mutex);
segments.emplace(segment->getRowKeyRange().getEnd(), segment);
id_to_segment.emplace(segment_id, segment);
};
wait_group->schedule(task);
}
wait_group->wait();
}
else
{
while (segment_id != 0)
{
auto segment = Segment::restoreSegment(log, *dm_context, segment_id);
segments.emplace(segment->getRowKeyRange().getEnd(), segment);
id_to_segment.emplace(segment_id, segment);
segment_id = segment->nextSegmentId();
}
}
}
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
throw;
}
setUpBackgroundTask(dm_context);
LOG_INFO(log, "Restore DeltaMerge Store end, ps_run_mode={}", magic_enum::enum_name(page_storage_run_mode));
}
DeltaMergeStore::~DeltaMergeStore()
{
LOG_INFO(log, "Release DeltaMerge Store start");
shutdown();
LOG_INFO(log, "Release DeltaMerge Store end");
}
void DeltaMergeStore::rename(String /*new_path*/, String new_database_name, String new_table_name)
{
path_pool->rename(new_database_name, new_table_name);
// TODO: replacing these two variables is not atomic, but could be good enough?
table_name.swap(new_table_name);
db_name.swap(new_database_name);
}
void DeltaMergeStore::dropAllSegments(bool keep_first_segment)
{
auto dm_context = newDMContext(global_context, global_context.getSettingsRef());
{
std::unique_lock lock(read_write_mutex);
auto segment_id = DELTA_MERGE_FIRST_SEGMENT_ID;
std::stack<PageIdU64> segment_ids;
while (segment_id != 0)
{
segment_ids.push(segment_id);
auto segment = id_to_segment[segment_id];
segment_id = segment->nextSegmentId();
}
WriteBatches wbs(*storage_pool, dm_context->getWriteLimiter());
while (!segment_ids.empty())
{
auto segment_id_to_drop = segment_ids.top();
if (keep_first_segment && (segment_id_to_drop == DELTA_MERGE_FIRST_SEGMENT_ID))
{
// This must be the last segment to drop
assert(segment_ids.size() == 1);
break;
}
auto segment_to_drop = id_to_segment[segment_id_to_drop];
segment_ids.pop();
SegmentPtr previous_segment;
SegmentPtr new_previous_segment;
if (!segment_ids.empty())
{
// This is not the last segment, so we need to set previous segment's next_segment_id to 0 to indicate that this segment has been dropped
auto previous_segment_id = segment_ids.top();
previous_segment = id_to_segment[previous_segment_id];
assert(previous_segment->nextSegmentId() == segment_id_to_drop);
auto previous_lock = previous_segment->mustGetUpdateLock();
FAIL_POINT_TRIGGER_EXCEPTION(FailPoints::exception_before_drop_segment);
// No need to abandon previous_segment, because it's delta and stable is managed by the new_previous_segment.
// Abandon previous_segment will actually abandon new_previous_segment
//
// And we need to use the previous_segment to manage the dropped segment's range,
// because if tiflash crash in the middle of the drop table process, and when restoring this table at restart,
// there are some possibilities that this table will trigger some background tasks,
// and in these background tasks, it may check that all ranges of this table should be managed by some segment.
new_previous_segment = previous_segment->dropNextSegment(wbs, segment_to_drop->getRowKeyRange());
FAIL_POINT_TRIGGER_EXCEPTION(FailPoints::exception_after_drop_segment);
}
// The order to drop the meta and data of this segment doesn't matter,
// Because there is no segment pointing to this segment,
// so it won't be restored again even the drop process was interrupted by restart
segments.erase(segment_to_drop->getRowKeyRange().getEnd());
id_to_segment.erase(segment_id_to_drop);
if (previous_segment)
{
assert(new_previous_segment);
assert(previous_segment->segmentId() == new_previous_segment->segmentId());
segments.erase(previous_segment->getRowKeyRange().getEnd());
segments.emplace(new_previous_segment->getRowKeyRange().getEnd(), new_previous_segment);
id_to_segment.erase(previous_segment->segmentId());
id_to_segment.emplace(new_previous_segment->segmentId(), new_previous_segment);
}
auto drop_lock = segment_to_drop->mustGetUpdateLock();
segment_to_drop->abandon(*dm_context);
segment_to_drop->drop(global_context.getFileProvider(), wbs);
}
}
}
void DeltaMergeStore::clearData()
{
// Remove all background task first
shutdown();
LOG_INFO(log, "Clear DeltaMerge segments data");
// We don't drop the first segment in clearData, because if we drop it and tiflash crashes before drop the table's metadata,
// when restart the table will try to restore the first segment but failed to do it which cause tiflash crash again.
// The reason this happens is that even we delete all data in a PageStorage instance,
// the call to PageStorage::getMaxId is still not 0 so tiflash treat it as an old table and will try to restore it's first segment.
dropAllSegments(true);
LOG_INFO(log, "Clear DeltaMerge segments data done");
}
void DeltaMergeStore::drop()
{
// Remove all background task first
shutdown();
LOG_INFO(log, "Drop DeltaMerge removing data from filesystem");
dropAllSegments(false);
storage_pool->drop();
// Drop data in storage path pool
path_pool->drop(/*recursive=*/true, /*must_success=*/false);
LOG_INFO(log, "Drop DeltaMerge done");
}
void DeltaMergeStore::shutdown()
{
bool v = false;
if (!shutdown_called.compare_exchange_strong(v, true))
return;
LOG_TRACE(log, "Shutdown DeltaMerge start");
// Must shutdown storage path pool to make sure the DMFile remove callbacks
// won't remove dmfiles unexpectly.
path_pool->shutdown();
// shutdown storage pool and clean up the local DMFile remove callbacks
storage_pool->shutdown();
background_pool.removeTask(background_task_handle);
blockable_background_pool.removeTask(blockable_background_pool_handle);
background_task_handle = nullptr;
blockable_background_pool_handle = nullptr;
LOG_TRACE(log, "Shutdown DeltaMerge end");
}
DMContextPtr DeltaMergeStore::newDMContext(const Context & db_context, const DB::Settings & db_settings, const String & tracing_id, ScanContextPtr scan_context_)
{
std::shared_lock lock(read_write_mutex);
// Here we use global context from db_context, instead of db_context directly.
// Because db_context could be a temporary object and won't last long enough during the query process.
// Like the context created by InterpreterSelectWithUnionQuery.
auto * ctx = new DMContext(db_context.getGlobalContext(),
path_pool,
storage_pool,
latest_gc_safe_point.load(std::memory_order_acquire),
keyspace_id,
physical_table_id,
is_common_handle,
rowkey_column_size,
db_settings,
scan_context_,
tracing_id);
return DMContextPtr(ctx);
}
inline Block getSubBlock(const Block & block, size_t offset, size_t limit)
{
if (!offset && limit == block.rows())
{
return block;
}
else
{
Block sub_block;
for (const auto & c : block)
{
auto column = c.column->cloneEmpty();
column->insertRangeFrom(*c.column, offset, limit);
auto sub_col = c.cloneEmpty();
sub_col.column = std::move(column);
sub_col.column_id = c.column_id;
sub_block.insert(std::move(sub_col));
}
return sub_block;
}
}
// Add an extra handle column if the `handle_define` is used as the primary key
// TODO: consider merging it into `RegionBlockReader`?
Block DeltaMergeStore::addExtraColumnIfNeed(const Context & db_context, const ColumnDefine & handle_define, Block && block)
{
if (pkIsHandle(handle_define))
{
if (!EXTRA_HANDLE_COLUMN_INT_TYPE->equals(*handle_define.type))
{
auto handle_pos = getPosByColumnId(block, handle_define.id);
addColumnToBlock(block, //
EXTRA_HANDLE_COLUMN_ID,
EXTRA_HANDLE_COLUMN_NAME,
EXTRA_HANDLE_COLUMN_INT_TYPE,
EXTRA_HANDLE_COLUMN_INT_TYPE->createColumn());
// Fill the new handle column with data in column[handle_pos] by applying cast.
DefaultExecutable(FunctionToInt64::create(db_context)).execute(block, {handle_pos}, block.columns() - 1);
}
else
{
// If types are identical, `FunctionToInt64` just take reference to the original column.
// We need a deep copy for the pk column or it will make trobule for later processing.
auto pk_col_with_name = getByColumnId(block, handle_define.id);
auto pk_column = pk_col_with_name.column;
ColumnPtr handle_column = pk_column->cloneResized(pk_column->size());
addColumnToBlock(block, //
EXTRA_HANDLE_COLUMN_ID,
EXTRA_HANDLE_COLUMN_NAME,
EXTRA_HANDLE_COLUMN_INT_TYPE,
handle_column);
}
}
return std::move(block);
}
void DeltaMergeStore::write(const Context & db_context, const DB::Settings & db_settings, Block & block)
{
LOG_TRACE(log, "Table write block, rows={} bytes={}", block.rows(), block.bytes());
EventRecorder write_block_recorder(ProfileEvents::DMWriteBlock, ProfileEvents::DMWriteBlockNS);
const auto rows = block.rows();
if (rows == 0)
return;
auto dm_context = newDMContext(db_context, db_settings, "write");
const auto bytes = block.bytes();
{
// Sort the block by handle & version in ascending order.
SortDescription sort;
sort.emplace_back(EXTRA_HANDLE_COLUMN_NAME, 1, 0);
sort.emplace_back(VERSION_COLUMN_NAME, 1, 0);
if (rows > 1 && !isAlreadySorted(block, sort))
stableSortBlock(block, sort);
}
Segments updated_segments;
size_t offset = 0;
size_t limit;
const auto handle_column = block.getByName(EXTRA_HANDLE_COLUMN_NAME).column;
auto rowkey_column = RowKeyColumnContainer(handle_column, is_common_handle);
// Write block by segments
while (offset != rows)
{
RowKeyValueRef start_key = rowkey_column.getRowKeyValue(offset);
WriteBatches wbs(*storage_pool, db_context.getWriteLimiter());
ColumnFilePtr write_column_file;
RowKeyRange write_range;
// Keep trying until succeeded.
while (true)
{
// Find the segment according to current start_key
SegmentPtr segment;
{
std::shared_lock lock(read_write_mutex);
auto segment_it = segments.upper_bound(start_key);
if (segment_it == segments.end())
{
// todo print meaningful start row key
throw Exception(fmt::format("Failed to locate segment begin with start: {}", start_key.toDebugString()), ErrorCodes::LOGICAL_ERROR);
}
segment = segment_it->second;
}
FAIL_POINT_PAUSE(FailPoints::pause_when_writing_to_dt_store);
// Do force merge or stop write if necessary.
waitForWrite(dm_context, segment);
if (segment->hasAbandoned())
continue;
const auto & rowkey_range = segment->getRowKeyRange();
// The [offset, rows - offset] can be exceeding the Segment's rowkey_range. Cut the range
// to fit the segment.
auto [cur_offset, cur_limit] = rowkey_range.getPosRange(handle_column, offset, rows - offset);
RUNTIME_CHECK_MSG(cur_offset == offset && cur_limit != 0,
"invalid cur_offset or cur_limit. is_common_handle={} start_key={} cur_offset={} cur_limit={} rows={} offset={} rowkey_range={}",
is_common_handle,
start_key.toRowKeyValue().toString(),
cur_offset,
cur_limit,
rows,
offset,
rowkey_range.toDebugString());
limit = cur_limit;
auto alloc_bytes = block.bytes(offset, limit);
bool is_small = limit < dm_context->delta_cache_limit_rows / 4 && alloc_bytes < dm_context->delta_cache_limit_bytes / 4;
// For small column files, data is appended to MemTableSet, then flushed later.
// For large column files, data is directly written to PageStorage, while the ColumnFile entry is appended to MemTableSet.
if (is_small)
{
if (segment->writeToCache(*dm_context, block, offset, limit))
{
GET_METRIC(tiflash_storage_subtask_throughput_bytes, type_write_to_cache).Increment(alloc_bytes);
GET_METRIC(tiflash_storage_subtask_throughput_rows, type_write_to_cache).Increment(limit);
updated_segments.push_back(segment);
break;
}
}
else
{
// If column file haven't been written, or the pk range has changed since last write, then write it and
// delete former written column file.
if (!write_column_file || (write_column_file && write_range != rowkey_range))
{
wbs.rollbackWrittenLogAndData();
wbs.clear();
// In this case we will construct a ColumnFile that does not contain block data in the memory.
// The block data has been written to PageStorage in wbs.
write_column_file = ColumnFileTiny::writeColumnFile(*dm_context, block, offset, limit, wbs);
wbs.writeLogAndData();
write_range = rowkey_range;
}
// Write could fail, because other threads could already updated the instance. Like split/merge, merge delta.
if (segment->writeToDisk(*dm_context, write_column_file))
{
GET_METRIC(tiflash_storage_subtask_throughput_bytes, type_write_to_disk).Increment(alloc_bytes);
GET_METRIC(tiflash_storage_subtask_throughput_rows, type_write_to_disk).Increment(limit);
updated_segments.push_back(segment);
break;
}
}
}
offset += limit;
}
GET_METRIC(tiflash_storage_throughput_bytes, type_write).Increment(bytes);
GET_METRIC(tiflash_storage_throughput_rows, type_write).Increment(rows);
if (db_settings.dt_flush_after_write)
{
RowKeyRange merge_range = RowKeyRange::newNone(is_common_handle, rowkey_column_size);
for (auto & segment : updated_segments)
merge_range = merge_range.merge(segment->getRowKeyRange());
flushCache(dm_context, merge_range);
}
fiu_do_on(FailPoints::random_exception_after_dt_write_done, {
static int num_call = 0;
if (num_call++ % 10 == 7)
throw Exception("Fail point random_exception_after_dt_write_done is triggered.", ErrorCodes::FAIL_POINT_ERROR);
});
// TODO: Update the tracing_id before checkSegmentUpdate
for (auto & segment : updated_segments)
checkSegmentUpdate(dm_context, segment, ThreadType::Write);
}
void DeltaMergeStore::deleteRange(const Context & db_context, const DB::Settings & db_settings, const RowKeyRange & delete_range)
{
LOG_INFO(log, "Table delete range, range={}", delete_range.toDebugString());
EventRecorder write_block_recorder(ProfileEvents::DMDeleteRange, ProfileEvents::DMDeleteRangeNS);
if (delete_range.none())
return;
auto dm_context = newDMContext(db_context, db_settings, "delete_range");
Segments updated_segments;
RowKeyRange cur_range = delete_range;
while (!cur_range.none())
{
RowKeyRange segment_range;
// Keep trying until succeeded.
while (true)
{
SegmentPtr segment;
{
std::shared_lock lock(read_write_mutex);
auto segment_it = segments.upper_bound(cur_range.getStart());
if (segment_it == segments.end())
{
throw Exception(
fmt::format("Failed to locate segment begin with start in range: {}", cur_range.toDebugString()),
ErrorCodes::LOGICAL_ERROR);
}
segment = segment_it->second;
}
waitForDeleteRange(dm_context, segment);
if (segment->hasAbandoned())
continue;
segment_range = segment->getRowKeyRange();
// Write could fail, because other threads could already updated the instance. Like split/merge, merge delta.
if (segment->write(*dm_context, delete_range.shrink(segment_range)))
{
updated_segments.push_back(segment);
break;
}
}
cur_range.setStart(segment_range.end);
cur_range.setEnd(delete_range.end);
}
// TODO: Update the tracing_id before checkSegmentUpdate?
for (auto & segment : updated_segments)
checkSegmentUpdate(dm_context, segment, ThreadType::Write);
}
bool DeltaMergeStore::flushCache(const Context & context, const RowKeyRange & range, bool try_until_succeed)
{
auto dm_context = newDMContext(context, context.getSettingsRef());
return flushCache(dm_context, range, try_until_succeed);
}
bool DeltaMergeStore::flushCache(const DMContextPtr & dm_context, const RowKeyRange & range, bool try_until_succeed)
{
size_t sleep_ms = 5;
RowKeyRange cur_range = range;
while (!cur_range.none())
{
RowKeyRange segment_range;
// Keep trying until succeeded if needed.
while (true)
{
SegmentPtr segment;
{
std::shared_lock lock(read_write_mutex);
auto segment_it = segments.upper_bound(cur_range.getStart());
if (segment_it == segments.end())
{
throw Exception(
fmt::format("Failed to locate segment begin with start in range: {}", cur_range.toDebugString()),
ErrorCodes::LOGICAL_ERROR);
}
segment = segment_it->second;
}
segment_range = segment->getRowKeyRange();
if (segment->flushCache(*dm_context))
{
break;
}
else if (!try_until_succeed)
{
return false;
}
// Flush could fail. Typical cases:
// #1. The segment is abandoned (due to an update is finished)
// #2. There is another flush in progress, for example, triggered in background
// Let's sleep 5ms ~ 100ms and then retry flush again.
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
sleep_ms = std::min(sleep_ms * 2, 100);
}
cur_range.setStart(segment_range.end);
}
return true;
}
bool DeltaMergeStore::mergeDeltaAll(const Context & context)
{
LOG_INFO(log, "Begin table mergeDeltaAll");
auto dm_context = newDMContext(context, context.getSettingsRef(), /*tracing_id*/ "mergeDeltaAll");
std::vector<SegmentPtr> all_segments;
{
std::shared_lock lock(read_write_mutex);
for (auto & [range_end, segment] : segments)
{
(void)range_end;
all_segments.push_back(segment);
}
}
bool all_succ = true;
for (auto & segment : all_segments)
{
bool succ = segmentMergeDelta(*dm_context, segment, MergeDeltaReason::Manual) != nullptr;
all_succ = all_succ && succ;
}
LOG_INFO(log, "Finish table mergeDeltaAll: {}", all_succ);
return all_succ;
}
std::optional<DM::RowKeyRange> DeltaMergeStore::mergeDeltaBySegment(const Context & context, const RowKeyValue & start_key)
{
LOG_INFO(log, "Table mergeDeltaBySegment, start={}", start_key.toDebugString());
SYNC_FOR("before_DeltaMergeStore::mergeDeltaBySegment");
updateGCSafePoint();
auto dm_context = newDMContext(context, context.getSettingsRef(),
/*tracing_id*/ fmt::format("mergeDeltaBySegment_{}", latest_gc_safe_point.load(std::memory_order_relaxed)));
size_t sleep_ms = 50;
while (true)
{
SegmentPtr segment;
{
std::shared_lock lock(read_write_mutex);
const auto segment_it = segments.upper_bound(start_key.toRowKeyValueRef());
if (segment_it == segments.end())
{
return std::nullopt;
}
segment = segment_it->second;
}
if (segment->flushCache(*dm_context))
{
const auto new_segment = segmentMergeDelta(*dm_context, segment, MergeDeltaReason::Manual);
if (new_segment)
{
const auto segment_end = new_segment->getRowKeyRange().end;
if (unlikely(*segment_end.value <= *start_key.value))
{
// The next start key must be > current start key
LOG_ERROR(log, "Assert new_segment.end {} > start {} failed", segment_end.toDebugString(), start_key.toDebugString());
throw Exception("Assert segment range failed", ErrorCodes::LOGICAL_ERROR);
}
return new_segment->getRowKeyRange();
} // else: sleep and retry
} // else: sleep and retry
SYNC_FOR("before_DeltaMergeStore::mergeDeltaBySegment|retry_segment");
// Typical cases:
// #1. flushCache failed
// - The segment is abandoned (due to segment updated)
// - There is another flush in progress (e.g. triggered in background)
// #2. segmentMergeDelta failed
// - The segment is abandoned (due to segment updated)
// - The segment is updating (e.g. a split-preparation is working, which occupies a for-write snapshot).
// It could be possible to take seconds to finish the segment updating, so let's sleep for a short time
// (50ms ~ 1000ms) and then retry.
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
sleep_ms = std::min(sleep_ms * 2, 1000);
}
}
void DeltaMergeStore::compact(const Context & db_context, const RowKeyRange & range)
{
auto dm_context = newDMContext(db_context, db_context.getSettingsRef(), /*tracing_id*/ "compact");
RowKeyRange cur_range = range;
while (!cur_range.none())
{
RowKeyRange segment_range;
// Keep trying until succeeded.
while (true)
{
SegmentPtr segment;
{
std::shared_lock lock(read_write_mutex);
auto segment_it = segments.upper_bound(cur_range.getStart());
if (segment_it == segments.end())
{
throw Exception(
fmt::format("Failed to locate segment begin with start in range: {}", cur_range.toDebugString()),
ErrorCodes::LOGICAL_ERROR);
}
segment = segment_it->second;
}
segment_range = segment->getRowKeyRange();
// compact could fail.
if (segment->compactDelta(*dm_context))
{
break;
}
}
cur_range.setStart(segment_range.end);
}
}
// Read data without mvcc filtering.
// just for debug
// readRaw is called under 'selraw xxxx'
BlockInputStreams DeltaMergeStore::readRaw(const Context & db_context,
const DB::Settings & db_settings,
const ColumnDefines & columns_to_read,
size_t num_streams,
bool keep_order,
const SegmentIdSet & read_segments,
size_t extra_table_id_index)
{
SegmentReadTasks tasks;
auto dm_context = newDMContext(db_context, db_settings, fmt::format("read_raw_{}", db_context.getCurrentQueryId()));
// If keep order is required, disable read thread.
auto enable_read_thread = db_context.getSettingsRef().dt_enable_read_thread && !keep_order;
{
std::shared_lock lock(read_write_mutex);
for (const auto & [handle, segment] : segments)
{
(void)handle;
if (read_segments.empty() || read_segments.count(segment->segmentId()))
{
auto segment_snap = segment->createSnapshot(*dm_context, false, CurrentMetrics::DT_SnapshotOfReadRaw);
if (unlikely(!segment_snap))
throw Exception("Failed to get segment snap", ErrorCodes::LOGICAL_ERROR);
tasks.push_back(std::make_shared<SegmentReadTask>(segment, segment_snap, RowKeyRanges{segment->getRowKeyRange()}));
}
}
}
fiu_do_on(FailPoints::force_slow_page_storage_snapshot_release, {
std::thread thread_hold_snapshots([this, tasks]() {
LOG_WARNING(log, "failpoint force_slow_page_storage_snapshot_release begin");
std::this_thread::sleep_for(std::chrono::seconds(5 * 60));
(void)tasks;
LOG_WARNING(log, "failpoint force_slow_page_storage_snapshot_release end");
});
thread_hold_snapshots.detach();
});
auto after_segment_read = [&](const DMContextPtr & dm_context_, const SegmentPtr & segment_) {
this->checkSegmentUpdate(dm_context_, segment_, ThreadType::Read);
};
size_t final_num_stream = std::min(num_streams, tasks.size());
String req_info;
if (db_context.getDAGContext() != nullptr && db_context.getDAGContext()->isMPPTask())
req_info = db_context.getDAGContext()->getMPPTaskId().toString();
auto read_task_pool = std::make_shared<SegmentReadTaskPool>(
physical_table_id,
dm_context,
columns_to_read,
EMPTY_FILTER,
std::numeric_limits<UInt64>::max(),
DEFAULT_BLOCK_SIZE,
/* read_mode */ ReadMode::Raw,
std::move(tasks),
after_segment_read,
req_info,
enable_read_thread,
final_num_stream);
BlockInputStreams res;
for (size_t i = 0; i < final_num_stream; ++i)
{
BlockInputStreamPtr stream;
if (enable_read_thread)
{
stream = std::make_shared<UnorderedInputStream>(
read_task_pool,
columns_to_read,
extra_table_id_index,
physical_table_id,
req_info);
}
else
{
stream = std::make_shared<DMSegmentThreadInputStream>(
dm_context,
read_task_pool,
after_segment_read,
columns_to_read,
EMPTY_FILTER,
std::numeric_limits<UInt64>::max(),