artmap 0.7.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
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
// 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.

//! # Writer algorithms (§9)
//!
//! Every write follows the same structure (§9.1):
//!
//! 1. the caller pins before any latch (Inv 6);
//! 2. optimistic descent with coupling (R1–R6), comparing existing leaf keys
//!    before any latch (user code never runs under a latch);
//! 3. prepare: allocate unpublished nodes from the [`Prepared`] pool;
//! 4. acquire: the parent (or `root_latch`) with a blocking `lock()` while
//!    holding nothing, followed by a pointer re-check; the target node with a
//!    version-checked `try_upgrade`;
//! 5. commit, inside [`AbortOnUnwind`]: `len` accounting before the
//!    publishing store (Inv 12), `Release` stores, unlock or mark obsolete;
//! 6. after every latch is released: retire displaced objects.
//!
//! A failed upgrade or re-check retries from the root. There is no lock-free
//! insert path (Inv 8, §9.9): every publication happens under the owning latch.

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

use std::ptr::NonNull;

use crate::latch::{AbortOnUnwind, SpinBackoff, WriteGuard};
use crate::raw::node::{NodeHeader, NodeType, MAX_PREFIX_LEN};
use crate::raw::slot::Slot;
use crate::raw::{
    common_prefix, LeafNode, Mode, NodePtr, Outcome, Prepared, Raw, RawTree, Storage, Unpublished,
};

/// Where an insert published its leaf, for the arena inserters' fast path
/// (§12.4): the node that holds it, the node's version *after our own unlock*
/// (never a re-load), and the key depth at which its children start.
#[derive(Copy, Clone, Debug)]
pub(crate) struct Hint<R> {
    pub(crate) node: R,
    pub(crate) version: u64,
    pub(crate) depth: usize,
}

/// Where the parent of the node being modified keeps it.
#[derive(Copy, Clone)]
enum Parent<R> {
    Root,
    Node { raw: R, version: u64, byte: u8 },
}

/// A held parent latch, re-checked to still point at the child.
enum ParentGuard<'t, A> {
    Root(WriteGuard<'t>),
    Node(&'t NodeHeader<A>, WriteGuard<'t>, u8),
}

impl<S: Storage> RawTree<S> {
    /// Acquires the latch that owns the pointer to `child` (Inv 7): blocking,
    /// while holding nothing, followed by a pointer re-check.
    fn lock_parent(
        &self,
        parent: Parent<Raw<S>>,
        child: Raw<S>,
    ) -> Option<ParentGuard<'_, S::Atomic>> {
        match parent {
            Parent::Root => {
                let w = self.root_latch.lock()?;
                (self.root() == child).then_some(ParentGuard::Root(w))
            }
            Parent::Node { raw, byte, .. } => {
                // SAFETY: `raw` was read from this tree during the current
                // pinned (or map-borrowed) operation, so the node is protected.
                let p = unsafe { self.node_ref(raw) };
                let w = p.latch.lock()?;
                (p.find_child(byte) == Some(child)).then_some(ParentGuard::Node(p, w, byte))
            }
        }
    }

    /// Publishes `new` in place of the child the parent guard protects.
    fn publish_in_parent(&self, pg: &ParentGuard<'_, S::Atomic>, new: Raw<S>) {
        match pg {
            ParentGuard::Root(w) => self.set_root(w, new),
            ParentGuard::Node(p, w, byte) => p.replace_child(w, *byte, new),
        }
    }

    /// Inserts the leaf owned by `owner`, whose key bytes (derived once, from
    /// the leaf itself, Inv 10) are `key`.
    ///
    /// `count` is the `len` delta of publishing the leaf (0 for a versioned
    /// leaf whose only version is a tombstone). On `Inserted` or `Replaced` the
    /// leaf is published and `owner` is disarmed.
    pub(crate) fn insert(
        &self,
        owner: &Unpublished<'_, S>,
        key: &[u8],
        mode: Mode,
        count: isize,
        guard: &S::Guard,
    ) -> Result<Outcome<S::Leaf>, S::Full> {
        self.insert_hinted(owner, key, mode, count, guard, &mut None)
    }

    /// As [`insert`](Self::insert), also reporting where the leaf landed.
    pub(crate) fn insert_hinted(
        &self,
        owner: &Unpublished<'_, S>,
        key: &[u8],
        mode: Mode,
        count: isize,
        guard: &S::Guard,
        hint: &mut Option<Hint<Raw<S>>>,
    ) -> Result<Outcome<S::Leaf>, S::Full> {
        let mut prep = Prepared::<S>::new();
        let r = self.insert_with(owner, key, mode, count, guard, &mut prep, hint);
        prep.release(&self.storage);
        r
    }

    /// The inserters' fast path: insert under the cached node without
    /// descending, if it is unchanged since our own unlock. `None` means "use
    /// the full insert"; `hint` is updated either way.
    ///
    /// # Safety
    /// The storage never frees nodes while the tree is alive (the arena), so
    /// `hint.node` is still a node of this tree's memory.
    pub(crate) unsafe fn insert_at_hint(
        &self,
        hint: &mut Hint<Raw<S>>,
        owner: &Unpublished<'_, S>,
        key: &[u8],
        count: isize,
    ) -> Option<Outcome<S::Leaf>> {
        let byte = *key.get(hint.depth)?;
        // SAFETY: per the contract, the node's memory is still valid.
        let node = unsafe { self.node_ref(hint.node) };
        // Unchanged since our unlock: its absolute path and prefix are the ones
        // the hint was taken for (Inv 7), so the key belongs here.
        let w = node.latch.try_upgrade(hint.version)?;
        if node.find_child(byte).is_some() || node.is_full() {
            hint.version = w.unlock();
            return None;
        }
        let new_ptr = owner.ptr();
        let bomb = AbortOnUnwind;
        self.len_add(count);
        owner.disarm();
        node.insert_child(&w, byte, self.storage.leaf_raw(new_ptr));
        bomb.defuse();
        hint.version = w.unlock();
        Some(Outcome::Inserted(new_ptr))
    }

    #[allow(clippy::too_many_arguments)]
    fn insert_with(
        &self,
        owner: &Unpublished<'_, S>,
        key: &[u8],
        mode: Mode,
        count: isize,
        guard: &S::Guard,
        prep: &mut Prepared<S>,
        hint: &mut Option<Hint<Raw<S>>>,
    ) -> Result<Outcome<S::Leaf>, S::Full> {
        let new_ptr = owner.ptr();
        let new_leaf = self.storage.leaf_raw(new_ptr);
        let mut backoff = SpinBackoff::new();
        'retry: loop {
            prep.reset();
            let root = self.root();

            // Empty tree: publish the first leaf under `root_latch` (D14).
            if root.is_null() {
                let Some(w) = self.root_latch.lock() else {
                    unreachable!("root latch is never obsolete")
                };
                if !self.root().is_null() {
                    drop(w);
                    continue 'retry;
                }
                let bomb = AbortOnUnwind;
                self.len_add(count);
                owner.disarm();
                self.set_root(&w, new_leaf);
                bomb.defuse();
                drop(w);
                return Ok(Outcome::Inserted(new_ptr));
            }

            // Root is a single leaf.
            if root.is_leaf() {
                // SAFETY: protected leaf read from `root`.
                let existing = unsafe { self.leaf_ref(root) };
                let ekey = existing.key_bytes();
                if ekey == key {
                    let old = self.storage_leaf(root);
                    if mode == Mode::InsertIfAbsent {
                        return Ok(Outcome::Existing(old));
                    }
                    let Some(w) = self.root_latch.lock() else {
                        unreachable!("root latch is never obsolete")
                    };
                    if self.root() != root {
                        drop(w);
                        continue 'retry;
                    }
                    let bomb = AbortOnUnwind;
                    owner.disarm();
                    self.set_root(&w, new_leaf);
                    existing.mark_removed();
                    bomb.defuse();
                    drop(w);
                    // SAFETY: unlinked under `root_latch` and marked; this is
                    // the only thread that unlinked it.
                    unsafe { self.storage.retire_leaf(old, guard) };
                    return Ok(Outcome::Replaced(old));
                }
                let common = common_prefix(ekey, key);
                let (chain, _) =
                    self.build_chain(prep, &key[..common], (ekey, root), (key, new_leaf), common)?;
                let Some(w) = self.root_latch.lock() else {
                    unreachable!("root latch is never obsolete")
                };
                if self.root() != root {
                    drop(w);
                    backoff.spin();
                    continue 'retry;
                }
                let bomb = AbortOnUnwind;
                self.len_add(count);
                owner.disarm();
                self.set_root(&w, chain);
                bomb.defuse();
                drop(w);
                prep.commit();
                return Ok(Outcome::Inserted(new_ptr));
            }

            // Root is an inner node: optimistic descent with coupling.
            let mut parent = Parent::Root;
            let mut node_raw = root;
            let mut depth = 0usize;
            loop {
                // SAFETY: protected inner node read from the tree.
                let node = unsafe { self.node_ref(node_raw) };
                let Some(v) = node.latch.read_version() else {
                    backoff.spin();
                    continue 'retry;
                };
                crate::hooks::pause(crate::hooks::Point::WriterAfterVersion);
                // R4: couple the child to its parent.
                if !self.still_parent(parent, node_raw) {
                    continue 'retry;
                }
                let prefix = node.load_prefix();
                let rest = key.get(depth..).unwrap_or(&[]);
                let matched = if prefix.is_prefix_of(rest) {
                    prefix.len
                } else {
                    common_prefix(prefix.as_slice(), rest)
                };

                if matched < prefix.len {
                    // Prefix split (§9.6).
                    if !node.latch.validate(v) {
                        continue 'retry;
                    }
                    let split_raw = {
                        let split = prep.node(&self.storage, NodeType::Node4)?;
                        // SAFETY: unpublished node from the pool, exclusively ours.
                        let s = unsafe { &mut *split.as_ptr() };
                        s.init_prefix(&prefix.as_slice()[..matched]);
                        s.push_child_unpublished(prefix.bytes[matched], node_raw);
                        if depth + matched == key.len() {
                            s.init_exact_leaf(new_leaf);
                        } else {
                            s.push_child_unpublished(key[depth + matched], new_leaf);
                        }
                        self.storage.node_raw(split)
                    };
                    crate::hooks::pause(crate::hooks::Point::WriterBeforeUpgrade);
                    let Some(pg) = self.lock_parent(parent, node_raw) else {
                        backoff.spin();
                        continue 'retry;
                    };
                    let Some(nw) = node.latch.try_upgrade(v) else {
                        drop(pg);
                        backoff.spin();
                        continue 'retry;
                    };
                    let bomb = AbortOnUnwind;
                    // Inv 7: this node's path changes, under its own latch.
                    node.store_prefix(&nw, &prefix.as_slice()[matched + 1..]);
                    self.len_add(count);
                    owner.disarm();
                    self.publish_in_parent(&pg, split_raw);
                    bomb.defuse();
                    drop(nw);
                    drop(pg);
                    prep.commit();
                    *hint = Some(Hint {
                        node: split_raw,
                        version: 0,
                        depth: depth + matched,
                    });
                    return Ok(Outcome::Inserted(new_ptr));
                }

                let node_depth = depth + prefix.len;
                if node_depth == key.len() {
                    // The exact-leaf home.
                    let exact = node.exact_leaf();
                    if !node.latch.validate(v) {
                        continue 'retry;
                    }
                    if !exact.is_null() {
                        let old = self.storage_leaf(exact);
                        if mode == Mode::InsertIfAbsent {
                            return Ok(Outcome::Existing(old));
                        }
                        let Some(nw) = node.latch.try_upgrade(v) else {
                            backoff.spin();
                            continue 'retry;
                        };
                        let bomb = AbortOnUnwind;
                        owner.disarm();
                        node.set_exact_leaf(&nw, new_leaf);
                        // SAFETY: protected leaf read from the tree.
                        unsafe { self.leaf_ref(exact) }.mark_removed();
                        bomb.defuse();
                        drop(nw);
                        // SAFETY: unlinked under the node latch and marked.
                        unsafe { self.storage.retire_leaf(old, guard) };
                        return Ok(Outcome::Replaced(old));
                    }
                    let Some(nw) = node.latch.try_upgrade(v) else {
                        backoff.spin();
                        continue 'retry;
                    };
                    let bomb = AbortOnUnwind;
                    self.len_add(count);
                    owner.disarm();
                    node.set_exact_leaf(&nw, new_leaf);
                    bomb.defuse();
                    drop(nw);
                    return Ok(Outcome::Inserted(new_ptr));
                }

                let byte = key[node_depth];
                let child = node.find_child(byte);
                if let Some(c) = child.filter(|c| !c.is_leaf()) {
                    // Descend without validating: the next level's coupling
                    // check validates this node (R3, R4).
                    parent = Parent::Node {
                        raw: node_raw,
                        version: v,
                        byte,
                    };
                    node_raw = c;
                    depth = node_depth + 1;
                    continue;
                }
                let full = node.is_full();
                if !node.latch.validate(v) {
                    continue 'retry;
                }
                match child {
                    None if full => {
                        // Grow (§9.5): build the larger node, then publish it in
                        // the parent and obsolete this one.
                        let grown_ty = node
                            .node_type
                            .grown()
                            .expect("a full node is never a Node256");
                        let grown = prep.node(&self.storage, grown_ty)?;
                        let Some(pg) = self.lock_parent(parent, node_raw) else {
                            backoff.spin();
                            continue 'retry;
                        };
                        let Some(nw) = node.latch.try_upgrade(v) else {
                            drop(pg);
                            backoff.spin();
                            continue 'retry;
                        };
                        // Prepare, still: the copy only writes unpublished memory.
                        // SAFETY: unpublished node from the pool, exclusively ours.
                        let g = unsafe { &mut *grown.as_ptr() };
                        node.copy_into(g);
                        g.push_child_unpublished(byte, new_leaf);
                        let grown_raw = self.storage.node_raw(grown);
                        let bomb = AbortOnUnwind;
                        self.len_add(count);
                        owner.disarm();
                        self.publish_in_parent(&pg, grown_raw);
                        nw.mark_obsolete();
                        bomb.defuse();
                        drop(pg);
                        prep.commit();
                        // A fresh node: version 0 until someone locks it.
                        *hint = Some(Hint {
                            node: grown_raw,
                            version: 0,
                            depth: node_depth,
                        });
                        let old = self.node_ptr(node_raw);
                        // SAFETY: unlinked under the parent latch and obsolete.
                        unsafe { self.storage.retire_node(old, guard) };
                        return Ok(Outcome::Inserted(new_ptr));
                    }
                    None => {
                        // Room in the node: lock only this node. Its absolute
                        // path cannot change without bumping its version (Inv 7).
                        crate::hooks::pause(crate::hooks::Point::WriterBeforeUpgrade);
                        let Some(nw) = node.latch.try_upgrade(v) else {
                            backoff.spin();
                            continue 'retry;
                        };
                        let bomb = AbortOnUnwind;
                        self.len_add(count);
                        owner.disarm();
                        node.insert_child(&nw, byte, new_leaf);
                        bomb.defuse();
                        *hint = Some(Hint {
                            node: node_raw,
                            version: nw.unlock(),
                            depth: node_depth,
                        });
                        return Ok(Outcome::Inserted(new_ptr));
                    }
                    Some(c) if c.is_leaf() => {
                        // SAFETY: protected leaf read from a validated slot.
                        let existing = unsafe { self.leaf_ref(c) };
                        let ekey = existing.key_bytes();
                        if ekey == key {
                            let old = self.storage_leaf(c);
                            if mode == Mode::InsertIfAbsent {
                                return Ok(Outcome::Existing(old));
                            }
                            let Some(nw) = node.latch.try_upgrade(v) else {
                                backoff.spin();
                                continue 'retry;
                            };
                            let bomb = AbortOnUnwind;
                            owner.disarm();
                            node.replace_child(&nw, byte, new_leaf);
                            existing.mark_removed();
                            bomb.defuse();
                            drop(nw);
                            // SAFETY: unlinked under the node latch and marked.
                            unsafe { self.storage.retire_leaf(old, guard) };
                            return Ok(Outcome::Replaced(old));
                        }
                        // Leaf split: both keys continue below `byte`.
                        let from = node_depth + 1;
                        let es = ekey.get(from..).unwrap_or(&[]);
                        let ns = &key[from..];
                        let common = common_prefix(es, ns);
                        let (chain, bottom) =
                            self.build_chain(prep, &ns[..common], (es, c), (ns, new_leaf), common)?;
                        let Some(nw) = node.latch.try_upgrade(v) else {
                            backoff.spin();
                            continue 'retry;
                        };
                        let bomb = AbortOnUnwind;
                        self.len_add(count);
                        owner.disarm();
                        node.replace_child(&nw, byte, chain);
                        bomb.defuse();
                        drop(nw);
                        prep.commit();
                        *hint = Some(Hint {
                            node: bottom,
                            version: 0,
                            depth: from + common,
                        });
                        return Ok(Outcome::Inserted(new_ptr));
                    }
                    Some(_) => unreachable!("inner children are descended above"),
                }
            }
        }
    }

    /// R4 coupling check after reading a child's version: the parent is
    /// unchanged, or (at the root) `root` still points at the child.
    #[inline]
    fn still_parent(&self, parent: Parent<Raw<S>>, child: Raw<S>) -> bool {
        match parent {
            Parent::Root => self.root() == child,
            Parent::Node { raw, version, .. } => {
                // SAFETY: protected node read from the tree in this operation.
                unsafe { self.node_ref(raw) }.latch.validate(version)
            }
        }
    }

    #[inline]
    fn storage_leaf(&self, raw: Raw<S>) -> NonNull<S::Leaf> {
        // SAFETY: `raw` is a protected leaf slot value of this tree.
        unsafe { self.storage.leaf(raw) }
    }

    #[inline]
    fn node_ptr(&self, raw: Raw<S>) -> NodePtr<S> {
        // SAFETY: `raw` is a protected inner-node slot value of this tree.
        unsafe { self.storage.node(raw) }
    }

    /// Builds, bottom-up and without recursion (Inv 13), the unpublished chain
    /// of `Node4`s that holds two leaves diverging after `prefix`.
    ///
    /// `a` and `b` are `(key suffix, leaf)` where each suffix starts at the
    /// chain's first byte; `common` is `prefix.len()`.
    fn build_chain(
        &self,
        prep: &mut Prepared<S>,
        prefix: &[u8],
        a: (&[u8], Raw<S>),
        b: (&[u8], Raw<S>),
        common: usize,
    ) -> Result<(Raw<S>, Raw<S>), S::Full> {
        debug_assert_eq!(prefix.len(), common);
        // Segments of 16 prefix bytes plus one branch byte above the bottom node.
        let mut segments = Vec::new();
        let mut rest = prefix;
        while rest.len() > MAX_PREFIX_LEN {
            segments.push((&rest[..MAX_PREFIX_LEN], rest[MAX_PREFIX_LEN]));
            rest = &rest[MAX_PREFIX_LEN + 1..];
        }
        let bottom = prep.node(&self.storage, NodeType::Node4)?;
        {
            // SAFETY: unpublished node from the pool, exclusively ours.
            let n = unsafe { &mut *bottom.as_ptr() };
            n.init_prefix(rest);
            for (suffix, leaf) in [a, b] {
                match suffix.get(common) {
                    None => n.init_exact_leaf(leaf),
                    Some(&byte) => n.push_child_unpublished(byte, leaf),
                }
            }
        }
        let bottom = self.storage.node_raw(bottom);
        let mut below = bottom;
        for (seg_prefix, byte) in segments.into_iter().rev() {
            let n = prep.node(&self.storage, NodeType::Node4)?;
            // SAFETY: unpublished node from the pool, exclusively ours.
            let r = unsafe { &mut *n.as_ptr() };
            r.init_prefix(seg_prefix);
            r.push_child_unpublished(byte, below);
            below = self.storage.node_raw(n);
        }
        Ok((below, bottom))
    }

    /// Removes the leaf for `key`, if `matches` accepts it. Returns it
    /// unlinked, marked removed and already retired (§9.4).
    ///
    /// `matches` runs before any latch: it compares keys (user code) for
    /// `remove`, or pointer identity for `remove_leaf`.
    pub(crate) fn remove(
        &self,
        key: &[u8],
        matches: impl Fn(NonNull<S::Leaf>) -> bool,
        guard: &S::Guard,
    ) -> Option<NonNull<S::Leaf>> {
        let mut backoff = SpinBackoff::new();
        'retry: loop {
            let root = self.root();
            if root.is_null() {
                return None;
            }
            if root.is_leaf() {
                let leaf = self.storage_leaf(root);
                if !matches(leaf) {
                    return None;
                }
                let Some(w) = self.root_latch.lock() else {
                    unreachable!("root latch is never obsolete")
                };
                if self.root() != root {
                    drop(w);
                    continue 'retry;
                }
                let bomb = AbortOnUnwind;
                self.set_root(&w, Raw::<S>::NULL);
                // SAFETY: protected leaf read from `root`.
                unsafe { leaf.as_ref() }.mark_removed();
                self.len_add(-1);
                bomb.defuse();
                drop(w);
                // SAFETY: unlinked under `root_latch` and marked.
                unsafe { self.storage.retire_leaf(leaf, guard) };
                return Some(leaf);
            }

            let mut parent = Parent::Root;
            let mut node_raw = root;
            let mut depth = 0usize;
            loop {
                // SAFETY: protected inner node read from the tree.
                let node = unsafe { self.node_ref(node_raw) };
                let Some(v) = node.latch.read_version() else {
                    backoff.spin();
                    continue 'retry;
                };
                if !self.still_parent(parent, node_raw) {
                    continue 'retry;
                }
                let prefix = node.load_prefix();
                let rest = key.get(depth..).unwrap_or(&[]);
                if !prefix.is_prefix_of(rest) {
                    if !node.latch.validate(v) {
                        continue 'retry;
                    }
                    return None;
                }
                let node_depth = depth + prefix.len;
                if node_depth == key.len() {
                    let exact = node.exact_leaf();
                    if !node.latch.validate(v) {
                        continue 'retry;
                    }
                    if exact.is_null() {
                        return None;
                    }
                    let leaf = self.storage_leaf(exact);
                    if !matches(leaf) {
                        return None;
                    }
                    let Some(nw) = node.latch.try_upgrade(v) else {
                        backoff.spin();
                        continue 'retry;
                    };
                    let bomb = AbortOnUnwind;
                    node.set_exact_leaf(&nw, Raw::<S>::NULL);
                    // SAFETY: protected leaf read from a validated slot.
                    unsafe { leaf.as_ref() }.mark_removed();
                    self.len_add(-1);
                    bomb.defuse();
                    drop(nw);
                    // SAFETY: unlinked under the node latch and marked.
                    unsafe { self.storage.retire_leaf(leaf, guard) };
                    return Some(leaf);
                }
                let byte = key[node_depth];
                let child = node.find_child(byte);
                if let Some(c) = child.filter(|c| !c.is_leaf()) {
                    // Coupled at the next level (R4).
                    parent = Parent::Node {
                        raw: node_raw,
                        version: v,
                        byte,
                    };
                    node_raw = c;
                    depth = node_depth + 1;
                    continue;
                }
                if !node.latch.validate(v) {
                    continue 'retry;
                }
                // A leaf child (inner children were descended above).
                let leaf = self.storage_leaf(child?);
                if !matches(leaf) {
                    return None;
                }
                let Some(nw) = node.latch.try_upgrade(v) else {
                    backoff.spin();
                    continue 'retry;
                };
                let bomb = AbortOnUnwind;
                node.remove_child(&nw, byte);
                // SAFETY: protected leaf read from a validated slot.
                unsafe { leaf.as_ref() }.mark_removed();
                self.len_add(-1);
                bomb.defuse();
                drop(nw);
                // SAFETY: unlinked under the node latch and marked.
                unsafe { self.storage.retire_leaf(leaf, guard) };
                return Some(leaf);
            }
        }
    }
}