artmap 0.8.0

A concurrent in-memory Adaptive Radix Tree (ART) featuring optimistic lock coupling.
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
// Copyright (c) 2026 SurrealDB Ltd
//
// 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.

//! # Concurrent multi-version adaptive radix tree

#![deny(unsafe_op_in_unsafe_fn, clippy::undocumented_unsafe_blocks)]

use std::borrow::Borrow;
use std::ops::{Bound, RangeBounds};

use crate::guard::{pin, Guard, GuardHandle};
use crate::key::AsBytes;
use crate::raw::cursor::{owned_bound, Cursor};
use crate::versioned::entry::VersionedEntryRef;
use crate::versioned::iter::Range;
use crate::versioned::tree::{chain, find_le, VersionedTree};

/// A concurrent ordered map with 64-bit MVCC versions per key.
///
/// Each key has a chain of versions, newest first; a version may be a
/// tombstone. Snapshot reads (`get_version_le`) take no latches. Writers of one
/// key serialise on a per-key latch; writers of different keys run in parallel.
///
/// ## Semantics
///
/// - `len()` is the number of keys whose newest version is live (not a
///   tombstone). It is exact when no operation is in flight, and approximate
///   while several threads write.
/// - `get_latest`/`get` return `None` when the newest version is a tombstone;
///   `get_version_le` returns `None` when the selected version is one.
///   Older snapshots are unaffected by later deletes.
/// - `version_count` and `get_all_versions` include tombstones.
/// - Scans (`iter`, `range`, `scan`) are latest-view: keys whose newest version
///   is a tombstone are skipped.
/// - After `prune_key(k, min, ..)` or `prune_all(min, ..)`, `get_version_le(k, v)`
///   is exact for `v >= min` and unsupported for `v < min` (the watermark
///   contract). Writes at or below `min` are unsupported too: a key that
///   pruning removed is created afresh by such a write, which then shows as
///   its newest version.
/// - A deleted key keeps its leaf and tombstone until a prune at or above the
///   tombstone's version unlinks it, or `remove_key` does. `remove_key` and
///   `remove_version` change history for every snapshot; `delete` does not.
pub struct VersionedArtMap<K, V> {
    tree: VersionedTree<K, V>,
}

impl<K, V> Default for VersionedArtMap<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> VersionedArtMap<K, V> {
    crate::sync::const_fn_unless_loom! {
        /// Creates an empty map.
        pub fn new() -> Self {
            Self {
                tree: VersionedTree::new(),
            }
        }
    }

    /// Creates an empty map. The capacity is a hint and currently unused.
    pub fn with_capacity(_capacity: usize) -> Self {
        Self::new()
    }

    /// The number of keys whose newest version is live.
    #[inline]
    pub fn len(&self) -> usize {
        self.tree.len()
    }

    /// `true` if no key has a live newest version.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<K: AsBytes + Send + 'static, V: Send + 'static> VersionedArtMap<K, V> {
    /// Pins the epoch, for the `*_with_guard` methods.
    #[inline]
    pub fn pin(&self) -> Guard<'_> {
        Guard::new()
    }

    /// The newest live value of `key`.
    #[inline]
    pub fn get<Q>(&self, key: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
        V: Clone,
    {
        self.get_latest(key).map(|(_, v)| v)
    }

    /// The newest live value of a raw byte key.
    #[inline]
    pub fn get_by_slice(&self, key: &[u8]) -> Option<V>
    where
        V: Clone,
    {
        self.get_slice(key)
    }

    /// The newest live value of a raw byte key.
    #[inline]
    pub fn get_slice(&self, key: &[u8]) -> Option<V>
    where
        V: Clone,
    {
        let _g = pin();
        let leaf = self.tree.raw.get(key)?;
        // SAFETY: protected by `_g`.
        let head = unsafe { leaf.as_ref() }.head();
        head.value().cloned()
    }

    /// The newest version and value of `key`, if live.
    #[inline]
    pub fn get_latest<Q>(&self, key: &Q) -> Option<(u64, V)>
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
        V: Clone,
    {
        let _g = pin();
        let leaf = self.tree.raw.get(key.as_bytes())?;
        // SAFETY: protected by `_g`.
        let head = unsafe { leaf.as_ref() }.head();
        head.value().cloned().map(|v| (head.version, v))
    }

    /// A handle on the newest live version of `key`, without cloning.
    pub fn get_entry<Q>(&self, key: &Q) -> Option<VersionedEntryRef<'_, K, V>>
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
    {
        let guard = GuardHandle::owned();
        let leaf = self.tree.raw.get(key.as_bytes())?;
        // SAFETY: protected by `guard`, which moves into the handle.
        let head = unsafe { leaf.as_ref() }.head();
        VersionedEntryRef::new(leaf, head, &self.tree, guard)
    }

    /// The newest version of `key` that is `<= max_version`, unless it is a
    /// tombstone. The basis of MVCC snapshot reads.
    ///
    /// ```
    /// let map = artmap::VersionedArtMap::<String, u32>::new();
    /// map.insert("k".to_string(), 10, 1);
    /// map.insert("k".to_string(), 20, 2);
    /// assert_eq!(map.get_version_le("k", 15), Some((10, 1)));
    /// assert_eq!(map.get_version_le("k", 25), Some((20, 2)));
    /// assert_eq!(map.get_version_le("k", 5), None);
    /// ```
    #[inline]
    pub fn get_version_le<Q>(&self, key: &Q, max_version: u64) -> Option<(u64, V)>
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
        V: Clone,
    {
        let g = &pin();
        self.version_le(key.as_bytes(), max_version, g)
    }

    /// As [`get_version_le`](Self::get_version_le), with a pre-pinned guard.
    #[inline]
    pub fn get_version_le_with_guard<Q>(
        &self,
        key: &Q,
        max_version: u64,
        guard: &Guard<'_>,
    ) -> Option<(u64, V)>
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
        V: Clone,
    {
        self.version_le(key.as_bytes(), max_version, &guard.inner)
    }

    fn version_le(&self, key: &[u8], max: u64, _g: &crossbeam_epoch::Guard) -> Option<(u64, V)>
    where
        V: Clone,
    {
        let leaf = self.tree.raw.get(key)?;
        // SAFETY: protected by `_g`.
        let n = find_le(unsafe { leaf.as_ref() }.head(), max)?;
        n.value().cloned().map(|v| (n.version, v))
    }

    /// `true` if the newest version of `key` is live.
    #[inline]
    pub fn contains_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
    {
        let _g = pin();
        self.tree
            .raw
            .get(key.as_bytes())
            // SAFETY: protected by `_g`.
            .is_some_and(|l| !unsafe { l.as_ref() }.head().is_tombstone())
    }

    /// Adds `version` of `key`. An existing version with the same number is
    /// replaced (out of place). Always returns `true`.
    #[inline]
    pub fn insert(&self, key: K, version: u64, value: V) -> bool {
        let g = &pin();
        self.tree.insert(key, version, Some(value), g);
        true
    }

    /// As [`insert`](Self::insert), with a pre-pinned guard.
    #[inline]
    pub fn insert_with_guard(&self, key: K, version: u64, value: V, guard: &Guard<'_>) -> bool {
        self.tree.insert(key, version, Some(value), &guard.inner);
        true
    }

    /// Alias for [`insert`](Self::insert).
    #[inline]
    pub fn insert_versioned(&self, key: K, version: u64, value: V) -> bool {
        self.insert(key, version, value)
    }

    /// Records a tombstone at `version` for `key`, creating the key if needed.
    /// Older snapshots are unchanged. Returns `true` if the key's newest
    /// version was live before and is now deleted.
    ///
    /// ```
    /// let map = artmap::VersionedArtMap::<String, u32>::new();
    /// map.insert("k".to_string(), 1, 7);
    /// assert!(map.delete("k".to_string(), 2));
    /// assert_eq!(map.get("k"), None);
    /// assert_eq!(map.get_version_le("k", 1), Some((1, 7)));
    /// assert_eq!(map.get_all_versions("k"), vec![(2, None), (1, Some(7))]);
    /// ```
    pub fn delete(&self, key: K, version: u64) -> bool {
        let g = &pin();
        self.tree.insert(key, version, None, g) < 0
    }

    /// Deletes the newest version of `key` in place of its value: publishes a
    /// tombstone with the same version number, so snapshots at or after that
    /// version see the key as absent. Returns the replaced version.
    #[deprecated(note = "use `delete(key, version)`, which does not rewrite history")]
    pub fn remove<Q>(&self, key: &Q) -> Option<VersionedEntryRef<'_, K, V>>
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
    {
        let guard = GuardHandle::owned();
        let (leaf, old) = self.tree.remove_head(key.as_bytes(), guard.guard())?;
        // SAFETY: `old` is retired through `guard`, which moves into the handle.
        VersionedEntryRef::new(leaf, unsafe { old.as_ref() }, &self.tree, guard)
    }

    /// Removes `key` and every version of it, for every snapshot, unlike
    /// [`delete`](Self::delete). Returns `true` if the key had any version,
    /// live or not.
    ///
    /// ```
    /// let map = artmap::VersionedArtMap::<String, u32>::new();
    /// map.insert("k".to_string(), 1, 7);
    /// map.delete("k".to_string(), 2);
    /// assert!(map.remove_key("k"));
    /// assert_eq!(map.get_version_le("k", 1), None);
    /// assert_eq!(map.version_count("k"), 0);
    /// assert!(!map.remove_key("k"));
    /// ```
    pub fn remove_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
    {
        let g = &pin();
        self.tree.remove_key(key.as_bytes(), g)
    }

    /// Removes exactly `version` of `key`, a value or a tombstone, for every
    /// snapshot, for example to roll back a write. The key goes with its last
    /// version. Returns `true` if that version existed.
    ///
    /// ```
    /// let map = artmap::VersionedArtMap::<String, u32>::new();
    /// map.insert("k".to_string(), 1, 10);
    /// map.insert("k".to_string(), 2, 20);
    /// assert!(map.remove_version("k", 2));
    /// assert_eq!(map.get("k"), Some(10));
    /// assert!(map.remove_version("k", 1));
    /// assert_eq!(map.version_count("k"), 0);
    /// assert!(!map.remove_version("k", 1));
    /// ```
    pub fn remove_version<Q>(&self, key: &Q, version: u64) -> bool
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
    {
        let g = &pin();
        self.tree.remove_version(key.as_bytes(), version, g)
    }

    /// Removes every key and version. Linearizable with respect to point
    /// operations: the linearization point is the swap of the root. Runs in
    /// O(n) on the calling thread, holding at most one node latch at a time.
    pub fn clear(&self) {
        let g = &pin();
        self.tree.clear(g);
    }

    /// Fits the tree to its keys, releasing the memory that removes and
    /// prunes leave in nodes too large for what they still hold. As
    /// [`ArtMap::shrink_to_fit`](crate::ArtMap::shrink_to_fit): a node left
    /// with one key gives way to it, one left with a single child node is
    /// merged into it when their prefixes fit, and every other node is shrunk
    /// to the smallest layout that holds its entries. Keys and their versions
    /// are not touched, so it runs alongside readers and writers.
    pub fn shrink_to_fit(&self) {
        let g = &pin();
        self.tree.raw.shrink_to_fit(g);
    }

    /// Checks the tree's structural invariants, and that `len()` equals the
    /// number of reachable keys whose newest version is live. Panics on a
    /// violation. Requires exclusive access, so it never races with writers.
    pub fn validate_invariants(&mut self) {
        self.tree.validate();
    }

    /// The number of versions of `key`, including tombstones.
    pub fn version_count<Q>(&self, key: &Q) -> usize
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
    {
        let _g = pin();
        match self.tree.raw.get(key.as_bytes()) {
            // SAFETY: protected by `_g`.
            Some(l) => chain(unsafe { l.as_ref() }.head()).count(),
            None => 0,
        }
    }

    /// Every version of `key`, newest first; `None` values are tombstones.
    pub fn get_all_versions<Q>(&self, key: &Q) -> Vec<(u64, Option<V>)>
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
        V: Clone,
    {
        let _g = pin();
        match self.tree.raw.get(key.as_bytes()) {
            // SAFETY: protected by `_g`.
            Some(l) => chain(unsafe { l.as_ref() }.head())
                .map(|n| (n.version, n.value().cloned()))
                .collect(),
            None => Vec::new(),
        }
    }

    /// Unlinks every version of `key` older than its newest version
    /// `<= min_version`. If that version is the key's newest one and is a
    /// tombstone (a `delete`, or a value that `is_tombstone` accepts), no
    /// snapshot at or above `min_version` can see the key, so the key itself
    /// is unlinked with all its versions. Returns the number of versions
    /// unlinked.
    ///
    /// `is_tombstone` runs without any latch held. See the type's docs for the
    /// watermark contract.
    ///
    /// ```
    /// let map = artmap::VersionedArtMap::<String, u32>::new();
    /// for v in 1..=4 {
    ///     map.insert("k".to_string(), v, v as u32);
    /// }
    /// // No snapshot below version 3 remains: versions 1 and 2 can go.
    /// assert_eq!(map.prune_key("k", 3, |_| false), 2);
    /// assert_eq!(map.get_all_versions("k"), vec![(4, Some(4)), (3, Some(3))]);
    /// ```
    pub fn prune_key<Q, F>(&self, key: &Q, min_version: u64, is_tombstone: F) -> usize
    where
        K: Borrow<Q>,
        Q: AsBytes + ?Sized,
        F: Fn(&V) -> bool,
    {
        let g = &pin();
        match self.tree.raw.get(key.as_bytes()) {
            Some(leaf) => self.tree.prune_leaf(leaf, min_version, &is_tombstone, g),
            None => 0,
        }
    }

    /// [`prune_key`](Self::prune_key) for every key, including deleted ones,
    /// which it unlinks once `min_version` passes their tombstone. Repins
    /// periodically so a long prune does not stall reclamation.
    ///
    /// ```
    /// let map = artmap::VersionedArtMap::<String, u32>::new();
    /// map.insert("a".to_string(), 1, 1);
    /// map.insert("b".to_string(), 1, 2);
    /// map.delete("b".to_string(), 2);
    /// assert_eq!(map.prune_all(2, |_| false), 2);
    /// // "b" is gone with both its versions; "a" keeps its only version.
    /// assert_eq!(map.version_count("b"), 0);
    /// assert_eq!(map.version_count("a"), 1);
    /// ```
    pub fn prune_all<F>(&self, min_version: u64, is_tombstone: F) -> usize
    where
        F: Fn(&V) -> bool,
    {
        let mut g = pin();
        let mut cursor = Cursor::new(Bound::Unbounded, Bound::Unbounded);
        let mut total = 0;
        let mut n = 0usize;
        while let Some(leaf) = cursor.next(&self.tree.raw) {
            total += self.tree.prune_leaf(leaf, min_version, &is_tombstone, &g);
            n += 1;
            if n % 1024 == 0 {
                // Frames hold node pointers protected by `g`: drop them first.
                cursor.invalidate(&self.tree.raw);
                g.repin();
            }
        }
        total
    }

    /// An iterator over the latest live version of each key in `range`.
    pub fn range<R, Q>(&self, range: R) -> Range<'_, K, V>
    where
        R: RangeBounds<Q>,
        Q: AsBytes + ?Sized,
    {
        Range::owned(
            &self.tree,
            owned_bound(range.start_bound()),
            owned_bound(range.end_bound()),
        )
    }

    /// As [`range`](Self::range), borrowing the caller's guard.
    pub fn range_with_guard<'a, R, Q>(&'a self, range: R, guard: &'a Guard<'_>) -> Range<'a, K, V>
    where
        R: RangeBounds<Q>,
        Q: AsBytes + ?Sized,
    {
        Range::borrowed(
            &self.tree,
            &guard.inner,
            owned_bound(range.start_bound()),
            owned_bound(range.end_bound()),
        )
    }

    /// An iterator over the latest live version of every key.
    pub fn iter(&self) -> Range<'_, K, V> {
        Range::owned(&self.tree, Bound::Unbounded, Bound::Unbounded)
    }

    /// As [`iter`](Self::iter), borrowing the caller's guard.
    pub fn iter_with_guard<'a>(&'a self, guard: &'a Guard<'_>) -> Range<'a, K, V> {
        Range::borrowed(&self.tree, &guard.inner, Bound::Unbounded, Bound::Unbounded)
    }

    /// Calls `callback(key, value, version)` for the latest live version of
    /// each key in `range`, until it returns `false`.
    ///
    /// One pin covers the whole scan, and no per-entry handle is created, so
    /// this is the cheapest way to visit a range.
    pub fn scan<R, Q, F>(&self, range: R, mut callback: F)
    where
        R: RangeBounds<Q>,
        Q: AsBytes + ?Sized,
        F: FnMut(&K, &V, u64) -> bool,
    {
        let guard = self.pin();
        for e in self.range_with_guard(range, &guard) {
            if !callback(e.key(), e.value(), e.version()) {
                break;
            }
        }
    }
}

impl<'a, K: AsBytes + Send + 'static, V: Send + 'static> IntoIterator
    for &'a VersionedArtMap<K, V>
{
    type Item = VersionedEntryRef<'a, K, V>;
    type IntoIter = Range<'a, K, V>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}