-
Notifications
You must be signed in to change notification settings - Fork 598
/
Copy pathmod.rs
2089 lines (1901 loc) · 76.2 KB
/
mod.rs
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 2024 RisingWave Labs
//
// 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.
mod spiller;
mod task_manager;
pub(crate) mod test_utils;
use std::cmp::Ordering;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::fmt::{Debug, Display, Formatter};
use std::future::{poll_fn, Future};
use std::mem::{replace, swap, take};
use std::sync::Arc;
use std::task::{ready, Context, Poll};
use futures::FutureExt;
use itertools::Itertools;
use more_asserts::assert_gt;
use prometheus::core::{AtomicU64, GenericGauge};
use prometheus::{HistogramTimer, IntGauge};
use risingwave_common::bitmap::BitmapBuilder;
use risingwave_common::catalog::TableId;
use risingwave_common::must_match;
use risingwave_hummock_sdk::table_watermark::{
TableWatermarks, VnodeWatermark, WatermarkDirection,
};
use risingwave_hummock_sdk::{HummockEpoch, LocalSstableInfo};
use task_manager::{TaskManager, UploadingTaskStatus};
use thiserror_ext::AsReport;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use tracing::{debug, error, info, warn};
use crate::hummock::event_handler::hummock_event_handler::{send_sync_result, BufferTracker};
use crate::hummock::event_handler::uploader::spiller::Spiller;
use crate::hummock::event_handler::uploader::uploader_imm::UploaderImm;
use crate::hummock::event_handler::LocalInstanceId;
use crate::hummock::local_version::pinned_version::PinnedVersion;
use crate::hummock::shared_buffer::shared_buffer_batch::SharedBufferBatchId;
use crate::hummock::store::version::StagingSstableInfo;
use crate::hummock::{HummockError, HummockResult, ImmutableMemtable};
use crate::mem_table::ImmId;
use crate::monitor::HummockStateStoreMetrics;
use crate::opts::StorageOpts;
use crate::store::SealCurrentEpochOptions;
/// Take epoch data inclusively before `epoch` out from `data`
fn take_before_epoch<T>(
data: &mut BTreeMap<HummockEpoch, T>,
epoch: HummockEpoch,
) -> BTreeMap<HummockEpoch, T> {
let mut before_epoch_data = data.split_off(&(epoch + 1));
swap(&mut before_epoch_data, data);
before_epoch_data
}
type UploadTaskInput = HashMap<LocalInstanceId, Vec<UploaderImm>>;
pub type UploadTaskPayload = HashMap<LocalInstanceId, Vec<ImmutableMemtable>>;
#[derive(Debug)]
pub struct UploadTaskOutput {
pub new_value_ssts: Vec<LocalSstableInfo>,
pub old_value_ssts: Vec<LocalSstableInfo>,
pub wait_poll_timer: Option<HistogramTimer>,
}
pub type SpawnUploadTask = Arc<
dyn Fn(UploadTaskPayload, UploadTaskInfo) -> JoinHandle<HummockResult<UploadTaskOutput>>
+ Send
+ Sync
+ 'static,
>;
#[derive(Clone)]
pub struct UploadTaskInfo {
pub task_size: usize,
pub epochs: Vec<HummockEpoch>,
pub imm_ids: HashMap<LocalInstanceId, Vec<ImmId>>,
}
impl Display for UploadTaskInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UploadTaskInfo")
.field("task_size", &self.task_size)
.field("epochs", &self.epochs)
.field("len(imm_ids)", &self.imm_ids.len())
.finish()
}
}
impl Debug for UploadTaskInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UploadTaskInfo")
.field("task_size", &self.task_size)
.field("epochs", &self.epochs)
.field("imm_ids", &self.imm_ids)
.finish()
}
}
mod uploader_imm {
use std::fmt::Formatter;
use std::ops::Deref;
use prometheus::core::{AtomicU64, GenericGauge};
use crate::hummock::event_handler::uploader::UploaderContext;
use crate::mem_table::ImmutableMemtable;
pub(super) struct UploaderImm {
inner: ImmutableMemtable,
size_guard: GenericGauge<AtomicU64>,
}
impl UploaderImm {
pub(super) fn new(imm: ImmutableMemtable, context: &UploaderContext) -> Self {
let size = imm.size();
let size_guard = context.stats.uploader_imm_size.clone();
size_guard.add(size as _);
Self {
inner: imm,
size_guard,
}
}
#[cfg(test)]
pub(super) fn for_test(imm: ImmutableMemtable) -> Self {
Self {
inner: imm,
size_guard: GenericGauge::new("test", "test").unwrap(),
}
}
}
impl std::fmt::Debug for UploaderImm {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.inner.fmt(f)
}
}
impl Deref for UploaderImm {
type Target = ImmutableMemtable;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl Drop for UploaderImm {
fn drop(&mut self) {
self.size_guard.sub(self.inner.size() as _);
}
}
}
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Copy, Clone, Debug)]
struct UploadingTaskId(usize);
/// A wrapper for a uploading task that compacts and uploads the imm payload. Task context are
/// stored so that when the task fails, it can be re-tried.
struct UploadingTask {
task_id: UploadingTaskId,
// newer data at the front
input: UploadTaskInput,
join_handle: JoinHandle<HummockResult<UploadTaskOutput>>,
task_info: UploadTaskInfo,
spawn_upload_task: SpawnUploadTask,
task_size_guard: GenericGauge<AtomicU64>,
task_count_guard: IntGauge,
}
impl Drop for UploadingTask {
fn drop(&mut self) {
self.task_size_guard.sub(self.task_info.task_size as u64);
self.task_count_guard.dec();
}
}
impl Debug for UploadingTask {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UploadingTask")
.field("input", &self.input)
.field("task_info", &self.task_info)
.finish()
}
}
fn get_payload_imm_ids(
payload: &UploadTaskPayload,
) -> HashMap<LocalInstanceId, Vec<SharedBufferBatchId>> {
payload
.iter()
.map(|(instance_id, imms)| {
(
*instance_id,
imms.iter().map(|imm| imm.batch_id()).collect_vec(),
)
})
.collect()
}
impl UploadingTask {
// INFO logs will be enabled for task with size exceeding 50MB.
const LOG_THRESHOLD_FOR_UPLOAD_TASK_SIZE: usize = 50 * (1 << 20);
fn input_to_payload(input: &UploadTaskInput) -> UploadTaskPayload {
input
.iter()
.map(|(instance_id, imms)| {
(
*instance_id,
imms.iter().map(|imm| (**imm).clone()).collect(),
)
})
.collect()
}
fn new(task_id: UploadingTaskId, input: UploadTaskInput, context: &UploaderContext) -> Self {
assert!(!input.is_empty());
let mut epochs = input
.iter()
.flat_map(|(_, imms)| imms.iter().flat_map(|imm| imm.epochs().iter().cloned()))
.sorted()
.dedup()
.collect_vec();
// reverse to make newer epochs comes first
epochs.reverse();
let payload = Self::input_to_payload(&input);
let imm_ids = get_payload_imm_ids(&payload);
let task_size = input
.values()
.map(|imms| imms.iter().map(|imm| imm.size()).sum::<usize>())
.sum();
let task_info = UploadTaskInfo {
task_size,
epochs,
imm_ids,
};
context
.buffer_tracker
.global_upload_task_size()
.add(task_size as u64);
if task_info.task_size > Self::LOG_THRESHOLD_FOR_UPLOAD_TASK_SIZE {
info!("start upload task: {:?}", task_info);
} else {
debug!("start upload task: {:?}", task_info);
}
let join_handle = (context.spawn_upload_task)(payload, task_info.clone());
context.stats.uploader_uploading_task_count.inc();
Self {
task_id,
input,
join_handle,
task_info,
spawn_upload_task: context.spawn_upload_task.clone(),
task_size_guard: context.buffer_tracker.global_upload_task_size().clone(),
task_count_guard: context.stats.uploader_uploading_task_count.clone(),
}
}
/// Poll the result of the uploading task
fn poll_result(
&mut self,
cx: &mut Context<'_>,
) -> Poll<HummockResult<Arc<StagingSstableInfo>>> {
Poll::Ready(match ready!(self.join_handle.poll_unpin(cx)) {
Ok(task_result) => task_result
.inspect(|_| {
if self.task_info.task_size > Self::LOG_THRESHOLD_FOR_UPLOAD_TASK_SIZE {
info!(task_info = ?self.task_info, "upload task finish");
} else {
debug!(task_info = ?self.task_info, "upload task finish");
}
})
.inspect_err(|e| error!(task_info = ?self.task_info, err = ?e.as_report(), "upload task failed"))
.map(|output| {
Arc::new(StagingSstableInfo::new(
output.new_value_ssts,
output.old_value_ssts,
self.task_info.epochs.clone(),
self.task_info.imm_ids.clone(),
self.task_info.task_size,
))
}),
Err(err) => Err(HummockError::other(format!(
"fail to join upload join handle: {}",
err.as_report()
))),
})
}
/// Poll the uploading task until it succeeds. If it fails, we will retry it.
fn poll_ok_with_retry(&mut self, cx: &mut Context<'_>) -> Poll<Arc<StagingSstableInfo>> {
loop {
let result = ready!(self.poll_result(cx));
match result {
Ok(sstables) => return Poll::Ready(sstables),
Err(e) => {
error!(
error = %e.as_report(),
task_info = ?self.task_info,
"a flush task failed, start retry",
);
self.join_handle = (self.spawn_upload_task)(
Self::input_to_payload(&self.input),
self.task_info.clone(),
);
// It is important not to return Poll::pending here immediately, because the new
// join_handle is not polled yet, and will not awake the current task when
// succeed. It will be polled in the next loop iteration.
}
}
}
}
pub fn get_task_info(&self) -> &UploadTaskInfo {
&self.task_info
}
}
impl TableUnsyncData {
fn add_table_watermarks(
&mut self,
epoch: HummockEpoch,
table_watermarks: Vec<VnodeWatermark>,
direction: WatermarkDirection,
) {
if table_watermarks.is_empty() {
return;
}
let vnode_count = table_watermarks[0].vnode_count();
for watermark in &table_watermarks {
assert_eq!(vnode_count, watermark.vnode_count());
}
fn apply_new_vnodes(
vnode_bitmap: &mut BitmapBuilder,
vnode_watermarks: &Vec<VnodeWatermark>,
) {
for vnode_watermark in vnode_watermarks {
for vnode in vnode_watermark.vnode_bitmap().iter_ones() {
assert!(
!vnode_bitmap.is_set(vnode),
"vnode {} write multiple table watermarks",
vnode
);
vnode_bitmap.set(vnode, true);
}
}
}
match &mut self.table_watermarks {
Some((prev_direction, prev_watermarks)) => {
assert_eq!(
*prev_direction, direction,
"table id {} new watermark direction not match with previous",
self.table_id
);
match prev_watermarks.entry(epoch) {
Entry::Occupied(mut entry) => {
let (prev_watermarks, vnode_bitmap) = entry.get_mut();
apply_new_vnodes(vnode_bitmap, &table_watermarks);
prev_watermarks.extend(table_watermarks);
}
Entry::Vacant(entry) => {
let mut vnode_bitmap = BitmapBuilder::zeroed(vnode_count);
apply_new_vnodes(&mut vnode_bitmap, &table_watermarks);
entry.insert((table_watermarks, vnode_bitmap));
}
}
}
None => {
let mut vnode_bitmap = BitmapBuilder::zeroed(vnode_count);
apply_new_vnodes(&mut vnode_bitmap, &table_watermarks);
self.table_watermarks = Some((
direction,
BTreeMap::from_iter([(epoch, (table_watermarks, vnode_bitmap))]),
));
}
}
}
}
impl UploaderData {
fn add_table_watermarks(
all_table_watermarks: &mut HashMap<TableId, TableWatermarks>,
table_id: TableId,
direction: WatermarkDirection,
watermarks: impl Iterator<Item = (HummockEpoch, Vec<VnodeWatermark>)>,
) {
let mut table_watermarks: Option<TableWatermarks> = None;
for (epoch, watermarks) in watermarks {
match &mut table_watermarks {
Some(prev_watermarks) => {
prev_watermarks.add_new_epoch_watermarks(
epoch,
Arc::from(watermarks),
direction,
);
}
None => {
table_watermarks =
Some(TableWatermarks::single_epoch(epoch, watermarks, direction));
}
}
}
if let Some(table_watermarks) = table_watermarks {
assert!(all_table_watermarks
.insert(table_id, table_watermarks)
.is_none());
}
}
}
struct LocalInstanceEpochData {
epoch: HummockEpoch,
// newer data comes first.
imms: VecDeque<UploaderImm>,
has_spilled: bool,
}
impl LocalInstanceEpochData {
fn new(epoch: HummockEpoch) -> Self {
Self {
epoch,
imms: VecDeque::new(),
has_spilled: false,
}
}
fn epoch(&self) -> HummockEpoch {
self.epoch
}
fn add_imm(&mut self, imm: UploaderImm) {
assert_eq!(imm.max_epoch(), imm.min_epoch());
assert_eq!(self.epoch, imm.min_epoch());
if let Some(prev_imm) = self.imms.front() {
assert_gt!(imm.batch_id(), prev_imm.batch_id());
}
self.imms.push_front(imm);
}
fn is_empty(&self) -> bool {
self.imms.is_empty()
}
}
struct LocalInstanceUnsyncData {
table_id: TableId,
instance_id: LocalInstanceId,
// None means that the current instance should have stopped advancing
current_epoch_data: Option<LocalInstanceEpochData>,
// newer data comes first.
sealed_data: VecDeque<LocalInstanceEpochData>,
// newer data comes first
flushing_imms: VecDeque<SharedBufferBatchId>,
}
impl LocalInstanceUnsyncData {
fn new(table_id: TableId, instance_id: LocalInstanceId, init_epoch: HummockEpoch) -> Self {
Self {
table_id,
instance_id,
current_epoch_data: Some(LocalInstanceEpochData::new(init_epoch)),
sealed_data: VecDeque::new(),
flushing_imms: Default::default(),
}
}
fn add_imm(&mut self, imm: UploaderImm) {
assert_eq!(self.table_id, imm.table_id);
self.current_epoch_data
.as_mut()
.expect("should be Some when adding new imm")
.add_imm(imm);
}
fn local_seal_epoch(&mut self, next_epoch: HummockEpoch) -> HummockEpoch {
let data = self
.current_epoch_data
.as_mut()
.expect("should be Some when seal new epoch");
let current_epoch = data.epoch;
debug!(
instance_id = self.instance_id,
next_epoch, current_epoch, "local seal epoch"
);
assert_gt!(next_epoch, current_epoch);
let epoch_data = replace(data, LocalInstanceEpochData::new(next_epoch));
if !epoch_data.is_empty() {
self.sealed_data.push_front(epoch_data);
}
current_epoch
}
// imm_ids from old to new, which means in ascending order
fn ack_flushed(&mut self, imm_ids: impl Iterator<Item = SharedBufferBatchId>) {
for imm_id in imm_ids {
assert_eq!(self.flushing_imms.pop_back().expect("should exist"), imm_id);
}
}
fn spill(&mut self, epoch: HummockEpoch) -> Vec<UploaderImm> {
let imms = if let Some(oldest_sealed_epoch) = self.sealed_data.back() {
match oldest_sealed_epoch.epoch.cmp(&epoch) {
Ordering::Less => {
unreachable!(
"should not spill at this epoch because there \
is unspilled data in previous epoch: prev epoch {}, spill epoch {}",
oldest_sealed_epoch.epoch, epoch
);
}
Ordering::Equal => {
let epoch_data = self.sealed_data.pop_back().unwrap();
assert_eq!(epoch, epoch_data.epoch);
epoch_data.imms
}
Ordering::Greater => VecDeque::new(),
}
} else {
let Some(current_epoch_data) = &mut self.current_epoch_data else {
return Vec::new();
};
match current_epoch_data.epoch.cmp(&epoch) {
Ordering::Less => {
assert!(
current_epoch_data.imms.is_empty(),
"should not spill at this epoch because there \
is unspilled data in current epoch epoch {}, spill epoch {}",
current_epoch_data.epoch,
epoch
);
VecDeque::new()
}
Ordering::Equal => {
if !current_epoch_data.imms.is_empty() {
current_epoch_data.has_spilled = true;
take(&mut current_epoch_data.imms)
} else {
VecDeque::new()
}
}
Ordering::Greater => VecDeque::new(),
}
};
self.add_flushing_imm(imms.iter().rev().map(|imm| imm.batch_id()));
imms.into_iter().collect()
}
fn add_flushing_imm(&mut self, imm_ids: impl Iterator<Item = SharedBufferBatchId>) {
for imm_id in imm_ids {
if let Some(prev_imm_id) = self.flushing_imms.front() {
assert_gt!(imm_id, *prev_imm_id);
}
self.flushing_imms.push_front(imm_id);
}
}
// start syncing the imm inclusively before the `epoch`
// returning data with newer data coming first
fn sync(&mut self, epoch: HummockEpoch) -> Vec<UploaderImm> {
// firstly added from old to new
let mut ret = Vec::new();
while let Some(epoch_data) = self.sealed_data.back()
&& epoch_data.epoch() <= epoch
{
let imms = self.sealed_data.pop_back().expect("checked exist").imms;
self.add_flushing_imm(imms.iter().rev().map(|imm| imm.batch_id()));
ret.extend(imms.into_iter().rev());
}
// reverse so that newer data comes first
ret.reverse();
if let Some(latest_epoch_data) = &self.current_epoch_data {
if latest_epoch_data.epoch <= epoch {
assert!(self.sealed_data.is_empty());
assert!(latest_epoch_data.is_empty());
assert!(!latest_epoch_data.has_spilled);
if cfg!(debug_assertions) {
panic!("sync epoch exceeds latest epoch, and the current instance should have been archived");
}
warn!(
instance_id = self.instance_id,
table_id = self.table_id.table_id,
"sync epoch exceeds latest epoch, and the current instance should have be archived"
);
self.current_epoch_data = None;
}
}
ret
}
fn assert_after_epoch(&self, epoch: HummockEpoch) {
if let Some(oldest_sealed_data) = self.sealed_data.back() {
assert!(!oldest_sealed_data.imms.is_empty());
assert_gt!(oldest_sealed_data.epoch, epoch);
} else if let Some(current_data) = &self.current_epoch_data {
if current_data.epoch <= epoch {
assert!(current_data.imms.is_empty() && !current_data.has_spilled);
}
}
}
}
struct TableUnsyncData {
table_id: TableId,
instance_data: HashMap<LocalInstanceId, LocalInstanceUnsyncData>,
#[expect(clippy::type_complexity)]
table_watermarks: Option<(
WatermarkDirection,
BTreeMap<HummockEpoch, (Vec<VnodeWatermark>, BitmapBuilder)>,
)>,
spill_tasks: BTreeMap<HummockEpoch, VecDeque<UploadingTaskId>>,
unsync_epochs: BTreeMap<HummockEpoch, ()>,
// Initialized to be `None`. Transform to `Some(_)` when called
// `local_seal_epoch` with a non-existing epoch, to mark that
// the fragment of the table has stopped.
stopped_next_epoch: Option<HummockEpoch>,
// newer epoch at the front
syncing_epochs: VecDeque<HummockEpoch>,
max_synced_epoch: Option<HummockEpoch>,
}
impl TableUnsyncData {
fn new(table_id: TableId, committed_epoch: Option<HummockEpoch>) -> Self {
Self {
table_id,
instance_data: Default::default(),
table_watermarks: None,
spill_tasks: Default::default(),
unsync_epochs: Default::default(),
stopped_next_epoch: None,
syncing_epochs: Default::default(),
max_synced_epoch: committed_epoch,
}
}
fn new_epoch(&mut self, epoch: HummockEpoch) {
debug!(table_id = ?self.table_id, epoch, "table new epoch");
if let Some(latest_epoch) = self.max_epoch() {
assert_gt!(epoch, latest_epoch);
}
self.unsync_epochs.insert(epoch, ());
}
fn sync(
&mut self,
epoch: HummockEpoch,
) -> (
impl Iterator<Item = (LocalInstanceId, Vec<UploaderImm>)> + '_,
Option<(
WatermarkDirection,
impl Iterator<Item = (HummockEpoch, Vec<VnodeWatermark>)>,
)>,
impl Iterator<Item = UploadingTaskId>,
BTreeMap<HummockEpoch, ()>,
) {
if let Some(prev_epoch) = self.max_sync_epoch() {
assert_gt!(epoch, prev_epoch)
}
let epochs = take_before_epoch(&mut self.unsync_epochs, epoch);
assert_eq!(
*epochs.last_key_value().expect("non-empty").0,
epoch,
"{epochs:?} {epoch} {:?}",
self.table_id
);
self.syncing_epochs.push_front(epoch);
(
self.instance_data
.iter_mut()
.map(move |(instance_id, data)| (*instance_id, data.sync(epoch))),
self.table_watermarks
.as_mut()
.map(|(direction, watermarks)| {
let watermarks = take_before_epoch(watermarks, epoch);
(
*direction,
watermarks
.into_iter()
.map(|(epoch, (watermarks, _))| (epoch, watermarks)),
)
}),
take_before_epoch(&mut self.spill_tasks, epoch)
.into_values()
.flat_map(|tasks| tasks.into_iter()),
epochs,
)
}
fn ack_synced(&mut self, sync_epoch: HummockEpoch) {
let min_sync_epoch = self.syncing_epochs.pop_back().expect("should exist");
assert_eq!(sync_epoch, min_sync_epoch);
self.max_synced_epoch = Some(sync_epoch);
}
fn ack_committed(&mut self, committed_epoch: HummockEpoch) {
let synced_epoch_advanced = {
if let Some(max_synced_epoch) = self.max_synced_epoch
&& max_synced_epoch >= committed_epoch
{
false
} else {
true
}
};
if synced_epoch_advanced {
self.max_synced_epoch = Some(committed_epoch);
if let Some(min_syncing_epoch) = self.syncing_epochs.back() {
assert_gt!(*min_syncing_epoch, committed_epoch);
}
self.assert_after_epoch(committed_epoch);
}
}
fn assert_after_epoch(&self, epoch: HummockEpoch) {
self.instance_data
.values()
.for_each(|instance_data| instance_data.assert_after_epoch(epoch));
if let Some((_, watermarks)) = &self.table_watermarks
&& let Some((oldest_epoch, _)) = watermarks.first_key_value()
{
assert_gt!(*oldest_epoch, epoch);
}
}
fn max_sync_epoch(&self) -> Option<HummockEpoch> {
self.syncing_epochs
.front()
.cloned()
.or(self.max_synced_epoch)
}
fn max_epoch(&self) -> Option<HummockEpoch> {
self.unsync_epochs
.last_key_value()
.map(|(epoch, _)| *epoch)
.or_else(|| self.max_sync_epoch())
}
fn is_empty(&self) -> bool {
self.instance_data.is_empty()
&& self.syncing_epochs.is_empty()
&& self.unsync_epochs.is_empty()
}
}
#[derive(Eq, Hash, PartialEq, Copy, Clone)]
struct UnsyncEpochId(HummockEpoch, TableId);
impl UnsyncEpochId {
fn epoch(&self) -> HummockEpoch {
self.0
}
}
fn get_unsync_epoch_id(epoch: HummockEpoch, table_ids: &HashSet<TableId>) -> Option<UnsyncEpochId> {
table_ids
.iter()
.min()
.map(|table_id| UnsyncEpochId(epoch, *table_id))
}
#[derive(Default)]
/// Unsync data, can be either imm or spilled sst, and some aggregated epoch information.
///
/// `instance_data` holds the imm of each individual local instance, and data are first added here.
/// The aggregated epoch information (table watermarks, etc.) and the spilled sst will be added to `epoch_data`.
struct UnsyncData {
table_data: HashMap<TableId, TableUnsyncData>,
// An index as a mapping from instance id to its table id
instance_table_id: HashMap<LocalInstanceId, TableId>,
unsync_epochs: HashMap<UnsyncEpochId, HashSet<TableId>>,
}
impl UnsyncData {
fn init_instance(
&mut self,
table_id: TableId,
instance_id: LocalInstanceId,
init_epoch: HummockEpoch,
) {
debug!(
table_id = table_id.table_id,
instance_id, init_epoch, "init epoch"
);
let table_data = self
.table_data
.get_mut(&table_id)
.unwrap_or_else(|| panic!("should exist. {table_id:?}"));
assert!(table_data
.instance_data
.insert(
instance_id,
LocalInstanceUnsyncData::new(table_id, instance_id, init_epoch)
)
.is_none());
assert!(self
.instance_table_id
.insert(instance_id, table_id)
.is_none());
assert!(table_data.unsync_epochs.contains_key(&init_epoch));
}
fn instance_data(
&mut self,
instance_id: LocalInstanceId,
) -> Option<&mut LocalInstanceUnsyncData> {
self.instance_table_id
.get_mut(&instance_id)
.cloned()
.map(move |table_id| {
self.table_data
.get_mut(&table_id)
.expect("should exist")
.instance_data
.get_mut(&instance_id)
.expect("should exist")
})
}
fn add_imm(&mut self, instance_id: LocalInstanceId, imm: UploaderImm) {
self.instance_data(instance_id)
.expect("should exist")
.add_imm(imm);
}
fn local_seal_epoch(
&mut self,
instance_id: LocalInstanceId,
next_epoch: HummockEpoch,
opts: SealCurrentEpochOptions,
) {
let table_id = self.instance_table_id[&instance_id];
let table_data = self.table_data.get_mut(&table_id).expect("should exist");
let instance_data = table_data
.instance_data
.get_mut(&instance_id)
.expect("should exist");
let epoch = instance_data.local_seal_epoch(next_epoch);
// When drop/cancel a streaming job, for the barrier to stop actor, the
// local instance will call `local_seal_epoch`, but the `next_epoch` won't be
// called `start_epoch` because we have stopped writing on it.
if !table_data.unsync_epochs.contains_key(&next_epoch) {
if let Some(stopped_next_epoch) = table_data.stopped_next_epoch {
if stopped_next_epoch != next_epoch {
let table_id = table_data.table_id.table_id;
let unsync_epochs = table_data.unsync_epochs.keys().collect_vec();
if cfg!(debug_assertions) {
panic!(
"table_id {} stop epoch {} different to prev stop epoch {}. unsync epochs: {:?}, syncing epochs {:?}, max_synced_epoch {:?}",
table_id, next_epoch, stopped_next_epoch, unsync_epochs, table_data.syncing_epochs, table_data.max_synced_epoch
);
} else {
warn!(
table_id,
stopped_next_epoch,
next_epoch,
?unsync_epochs,
syncing_epochs = ?table_data.syncing_epochs,
max_synced_epoch = ?table_data.max_synced_epoch,
"different stop epoch"
);
}
}
} else {
if let Some(max_epoch) = table_data.max_epoch() {
assert_gt!(next_epoch, max_epoch);
}
debug!(?table_id, epoch, next_epoch, "table data has stopped");
table_data.stopped_next_epoch = Some(next_epoch);
}
}
if let Some((direction, table_watermarks)) = opts.table_watermarks {
table_data.add_table_watermarks(epoch, table_watermarks, direction);
}
}
fn may_destroy_instance(&mut self, instance_id: LocalInstanceId) -> Option<TableUnsyncData> {
if let Some(table_id) = self.instance_table_id.remove(&instance_id) {
debug!(instance_id, "destroy instance");
let table_data = self.table_data.get_mut(&table_id).expect("should exist");
assert!(table_data.instance_data.remove(&instance_id).is_some());
if table_data.is_empty() {
Some(self.table_data.remove(&table_id).expect("should exist"))
} else {
None
}
} else {
None
}
}
}
impl UploaderData {
fn sync(
&mut self,
epoch: HummockEpoch,
context: &UploaderContext,
table_ids: HashSet<TableId>,
sync_result_sender: oneshot::Sender<HummockResult<SyncedData>>,
) {
let mut all_table_watermarks = HashMap::new();
let mut uploading_tasks = HashSet::new();
let mut spilled_tasks = BTreeSet::new();
let mut flush_payload = HashMap::new();
if let Some(UnsyncEpochId(_, min_table_id)) = get_unsync_epoch_id(epoch, &table_ids) {
let min_table_id_data = self
.unsync_data
.table_data
.get_mut(&min_table_id)
.expect("should exist");
let epochs = take_before_epoch(&mut min_table_id_data.unsync_epochs.clone(), epoch);
for epoch in epochs.keys() {
assert_eq!(
self.unsync_data
.unsync_epochs
.remove(&UnsyncEpochId(*epoch, min_table_id))
.expect("should exist"),
table_ids
);
}
for table_id in &table_ids {
let table_data = self
.unsync_data
.table_data
.get_mut(table_id)
.expect("should exist");
let (unflushed_payload, table_watermarks, task_ids, table_unsync_epochs) =
table_data.sync(epoch);
assert_eq!(table_unsync_epochs, epochs);
for (instance_id, payload) in unflushed_payload {
if !payload.is_empty() {
flush_payload.insert(instance_id, payload);
}
}
if let Some((direction, watermarks)) = table_watermarks {
Self::add_table_watermarks(
&mut all_table_watermarks,
*table_id,
direction,
watermarks,
);
}
for task_id in task_ids {
if self.spilled_data.contains_key(&task_id) {
spilled_tasks.insert(task_id);
} else {
uploading_tasks.insert(task_id);
}
}
}
}
let sync_id = {
let sync_id = self.next_sync_id;
self.next_sync_id += 1;
SyncId(sync_id)
};
if let Some(extra_flush_task_id) = self.task_manager.sync(
context,
sync_id,
flush_payload,
uploading_tasks.iter().cloned(),
&table_ids,
) {
uploading_tasks.insert(extra_flush_task_id);
}
// iter from large task_id to small one so that newer data at the front
let uploaded = spilled_tasks
.iter()
.rev()
.map(|task_id| {
let (sst, spill_table_ids) =
self.spilled_data.remove(task_id).expect("should exist");
assert!(
spill_table_ids.is_subset(&table_ids),
"spilled tabled ids {:?} not a subset of sync table id {:?}",
spill_table_ids,
table_ids
);
sst
})
.collect();