trine-kv 0.2.0

Embedded LSM MVCC key-value database.
Documentation
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
use std::{
    cmp::Ordering as CmpOrdering, collections::BinaryHeap, ops::Bound, path::PathBuf, sync::Arc,
};

use crate::{
    blob::ValueRef,
    error::{Error, Result},
    internal_key::{
        InternalKey, ValueKind, first_internal_key_for_user, last_internal_key_for_user,
    },
    memtable::Memtable,
    range_tombstone::{RangeTombstoneIndex, RangeTombstoneLike},
    snapshot::Snapshot,
    stats::BlobReadMetrics,
    storage::NativeFileBackend,
    table::TablePointCursor,
    types::{KeyRange, KeyValue, Sequence, Value},
};

/// Scan direction for range and prefix iterators.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Direction {
    /// Visit keys in ascending byte order.
    #[default]
    Forward,
    /// Visit keys in descending byte order.
    Reverse,
}

/// Eager iterator that returns owned key/value rows.
#[derive(Debug, Clone)]
pub struct Iter {
    direction: Direction,
    inner: IterInner,
}

/// Iterator that can defer reading large blob values until requested.
#[derive(Debug, Clone)]
pub struct LazyIter {
    direction: Direction,
    scan: LazyScan,
}

/// Row returned by `LazyIter`.
#[derive(Debug, Clone)]
pub struct LazyKeyValue {
    /// User key bytes.
    pub key: Vec<u8>,
    /// Value handle that may defer reading blob bytes.
    pub value: LazyValue,
}

/// Value returned by `LazyIter`.
#[derive(Debug, Clone)]
pub struct LazyValue {
    inner: LazyValueInner,
}

#[derive(Debug, Clone)]
enum LazyValueInner {
    Inline(Vec<u8>),
    Blob {
        db_path: PathBuf,
        native_storage: Option<NativeFileBackend>,
        internal_key: InternalKey,
        value: ValueRef,
        blob_reads: Option<Arc<BlobReadMetrics>>,
        _read_pin: Arc<Snapshot>,
    },
}

#[derive(Debug, Clone)]
enum IterInner {
    Items(std::vec::IntoIter<KeyValue>),
    Lazy(LazyScan),
}

#[derive(Debug, Clone)]
pub(crate) struct ScanSourceInput {
    pub(crate) read_sequence: Sequence,
    pub(crate) read_pin: Snapshot,
    pub(crate) db_path: Option<PathBuf>,
    pub(crate) native_storage: Option<NativeFileBackend>,
    pub(crate) blob_reads: Option<Arc<BlobReadMetrics>>,
    pub(crate) range_tombstones: Vec<ScanRangeTombstone>,
    pub(crate) sources: Vec<RecordSource>,
}

impl Iter {
    /// Creates an empty iterator with the requested direction.
    #[must_use]
    pub fn empty(direction: Direction) -> Self {
        Self::from_items(Vec::new(), direction)
    }

    /// Creates an iterator from already-owned rows.
    #[must_use]
    pub fn from_items(mut items: Vec<KeyValue>, direction: Direction) -> Self {
        if direction == Direction::Reverse {
            items.reverse();
        }

        Self {
            direction,
            inner: IterInner::Items(items.into_iter()),
        }
    }

    pub(crate) fn from_sources(direction: Direction, input: ScanSourceInput) -> Self {
        Self {
            direction,
            inner: IterInner::Lazy(LazyScan {
                direction,
                read_sequence: input.read_sequence,
                read_pin: Arc::new(input.read_pin),
                db_path: input.db_path,
                native_storage: input.native_storage,
                blob_reads: input.blob_reads,
                range_tombstones: RangeTombstoneIndex::new(input.range_tombstones),
                sources: input.sources,
                source_heap: BinaryHeap::new(),
                source_heap_initialized: false,
            }),
        }
    }

    /// Returns this iterator's scan direction.
    #[must_use]
    pub const fn direction(&self) -> Direction {
        self.direction
    }
}

impl LazyIter {
    pub(crate) fn from_sources(direction: Direction, input: ScanSourceInput) -> Self {
        Self {
            direction,
            scan: LazyScan {
                direction,
                read_sequence: input.read_sequence,
                read_pin: Arc::new(input.read_pin),
                db_path: input.db_path,
                native_storage: input.native_storage,
                blob_reads: input.blob_reads,
                range_tombstones: RangeTombstoneIndex::new(input.range_tombstones),
                sources: input.sources,
                source_heap: BinaryHeap::new(),
                source_heap_initialized: false,
            },
        }
    }

    /// Returns this iterator's scan direction.
    #[must_use]
    pub const fn direction(&self) -> Direction {
        self.direction
    }
}

impl LazyKeyValue {
    /// Reads any deferred value bytes synchronously and returns an owned row.
    pub fn into_key_value_sync(self) -> Result<KeyValue> {
        Ok(KeyValue::new(self.key, self.value.into_value_sync()?))
    }

    /// Reads any deferred value bytes asynchronously and returns an owned row.
    pub async fn into_key_value(self) -> Result<KeyValue> {
        let value = self.value.into_value().await?;
        Ok(KeyValue::new(self.key, value))
    }
}

impl LazyValue {
    /// Returns `true` if the value bytes are already inline.
    #[must_use]
    pub fn is_inline(&self) -> bool {
        matches!(self.inner, LazyValueInner::Inline(_))
    }

    /// Reads the value bytes synchronously without consuming this handle.
    pub fn read_sync(&self) -> Result<Value> {
        match &self.inner {
            LazyValueInner::Inline(bytes) => Ok(bytes.clone()),
            LazyValueInner::Blob {
                db_path,
                native_storage: _,
                internal_key,
                value,
                blob_reads,
                _read_pin: _,
            } => {
                let bytes =
                    crate::blob::read_value_for_internal_key(db_path, value, Some(internal_key))?;
                if let Some(blob_reads) = blob_reads {
                    blob_reads.record(bytes.len() as u64);
                }
                Ok(bytes)
            }
        }
    }

    /// Reads the value bytes synchronously and consumes this handle.
    pub fn into_value_sync(self) -> Result<Value> {
        match self.inner {
            LazyValueInner::Inline(bytes) => Ok(bytes),
            LazyValueInner::Blob {
                db_path,
                native_storage: _,
                internal_key,
                value,
                blob_reads,
                _read_pin: _,
            } => {
                let bytes = crate::blob::read_value_for_internal_key(
                    &db_path,
                    &value,
                    Some(&internal_key),
                )?;
                if let Some(blob_reads) = blob_reads {
                    blob_reads.record(bytes.len() as u64);
                }
                Ok(bytes)
            }
        }
    }

    /// Reads the value bytes asynchronously without consuming this handle.
    pub async fn read(&self) -> Result<Value> {
        match &self.inner {
            LazyValueInner::Inline(bytes) => Ok(bytes.clone()),
            LazyValueInner::Blob {
                db_path,
                native_storage: Some(native_storage),
                internal_key,
                value,
                blob_reads,
                _read_pin: _,
            } => {
                let bytes = crate::blob::read_value_for_internal_key_with_backend_async(
                    native_storage,
                    db_path,
                    value,
                    Some(internal_key),
                )
                .await?;
                if let Some(blob_reads) = blob_reads {
                    blob_reads.record(bytes.len() as u64);
                }
                Ok(bytes)
            }
            LazyValueInner::Blob {
                native_storage: None,
                ..
            } => self.read_sync(),
        }
    }

    /// Reads the value bytes asynchronously and consumes this handle.
    pub async fn into_value(self) -> Result<Value> {
        match self.inner {
            LazyValueInner::Inline(bytes) => Ok(bytes),
            LazyValueInner::Blob {
                db_path,
                native_storage: Some(native_storage),
                internal_key,
                value,
                blob_reads,
                _read_pin: _,
            } => {
                let bytes = crate::blob::read_value_for_internal_key_with_backend_async(
                    &native_storage,
                    &db_path,
                    &value,
                    Some(&internal_key),
                )
                .await?;
                if let Some(blob_reads) = blob_reads {
                    blob_reads.record(bytes.len() as u64);
                }
                Ok(bytes)
            }
            LazyValueInner::Blob {
                db_path,
                native_storage: None,
                internal_key,
                value,
                blob_reads,
                _read_pin: _,
            } => {
                let bytes = crate::blob::read_value_for_internal_key(
                    &db_path,
                    &value,
                    Some(&internal_key),
                )?;
                if let Some(blob_reads) = blob_reads {
                    blob_reads.record(bytes.len() as u64);
                }
                Ok(bytes)
            }
        }
    }
}

impl Iter {
    /// Returns the next owned row, reading deferred sources asynchronously when needed.
    pub async fn next(&mut self) -> Result<Option<KeyValue>> {
        match &mut self.inner {
            IterInner::Items(items) => Ok(items.next()),
            IterInner::Lazy(scan) => scan.next_async().await,
        }
    }

    /// Returns the next owned row using the synchronous iterator path.
    pub fn next_sync(&mut self) -> Option<Result<KeyValue>> {
        Iterator::next(self)
    }
}

impl LazyIter {
    /// Returns the next lazy row, reading deferred metadata asynchronously when needed.
    pub async fn next(&mut self) -> Result<Option<LazyKeyValue>> {
        self.scan.next_lazy_async().await
    }

    /// Returns the next lazy row using the synchronous iterator path.
    pub fn next_sync(&mut self) -> Option<Result<LazyKeyValue>> {
        Iterator::next(self)
    }
}

impl Iterator for Iter {
    type Item = Result<KeyValue>;

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.inner {
            IterInner::Items(items) => items.next().map(Ok),
            IterInner::Lazy(scan) => scan.next(),
        }
    }
}

impl Iterator for LazyIter {
    type Item = Result<LazyKeyValue>;

    fn next(&mut self) -> Option<Self::Item> {
        self.scan.next_lazy()
    }
}

#[derive(Debug, Clone)]
struct LazyScan {
    direction: Direction,
    read_sequence: Sequence,
    read_pin: Arc<Snapshot>,
    db_path: Option<PathBuf>,
    native_storage: Option<NativeFileBackend>,
    blob_reads: Option<Arc<BlobReadMetrics>>,
    range_tombstones: RangeTombstoneIndex<ScanRangeTombstone>,
    sources: Vec<RecordSource>,
    source_heap: BinaryHeap<SourceHeapEntry>,
    source_heap_initialized: bool,
}

impl LazyScan {
    fn next(&mut self) -> Option<Result<KeyValue>> {
        self.next_lazy()
            .map(|item| item.and_then(LazyKeyValue::into_key_value_sync))
    }

    async fn next_async(&mut self) -> Result<Option<KeyValue>> {
        let Some(item) = self.next_lazy_async().await? else {
            return Ok(None);
        };
        item.into_key_value().await.map(Some)
    }

    fn next_lazy(&mut self) -> Option<Result<LazyKeyValue>> {
        if !self.source_heap_initialized {
            if let Err(error) = self.initialize_source_heap() {
                return Some(Err(error));
            }
        }

        loop {
            let entry = self.source_heap.pop()?;
            let user_key = entry.user_key;
            let mut source_indices = vec![entry.source_index];
            while self
                .source_heap
                .peek()
                .is_some_and(|entry| entry.user_key == user_key)
            {
                let entry = self
                    .source_heap
                    .pop()
                    .expect("heap peek promised another source entry");
                source_indices.push(entry.source_index);
            }

            let mut first_record = None;
            let mut rest_records = Vec::new();

            for source_index in source_indices {
                match self.sources[source_index].take_current_group() {
                    Ok(Some(group)) => {
                        push_group_records(&mut first_record, &mut rest_records, group);
                    }
                    Ok(None) => {}
                    Err(error) => return Some(Err(error)),
                }
                if let Err(error) = self.push_source_heap_entry(source_index) {
                    return Some(Err(error));
                }
            }

            let Some(first_record) = first_record else {
                continue;
            };
            match self.visible_lazy_item_from_records(first_record, rest_records) {
                Ok(Some(item)) => return Some(Ok(item)),
                Ok(None) => {}
                Err(error) => return Some(Err(error)),
            }
        }
    }

    async fn next_lazy_async(&mut self) -> Result<Option<LazyKeyValue>> {
        if !self.source_heap_initialized {
            self.initialize_source_heap_async().await?;
        }

        loop {
            let Some(entry) = self.source_heap.pop() else {
                return Ok(None);
            };
            let user_key = entry.user_key;
            let mut source_indices = vec![entry.source_index];
            while self
                .source_heap
                .peek()
                .is_some_and(|entry| entry.user_key == user_key)
            {
                let entry = self
                    .source_heap
                    .pop()
                    .expect("heap peek promised another source entry");
                source_indices.push(entry.source_index);
            }

            let mut first_record = None;
            let mut rest_records = Vec::new();

            for source_index in source_indices {
                if let Some(group) = self.sources[source_index]
                    .take_current_group_async()
                    .await?
                {
                    push_group_records(&mut first_record, &mut rest_records, group);
                }
                self.push_source_heap_entry_async(source_index).await?;
            }

            let Some(first_record) = first_record else {
                continue;
            };
            if let Some(item) = self.visible_lazy_item_from_records(first_record, rest_records)? {
                return Ok(Some(item));
            }
        }
    }

    fn initialize_source_heap(&mut self) -> Result<()> {
        for source_index in 0..self.sources.len() {
            self.push_source_heap_entry(source_index)?;
        }
        self.source_heap_initialized = true;
        Ok(())
    }

    async fn initialize_source_heap_async(&mut self) -> Result<()> {
        for source_index in 0..self.sources.len() {
            self.push_source_heap_entry_async(source_index).await?;
        }
        self.source_heap_initialized = true;
        Ok(())
    }

    fn push_source_heap_entry(&mut self, source_index: usize) -> Result<()> {
        let Some(user_key) = self.sources[source_index]
            .current_key()?
            .map(<[u8]>::to_vec)
        else {
            return Ok(());
        };
        self.source_heap.push(SourceHeapEntry {
            user_key,
            source_index,
            direction: self.direction,
        });
        Ok(())
    }

    async fn push_source_heap_entry_async(&mut self, source_index: usize) -> Result<()> {
        let Some(user_key) = self.sources[source_index].current_user_key_async().await? else {
            return Ok(());
        };
        self.source_heap.push(SourceHeapEntry {
            user_key,
            source_index,
            direction: self.direction,
        });
        Ok(())
    }

    fn visible_lazy_item_from_records(
        &self,
        first_record: ScanRecord,
        mut rest_records: Vec<ScanRecord>,
    ) -> Result<Option<LazyKeyValue>> {
        if rest_records.is_empty() {
            return self.visible_lazy_item_from_sorted_records(std::iter::once(first_record));
        }

        rest_records.push(first_record);
        rest_records.sort_by(|left, right| left.0.cmp(&right.0));

        self.visible_lazy_item_from_sorted_records(rest_records)
    }

    fn visible_lazy_item_from_sorted_records(
        &self,
        records: impl IntoIterator<Item = ScanRecord>,
    ) -> Result<Option<LazyKeyValue>> {
        for (internal_key, value) in records {
            if internal_key.sequence() > self.read_sequence {
                continue;
            }

            match internal_key.kind() {
                ValueKind::Put => {
                    if range_tombstones_cover(
                        &self.range_tombstones,
                        internal_key.user_key(),
                        internal_key.sequence(),
                        internal_key.batch_index(),
                        self.read_sequence,
                    ) {
                        return Ok(None);
                    }

                    let key = internal_key.user_key().to_vec();
                    let value = lazy_value(
                        value,
                        internal_key,
                        self.db_path.as_deref(),
                        self.native_storage.clone(),
                        self.blob_reads.clone(),
                        Arc::clone(&self.read_pin),
                    )?;
                    return Ok(Some(LazyKeyValue { key, value }));
                }
                ValueKind::PointDelete => return Ok(None),
                ValueKind::RangeDelete => {}
            }
        }

        Ok(None)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SourceHeapEntry {
    user_key: Vec<u8>,
    source_index: usize,
    direction: Direction,
}

impl Ord for SourceHeapEntry {
    fn cmp(&self, other: &Self) -> CmpOrdering {
        debug_assert_eq!(self.direction, other.direction);
        match compare_scan_keys(&self.user_key, &other.user_key, self.direction) {
            CmpOrdering::Less => CmpOrdering::Greater,
            CmpOrdering::Equal => other.source_index.cmp(&self.source_index),
            CmpOrdering::Greater => CmpOrdering::Less,
        }
    }
}

impl PartialOrd for SourceHeapEntry {
    fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
        Some(self.cmp(other))
    }
}

fn push_group_records(
    first_record: &mut Option<ScanRecord>,
    rest_records: &mut Vec<ScanRecord>,
    group: RecordGroup,
) {
    if let Some(previous_first) = first_record.take() {
        rest_records.push(previous_first);
    }
    *first_record = Some(group.first);
    rest_records.extend(group.rest);
}

fn compare_scan_keys(left: &[u8], right: &[u8], direction: Direction) -> CmpOrdering {
    match direction {
        Direction::Forward => left.cmp(right),
        Direction::Reverse => right.cmp(left),
    }
}

pub(crate) type ScanRecord = (InternalKey, Option<ValueRef>);

#[derive(Debug, Clone)]
pub(crate) struct RecordGroup {
    pub(crate) user_key: Vec<u8>,
    pub(crate) first: ScanRecord,
    pub(crate) rest: Vec<ScanRecord>,
}

#[derive(Debug, Clone)]
pub(crate) struct RecordSource {
    cursor: SourceCursor,
    current: Option<RecordGroup>,
}

impl RecordSource {
    pub(crate) fn memtable(
        memtable: Arc<Memtable>,
        selector: ScanSelector,
        direction: Direction,
    ) -> Self {
        Self {
            cursor: SourceCursor::Memtable(MemtableCursor::new(memtable, selector, direction)),
            current: None,
        }
    }

    pub(crate) fn table(cursor: TablePointCursor) -> Self {
        Self {
            cursor: SourceCursor::Table(cursor),
            current: None,
        }
    }

    fn current_key(&mut self) -> Result<Option<&[u8]>> {
        self.ensure_current()?;
        Ok(self.current.as_ref().map(|group| group.user_key.as_slice()))
    }

    fn take_current_group(&mut self) -> Result<Option<RecordGroup>> {
        self.ensure_current()?;
        Ok(self.current.take())
    }

    async fn current_user_key_async(&mut self) -> Result<Option<Vec<u8>>> {
        self.ensure_current_async().await?;
        Ok(self.current.as_ref().map(|group| group.user_key.clone()))
    }

    async fn take_current_group_async(&mut self) -> Result<Option<RecordGroup>> {
        self.ensure_current_async().await?;
        Ok(self.current.take())
    }

    fn ensure_current(&mut self) -> Result<()> {
        if self.current.is_none() {
            self.current = self.cursor.next_group()?;
        }
        Ok(())
    }

    async fn ensure_current_async(&mut self) -> Result<()> {
        if self.current.is_none() {
            self.current = self.cursor.next_group_async().await?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone)]
enum SourceCursor {
    Memtable(MemtableCursor),
    Table(TablePointCursor),
}

impl SourceCursor {
    fn next_group(&mut self) -> Result<Option<RecordGroup>> {
        match self {
            Self::Memtable(cursor) => cursor.next_group(),
            Self::Table(cursor) => cursor.next_group(),
        }
    }

    async fn next_group_async(&mut self) -> Result<Option<RecordGroup>> {
        match self {
            Self::Memtable(cursor) => cursor.next_group_async().await,
            Self::Table(cursor) => cursor.next_group_async().await,
        }
    }
}

#[derive(Debug, Clone)]
struct MemtableCursor {
    // The cursor keeps the memtable handle that was active when the scan was
    // created. A later flush can swap in a fresh active memtable without
    // changing what this iterator is allowed to see.
    memtable: Arc<Memtable>,
    selector: ScanSelector,
    direction: Direction,
    lower_bound: Bound<InternalKey>,
    upper_bound: Bound<InternalKey>,
    exhausted: bool,
}

impl MemtableCursor {
    fn new(memtable: Arc<Memtable>, selector: ScanSelector, direction: Direction) -> Self {
        let (lower_bound, upper_bound) = memtable_scan_bounds(&selector);

        Self {
            memtable,
            selector,
            direction,
            lower_bound,
            upper_bound,
            exhausted: false,
        }
    }

    fn next_group(&mut self) -> Result<Option<RecordGroup>> {
        match self.direction {
            Direction::Forward => self.next_group_forward(),
            Direction::Reverse => self.next_group_reverse(),
        }
    }

    // Memtable advancement has no I/O, but it participates in the async scan
    // chain so mixed memtable/table sources share one awaitable shape.
    #[allow(clippy::unused_async)]
    async fn next_group_async(&mut self) -> Result<Option<RecordGroup>> {
        self.next_group()
    }

    fn next_group_forward(&mut self) -> Result<Option<RecordGroup>> {
        if self.exhausted {
            return Ok(None);
        }

        let entries = self
            .memtable
            .read_entries()
            .map_err(|_| lock_poisoned("memtable entries"))?;
        let mut records = Vec::new();
        let mut group_user_key = None;

        for (internal_key, value) in
            entries.range((self.lower_bound.clone(), self.upper_bound.clone()))
        {
            match self.selector.forward_key_state(internal_key.user_key()) {
                ForwardKeyState::Before => {}
                ForwardKeyState::Match => {
                    let user_key =
                        group_user_key.get_or_insert_with(|| internal_key.user_key().to_vec());
                    if internal_key.user_key() == user_key.as_slice() {
                        records.push((internal_key.clone(), value.clone()));
                    } else {
                        break;
                    }
                }
                ForwardKeyState::After => {
                    self.exhausted = true;
                    return Ok(None);
                }
            }
        }
        drop(entries);

        let Some(user_key) = group_user_key else {
            self.exhausted = true;
            return Ok(None);
        };
        self.lower_bound = Bound::Excluded(last_internal_key_for_user(&user_key));
        Ok(Some(record_group_from_records(user_key, records)))
    }

    fn next_group_reverse(&mut self) -> Result<Option<RecordGroup>> {
        if self.exhausted {
            return Ok(None);
        }

        let entries = self
            .memtable
            .read_entries()
            .map_err(|_| lock_poisoned("memtable entries"))?;
        let mut records = Vec::new();
        let mut group_user_key = None;

        for (internal_key, value) in entries
            .range((self.lower_bound.clone(), self.upper_bound.clone()))
            .rev()
        {
            match self.selector.reverse_key_state(internal_key.user_key()) {
                ReverseKeyState::Above => {}
                ReverseKeyState::Match => {
                    let user_key =
                        group_user_key.get_or_insert_with(|| internal_key.user_key().to_vec());
                    if internal_key.user_key() == user_key.as_slice() {
                        records.push((internal_key.clone(), value.clone()));
                    } else {
                        break;
                    }
                }
                ReverseKeyState::Below => {
                    self.exhausted = true;
                    return Ok(None);
                }
            }
        }
        drop(entries);

        let Some(user_key) = group_user_key else {
            self.exhausted = true;
            return Ok(None);
        };
        self.upper_bound = Bound::Excluded(first_internal_key_for_user(&user_key));
        Ok(Some(record_group_from_records(user_key, records)))
    }
}

fn record_group_from_records(user_key: Vec<u8>, mut records: Vec<ScanRecord>) -> RecordGroup {
    let first = records
        .pop()
        .expect("memtable cursor only builds groups after finding a record");
    let (first, rest) = sort_group_records(first, records);
    RecordGroup {
        user_key,
        first,
        rest,
    }
}

pub(crate) fn sort_group_records(
    first: ScanRecord,
    mut rest: Vec<ScanRecord>,
) -> (ScanRecord, Vec<ScanRecord>) {
    if rest.is_empty() {
        return (first, rest);
    }

    rest.push(first);
    rest.sort_by(|left, right| left.0.cmp(&right.0));
    let mut records = rest.into_iter();
    let first = records
        .next()
        .expect("non-empty record group must keep a first record");
    let rest = records.collect();
    (first, rest)
}

fn memtable_scan_bounds(selector: &ScanSelector) -> (Bound<InternalKey>, Bound<InternalKey>) {
    match selector {
        ScanSelector::Range(range) => (
            memtable_start_bound(&range.start),
            memtable_end_bound(&range.end),
        ),
        ScanSelector::Prefix(prefix) => {
            let start = Bound::Included(first_internal_key_for_user(prefix));
            let end = prefix_successor(prefix).map_or(Bound::Unbounded, |end| {
                Bound::Excluded(first_internal_key_for_user(&end))
            });
            (start, end)
        }
    }
}

fn memtable_start_bound(start: &Bound<Vec<u8>>) -> Bound<InternalKey> {
    match start {
        Bound::Included(key) => Bound::Included(first_internal_key_for_user(key)),
        Bound::Excluded(key) => Bound::Excluded(last_internal_key_for_user(key)),
        Bound::Unbounded => Bound::Unbounded,
    }
}

fn memtable_end_bound(end: &Bound<Vec<u8>>) -> Bound<InternalKey> {
    match end {
        Bound::Included(key) => Bound::Included(last_internal_key_for_user(key)),
        Bound::Excluded(key) => Bound::Excluded(first_internal_key_for_user(key)),
        Bound::Unbounded => Bound::Unbounded,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ScanSelector {
    Range(KeyRange),
    Prefix(Vec<u8>),
}

impl ScanSelector {
    pub(crate) fn forward_key_state(&self, key: &[u8]) -> ForwardKeyState {
        match self {
            Self::Range(range) => {
                if key_is_before_start(key, &range.start) {
                    ForwardKeyState::Before
                } else if key_is_after_end(key, &range.end) {
                    ForwardKeyState::After
                } else {
                    ForwardKeyState::Match
                }
            }
            Self::Prefix(prefix) => {
                if key < prefix.as_slice() {
                    ForwardKeyState::Before
                } else if key.starts_with(prefix) {
                    ForwardKeyState::Match
                } else {
                    ForwardKeyState::After
                }
            }
        }
    }

    pub(crate) fn reverse_key_state(&self, key: &[u8]) -> ReverseKeyState {
        match self {
            Self::Range(range) => {
                if key_is_after_end(key, &range.end) {
                    ReverseKeyState::Above
                } else if key_is_before_start(key, &range.start) {
                    ReverseKeyState::Below
                } else {
                    ReverseKeyState::Match
                }
            }
            Self::Prefix(prefix) => {
                if key.starts_with(prefix) {
                    ReverseKeyState::Match
                } else if key < prefix.as_slice() {
                    ReverseKeyState::Below
                } else {
                    ReverseKeyState::Above
                }
            }
        }
    }

    pub(crate) fn prefix(&self) -> Option<&[u8]> {
        match self {
            Self::Range(_) => None,
            Self::Prefix(prefix) => Some(prefix),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ForwardKeyState {
    Before,
    Match,
    After,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReverseKeyState {
    Above,
    Match,
    Below,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ScanRangeTombstone {
    range: KeyRange,
    sequence: Sequence,
    batch_index: u32,
}

impl ScanRangeTombstone {
    #[must_use]
    pub(crate) fn new(range: KeyRange, sequence: Sequence, batch_index: u32) -> Self {
        Self {
            range,
            sequence,
            batch_index,
        }
    }

    fn covers_visible_point(
        &self,
        key: &[u8],
        point_sequence: Sequence,
        point_batch_index: u32,
        read_sequence: Sequence,
    ) -> bool {
        if self.sequence > read_sequence || !key_is_in_range(key, &self.range) {
            return false;
        }

        self.sequence > point_sequence
            || (self.sequence == point_sequence && self.batch_index > point_batch_index)
    }
}

impl RangeTombstoneLike for ScanRangeTombstone {
    fn range(&self) -> &KeyRange {
        &self.range
    }
}

fn range_tombstones_cover(
    range_tombstones: &RangeTombstoneIndex<ScanRangeTombstone>,
    key: &[u8],
    point_sequence: Sequence,
    point_batch_index: u32,
    read_sequence: Sequence,
) -> bool {
    range_tombstones.covering_key(key).any(|tombstone| {
        tombstone.covers_visible_point(key, point_sequence, point_batch_index, read_sequence)
    })
}

fn lock_poisoned(lock_name: &'static str) -> Error {
    Error::Corruption {
        message: format!("{lock_name} lock poisoned"),
    }
}

fn lazy_value(
    value: Option<ValueRef>,
    internal_key: InternalKey,
    db_path: Option<&std::path::Path>,
    native_storage: Option<NativeFileBackend>,
    blob_reads: Option<Arc<BlobReadMetrics>>,
    read_pin: Arc<Snapshot>,
) -> Result<LazyValue> {
    let value = value.ok_or_else(|| Error::Corruption {
        message: "put record is missing value bytes".to_owned(),
    })?;

    match value {
        ValueRef::Inline(bytes) => Ok(LazyValue {
            inner: LazyValueInner::Inline(bytes),
        }),
        ValueRef::BlobIndex(_) | ValueRef::Blob { .. } => {
            let db_path = db_path.ok_or_else(|| Error::Corruption {
                message: "in-memory database cannot read blob value references".to_owned(),
            })?;
            Ok(LazyValue {
                inner: LazyValueInner::Blob {
                    db_path: db_path.to_path_buf(),
                    native_storage,
                    internal_key,
                    value,
                    blob_reads,
                    _read_pin: read_pin,
                },
            })
        }
    }
}

pub(crate) fn prefix_successor(prefix: &[u8]) -> Option<Vec<u8>> {
    let mut end = prefix.to_vec();
    while let Some(last) = end.last_mut() {
        if *last == u8::MAX {
            end.pop();
        } else {
            *last += 1;
            return Some(end);
        }
    }

    None
}

fn key_is_before_start(key: &[u8], start: &Bound<Vec<u8>>) -> bool {
    match start {
        Bound::Included(start) => key < start.as_slice(),
        Bound::Excluded(start) => key <= start.as_slice(),
        Bound::Unbounded => false,
    }
}

fn key_is_after_end(key: &[u8], end: &Bound<Vec<u8>>) -> bool {
    match end {
        Bound::Included(end) => key > end.as_slice(),
        Bound::Excluded(end) => key >= end.as_slice(),
        Bound::Unbounded => false,
    }
}

fn key_is_in_range(key: &[u8], range: &KeyRange) -> bool {
    !key_is_before_start(key, &range.start) && !key_is_after_end(key, &range.end)
}

#[cfg(test)]
mod tests {
    use std::{collections::BinaryHeap, sync::Arc};

    use super::{Direction, Iter, RecordSource, ScanSelector, ScanSourceInput, SourceHeapEntry};
    use crate::{
        blob::ValueRef,
        internal_key::{InternalKey, ValueKind},
        memtable::Memtable,
        snapshot::Snapshot,
        types::{KeyRange, Sequence},
    };

    #[test]
    fn source_heap_orders_forward_and_reverse_keys() {
        let mut forward = BinaryHeap::new();
        forward.push(heap_entry(b"c", 0, Direction::Forward));
        forward.push(heap_entry(b"a", 1, Direction::Forward));
        forward.push(heap_entry(b"b", 2, Direction::Forward));

        assert_eq!(forward.pop().expect("entry").user_key, b"a");
        assert_eq!(forward.pop().expect("entry").user_key, b"b");
        assert_eq!(forward.pop().expect("entry").user_key, b"c");

        let mut reverse = BinaryHeap::new();
        reverse.push(heap_entry(b"c", 0, Direction::Reverse));
        reverse.push(heap_entry(b"a", 1, Direction::Reverse));
        reverse.push(heap_entry(b"b", 2, Direction::Reverse));

        assert_eq!(reverse.pop().expect("entry").user_key, b"c");
        assert_eq!(reverse.pop().expect("entry").user_key, b"b");
        assert_eq!(reverse.pop().expect("entry").user_key, b"a");
    }

    #[test]
    fn lazy_scan_heap_merge_preserves_forward_and_reverse_order() {
        let left = memtable_with(&[(b"a", b"a1"), (b"c", b"c1")]);
        let right = memtable_with(&[(b"b", b"b1"), (b"d", b"d1")]);

        let forward = Iter::from_sources(
            Direction::Forward,
            ScanSourceInput {
                read_sequence: Sequence::new(4),
                read_pin: Snapshot::new(Sequence::new(4)),
                db_path: None,
                native_storage: None,
                blob_reads: None,
                range_tombstones: Vec::new(),
                sources: vec![
                    RecordSource::memtable(
                        Arc::clone(&left),
                        ScanSelector::Range(KeyRange::all()),
                        Direction::Forward,
                    ),
                    RecordSource::memtable(
                        Arc::clone(&right),
                        ScanSelector::Range(KeyRange::all()),
                        Direction::Forward,
                    ),
                ],
            },
        );
        assert_eq!(
            collect_keys(forward),
            vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), b"d".to_vec()]
        );

        let reverse = Iter::from_sources(
            Direction::Reverse,
            ScanSourceInput {
                read_sequence: Sequence::new(4),
                read_pin: Snapshot::new(Sequence::new(4)),
                db_path: None,
                native_storage: None,
                blob_reads: None,
                range_tombstones: Vec::new(),
                sources: vec![
                    RecordSource::memtable(
                        left,
                        ScanSelector::Range(KeyRange::all()),
                        Direction::Reverse,
                    ),
                    RecordSource::memtable(
                        right,
                        ScanSelector::Range(KeyRange::all()),
                        Direction::Reverse,
                    ),
                ],
            },
        );
        assert_eq!(
            collect_keys(reverse),
            vec![b"d".to_vec(), b"c".to_vec(), b"b".to_vec(), b"a".to_vec()]
        );
    }

    fn heap_entry(user_key: &[u8], source_index: usize, direction: Direction) -> SourceHeapEntry {
        SourceHeapEntry {
            user_key: user_key.to_vec(),
            source_index,
            direction,
        }
    }

    fn memtable_with(records: &[(&[u8], &[u8])]) -> Arc<Memtable> {
        let memtable = Arc::new(Memtable::default());
        {
            let mut entries = memtable.write_entries().expect("memtable lock");
            for (index, (key, value)) in records.iter().enumerate() {
                entries.insert(
                    InternalKey::new(
                        *key,
                        Sequence::new(u64::try_from(index + 1).expect("test sequence fits")),
                        ValueKind::Put,
                        0,
                    ),
                    Some(ValueRef::Inline((*value).to_vec())),
                );
            }
        }
        memtable
    }

    fn collect_keys(iter: Iter) -> Vec<Vec<u8>> {
        iter.map(|item| item.expect("iterator item").key)
            .collect::<Vec<_>>()
    }
}