forked from pingcap/tiflash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeltaMergeStore_InternalSegment.cpp
More file actions
1534 lines (1340 loc) · 53.6 KB
/
DeltaMergeStore_InternalSegment.cpp
File metadata and controls
1534 lines (1340 loc) · 53.6 KB
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/SyncPoint/SyncPoint.h>
#include <Common/TiFlashMetrics.h>
#include <IO/FileProvider/FileProvider.h>
#include <Interpreters/Context.h>
#include <Storages/DeltaMerge/ColumnFile/ColumnFileDataProvider.h>
#include <Storages/DeltaMerge/ColumnFile/ColumnFileTinyLocalIndexWriter.h>
#include <Storages/DeltaMerge/DMContext.h>
#include <Storages/DeltaMerge/Delta/DeltaValueSpace.h>
#include <Storages/DeltaMerge/DeltaMergeStore.h>
#include <Storages/DeltaMerge/File/DMFileLocalIndexWriter.h>
#include <Storages/DeltaMerge/LocalIndexerScheduler.h>
#include <Storages/DeltaMerge/Segment.h>
#include <Storages/DeltaMerge/WriteBatchesImpl.h>
#include <common/logger_useful.h>
#include <magic_enum.hpp>
namespace CurrentMetrics
{
extern const Metric DT_DeltaMerge;
extern const Metric DT_DeltaMergeTotalBytes;
extern const Metric DT_DeltaMergeTotalRows;
extern const Metric DT_SegmentSplit;
extern const Metric DT_SegmentMerge;
extern const Metric DT_SnapshotOfSegmentSplit;
extern const Metric DT_SnapshotOfSegmentMerge;
extern const Metric DT_SnapshotOfDeltaMerge;
extern const Metric DT_SnapshotOfSegmentIngest;
extern const Metric DT_SnapshotOfSegmentIngestIndex;
} // namespace CurrentMetrics
namespace DB::ErrorCodes
{
extern const int ABORTED;
}
namespace DB::DM
{
void DeltaMergeStore::DMFileIDToSegmentIDs::remove(const SegmentPtr & segment)
{
RUNTIME_CHECK(segment != nullptr);
for (const auto & dmfile : segment->getStable()->getDMFiles())
{
if (auto it = u_map.find(dmfile->fileId()); it != u_map.end())
{
it->second.erase(segment->segmentId());
}
}
}
void DeltaMergeStore::DMFileIDToSegmentIDs::add(const SegmentPtr & segment)
{
RUNTIME_CHECK(segment != nullptr);
for (const auto & dmfile : segment->getStable()->getDMFiles())
{
u_map[dmfile->fileId()].insert(segment->segmentId());
}
}
const DeltaMergeStore::DMFileIDToSegmentIDs::Value & DeltaMergeStore::DMFileIDToSegmentIDs::get(
PageIdU64 dmfile_id) const
{
static const Value empty;
if (auto it = u_map.find(dmfile_id); it != u_map.end())
{
return it->second;
}
return empty;
}
void DeltaMergeStore::removeSegment(std::unique_lock<std::shared_mutex> &, const SegmentPtr & segment)
{
segments.erase(segment->getRowKeyRange().getEnd());
id_to_segment.erase(segment->segmentId());
dmfile_id_to_segment_ids.remove(segment);
}
void DeltaMergeStore::addSegment(std::unique_lock<std::shared_mutex> &, const SegmentPtr & segment)
{
RUNTIME_CHECK_MSG(
!segments.contains(segment->getRowKeyRange().getEnd()),
"Trying to add segment {} but there is a segment with the same key exists. Old segment must be removed "
"before adding new.",
segment->simpleInfo());
segments[segment->getRowKeyRange().getEnd()] = segment;
id_to_segment[segment->segmentId()] = segment;
dmfile_id_to_segment_ids.add(segment);
}
void DeltaMergeStore::replaceSegment(
std::unique_lock<std::shared_mutex> &,
const SegmentPtr & old_segment,
const SegmentPtr & new_segment)
{
RUNTIME_CHECK(
old_segment->segmentId() == new_segment->segmentId(),
old_segment->segmentId(),
new_segment->segmentId());
segments.erase(old_segment->getRowKeyRange().getEnd());
dmfile_id_to_segment_ids.remove(old_segment);
segments[new_segment->getRowKeyRange().getEnd()] = new_segment;
id_to_segment[new_segment->segmentId()] = new_segment;
dmfile_id_to_segment_ids.add(new_segment);
}
SegmentPair DeltaMergeStore::segmentSplit(
DMContext & dm_context,
const SegmentPtr & segment,
SegmentSplitReason reason,
std::optional<RowKeyValue> opt_split_at,
SegmentSplitMode opt_split_mode)
{
LOG_INFO(
log,
"Split - Begin, mode={} reason={}{} safe_point={} segment={}",
magic_enum::enum_name(opt_split_mode),
magic_enum::enum_name(reason),
(opt_split_at.has_value() ? fmt::format(" force_split_at={}", opt_split_at->toDebugString()) : ""),
dm_context.min_version,
segment->info());
SegmentSnapshotPtr segment_snap;
ColumnDefinesPtr schema_snap;
{
std::shared_lock lock(read_write_mutex);
if (!isSegmentValid(lock, segment))
{
LOG_DEBUG(log, "Split - Give up segmentSplit because not valid, segment={}", segment->simpleInfo());
return {};
}
segment_snap
= segment->createSnapshot(dm_context, /* for_update */ true, CurrentMetrics::DT_SnapshotOfSegmentSplit);
if (!segment_snap)
{
LOG_DEBUG(log, "Split - Give up segmentSplit because snapshot failed, segment={}", segment->simpleInfo());
return {};
}
if (!opt_split_at.has_value() && !segment_snap->getRows())
{
// When opt_split_at is not specified, we skip split for empty segments.
LOG_DEBUG(log, "Split - Give up auto segmentSplit because no row, segment={}", segment->simpleInfo());
return {};
}
schema_snap = store_columns;
}
// Not counting the early give up action.
auto delta_bytes = static_cast<Int64>(segment_snap->delta->getBytes());
auto delta_rows = static_cast<Int64>(segment_snap->delta->getRows());
size_t duplicated_bytes = 0;
size_t duplicated_rows = 0;
CurrentMetrics::Increment cur_dm_segments{CurrentMetrics::DT_SegmentSplit};
switch (reason)
{
case SegmentSplitReason::ForegroundWrite:
GET_METRIC(tiflash_storage_subtask_count, type_seg_split_fg).Increment();
break;
case SegmentSplitReason::Background:
GET_METRIC(tiflash_storage_subtask_count, type_seg_split_bg).Increment();
break;
case SegmentSplitReason::ForIngest:
GET_METRIC(tiflash_storage_subtask_count, type_seg_split_ingest).Increment();
break;
}
Stopwatch watch_seg_split;
SCOPE_EXIT({
switch (reason)
{
case SegmentSplitReason::ForegroundWrite:
GET_METRIC(tiflash_storage_subtask_duration_seconds, type_seg_split_fg)
.Observe(watch_seg_split.elapsedSeconds());
break;
case SegmentSplitReason::Background:
GET_METRIC(tiflash_storage_subtask_duration_seconds, type_seg_split_bg)
.Observe(watch_seg_split.elapsedSeconds());
break;
case SegmentSplitReason::ForIngest:
GET_METRIC(tiflash_storage_subtask_duration_seconds, type_seg_split_ingest)
.Observe(watch_seg_split.elapsedSeconds());
break;
}
});
WriteBatches wbs(*storage_pool, dm_context.getWriteLimiter());
Segment::SplitMode seg_split_mode;
switch (opt_split_mode)
{
case SegmentSplitMode::Auto:
seg_split_mode = Segment::SplitMode::Auto;
break;
case SegmentSplitMode::Logical:
seg_split_mode = Segment::SplitMode::Logical;
break;
case SegmentSplitMode::Physical:
seg_split_mode = Segment::SplitMode::Physical;
break;
default:
seg_split_mode = Segment::SplitMode::Auto;
break;
}
auto range = segment->getRowKeyRange();
auto split_info_opt
= segment->prepareSplit(dm_context, schema_snap, segment_snap, opt_split_at, seg_split_mode, wbs);
if (!split_info_opt.has_value())
{
// Likely we can not find an appropriate split point for this segment later, forbid the split until this segment get updated through applying delta-merge. Or it will slow down the write a lot.
segment->forbidSplit();
LOG_WARNING(
log,
"Split - Give up segmentSplit and forbid later auto split because prepare split failed, segment={}",
segment->simpleInfo());
return {};
}
auto & split_info = split_info_opt.value();
wbs.writeLogAndData();
split_info.my_stable->enableDMFilesGC(dm_context);
split_info.other_stable->enableDMFilesGC(dm_context);
SegmentPtr new_left, new_right;
{
std::unique_lock lock(read_write_mutex);
if (!isSegmentValid(lock, segment))
{
LOG_DEBUG(log, "Split - Give up segmentSplit because not valid, segment={}", segment->simpleInfo());
wbs.setRollback();
return {};
}
auto segment_lock = segment->mustGetUpdateLock();
std::tie(new_left, new_right) = segment->applySplit(segment_lock, dm_context, segment_snap, wbs, split_info);
wbs.writeMeta();
segment->abandon(dm_context);
removeSegment(lock, segment);
addSegment(lock, new_left);
addSegment(lock, new_right);
if constexpr (DM_RUN_CHECK)
{
new_left->check(dm_context, "After split left");
new_right->check(dm_context, "After split right");
}
duplicated_bytes = new_left->getDelta()->getBytes();
duplicated_rows = new_right->getDelta()->getBytes();
LOG_INFO(
log,
"Split - {} - Finish, segment is split into two, old_segment={} new_left={} new_right={}",
split_info.is_logical ? "SplitLogical" : "SplitPhysical",
segment->info(),
new_left->info(),
new_right->info());
}
wbs.writeRemoves();
if (!split_info.is_logical)
{
GET_METRIC(tiflash_storage_throughput_bytes, type_split).Increment(delta_bytes);
GET_METRIC(tiflash_storage_throughput_rows, type_split).Increment(delta_rows);
}
else
{
// For logical split, delta is duplicated into two segments. And will be merged into stable twice later. So we need to decrease it here.
// Otherwise the final total delta merge bytes is greater than bytes written into.
GET_METRIC(tiflash_storage_throughput_bytes, type_split).Decrement(duplicated_bytes);
GET_METRIC(tiflash_storage_throughput_rows, type_split).Decrement(duplicated_rows);
}
if constexpr (DM_RUN_CHECK)
check(dm_context.global_context);
// For logical split, no new DMFile is created, new_left and new_right share the same DMFile with the old segment.
// Even if the index build process of the old segment is not finished, after it is finished,
// it will also trigger the new_left and new_right to bump the meta version.
// So there is no need to check the local index update for logical split.
if (!split_info.is_logical)
{
segmentEnsureStableLocalIndexAsync(new_left);
segmentEnsureStableLocalIndexAsync(new_right);
}
return {new_left, new_right};
}
SegmentPtr DeltaMergeStore::segmentMerge(
DMContext & dm_context,
const std::vector<SegmentPtr> & ordered_segments,
SegmentMergeReason reason)
{
RUNTIME_CHECK(ordered_segments.size() >= 2, ordered_segments.size());
LOG_INFO(
log,
"Merge - Begin, reason={} safe_point={} segments_to_merge={}",
magic_enum::enum_name(reason),
dm_context.min_version,
Segment::simpleInfo(ordered_segments));
std::vector<SegmentSnapshotPtr> ordered_snapshots;
ordered_snapshots.reserve(ordered_segments.size());
ColumnDefinesPtr schema_snap;
{
std::shared_lock lock(read_write_mutex);
for (const auto & seg : ordered_segments)
{
if (!isSegmentValid(lock, seg))
{
LOG_DEBUG(log, "Merge - Give up segmentMerge because not valid, segment={}", seg->simpleInfo());
return {};
}
}
for (const auto & seg : ordered_segments)
{
auto snap
= seg->createSnapshot(dm_context, /* for_update */ true, CurrentMetrics::DT_SnapshotOfSegmentMerge);
if (!snap)
{
LOG_DEBUG(log, "Merge - Give up segmentMerge because snapshot failed, segment={}", seg->simpleInfo());
return {};
}
ordered_snapshots.emplace_back(snap);
}
schema_snap = store_columns;
}
// Not counting the early give up action.
Int64 delta_bytes = 0;
Int64 delta_rows = 0;
for (const auto & snap : ordered_snapshots)
{
delta_bytes += static_cast<Int64>(snap->delta->getBytes());
delta_rows += static_cast<Int64>(snap->delta->getRows());
}
CurrentMetrics::Increment cur_dm_segments{CurrentMetrics::DT_SegmentMerge};
switch (reason)
{
case SegmentMergeReason::BackgroundGCThread:
GET_METRIC(tiflash_storage_subtask_count, type_seg_merge_bg_gc).Increment();
break;
default:
break;
}
Stopwatch watch_seg_merge;
SCOPE_EXIT({
switch (reason)
{
case SegmentMergeReason::BackgroundGCThread:
GET_METRIC(tiflash_storage_subtask_duration_seconds, type_seg_merge_bg_gc)
.Observe(watch_seg_merge.elapsedSeconds());
break;
default:
break;
}
});
WriteBatches wbs(*storage_pool, dm_context.getWriteLimiter());
auto merged_stable = Segment::prepareMerge(dm_context, schema_snap, ordered_segments, ordered_snapshots, wbs);
wbs.writeLogAndData();
merged_stable->enableDMFilesGC(dm_context);
SYNC_FOR("after_DeltaMergeStore::segmentMerge|prepare_merge");
SegmentPtr merged;
{
std::unique_lock lock(read_write_mutex);
for (const auto & seg : ordered_segments)
{
if (!isSegmentValid(lock, seg))
{
LOG_DEBUG(log, "Merge - Give up segmentMerge because not valid, segment={}", seg->simpleInfo());
wbs.setRollback();
return {};
}
}
std::vector<Segment::Lock> locks;
locks.reserve(ordered_segments.size());
for (const auto & seg : ordered_segments)
locks.emplace_back(seg->mustGetUpdateLock());
merged = Segment::applyMerge(locks, dm_context, ordered_segments, ordered_snapshots, wbs, merged_stable);
wbs.writeMeta();
for (const auto & seg : ordered_segments)
{
seg->abandon(dm_context);
removeSegment(lock, seg);
}
addSegment(lock, merged);
if constexpr (DM_RUN_CHECK)
merged->check(dm_context, "After segment merge");
LOG_INFO(
log,
"Merge - Finish, {} segments are merged into one, reason={} merged={} segments_to_merge={}",
ordered_segments.size(),
magic_enum::enum_name(reason),
merged->info(),
Segment::info(ordered_segments));
}
wbs.writeRemoves();
GET_METRIC(tiflash_storage_throughput_bytes, type_merge).Increment(delta_bytes);
GET_METRIC(tiflash_storage_throughput_rows, type_merge).Increment(delta_rows);
if constexpr (DM_RUN_CHECK)
check(dm_context.global_context);
segmentEnsureStableLocalIndexAsync(merged);
return merged;
}
void DeltaMergeStore::checkAllSegmentsLocalIndex(std::vector<IndexID> && dropped_indexes)
{
if (!getLocalIndexInfosSnapshot())
return;
LOG_INFO(log, "CheckAllSegmentsLocalIndex - Begin");
size_t segments_updated_meta = 0;
auto dm_context = newDMContext(global_context, global_context.getSettingsRef(), "checkAllSegmentsLocalIndex");
// 1. Make all segments referencing latest meta version.
{
Stopwatch watch;
std::unique_lock lock(read_write_mutex);
std::map<PageIdU64, DMFilePtr> latest_dmf_by_id;
for (const auto & [end, segment] : segments)
{
UNUSED(end);
for (const auto & dm_file : segment->getStable()->getDMFiles())
{
auto & latest_dmf = latest_dmf_by_id[dm_file->fileId()];
if (!latest_dmf || dm_file->metaVersion() > latest_dmf->metaVersion())
// Note: pageId could be different. It is fine.
latest_dmf = dm_file;
}
}
for (const auto & [end, segment] : segments)
{
UNUSED(end);
for (const auto & dm_file : segment->getStable()->getDMFiles())
{
auto & latest_dmf = latest_dmf_by_id.at(dm_file->fileId());
if (dm_file->metaVersion() < latest_dmf->metaVersion())
{
// Note: pageId could be different. It is fine, replaceStableMetaVersion will fix it.
auto update_result = segmentUpdateMeta(lock, *dm_context, segment, {latest_dmf});
RUNTIME_CHECK(update_result != nullptr, segment->simpleInfo());
++segments_updated_meta;
}
}
}
LOG_INFO(
log,
"CheckAllSegmentsLocalIndex - Finish, updated_meta={}, elapsed={:.3f}s",
segments_updated_meta,
watch.elapsedSeconds());
}
size_t segments_missing_indexes = 0;
// 2. Trigger EnsureStableLocalIndex & EnsureDeltaLocalIndex for all segments.
// There could be new segments between 1 and 2, which is fine. New segments
// will invoke EnsureStableLocalIndex & EnsureDeltaLocalIndex at creation time.
{
// There must be a lock, because segments[] may be mutated.
// And one lock for all is fine, because segmentEnsureStableLocalIndexAsync & segmentEnsureDeltaLocalIndexAsync is non-blocking, it
// simply put tasks in the background.
std::shared_lock lock(read_write_mutex);
for (const auto & [end, segment] : segments)
{
UNUSED(end);
// cleanup the index error message for dropped indexes
segment->clearIndexBuildError(dropped_indexes);
bool stable_missing_indexes = segmentEnsureStableLocalIndexAsync(segment);
bool delta_missing_indexes = segmentEnsureDeltaLocalIndexAsync(segment);
segments_missing_indexes += (stable_missing_indexes || delta_missing_indexes);
}
}
LOG_INFO(
log,
"CheckAllSegmentsLocalIndex - Finish, segments_[updated_meta/missing_index]={}/{}",
segments_updated_meta,
segments_missing_indexes);
}
bool DeltaMergeStore::segmentEnsureStableLocalIndexAsync(const SegmentPtr & segment)
{
RUNTIME_CHECK(segment != nullptr);
auto local_index_infos_snap = getLocalIndexInfosSnapshot();
if (!local_index_infos_snap)
return false;
// No lock is needed, stable meta is immutable.
const auto build_info
= DMFileLocalIndexWriter::getLocalIndexBuildInfo(local_index_infos_snap, segment->getStable()->getDMFiles());
if (!build_info.indexes_to_build || build_info.indexes_to_build->empty() || build_info.dm_files.empty())
return false;
if (auto encryption_enabled = global_context.getFileProvider()->isEncryptionEnabled(); encryption_enabled)
{
segment->setIndexBuildError(
build_info.indexesIDs(),
"Encryption-at-rest on TiFlash is enabled, which does not support building vector index");
return false;
}
auto store_weak_ptr = weak_from_this();
auto tracing_id = fmt::format("segmentEnsureStableLocalIndex source_segment={}", segment->simpleInfo());
auto workload = [store_weak_ptr, build_info, tracing_id]() -> void {
auto store = store_weak_ptr.lock();
if (store == nullptr) // Store is destroyed before the task is executed.
return;
auto dm_context = store->newDMContext( //
store->global_context,
store->global_context.getSettingsRef(),
tracing_id);
store->segmentEnsureStableLocalIndexWithErrorReport(*dm_context, build_info);
};
auto indexer_scheduler = global_context.getGlobalLocalIndexerScheduler();
RUNTIME_CHECK(indexer_scheduler != nullptr);
try
{
// new task of these index are generated, clear existing error_message in segment
segment->clearIndexBuildError(build_info.indexesIDs());
auto file_ids = build_info.filesIDs();
if (file_ids.empty())
return true;
auto [ok, reason] = indexer_scheduler->pushTask(LocalIndexerScheduler::Task{
.keyspace_id = keyspace_id,
.table_id = physical_table_id,
.file_ids = file_ids,
.request_memory = build_info.estimated_memory_bytes,
.workload = workload,
});
if (ok)
return true;
segment->setIndexBuildError(build_info.indexesIDs(), reason);
LOG_ERROR(
log->getChild(tracing_id),
"Failed to generate async segment stable index task, index_ids={} reason={}",
build_info.indexesIDs(),
reason);
return false;
}
catch (...)
{
const auto message = getCurrentExceptionMessage(false, false);
segment->setIndexBuildError(build_info.indexesIDs(), message);
tryLogCurrentException(log);
// catch and ignore the exception
// not able to push task to index scheduler
return false;
}
}
bool DeltaMergeStore::segmentWaitStableLocalIndexReady(const SegmentPtr & segment) const
{
RUNTIME_CHECK(segment != nullptr);
auto local_index_infos_snap = getLocalIndexInfosSnapshot();
if (!local_index_infos_snap)
return true;
// No lock is needed, stable meta is immutable.
auto segment_id = segment->segmentId();
auto build_info
= DMFileLocalIndexWriter::getLocalIndexBuildInfo(local_index_infos_snap, segment->getStable()->getDMFiles());
if (!build_info.indexes_to_build || build_info.indexes_to_build->empty())
return true;
static constexpr size_t MAX_CHECK_TIME_SECONDS = 60; // 60s
Stopwatch watch;
while (watch.elapsedSeconds() < MAX_CHECK_TIME_SECONDS)
{
DMFilePtr dmfile;
{
std::shared_lock lock(read_write_mutex);
auto seg = id_to_segment.at(segment_id);
assert(!seg->getStable()->getDMFiles().empty());
dmfile = seg->getStable()->getDMFiles()[0];
}
if (!dmfile)
return false; // DMFile is not exist, return false
bool all_indexes_built = true;
for (const auto & index : *build_info.indexes_to_build)
{
const auto [state, bytes] = dmfile->getLocalIndexState(index.column_id, index.index_id);
UNUSED(bytes);
all_indexes_built = all_indexes_built
// dmfile built before the column_id added or index already built
&& (state == DMFileMeta::LocalIndexState::NoNeed || state == DMFileMeta::LocalIndexState::IndexBuilt);
}
if (all_indexes_built)
return true;
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 0.1s
}
return false;
}
SegmentPtr DeltaMergeStore::segmentUpdateMeta(
std::unique_lock<std::shared_mutex> & read_write_lock,
DMContext & dm_context,
const SegmentPtr & segment,
const DMFiles & new_dm_files)
{
if (!isSegmentValid(read_write_lock, segment))
{
LOG_WARNING(log, "SegmentUpdateMeta - Give up because segment not valid, segment={}", segment->simpleInfo());
return {};
}
auto lock = segment->mustGetUpdateLock();
auto new_segment = segment->replaceStableMetaVersion(lock, dm_context, new_dm_files);
if (new_segment == nullptr)
{
LOG_WARNING(
log,
"SegmentUpdateMeta - Failed due to replace stableMeta failed, segment={}",
segment->simpleInfo());
return {};
}
replaceSegment(read_write_lock, segment, new_segment);
// Must not abandon old segment, because they share the same delta.
// segment->abandon(dm_context);
if constexpr (DM_RUN_CHECK)
{
new_segment->check(dm_context, "After SegmentUpdateMeta");
}
LOG_INFO(
log,
"SegmentUpdateMeta - Finish, old_segment={} new_segment={}",
segment->simpleInfo(),
new_segment->simpleInfo());
return new_segment;
}
void DeltaMergeStore::segmentEnsureStableLocalIndex(
DMContext & dm_context,
const LocalIndexBuildInfo & index_build_info)
{
// 1. Acquire a snapshot for PageStorage, and keep the snapshot until index is built.
// This helps keep DMFile valid during the index build process.
// We don't acquire a snapshot from the source_segment, because the source_segment
// may be abandoned at this moment.
//
// Note that we cannot simply skip the index building when seg is not valid any more,
// because segL and segR is still referencing them, consider this case:
// 1. seg=PhysicalSplit
// 2. Add CreateStableLocalIndex(seg) to ThreadPool
// 3. segL, segR=LogicalSplit(seg)
// 4. CreateStableLocalIndex(seg)
auto storage_snapshot = std::make_shared<StorageSnapshot>( //
*dm_context.storage_pool,
dm_context.getReadLimiter(),
dm_context.tracing_id);
auto tracing_logger = log->getChild(getLogTracingId(dm_context));
RUNTIME_CHECK(index_build_info.dm_files.size() == 1); // size > 1 is currently not supported.
const auto & dm_file = index_build_info.dm_files[0];
auto is_file_valid = [this, dm_file] {
std::shared_lock lock(read_write_mutex);
auto segment_ids = dmfile_id_to_segment_ids.get(dm_file->fileId());
return !segment_ids.empty();
};
// 2. Check whether the DMFile has been referenced by any valid segment.
if (!is_file_valid())
{
LOG_DEBUG(tracing_logger, "EnsureStableLocalIndex - Give up because no segment to update");
return;
}
LOG_INFO(
tracing_logger,
"EnsureStableLocalIndex - Begin building index, dm_files={}",
DMFile::info(index_build_info.dm_files));
// 2. Build the index.
DMFileLocalIndexWriter iw(DMFileLocalIndexWriter::Options{
.path_pool = path_pool,
.index_infos = index_build_info.indexes_to_build,
.dm_files = index_build_info.dm_files,
.dm_context = dm_context,
});
DMFiles new_dmfiles{};
try
{
// When file is not valid we need to abort the index build.
new_dmfiles = iw.build(is_file_valid);
}
catch (const Exception & e)
{
if (e.code() == ErrorCodes::ABORTED)
{
LOG_INFO(
tracing_logger,
"EnsureStableLocalIndex - Build index aborted because DMFile is no longer valid, dm_files={}",
DMFile::info(index_build_info.dm_files));
return;
}
throw;
}
RUNTIME_CHECK(!new_dmfiles.empty());
LOG_INFO(
tracing_logger,
"EnsureStableLocalIndex - Finish building index, dm_files={}",
DMFile::info(index_build_info.dm_files));
// 3. Update the meta version of the segments to the latest one.
// To avoid logical split between step 2 and 3, get lastest segments to update again.
// If TiFlash crashes during updating the meta version, some segments' meta are updated and some are not.
// So after TiFlash restarts, we will update meta versions to latest versions again.
{
// We must acquire a single lock when updating multiple segments.
// Otherwise we may miss new segments.
std::unique_lock lock(read_write_mutex);
auto segment_ids = dmfile_id_to_segment_ids.get(dm_file->fileId());
for (const auto & seg_id : segment_ids)
{
auto segment = id_to_segment[seg_id];
auto new_segment = segmentUpdateMeta(lock, dm_context, segment, new_dmfiles);
// Expect update meta always success, because the segment must be valid and bump meta should succeed.
RUNTIME_CHECK_MSG(
new_segment != nullptr,
"Update meta failed for segment {} ident={}",
segment->simpleInfo(),
tracing_logger->identifier());
}
}
}
// A wrapper of `segmentEnsureStableLocalIndex`
// If any exception thrown, the error message will be recorded to
// the related segment(s)
void DeltaMergeStore::segmentEnsureStableLocalIndexWithErrorReport(
DMContext & dm_context,
const LocalIndexBuildInfo & index_build_info)
{
auto handle_error = [this, &index_build_info](const std::vector<IndexID> & index_ids) {
const auto message = getCurrentExceptionMessage(false, false);
std::unordered_map<PageIdU64, SegmentPtr> segment_to_add_msg;
{
std::unique_lock lock(read_write_mutex);
for (const auto & dmf : index_build_info.dm_files)
{
const auto segment_ids = dmfile_id_to_segment_ids.get(dmf->fileId());
for (const auto & seg_id : segment_ids)
{
if (segment_to_add_msg.contains(seg_id))
continue;
segment_to_add_msg.emplace(seg_id, id_to_segment[seg_id]);
}
}
}
for (const auto & [seg_id, seg] : segment_to_add_msg)
{
UNUSED(seg_id);
seg->setIndexBuildError(index_ids, message);
}
};
try
{
segmentEnsureStableLocalIndex(dm_context, index_build_info);
}
catch (DB::Exception & e)
{
const auto index_ids = index_build_info.indexesIDs();
e.addMessage(fmt::format("while building stable index for index_ids={}", index_ids));
handle_error(index_ids);
// rethrow
throw;
}
catch (...)
{
const auto index_ids = index_build_info.indexesIDs();
handle_error(index_ids);
// rethrow
throw;
}
}
namespace
{
struct LocalIndexOnDeltaVSBuildInfo
{
ColumnFileTinyLocalIndexWriter::LocalIndexBuildInfo build_info;
std::weak_ptr<DeltaValueSpace> delta_weak_ptr;
};
std::optional<LocalIndexOnDeltaVSBuildInfo> //
genBuildInfoFromDeltaVS(const SegmentPtr & segment, const LocalIndexInfosSnapshot & local_index_infos)
{
// Acquire a lock to make sure delta is not changed during the process.
auto lock = segment->getUpdateLock();
if (!lock)
return std::nullopt;
// The segment is running an update(SegmentMergeDelta/SegmentMerge/SegmentSplit) task, skip the index build.
if (segment->getDelta()->isUpdating())
return std::nullopt;
// In case nothing to be built
auto column_file_persisted_set = segment->getDelta()->getPersistedFileSet();
if (!column_file_persisted_set)
return std::nullopt;
auto build_info
= ColumnFileTinyLocalIndexWriter::getLocalIndexBuildInfo(local_index_infos, column_file_persisted_set);
if (!build_info.indexes_to_build || build_info.indexes_to_build->empty())
return std::nullopt;
// Use weak_ptr to avoid blocking gc.
auto delta_weak_ptr = std::weak_ptr<DeltaValueSpace>(segment->getDelta());
lock->unlock();
return LocalIndexOnDeltaVSBuildInfo{build_info, delta_weak_ptr};
}
} // namespace
bool DeltaMergeStore::segmentEnsureDeltaLocalIndexAsync(const SegmentPtr & segment)
{
RUNTIME_CHECK(segment != nullptr);
auto local_index_infos_snap = getLocalIndexInfosSnapshot();
if (!local_index_infos_snap)
return false;
auto delta_vs_build_info = genBuildInfoFromDeltaVS(segment, local_index_infos_snap);
if (!delta_vs_build_info)
{
LOG_DEBUG(
log,
"segmentEnsureDeltaLocalIndexAsync - Give up because no index to build or delta is being updated, "
"segment={}",
segment->simpleInfo());
return true;
}
auto store_weak_ptr = weak_from_this();
const auto source_segment_info = segment->simpleInfo();
auto workload = [store_weak_ptr, delta_vs_build_info, source_segment_info]() -> void {
auto store = store_weak_ptr.lock();
if (!store) // Store is destroyed before the task is executed.
return;
auto delta = delta_vs_build_info->delta_weak_ptr.lock();
if (!delta) // Delta is destroyed before the task is executed.
return;
auto tracing_id = fmt::format("segmentEnsureDeltaLocalIndexAsync source_segment={}", source_segment_info);
auto dm_context = store->newDMContext( //
store->global_context,
store->global_context.getSettingsRef(),
tracing_id);
store->segmentEnsureDeltaLocalIndex(
*dm_context,
delta_vs_build_info->build_info.indexes_to_build,
delta,
source_segment_info);
};
auto indexer_scheduler = global_context.getGlobalLocalIndexerScheduler();
RUNTIME_CHECK(indexer_scheduler != nullptr);
try
{
// new task of these index are generated, clear existing error_message in segment
segment->clearIndexBuildError(delta_vs_build_info->build_info.index_ids);
auto [ok, reason] = indexer_scheduler->pushTask(LocalIndexerScheduler::Task{
.keyspace_id = keyspace_id,
.table_id = physical_table_id,
.file_ids = delta_vs_build_info->build_info.file_ids,
.request_memory = delta_vs_build_info->build_info.estimated_memory_bytes,
.workload = workload,
});
if (ok)
return true;
segment->setIndexBuildError(delta_vs_build_info->build_info.index_ids, reason);
auto tracing_id = fmt::format("segmentEnsureDeltaLocalIndexAsync source_segment={}", source_segment_info);
LOG_ERROR(
log->getChild(tracing_id),
"Failed to generate async segment stable index task, index_ids={} reason={}",
delta_vs_build_info->build_info.index_ids,
reason);
return false;
}
catch (...)
{
const auto message = getCurrentExceptionMessage(false, false);
segment->setIndexBuildError(delta_vs_build_info->build_info.index_ids, message);
tryLogCurrentException(log);
// catch and ignore the exception
// not able to push task to index scheduler
return false;
}
}
bool DeltaMergeStore::segmentWaitDeltaLocalIndexReady(const SegmentPtr & segment) const
{
RUNTIME_CHECK(segment != nullptr);
auto local_index_infos_snap = getLocalIndexInfosSnapshot();
if (!local_index_infos_snap)
return true;
auto delta_vs_build_info = genBuildInfoFromDeltaVS(segment, local_index_infos_snap);
if (!delta_vs_build_info)
{
LOG_INFO(
log,
"WaitDeltaLocalIndexReady - Give up because no index to build or delta is being updated, segment={}",
segment->simpleInfo());
return true;
}
auto segment_id = segment->segmentId();
static constexpr size_t MAX_CHECK_TIME_SECONDS = 60; // 60s
Stopwatch watch;
while (watch.elapsedSeconds() < MAX_CHECK_TIME_SECONDS)
{
ColumnFilePersistedSetPtr column_file_persisted_set;
{
std::shared_lock lock(read_write_mutex);
auto seg = id_to_segment.at(segment_id);
column_file_persisted_set = seg->getDelta()->getPersistedFileSet();
}
if (!column_file_persisted_set)
return false; // ColumnFilePersistedSet is not exist, return false
bool all_indexes_built = true;
auto delta_ptr = delta_vs_build_info->delta_weak_ptr.lock();
if (auto lock = delta_ptr ? delta_ptr->getLock() : std::nullopt; lock)