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

//! # Optimistic version latch
//!
//! [`HybridLatch`] is a sequence lock used for optimistic lock coupling. The
//! protocol it implements is normative (`docs/SAFETY.md` §5):
//!
//! - **W1**: a writer acquires the latch with an `Acquire` CAS and then issues
//!   `fence(Release)`, so the lock-bit store is ordered before every store in
//!   the critical section (the `crossbeam` `SeqLock::write` pattern).
//! - **W4**: `unlock` stores `v + STEP` with `Release`; `mark_obsolete` stores
//!   `v | OBSOLETE` and is used only on nodes already unlinked (Inv 7).
//! - **R1/R5**: a reader takes `read_version()` (`Acquire`), and validates with
//!   `fence(Acquire)` followed by a `Relaxed` load.
//!
//! Exclusive access is represented by a [`WriteGuard`]. Dropping it releases
//! the latch and bumps the version, so unwinding out of a *prepare* phase is
//! harmless (Inv 6). Commit phases are wrapped in [`AbortOnUnwind`].

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

use crate::sync::atomic::{fence, AtomicU64, AtomicU8, Ordering};

/// Switches for the loom mutant self-checks (§16.3): each model must fail
/// with the fence it depends on removed, which proves the model explores.
/// Loom runs every thread of a model on the calling OS thread, so
/// thread-local switches affect exactly one model at a time.
#[cfg(loom)]
pub(crate) mod mutants {
    use std::cell::Cell;

    std::thread_local! {
        pub(crate) static SKIP_W1_FENCE: Cell<bool> = const { Cell::new(false) };
        pub(crate) static SKIP_R5_FENCE: Cell<bool> = const { Cell::new(false) };
        pub(crate) static SKIP_R4_COUPLING: Cell<bool> = const { Cell::new(false) };
        /// Finds a version-chain position before taking `chain_latch` (§11.4).
        pub(crate) static CHAIN_POSITION_UNLATCHED: Cell<bool> = const { Cell::new(false) };
    }
}

pub(crate) const LOCK_BIT: u64 = 0b01;
pub(crate) const OBSOLETE_BIT: u64 = 0b10;
pub(crate) const VERSION_STEP: u64 = 0b100;

/// An atomic version latch supporting optimistic reads and exclusive writes.
#[repr(transparent)]
pub(crate) struct HybridLatch {
    version: AtomicU64,
}

/// Proof that this thread holds `latch` exclusively.
///
/// Dropping it unlocks and bumps the version.
#[must_use = "dropping a WriteGuard immediately releases the latch"]
pub(crate) struct WriteGuard<'l> {
    latch: &'l HybridLatch,
    /// Version at acquisition: unlocked and not obsolete.
    v: u64,
}

impl HybridLatch {
    crate::sync::const_fn_unless_loom! {
        /// Creates an unlocked, live latch at version 0.
        #[inline]
        pub(crate) fn new() -> Self {
            Self {
                version: AtomicU64::new(0),
            }
        }
    }

    /// R1: `Some(v)` if the latch is unlocked and not obsolete.
    #[inline]
    pub(crate) fn read_version(&self) -> Option<u64> {
        let v = self.version.load(Ordering::Acquire);
        (v & (LOCK_BIT | OBSOLETE_BIT) == 0).then_some(v)
    }

    /// R5: `true` if no writer has entered a critical section since `v` was read.
    #[inline]
    pub(crate) fn validate(&self, v: u64) -> bool {
        #[cfg(loom)]
        if mutants::SKIP_R5_FENCE.with(|m| m.get()) {
            return self.version.load(Ordering::Relaxed) == v;
        }
        fence(Ordering::Acquire);
        self.version.load(Ordering::Relaxed) == v
    }

    /// `true` if the latch has been marked obsolete.
    #[inline]
    pub(crate) fn is_obsolete(&self) -> bool {
        self.version.load(Ordering::Acquire) & OBSOLETE_BIT != 0
    }

    /// Upgrades an optimistic read at version `v` to exclusive access (W1).
    ///
    /// Fails if the latch changed since `v` was read, or if `v` itself is
    /// locked or obsolete (for example a stale cached version).
    #[must_use = "binding the guard is what holds the latch"]
    #[inline]
    pub(crate) fn try_upgrade(&self, v: u64) -> Option<WriteGuard<'_>> {
        if v & (LOCK_BIT | OBSOLETE_BIT) != 0 {
            return None;
        }
        self.version
            .compare_exchange(v, v | LOCK_BIT, Ordering::Acquire, Ordering::Relaxed)
            .ok()?;
        // W1: orders the lock-bit store before every in-section store.
        #[cfg(loom)]
        if mutants::SKIP_W1_FENCE.with(|m| m.get()) {
            return Some(WriteGuard { latch: self, v });
        }
        fence(Ordering::Release);
        Some(WriteGuard { latch: self, v })
    }

    /// Blocking acquire. Used only while holding no other latch (Inv 7), or
    /// for the terminal `chain_latch`. `None` if the latch is obsolete.
    #[must_use = "binding the guard is what holds the latch"]
    pub(crate) fn lock(&self) -> Option<WriteGuard<'_>> {
        let mut backoff = SpinBackoff::new();
        loop {
            let v = self.version.load(Ordering::Relaxed);
            if v & OBSOLETE_BIT != 0 {
                return None;
            }
            if v & LOCK_BIT == 0 {
                if let Some(w) = self.try_upgrade(v) {
                    return Some(w);
                }
            }
            backoff.spin();
        }
    }
}

impl WriteGuard<'_> {
    /// W4: releases the latch and returns the new version, so callers that
    /// cache versions (the arena inserters) never re-load it.
    #[inline]
    pub(crate) fn unlock(self) -> u64 {
        let nv = self.v.wrapping_add(VERSION_STEP);
        self.latch.version.store(nv, Ordering::Release);
        std::mem::forget(self);
        nv
    }

    /// W4 / Inv 7: marks the latch obsolete. Only for nodes already unlinked
    /// from their parent; every later upgrade or validation fails.
    #[inline]
    pub(crate) fn mark_obsolete(self) {
        self.latch
            .version
            .store(self.v | OBSOLETE_BIT, Ordering::Release);
        std::mem::forget(self);
    }

    /// The latch this guard holds (for capability `debug_assert`s).
    #[allow(dead_code)] // used by the arena chain protocol
    #[inline]
    pub(crate) fn latch(&self) -> &HybridLatch {
        self.latch
    }

    /// `true` if this guard holds `latch`.
    #[inline]
    pub(crate) fn holds(&self, latch: &HybridLatch) -> bool {
        std::ptr::eq(self.latch, latch)
    }
}

impl Drop for WriteGuard<'_> {
    #[inline]
    fn drop(&mut self) {
        self.latch
            .version
            .store(self.v.wrapping_add(VERSION_STEP), Ordering::Release);
    }
}

/// A one-byte lock that serialises the writers of one version chain. It is
/// terminal in the lock order (Inv 7).
///
/// Chain readers never validate it: they load `head` and `next` with
/// `Acquire`, paired with the writers' `Release` stores. So, unlike a
/// [`HybridLatch`], it needs no version and cannot become obsolete: plain
/// mutual exclusion (`Acquire` on lock, `Release` on unlock) is enough, in one
/// byte instead of eight.
#[repr(transparent)]
pub(crate) struct ChainLock {
    locked: AtomicU8,
}

/// Proof that this thread holds a [`ChainLock`]. Dropping it unlocks.
#[must_use = "dropping a ChainGuard immediately releases the lock"]
pub(crate) struct ChainGuard<'l> {
    lock: &'l ChainLock,
}

impl ChainLock {
    crate::sync::const_fn_unless_loom! {
        /// Creates an unlocked lock.
        #[inline]
        pub(crate) fn new() -> Self {
            Self {
                locked: AtomicU8::new(0),
            }
        }
    }

    /// Blocking acquire (test and test-and-set, with backoff).
    #[must_use = "binding the guard is what holds the lock"]
    #[inline]
    pub(crate) fn lock(&self) -> ChainGuard<'_> {
        let mut backoff = SpinBackoff::new();
        loop {
            if self
                .locked
                .compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed)
                .is_ok()
            {
                return ChainGuard { lock: self };
            }
            while self.locked.load(Ordering::Relaxed) != 0 {
                backoff.spin();
            }
        }
    }
}

impl ChainGuard<'_> {
    /// `true` if this guard holds `lock`.
    #[inline]
    pub(crate) fn holds(&self, lock: &ChainLock) -> bool {
        std::ptr::eq(self.lock, lock)
    }
}

impl Drop for ChainGuard<'_> {
    #[inline]
    fn drop(&mut self) {
        self.lock.locked.store(0, Ordering::Release);
    }
}

/// Aborts the process if dropped.
///
/// Created at the start of a commit phase and [`defuse`](Self::defuse)d at its
/// end: an unexpected panic inside a commit phase must never publish a torn
/// node by unwinding through a [`WriteGuard`] (Inv 6, §5.3).
pub(crate) struct AbortOnUnwind;

impl AbortOnUnwind {
    /// Ends the commit phase.
    #[inline]
    pub(crate) fn defuse(self) {
        std::mem::forget(self)
    }
}

impl Drop for AbortOnUnwind {
    #[cold]
    fn drop(&mut self) {
        // Printing first gives the user a pointer to the cause.
        eprintln!("artmap: panic inside a commit phase; aborting to avoid publishing a torn node");
        std::process::abort()
    }
}

/// Exponential backoff for spinning writers and retrying readers.
///
/// Uses the `crate::sync` shims, so loom models of a contended `lock()`
/// yield to the scheduler instead of spinning forever (§16.3).
pub(crate) struct SpinBackoff {
    step: u32,
}

impl SpinBackoff {
    #[inline]
    pub(crate) const fn new() -> Self {
        Self { step: 0 }
    }

    #[inline]
    pub(crate) fn spin(&mut self) {
        if cfg!(loom) || self.step > 6 {
            crate::sync::yield_now();
        } else {
            for _ in 0..(1u32 << self.step) {
                crate::sync::spin_loop();
            }
        }
        if self.step < 16 {
            self.step += 1;
        }
    }
}

#[cfg(all(test, not(loom)))]
mod tests {
    use super::*;

    /// `true` if an acquisition failed (and so holds nothing).
    fn fails(r: Option<WriteGuard<'_>>) -> bool {
        r.is_none()
    }

    #[test]
    fn latch_lifecycle() {
        let latch = HybridLatch::new();
        let v0 = latch.read_version().expect("initial version");
        assert!(latch.validate(v0));

        let w = latch.try_upgrade(v0).expect("upgrade");
        assert!(w.holds(&latch));
        assert!(
            latch.read_version().is_none(),
            "locked latch has no read version"
        );
        assert!(!latch.validate(v0), "validation fails while locked");
        let v1 = w.unlock();
        assert_eq!(v1, v0 + VERSION_STEP);
        assert_eq!(latch.read_version(), Some(v1));
        assert!(!latch.validate(v0));
        assert!(fails(latch.try_upgrade(v0)), "stale version cannot upgrade");

        let w = latch.lock().expect("lock");
        w.mark_obsolete();
        assert!(latch.is_obsolete());
        assert!(latch.read_version().is_none());
        assert!(fails(latch.lock()), "obsolete latch cannot be locked");
    }

    #[test]
    fn upgrade_rejects_flagged_versions() {
        let latch = HybridLatch::new();
        assert!(fails(latch.try_upgrade(LOCK_BIT)));
        assert!(fails(latch.try_upgrade(OBSOLETE_BIT)));
        let w = latch.lock().unwrap();
        // A stale version that happens to equal the locked word must fail.
        assert!(fails(latch.try_upgrade(LOCK_BIT)));
        drop(w);
    }

    #[test]
    fn concurrent_mutual_exclusion() {
        use std::cell::UnsafeCell;
        use std::sync::{Arc, Barrier};

        struct Shared {
            latch: HybridLatch,
            counter: UnsafeCell<usize>,
        }
        // SAFETY: `counter` is only accessed while holding `latch`.
        unsafe impl Sync for Shared {}

        let threads = if cfg!(miri) { 3 } else { 16 };
        let per = if cfg!(miri) { 50 } else { 20_000 };
        let s = Arc::new(Shared {
            latch: HybridLatch::new(),
            counter: UnsafeCell::new(0),
        });
        let barrier = Arc::new(Barrier::new(threads));
        let handles: Vec<_> = (0..threads)
            .map(|_| {
                let (s, barrier) = (Arc::clone(&s), Arc::clone(&barrier));
                std::thread::spawn(move || {
                    barrier.wait();
                    for _ in 0..per {
                        let w = s.latch.lock().unwrap();
                        // SAFETY: exclusive while `w` is held.
                        unsafe { *s.counter.get() += 1 };
                        drop(w);
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        // SAFETY: all writers joined.
        assert_eq!(unsafe { *s.counter.get() }, threads * per);
        assert!(s.latch.read_version().is_some());
    }

    #[test]
    fn validation_fails_across_a_concurrent_write() {
        use std::sync::atomic::AtomicBool;
        use std::sync::Arc;

        let latch = Arc::new(HybridLatch::new());
        let running = Arc::new(AtomicBool::new(true));
        let (l, r) = (Arc::clone(&latch), Arc::clone(&running));
        let writer = std::thread::spawn(move || {
            let mut n = 0;
            while r.load(std::sync::atomic::Ordering::Relaxed) && n < 50_000 {
                let w = l.lock().unwrap();
                std::hint::spin_loop();
                drop(w);
                n += 1;
            }
        });
        for _ in 0..if cfg!(miri) { 200 } else { 100_000 } {
            // Under a busy writer, a read may see the latch locked, validate,
            // or fail validation; all three are correct outcomes.
            if let Some(v) = latch.read_version() {
                std::hint::spin_loop();
                std::hint::black_box(latch.validate(v));
            }
        }
        running.store(false, std::sync::atomic::Ordering::Relaxed);
        writer.join().unwrap();
        // With the writer gone, a read is stable and always validates.
        let v = latch.read_version().expect("no writer holds the latch");
        assert!(latch.validate(v));
    }

    #[test]
    fn obsolete_is_permanent() {
        let latch = HybridLatch::new();
        let v = latch.read_version().unwrap();
        latch.lock().unwrap().mark_obsolete();
        assert!(latch.is_obsolete());
        assert!(fails(latch.lock()));
        assert!(fails(latch.try_upgrade(v)));
        assert!(latch.read_version().is_none());
        assert!(!latch.validate(v));
    }

    #[test]
    fn guard_drop_unlocks_on_unwind() {
        let latch = HybridLatch::new();
        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _w = latch.lock().unwrap();
            panic!("prepare phase panic");
        }));
        assert!(r.is_err());
        assert!(
            latch.read_version().is_some(),
            "latch released by unwinding"
        );
    }
}