trine-kv 0.6.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
use std::{
    collections::BTreeMap,
    sync::{Arc, Mutex},
};

use crate::{
    bucket::Bucket,
    error::{Error, Result},
    invariants::{SnapshotReachability, classify_snapshot_reachability},
    iterator::{Iter, LazyIter},
    types::{KeyRange, ReadVersion, Sequence, Value},
};

#[derive(Debug, Default)]
pub(crate) struct SnapshotTracker {
    active: Mutex<BTreeMap<Sequence, usize>>,
    compaction_floors: Mutex<BTreeMap<Sequence, usize>>,
}

impl SnapshotTracker {
    pub(crate) fn pinned_snapshot(self: &Arc<Self>, read_sequence: Sequence) -> Snapshot {
        self.pin(read_sequence);
        Snapshot {
            read_sequence,
            pin: Some(SnapshotPin {
                tracker: Arc::clone(self),
            }),
        }
    }

    pub(crate) fn pinned_retained_snapshot(
        self: &Arc<Self>,
        read_sequence: Sequence,
        latest_sequence: Sequence,
        retained_floor: Sequence,
    ) -> Result<Snapshot> {
        let compaction_floors = self
            .compaction_floors
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let compaction_floor = compaction_floors.keys().next_back().copied();
        if compaction_floor.is_some_and(|floor| read_sequence < floor) {
            return Err(Error::runtime_busy(
                "requested snapshot is older than an admitted compaction; retry after maintenance",
            ));
        }
        let mut active = self
            .active
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let oldest_retained = active
            .keys()
            .next()
            .copied()
            .unwrap_or(latest_sequence)
            .min(retained_floor);
        let requested = ReadVersion::from_sequence(read_sequence);
        match classify_snapshot_reachability(
            read_sequence.get(),
            oldest_retained.get(),
            latest_sequence.get(),
        ) {
            SnapshotReachability::TooNew => {
                return Err(Error::ReadVersionTooNew {
                    requested,
                    latest: ReadVersion::from_sequence(latest_sequence),
                });
            }
            SnapshotReachability::TooOld => {
                return Err(Error::ReadVersionExpired {
                    requested,
                    oldest_retained: ReadVersion::from_sequence(oldest_retained),
                });
            }
            SnapshotReachability::Reachable => {}
        }

        *active.entry(read_sequence).or_default() += 1;
        drop(active);
        drop(compaction_floors);
        Ok(Snapshot {
            read_sequence,
            pin: Some(SnapshotPin {
                tracker: Arc::clone(self),
            }),
        })
    }

    pub(crate) fn oldest_active_or(&self, fallback: Sequence) -> Sequence {
        self.active
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .keys()
            .next()
            .copied()
            .unwrap_or(fallback)
    }

    pub(crate) fn active_count(&self) -> usize {
        self.active
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .values()
            .sum()
    }

    pub(crate) fn begin_compaction(
        self: &Arc<Self>,
        retained_floor_without_snapshots: Sequence,
    ) -> (Sequence, CompactionSnapshotGuard) {
        let mut floors = self
            .compaction_floors
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        // Snapshot admission holds the floor lock until it has inserted into
        // `active`; taking the locks in the same order makes admission atomic.
        let active = self
            .active
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let floor = active
            .keys()
            .next()
            .copied()
            .unwrap_or(retained_floor_without_snapshots)
            .min(retained_floor_without_snapshots);
        *floors.entry(floor).or_default() += 1;
        drop(active);
        drop(floors);
        (
            floor,
            CompactionSnapshotGuard {
                tracker: Arc::clone(self),
                floor,
            },
        )
    }

    fn pin(&self, read_sequence: Sequence) {
        let mut active = self
            .active
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        *active.entry(read_sequence).or_default() += 1;
    }

    fn unpin(&self, read_sequence: Sequence) {
        let mut active = self
            .active
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(count) = active.get_mut(&read_sequence) {
            *count -= 1;
            if *count == 0 {
                active.remove(&read_sequence);
            }
        }
    }
}

#[derive(Debug)]
pub(crate) struct CompactionSnapshotGuard {
    tracker: Arc<SnapshotTracker>,
    floor: Sequence,
}

impl Drop for CompactionSnapshotGuard {
    fn drop(&mut self) {
        let mut floors = self
            .tracker
            .compaction_floors
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(count) = floors.get_mut(&self.floor) {
            if *count <= 1 {
                floors.remove(&self.floor);
            } else {
                *count -= 1;
            }
        }
    }
}

#[derive(Debug)]
struct SnapshotPin {
    tracker: Arc<SnapshotTracker>,
}

/// Repeatable-read handle pinned to a committed read version.
#[derive(Debug)]
pub struct Snapshot {
    read_sequence: Sequence,
    pin: Option<SnapshotPin>,
}

impl Snapshot {
    #[must_use]
    pub(crate) const fn new(read_sequence: Sequence) -> Self {
        Self {
            read_sequence,
            pin: None,
        }
    }

    pub(crate) fn read_sequence_for(
        &self,
        expected_tracker: &Arc<SnapshotTracker>,
    ) -> Result<Sequence> {
        let belongs_to_database = self
            .pin
            .as_ref()
            .is_some_and(|pin| Arc::ptr_eq(&pin.tracker, expected_tracker));
        if !belongs_to_database {
            return Err(Error::SnapshotDatabaseMismatch);
        }
        Ok(self.read_sequence)
    }

    /// Returns the public read version visible through this snapshot.
    ///
    /// All point, range, and prefix reads made through this snapshot use this
    /// same database-wide read boundary, even when newer writes commit before
    /// the reads run. The snapshot keeps that retained version pinned until all
    /// snapshot clones are dropped.
    #[must_use]
    pub const fn read_version(&self) -> ReadVersion {
        ReadVersion::from_sequence(self.read_sequence)
    }

    #[must_use]
    pub(crate) fn is_pinned(&self) -> bool {
        self.pin.is_some()
    }

    /// Synchronously reads `key` from `bucket` at this snapshot.
    pub fn get_sync(&self, bucket: &Bucket, key: &[u8]) -> Result<Option<Value>> {
        bucket.get_at_sync(self, key)
    }

    /// Synchronously scans `range` forward at this snapshot.
    pub fn range_sync(&self, bucket: &Bucket, range: &KeyRange) -> Result<Iter> {
        bucket.range_at_sync(self, range)
    }

    /// Synchronously scans `range` forward with lazy value reads at this snapshot.
    pub fn range_lazy_sync(&self, bucket: &Bucket, range: &KeyRange) -> Result<LazyIter> {
        bucket.range_lazy_at_sync(self, range)
    }

    /// Synchronously scans `range` in reverse at this snapshot.
    pub fn range_reverse_sync(&self, bucket: &Bucket, range: &KeyRange) -> Result<Iter> {
        bucket.range_reverse_at_sync(self, range)
    }

    /// Synchronously scans `range` in reverse with lazy value reads at this snapshot.
    pub fn range_lazy_reverse_sync(&self, bucket: &Bucket, range: &KeyRange) -> Result<LazyIter> {
        bucket.range_lazy_reverse_at_sync(self, range)
    }

    /// Synchronously scans keys beginning with `prefix` at this snapshot.
    pub fn prefix_sync(&self, bucket: &Bucket, prefix: impl Into<Vec<u8>>) -> Result<Iter> {
        bucket.prefix_at_sync(self, prefix)
    }

    /// Synchronously scans keys beginning with `prefix` with lazy value reads.
    pub fn prefix_lazy_sync(
        &self,
        bucket: &Bucket,
        prefix: impl Into<Vec<u8>>,
    ) -> Result<LazyIter> {
        bucket.prefix_lazy_at_sync(self, prefix)
    }

    /// Synchronously scans keys beginning with `prefix` in reverse.
    pub fn prefix_reverse_sync(&self, bucket: &Bucket, prefix: impl Into<Vec<u8>>) -> Result<Iter> {
        bucket.prefix_reverse_at_sync(self, prefix)
    }

    /// Synchronously scans keys beginning with `prefix` in reverse with lazy value reads.
    pub fn prefix_lazy_reverse_sync(
        &self,
        bucket: &Bucket,
        prefix: impl Into<Vec<u8>>,
    ) -> Result<LazyIter> {
        bucket.prefix_lazy_reverse_at_sync(self, prefix)
    }

    /// Asynchronously reads `key` from `bucket` at this snapshot.
    pub async fn get(&self, bucket: &Bucket, key: &[u8]) -> Result<Option<Value>> {
        bucket.get_at(self, key).await
    }

    /// Asynchronously scans `range` forward at this snapshot.
    pub async fn range(&self, bucket: &Bucket, range: &KeyRange) -> Result<Iter> {
        bucket.range_at(self, range).await
    }

    /// Asynchronously scans `range` forward with lazy value reads at this snapshot.
    pub async fn range_lazy(&self, bucket: &Bucket, range: &KeyRange) -> Result<LazyIter> {
        bucket.range_lazy_at(self, range).await
    }

    /// Asynchronously scans `range` in reverse at this snapshot.
    pub async fn range_reverse(&self, bucket: &Bucket, range: &KeyRange) -> Result<Iter> {
        bucket.range_reverse_at(self, range).await
    }

    /// Asynchronously scans `range` in reverse with lazy value reads at this snapshot.
    pub async fn range_lazy_reverse(&self, bucket: &Bucket, range: &KeyRange) -> Result<LazyIter> {
        bucket.range_lazy_reverse_at(self, range).await
    }

    /// Asynchronously scans keys beginning with `prefix` at this snapshot.
    pub async fn prefix(&self, bucket: &Bucket, prefix: impl Into<Vec<u8>>) -> Result<Iter> {
        bucket.prefix_at(self, prefix).await
    }

    /// Asynchronously scans keys beginning with `prefix` with lazy value reads.
    pub async fn prefix_lazy(
        &self,
        bucket: &Bucket,
        prefix: impl Into<Vec<u8>>,
    ) -> Result<LazyIter> {
        bucket.prefix_lazy_at(self, prefix).await
    }

    /// Asynchronously scans keys beginning with `prefix` in reverse.
    pub async fn prefix_reverse(
        &self,
        bucket: &Bucket,
        prefix: impl Into<Vec<u8>>,
    ) -> Result<Iter> {
        bucket.prefix_reverse_at(self, prefix).await
    }

    /// Asynchronously scans keys beginning with `prefix` in reverse with lazy value reads.
    pub async fn prefix_lazy_reverse(
        &self,
        bucket: &Bucket,
        prefix: impl Into<Vec<u8>>,
    ) -> Result<LazyIter> {
        bucket.prefix_lazy_reverse_at(self, prefix).await
    }
}

impl Clone for Snapshot {
    fn clone(&self) -> Self {
        if let Some(pin) = &self.pin {
            pin.tracker.pin(self.read_sequence);
            Self {
                read_sequence: self.read_sequence,
                pin: Some(SnapshotPin {
                    tracker: Arc::clone(&pin.tracker),
                }),
            }
        } else {
            Self::new(self.read_sequence)
        }
    }
}

impl Drop for Snapshot {
    fn drop(&mut self) {
        if let Some(pin) = &self.pin {
            pin.tracker.unpin(self.read_sequence);
        }
    }
}

impl PartialEq for Snapshot {
    fn eq(&self, other: &Self) -> bool {
        self.read_sequence == other.read_sequence
    }
}

impl Eq for Snapshot {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn admitted_compaction_blocks_new_older_snapshot_until_install_finishes() {
        let tracker = Arc::new(SnapshotTracker::default());
        let (floor, guard) = tracker.begin_compaction(Sequence::new(10));
        assert_eq!(floor, Sequence::new(10));

        let error = tracker
            .pinned_retained_snapshot(Sequence::new(5), Sequence::new(20), Sequence::new(0))
            .expect_err("older snapshot cannot enter an admitted compaction");
        assert!(matches!(error, Error::RuntimeBusy { .. }));

        drop(guard);
        tracker
            .pinned_retained_snapshot(Sequence::new(5), Sequence::new(20), Sequence::new(0))
            .expect("snapshot admission resumes after compaction guard drops");
    }

    #[test]
    fn already_pinned_snapshot_lowers_new_compaction_floor() {
        let tracker = Arc::new(SnapshotTracker::default());
        let snapshot = tracker.pinned_snapshot(Sequence::new(4));
        let (floor, _guard) = tracker.begin_compaction(Sequence::new(10));
        assert_eq!(floor, Sequence::new(4));
        drop(snapshot);
    }
}