risingwave_storage/hummock/compactor/
iterator.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
// 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.

use std::cmp::Ordering;
use std::collections::HashSet;
use std::sync::atomic::AtomicU64;
use std::sync::{atomic, Arc};
use std::time::Instant;

use await_tree::InstrumentAwait;
use fail::fail_point;
use risingwave_hummock_sdk::compaction_group::StateTableId;
use risingwave_hummock_sdk::key::FullKey;
use risingwave_hummock_sdk::key_range::KeyRange;
use risingwave_hummock_sdk::sstable_info::SstableInfo;
use risingwave_hummock_sdk::KeyComparator;

use crate::hummock::block_stream::BlockDataStream;
use crate::hummock::compactor::task_progress::TaskProgress;
use crate::hummock::iterator::{Forward, HummockIterator, ValueMeta};
use crate::hummock::sstable_store::SstableStoreRef;
use crate::hummock::value::HummockValue;
use crate::hummock::{BlockHolder, BlockIterator, BlockMeta, HummockResult};
use crate::monitor::StoreLocalStatistic;

const PROGRESS_KEY_INTERVAL: usize = 100;

/// Iterates over the KV-pairs of an SST while downloading it.
/// `SstableStreamIterator` encapsulates operations on `sstables`, constructing block streams and accessing the corresponding data via `block_metas`.
///  Note that a `block_meta` does not necessarily correspond to the entire sstable, but rather to a subset, which is documented via the `block_idx`.
pub struct SstableStreamIterator {
    sstable_store: SstableStoreRef,
    /// The block metas subset of the SST.
    block_metas: Vec<BlockMeta>,
    /// The downloading stream.
    block_stream: Option<BlockDataStream>,

    /// Iterates over the KV-pairs of the current block.
    block_iter: Option<BlockIterator>,

    /// Index of the current block.
    block_idx: usize,

    /// Counts the time used for IO.
    stats_ptr: Arc<AtomicU64>,

    /// For key sanity check of divided SST and debugging
    sstable_info: SstableInfo,

    /// To Filter out the blocks
    sstable_table_ids: HashSet<StateTableId>,
    task_progress: Arc<TaskProgress>,
    io_retry_times: usize,
    max_io_retry_times: usize,

    // key range cache
    key_range_left: FullKey<Vec<u8>>,
    key_range_right: FullKey<Vec<u8>>,
    key_range_right_exclusive: bool,
}

impl SstableStreamIterator {
    // We have to handle two internal iterators.
    //   `block_stream`: iterates over the blocks of the table.
    //     `block_iter`: iterates over the KV-pairs of the current block.
    // These iterators work in different ways.

    // BlockIterator works as follows: After new(), we call seek(). That brings us
    // to the first element. Calling next() then brings us to the second element and does not
    // return anything.

    // BlockStream follows a different approach. After new(), we do not seek, instead next()
    // returns the first value.

    /// Initialises a new [`SstableStreamIterator`] which iterates over the given [`BlockDataStream`].
    /// The iterator reads at most `max_block_count` from the stream.
    pub fn new(
        block_metas: Vec<BlockMeta>,
        sstable_info: SstableInfo,
        stats: &StoreLocalStatistic,
        task_progress: Arc<TaskProgress>,
        sstable_store: SstableStoreRef,
        max_io_retry_times: usize,
    ) -> Self {
        let sstable_table_ids = HashSet::from_iter(sstable_info.table_ids.iter().cloned());

        // filter the block meta with key range
        let block_metas = filter_block_metas(
            &block_metas,
            &sstable_table_ids,
            sstable_info.key_range.clone(),
        );

        let key_range_left = FullKey::decode(&sstable_info.key_range.left).to_vec();
        let key_range_right = FullKey::decode(&sstable_info.key_range.right).to_vec();
        let key_range_right_exclusive = sstable_info.key_range.right_exclusive;

        Self {
            block_stream: None,
            block_iter: None,
            block_metas,
            block_idx: 0,
            stats_ptr: stats.remote_io_time.clone(),
            sstable_table_ids,
            sstable_info,
            sstable_store,
            task_progress,
            io_retry_times: 0,
            max_io_retry_times,
            key_range_left,
            key_range_right,
            key_range_right_exclusive,
        }
    }

    async fn create_stream(&mut self) -> HummockResult<()> {
        let block_stream = self
            .sstable_store
            .get_stream_for_blocks(
                self.sstable_info.object_id,
                &self.block_metas[self.block_idx..],
            )
            .verbose_instrument_await("stream_iter_get_stream")
            .await?;
        self.block_stream = Some(block_stream);
        Ok(())
    }

    async fn prune_from_valid_block_iter(&mut self) -> HummockResult<()> {
        while let Some(block_iter) = self.block_iter.as_mut() {
            if self
                .sstable_table_ids
                .contains(&block_iter.table_id().table_id)
            {
                return Ok(());
            } else {
                self.next_block().await?;
            }
        }
        Ok(())
    }

    /// Initialises the iterator by moving it to the first KV-pair in the stream's first block where
    /// key >= `seek_key`. If that block does not contain such a KV-pair, the iterator continues to
    /// the first KV-pair of the next block. If `seek_key` is not given, the iterator will move to
    /// the very first KV-pair of the stream's first block.
    pub async fn seek(&mut self, seek_key: Option<FullKey<&[u8]>>) -> HummockResult<()> {
        // Load first block.
        self.next_block().await?;

        // We assume that a block always contains at least one KV pair. Subsequently, if
        // `next_block()` loads a new block (i.e., `block_iter` is not `None`), then `block_iter` is
        // also valid and pointing on the block's first KV-pair.

        let seek_key = if let Some(seek_key) = seek_key {
            if seek_key.cmp(&self.key_range_left.to_ref()).is_lt() {
                Some(self.key_range_left.to_ref())
            } else {
                Some(seek_key)
            }
        } else {
            Some(self.key_range_left.to_ref())
        };

        if let (Some(block_iter), Some(seek_key)) = (self.block_iter.as_mut(), seek_key) {
            block_iter.seek(seek_key);

            if !block_iter.is_valid() {
                // `seek_key` is larger than everything in the first block.
                self.next_block().await?;
            }
        }

        self.prune_from_valid_block_iter().await?;
        Ok(())
    }

    /// Loads a new block, creates a new iterator for it, and stores that iterator in
    /// `self.block_iter`. The created iterator points to the block's first KV-pair. If the end of
    /// the stream is reached or `self.remaining_blocks` is zero, then the function sets
    /// `self.block_iter` to `None`.
    async fn next_block(&mut self) -> HummockResult<()> {
        // Check if we want and if we can load the next block.
        let now = Instant::now();
        let _time_stat = scopeguard::guard(self.stats_ptr.clone(), |stats_ptr: Arc<AtomicU64>| {
            let add = (now.elapsed().as_secs_f64() * 1000.0).ceil();
            stats_ptr.fetch_add(add as u64, atomic::Ordering::Relaxed);
        });
        if self.block_idx < self.block_metas.len() {
            loop {
                let ret = match &mut self.block_stream {
                    Some(block_stream) => block_stream.next_block().await,
                    None => {
                        self.create_stream().await?;
                        continue;
                    }
                };
                match ret {
                    Ok(Some(block)) => {
                        let mut block_iter =
                            BlockIterator::new(BlockHolder::from_owned_block(block));
                        block_iter.seek_to_first();
                        self.block_idx += 1;
                        self.block_iter = Some(block_iter);
                        return Ok(());
                    }
                    Ok(None) => break,
                    Err(e) => {
                        if !e.is_object_error() || !self.need_recreate_io_stream() {
                            return Err(e);
                        }
                        self.block_stream.take();
                        self.io_retry_times += 1;
                        fail_point!("create_stream_err");

                        tracing::warn!(
                            "retry create stream for sstable {} times, sstinfo={}",
                            self.io_retry_times,
                            self.sst_debug_info()
                        );
                    }
                }
            }
        }
        self.block_idx = self.block_metas.len();
        self.block_iter = None;

        Ok(())
    }

    /// Moves to the next KV-pair in the table. Assumes that the current position is valid. Even if
    /// the next position is invalid, the function returns `Ok(())`.
    ///
    /// Do not use `next()` to initialise the iterator (i.e. do not use it to find the first
    /// KV-pair). Instead, use `seek()`. Afterwards, use `next()` to reach the second KV-pair and
    /// onwards.
    pub async fn next(&mut self) -> HummockResult<()> {
        if !self.is_valid() {
            return Ok(());
        }

        let block_iter = self.block_iter.as_mut().expect("no block iter");
        block_iter.next();
        if !block_iter.is_valid() {
            self.next_block().await?;
            self.prune_from_valid_block_iter().await?;
        }

        if !self.is_valid() {
            return Ok(());
        }

        // Check if we need to skip the block.
        let key = self
            .block_iter
            .as_ref()
            .unwrap_or_else(|| panic!("no block iter sstinfo={}", self.sst_debug_info()))
            .key();

        if self.exceed_key_range_right(key) {
            self.block_iter = None;
        }

        Ok(())
    }

    pub fn key(&self) -> FullKey<&[u8]> {
        let key = self
            .block_iter
            .as_ref()
            .unwrap_or_else(|| panic!("no block iter sstinfo={}", self.sst_debug_info()))
            .key();

        assert!(
            !self.exceed_key_range_left(key),
            "key {:?} key_range_left {:?}",
            key,
            self.key_range_left.to_ref()
        );

        assert!(
            !self.exceed_key_range_right(key),
            "key {:?} key_range_right {:?} key_range_right_exclusive {}",
            key,
            self.key_range_right.to_ref(),
            self.key_range_right_exclusive
        );

        key
    }

    pub fn value(&self) -> HummockValue<&[u8]> {
        let raw_value = self
            .block_iter
            .as_ref()
            .unwrap_or_else(|| panic!("no block iter sstinfo={}", self.sst_debug_info()))
            .value();
        HummockValue::from_slice(raw_value)
            .unwrap_or_else(|_| panic!("decode error sstinfo={}", self.sst_debug_info()))
    }

    pub fn is_valid(&self) -> bool {
        // True iff block_iter exists and is valid.
        self.block_iter.as_ref().map_or(false, |i| i.is_valid())
    }

    fn sst_debug_info(&self) -> String {
        format!(
            "object_id={}, sst_id={}, meta_offset={}, table_ids={:?}",
            self.sstable_info.object_id,
            self.sstable_info.sst_id,
            self.sstable_info.meta_offset,
            self.sstable_info.table_ids
        )
    }

    fn need_recreate_io_stream(&self) -> bool {
        self.io_retry_times < self.max_io_retry_times
    }

    fn exceed_key_range_left(&self, key: FullKey<&[u8]>) -> bool {
        key.cmp(&self.key_range_left.to_ref()).is_lt()
    }

    fn exceed_key_range_right(&self, key: FullKey<&[u8]>) -> bool {
        if self.key_range_right_exclusive {
            key.cmp(&self.key_range_right.to_ref()).is_ge()
        } else {
            key.cmp(&self.key_range_right.to_ref()).is_gt()
        }
    }
}

impl Drop for SstableStreamIterator {
    fn drop(&mut self) {
        self.task_progress.dec_num_pending_read_io()
    }
}

/// Iterates over the KV-pairs of a given list of SSTs. The key-ranges of these SSTs are assumed to
/// be consecutive and non-overlapping.
pub struct ConcatSstableIterator {
    /// **CAUTION:** `key_range` is used for optimization. It doesn't guarantee value returned by
    /// the iterator is in this range.
    key_range: KeyRange,

    /// The iterator of the current table.
    sstable_iter: Option<SstableStreamIterator>,

    /// Current table index.
    cur_idx: usize,

    /// All non-overlapping tables.
    sstables: Vec<SstableInfo>,

    existing_table_ids: HashSet<StateTableId>,

    sstable_store: SstableStoreRef,

    stats: StoreLocalStatistic,
    task_progress: Arc<TaskProgress>,
    max_io_retry_times: usize,
}

impl ConcatSstableIterator {
    /// Caller should make sure that `tables` are non-overlapping,
    /// arranged in ascending order when it serves as a forward iterator,
    /// and arranged in descending order when it serves as a backward iterator.
    pub fn new(
        existing_table_ids: Vec<StateTableId>,
        sst_infos: Vec<SstableInfo>,
        key_range: KeyRange,
        sstable_store: SstableStoreRef,
        task_progress: Arc<TaskProgress>,
        max_io_retry_times: usize,
    ) -> Self {
        Self {
            key_range,
            sstable_iter: None,
            cur_idx: 0,
            sstables: sst_infos,
            existing_table_ids: HashSet::from_iter(existing_table_ids),
            sstable_store,
            task_progress,
            stats: StoreLocalStatistic::default(),
            max_io_retry_times,
        }
    }

    #[cfg(test)]
    pub fn for_test(
        existing_table_ids: Vec<StateTableId>,
        sst_infos: Vec<SstableInfo>,
        key_range: KeyRange,
        sstable_store: SstableStoreRef,
    ) -> Self {
        Self::new(
            existing_table_ids,
            sst_infos,
            key_range,
            sstable_store,
            Arc::new(TaskProgress::default()),
            0,
        )
    }

    /// Resets the iterator, loads the specified SST, and seeks in that SST to `seek_key` if given.
    async fn seek_idx(
        &mut self,
        idx: usize,
        seek_key: Option<FullKey<&[u8]>>,
    ) -> HummockResult<()> {
        self.sstable_iter.take();
        let mut seek_key: Option<FullKey<&[u8]>> = match (seek_key, self.key_range.left.is_empty())
        {
            (Some(seek_key), false) => match seek_key.cmp(&FullKey::decode(&self.key_range.left)) {
                Ordering::Less | Ordering::Equal => Some(FullKey::decode(&self.key_range.left)),
                Ordering::Greater => Some(seek_key),
            },
            (Some(seek_key), true) => Some(seek_key),
            (None, true) => None,
            (None, false) => Some(FullKey::decode(&self.key_range.left)),
        };

        self.cur_idx = idx;
        while self.cur_idx < self.sstables.len() {
            let table_info = &self.sstables[self.cur_idx];
            let mut found = table_info
                .table_ids
                .iter()
                .any(|table_id| self.existing_table_ids.contains(table_id));
            if !found {
                self.cur_idx += 1;
                seek_key = None;
                continue;
            }
            let sstable = self
                .sstable_store
                .sstable(table_info, &mut self.stats)
                .verbose_instrument_await("stream_iter_sstable")
                .await?;

            let filter_key_range = match seek_key {
                Some(seek_key) => {
                    KeyRange::new(seek_key.encode().into(), self.key_range.right.clone())
                }
                None => self.key_range.clone(),
            };

            let block_metas = filter_block_metas(
                &sstable.meta.block_metas,
                &self.existing_table_ids,
                filter_key_range,
            );

            if block_metas.is_empty() {
                found = false;
            } else {
                self.task_progress.inc_num_pending_read_io();
                let mut sstable_iter = SstableStreamIterator::new(
                    block_metas,
                    table_info.clone(),
                    &self.stats,
                    self.task_progress.clone(),
                    self.sstable_store.clone(),
                    self.max_io_retry_times,
                );
                sstable_iter.seek(seek_key).await?;

                if sstable_iter.is_valid() {
                    self.sstable_iter = Some(sstable_iter);
                } else {
                    found = false;
                }
            }
            if found {
                return Ok(());
            } else {
                self.cur_idx += 1;
                seek_key = None;
            }
        }
        Ok(())
    }
}

impl HummockIterator for ConcatSstableIterator {
    type Direction = Forward;

    async fn next(&mut self) -> HummockResult<()> {
        let sstable_iter = self.sstable_iter.as_mut().expect("no table iter");

        // Does just calling `next()` suffice?
        sstable_iter.next().await?;
        if sstable_iter.is_valid() {
            Ok(())
        } else {
            // No, seek to next table.
            self.seek_idx(self.cur_idx + 1, None).await?;
            Ok(())
        }
    }

    fn key(&self) -> FullKey<&[u8]> {
        self.sstable_iter.as_ref().expect("no table iter").key()
    }

    fn value(&self) -> HummockValue<&[u8]> {
        self.sstable_iter.as_ref().expect("no table iter").value()
    }

    fn is_valid(&self) -> bool {
        self.sstable_iter.as_ref().map_or(false, |i| i.is_valid())
    }

    async fn rewind(&mut self) -> HummockResult<()> {
        self.seek_idx(0, None).await
    }

    /// Resets the iterator and seeks to the first position where the stored key >= `key`.
    async fn seek<'a>(&'a mut self, key: FullKey<&'a [u8]>) -> HummockResult<()> {
        let seek_key = if self.key_range.left.is_empty() {
            key
        } else {
            match key.cmp(&FullKey::decode(&self.key_range.left)) {
                Ordering::Less | Ordering::Equal => FullKey::decode(&self.key_range.left),
                Ordering::Greater => key,
            }
        };
        let table_idx = self.sstables.partition_point(|table| {
            // We use the maximum key of an SST for the search. That way, we guarantee that the
            // resulting SST contains either that key or the next-larger KV-pair. Subsequently,
            // we avoid calling `seek_idx()` twice if the determined SST does not contain `key`.

            // Note that we need to use `<` instead of `<=` to ensure that all keys in an SST
            // (including its max. key) produce the same search result.
            let max_sst_key = &table.key_range.right;
            FullKey::decode(max_sst_key).cmp(&seek_key) == Ordering::Less
        });

        self.seek_idx(table_idx, Some(key)).await
    }

    fn collect_local_statistic(&self, stats: &mut StoreLocalStatistic) {
        stats.add(&self.stats)
    }

    fn value_meta(&self) -> ValueMeta {
        let iter = self.sstable_iter.as_ref().expect("no table iter");
        // sstable_iter's block_idx must have advanced at least one.
        // See SstableStreamIterator::next_block.
        assert!(iter.block_idx >= 1);
        ValueMeta {
            object_id: Some(iter.sstable_info.object_id),
            block_id: Some(iter.block_idx as u64 - 1),
        }
    }
}

pub struct MonitoredCompactorIterator<I> {
    inner: I,
    task_progress: Arc<TaskProgress>,

    processed_key_num: usize,
}

impl<I: HummockIterator<Direction = Forward>> MonitoredCompactorIterator<I> {
    pub fn new(inner: I, task_progress: Arc<TaskProgress>) -> Self {
        Self {
            inner,
            task_progress,
            processed_key_num: 0,
        }
    }
}

impl<I: HummockIterator<Direction = Forward>> HummockIterator for MonitoredCompactorIterator<I> {
    type Direction = Forward;

    async fn next(&mut self) -> HummockResult<()> {
        self.inner.next().await?;
        self.processed_key_num += 1;

        if self.processed_key_num % PROGRESS_KEY_INTERVAL == 0 {
            self.task_progress
                .inc_progress_key(PROGRESS_KEY_INTERVAL as _);
        }

        Ok(())
    }

    fn key(&self) -> FullKey<&[u8]> {
        self.inner.key()
    }

    fn value(&self) -> HummockValue<&[u8]> {
        self.inner.value()
    }

    fn is_valid(&self) -> bool {
        self.inner.is_valid()
    }

    async fn rewind(&mut self) -> HummockResult<()> {
        self.processed_key_num = 0;
        self.inner.rewind().await?;
        Ok(())
    }

    async fn seek<'a>(&'a mut self, key: FullKey<&'a [u8]>) -> HummockResult<()> {
        self.processed_key_num = 0;
        self.inner.seek(key).await?;
        Ok(())
    }

    fn collect_local_statistic(&self, stats: &mut StoreLocalStatistic) {
        self.inner.collect_local_statistic(stats)
    }

    fn value_meta(&self) -> ValueMeta {
        self.inner.value_meta()
    }
}

pub(crate) fn filter_block_metas(
    block_metas: &Vec<BlockMeta>,
    existing_table_ids: &HashSet<u32>,
    key_range: KeyRange,
) -> Vec<BlockMeta> {
    if block_metas.is_empty() {
        return vec![];
    }

    let mut start_index = if key_range.left.is_empty() {
        0
    } else {
        // start_index points to the greatest block whose smallest_key <= seek_key.
        block_metas
            .partition_point(|block| {
                KeyComparator::compare_encoded_full_key(&key_range.left, &block.smallest_key)
                    != Ordering::Less
            })
            .saturating_sub(1)
    };

    let mut end_index = if key_range.right.is_empty() {
        block_metas.len()
    } else {
        let ret = block_metas.partition_point(|block| {
            KeyComparator::compare_encoded_full_key(&block.smallest_key, &key_range.right)
                != Ordering::Greater
        });

        if ret == 0 {
            // not found
            return vec![];
        }

        ret
    }
    .saturating_sub(1);

    // skip blocks that are not in existing_table_ids
    while start_index <= end_index {
        let start_block_table_id = block_metas[start_index].table_id().table_id();
        if existing_table_ids.contains(&start_block_table_id) {
            break;
        }

        // skip this table_id
        let old_start_index = start_index;
        let block_metas_to_search = &block_metas[start_index..=end_index];

        start_index += block_metas_to_search
            .partition_point(|block_meta| block_meta.table_id().table_id() == start_block_table_id);

        if old_start_index == start_index {
            // no more blocks with the same table_id
            break;
        }
    }

    while start_index <= end_index {
        let end_block_table_id = block_metas[end_index].table_id().table_id();
        if existing_table_ids.contains(&end_block_table_id) {
            break;
        }

        let old_end_index = end_index;
        let block_metas_to_search = &block_metas[start_index..=end_index];

        end_index = start_index
            + block_metas_to_search
                .partition_point(|block_meta| block_meta.table_id().table_id() < end_block_table_id)
                .saturating_sub(1);

        if end_index == old_end_index {
            // no more blocks with the same table_id
            break;
        }
    }

    if start_index > end_index {
        return vec![];
    }

    block_metas[start_index..=end_index].to_vec()
}

#[cfg(test)]
mod tests {
    use std::cmp::Ordering;
    use std::collections::HashSet;

    use risingwave_common::catalog::TableId;
    use risingwave_hummock_sdk::key::{next_full_key, prev_full_key, FullKey, FullKeyTracker};
    use risingwave_hummock_sdk::key_range::KeyRange;

    use crate::hummock::compactor::ConcatSstableIterator;
    use crate::hummock::iterator::test_utils::mock_sstable_store;
    use crate::hummock::iterator::{HummockIterator, MergeIterator};
    use crate::hummock::test_utils::{
        default_builder_opt_for_test, gen_test_sstable_info, test_key_of, test_value_of,
        TEST_KEYS_COUNT,
    };
    use crate::hummock::value::HummockValue;
    use crate::hummock::BlockMeta;

    #[tokio::test]
    async fn test_concat_iterator() {
        let sstable_store = mock_sstable_store().await;
        let mut table_infos = vec![];
        for object_id in 0..3 {
            let start_index = object_id * TEST_KEYS_COUNT;
            let end_index = (object_id + 1) * TEST_KEYS_COUNT;
            let table_info = gen_test_sstable_info(
                default_builder_opt_for_test(),
                object_id as u64,
                (start_index..end_index)
                    .map(|i| (test_key_of(i), HummockValue::put(test_value_of(i)))),
                sstable_store.clone(),
            )
            .await;
            table_infos.push(table_info);
        }
        let start_index = 5000;
        let end_index = 25000;

        let kr = KeyRange::new(
            test_key_of(start_index).encode().into(),
            test_key_of(end_index).encode().into(),
        );
        let mut iter = ConcatSstableIterator::for_test(
            vec![0],
            table_infos.clone(),
            kr.clone(),
            sstable_store.clone(),
        );
        iter.seek(FullKey::decode(&kr.left)).await.unwrap();

        for idx in start_index..end_index {
            let key = iter.key();
            let val = iter.value();
            assert_eq!(key, test_key_of(idx).to_ref(), "failed at {}", idx);
            assert_eq!(
                val.into_user_value().unwrap(),
                test_value_of(idx).as_slice()
            );
            iter.next().await.unwrap();
        }

        // seek non-overlap range
        let kr = KeyRange::new(
            test_key_of(30000).encode().into(),
            test_key_of(40000).encode().into(),
        );
        let mut iter = ConcatSstableIterator::for_test(
            vec![0],
            table_infos.clone(),
            kr.clone(),
            sstable_store.clone(),
        );
        iter.seek(FullKey::decode(&kr.left)).await.unwrap();
        assert!(!iter.is_valid());
        let kr = KeyRange::new(
            test_key_of(start_index).encode().into(),
            test_key_of(40000).encode().into(),
        );
        let mut iter = ConcatSstableIterator::for_test(
            vec![0],
            table_infos.clone(),
            kr.clone(),
            sstable_store.clone(),
        );
        iter.seek(FullKey::decode(&kr.left)).await.unwrap();
        for idx in start_index..30000 {
            let key = iter.key();
            let val = iter.value();
            assert_eq!(key, test_key_of(idx).to_ref(), "failed at {}", idx);
            assert_eq!(
                val.into_user_value().unwrap(),
                test_value_of(idx).as_slice()
            );
            iter.next().await.unwrap();
        }
        assert!(!iter.is_valid());

        // Test seek. Result is dominated by given seek key rather than key range.
        let kr = KeyRange::new(
            test_key_of(0).encode().into(),
            test_key_of(40000).encode().into(),
        );
        let mut iter = ConcatSstableIterator::for_test(
            vec![0],
            table_infos.clone(),
            kr.clone(),
            sstable_store.clone(),
        );
        iter.seek(test_key_of(10000).to_ref()).await.unwrap();
        assert!(iter.is_valid() && iter.cur_idx == 1 && iter.key() == test_key_of(10000).to_ref());
        iter.seek(test_key_of(10001).to_ref()).await.unwrap();
        assert!(iter.is_valid() && iter.cur_idx == 1 && iter.key() == test_key_of(10001).to_ref());
        iter.seek(test_key_of(9999).to_ref()).await.unwrap();
        assert!(iter.is_valid() && iter.cur_idx == 0 && iter.key() == test_key_of(9999).to_ref());
        iter.seek(test_key_of(1).to_ref()).await.unwrap();
        assert!(iter.is_valid() && iter.cur_idx == 0 && iter.key() == test_key_of(1).to_ref());
        iter.seek(test_key_of(29999).to_ref()).await.unwrap();
        assert!(iter.is_valid() && iter.cur_idx == 2 && iter.key() == test_key_of(29999).to_ref());
        iter.seek(test_key_of(30000).to_ref()).await.unwrap();
        assert!(!iter.is_valid());

        // Test seek. Result is dominated by key range rather than given seek key.
        let kr = KeyRange::new(
            test_key_of(6000).encode().into(),
            test_key_of(16000).encode().into(),
        );
        let mut iter = ConcatSstableIterator::for_test(
            vec![0],
            table_infos.clone(),
            kr.clone(),
            sstable_store.clone(),
        );
        iter.seek(test_key_of(17000).to_ref()).await.unwrap();
        assert!(!iter.is_valid());
        iter.seek(test_key_of(1).to_ref()).await.unwrap();
        assert!(iter.is_valid() && iter.cur_idx == 0 && iter.key() == FullKey::decode(&kr.left));
    }

    #[tokio::test]
    async fn test_concat_iterator_seek_idx() {
        let sstable_store = mock_sstable_store().await;
        let mut table_infos = vec![];
        for object_id in 0..3 {
            let start_index = object_id * TEST_KEYS_COUNT + TEST_KEYS_COUNT / 2;
            let end_index = (object_id + 1) * TEST_KEYS_COUNT;
            let table_info = gen_test_sstable_info(
                default_builder_opt_for_test(),
                object_id as u64,
                (start_index..end_index)
                    .map(|i| (test_key_of(i), HummockValue::put(test_value_of(i)))),
                sstable_store.clone(),
            )
            .await;
            table_infos.push(table_info);
        }

        // Test seek_idx. Result is dominated by given seek key rather than key range.
        let kr = KeyRange::new(
            test_key_of(0).encode().into(),
            test_key_of(40000).encode().into(),
        );
        let mut iter = ConcatSstableIterator::for_test(
            vec![0],
            table_infos.clone(),
            kr.clone(),
            sstable_store.clone(),
        );
        let sst = sstable_store
            .sstable(&iter.sstables[0], &mut iter.stats)
            .await
            .unwrap();
        let block_metas = &sst.meta.block_metas;
        let block_1_smallest_key = block_metas[1].smallest_key.clone();
        let block_2_smallest_key = block_metas[2].smallest_key.clone();
        // Use block_1_smallest_key as seek key and result in the first KV of block 1.
        let seek_key = block_1_smallest_key.clone();
        iter.seek_idx(0, Some(FullKey::decode(&seek_key)))
            .await
            .unwrap();
        assert!(iter.is_valid() && iter.key() == FullKey::decode(block_1_smallest_key.as_slice()));
        // Use prev_full_key(block_1_smallest_key) as seek key and result in the first KV of block
        // 1.
        let seek_key = prev_full_key(block_1_smallest_key.as_slice());
        iter.seek_idx(0, Some(FullKey::decode(&seek_key)))
            .await
            .unwrap();
        assert!(iter.is_valid() && iter.key() == FullKey::decode(block_1_smallest_key.as_slice()));
        iter.next().await.unwrap();
        let block_1_second_key = iter.key().to_vec();
        // Use a big enough seek key and result in invalid iterator.
        let seek_key = test_key_of(30001);
        iter.seek_idx(table_infos.len() - 1, Some(seek_key.to_ref()))
            .await
            .unwrap();
        assert!(!iter.is_valid());

        // Test seek_idx. Result is dominated by key range rather than given seek key.
        let kr = KeyRange::new(
            next_full_key(&block_1_smallest_key).into(),
            prev_full_key(&block_2_smallest_key).into(),
        );
        let mut iter = ConcatSstableIterator::for_test(
            vec![0],
            table_infos.clone(),
            kr.clone(),
            sstable_store.clone(),
        );
        // Use block_2_smallest_key as seek key and result in invalid iterator.
        let seek_key = FullKey::decode(&block_2_smallest_key);
        assert!(seek_key.cmp(&FullKey::decode(&kr.right)) == Ordering::Greater);
        iter.seek_idx(0, Some(seek_key)).await.unwrap();
        assert!(!iter.is_valid());
        // Use a small enough seek key and result in the second KV of block 1.
        let seek_key = test_key_of(0).encode();
        iter.seek_idx(0, Some(FullKey::decode(&seek_key)))
            .await
            .unwrap();
        assert!(iter.is_valid());
        assert_eq!(iter.key(), block_1_second_key.to_ref());

        // Use None seek key and result in the second KV of block 1.
        iter.seek_idx(0, None).await.unwrap();
        assert!(iter.is_valid());
        assert_eq!(iter.key(), block_1_second_key.to_ref());
    }

    #[tokio::test]
    async fn test_filter_block_metas() {
        use crate::hummock::compactor::iterator::filter_block_metas;

        {
            let block_metas = Vec::default();

            let ret = filter_block_metas(&block_metas, &HashSet::default(), KeyRange::default());

            assert!(ret.is_empty());
        }

        {
            let block_metas = vec![
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(1), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(2), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(3), Vec::default(), 0).encode(),
                    ..Default::default()
                },
            ];

            let ret = filter_block_metas(
                &block_metas,
                &HashSet::from_iter(vec![1_u32, 2, 3].into_iter()),
                KeyRange::default(),
            );

            assert_eq!(3, ret.len());
            assert_eq!(
                1,
                FullKey::decode(&ret[0].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
            assert_eq!(
                3,
                FullKey::decode(&ret[2].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
        }

        {
            let block_metas = vec![
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(1), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(2), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(3), Vec::default(), 0).encode(),
                    ..Default::default()
                },
            ];

            let ret = filter_block_metas(
                &block_metas,
                &HashSet::from_iter(vec![2_u32, 3].into_iter()),
                KeyRange::default(),
            );

            assert_eq!(2, ret.len());
            assert_eq!(
                2,
                FullKey::decode(&ret[0].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
            assert_eq!(
                3,
                FullKey::decode(&ret[1].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
        }

        {
            let block_metas = vec![
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(1), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(2), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(3), Vec::default(), 0).encode(),
                    ..Default::default()
                },
            ];

            let ret = filter_block_metas(
                &block_metas,
                &HashSet::from_iter(vec![1_u32, 2_u32].into_iter()),
                KeyRange::default(),
            );

            assert_eq!(2, ret.len());
            assert_eq!(
                1,
                FullKey::decode(&ret[0].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
            assert_eq!(
                2,
                FullKey::decode(&ret[1].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
        }

        {
            let block_metas = vec![
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(1), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(2), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(3), Vec::default(), 0).encode(),
                    ..Default::default()
                },
            ];
            let ret = filter_block_metas(
                &block_metas,
                &HashSet::from_iter(vec![2_u32].into_iter()),
                KeyRange::default(),
            );

            assert_eq!(1, ret.len());
            assert_eq!(
                2,
                FullKey::decode(&ret[0].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
        }

        {
            let block_metas = vec![
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(1), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(1), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(1), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(2), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(3), Vec::default(), 0).encode(),
                    ..Default::default()
                },
            ];
            let ret = filter_block_metas(
                &block_metas,
                &HashSet::from_iter(vec![2_u32].into_iter()),
                KeyRange::default(),
            );

            assert_eq!(1, ret.len());
            assert_eq!(
                2,
                FullKey::decode(&ret[0].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
        }

        {
            let block_metas = vec![
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(1), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(2), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(3), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(3), Vec::default(), 0).encode(),
                    ..Default::default()
                },
                BlockMeta {
                    smallest_key: FullKey::for_test(TableId::new(3), Vec::default(), 0).encode(),
                    ..Default::default()
                },
            ];

            let ret = filter_block_metas(
                &block_metas,
                &HashSet::from_iter(vec![2_u32].into_iter()),
                KeyRange::default(),
            );

            assert_eq!(1, ret.len());
            assert_eq!(
                2,
                FullKey::decode(&ret[0].smallest_key)
                    .user_key
                    .table_id
                    .table_id()
            );
        }
    }

    #[tokio::test]
    async fn test_iterator_same_obj() {
        let sstable_store = mock_sstable_store().await;

        let table_info = gen_test_sstable_info(
            default_builder_opt_for_test(),
            1_u64,
            (1..10000).map(|i| (test_key_of(i), HummockValue::put(test_value_of(i)))),
            sstable_store.clone(),
        )
        .await;

        let split_key = test_key_of(5000).encode();

        let mut sst_1 = table_info.clone();
        sst_1.key_range.right = split_key.clone().into();
        sst_1.key_range.right_exclusive = true;

        let total_key_count = sst_1.total_key_count;
        let mut sst_2 = table_info.clone();
        sst_2.sst_id = sst_1.sst_id + 1;
        sst_2.key_range.left = split_key.clone().into();

        {
            // test concate
            let mut full_key_tracker = FullKeyTracker::<Vec<u8>>::new(FullKey::default());

            let mut iter = ConcatSstableIterator::for_test(
                vec![0],
                vec![sst_1.clone(), sst_2.clone()],
                KeyRange::default(),
                sstable_store.clone(),
            );

            iter.rewind().await.unwrap();

            let mut key_count = 0;
            while iter.is_valid() {
                let is_new_user_key = full_key_tracker.observe(iter.key());
                assert!(is_new_user_key);
                key_count += 1;
                iter.next().await.unwrap();
            }

            assert_eq!(total_key_count, key_count);
        }

        {
            let mut full_key_tracker = FullKeyTracker::<Vec<u8>>::new(FullKey::default());
            let concat_1 = ConcatSstableIterator::for_test(
                vec![0],
                vec![sst_1.clone()],
                KeyRange::default(),
                sstable_store.clone(),
            );

            let concat_2 = ConcatSstableIterator::for_test(
                vec![0],
                vec![sst_2.clone()],
                KeyRange::default(),
                sstable_store.clone(),
            );

            let mut key_count = 0;
            let mut iter = MergeIterator::for_compactor(vec![concat_1, concat_2]);
            iter.rewind().await.unwrap();
            while iter.is_valid() {
                full_key_tracker.observe(iter.key());
                key_count += 1;
                iter.next().await.unwrap();
            }
            assert_eq!(total_key_count, key_count);
        }
    }
}