Skip to main content

relate_executor/graph/
pin.rs

1//! Snapshot pins: the lock-free pin-slot protocol that keeps GC from
2//! dropping versions a statement still reads (ADR-0023, ADR-0038,
3//! ADR-0111). Split out of `graph/mod.rs` (LABS-677).
4
5use relate_core::Result;
6
7use super::*;
8
9/// 256 in-flight statements; excess pins retry a bounded number of times and
10/// then fail with a typed "snapshot pin" error (ADR-0038, ADR-0111).
11pub(super) const PIN_SLOTS: usize = 256;
12pub(super) const PIN_FREE: u64 = 0;
13pub(super) const PIN_CLAIMING: u64 = u64::MAX;
14/// Bounded retry budget for a full pin table. Each retry scans all 256 slots
15/// and yields once; the budget is deliberately small so a saturated table
16/// fails in microseconds to low milliseconds rather than stalling forever
17/// (ADR-0111). The slot array and lock-free protocol are unchanged (ADR-0038).
18pub(super) const PIN_ACQUIRE_RETRIES: u32 = 1024;
19
20/// Registered `snapshot_ts` until drop (ADR-0023 / ADR-0038).
21pub struct SnapshotPin<'a> {
22    graph: &'a Graph,
23    ts: u64,
24    slot: usize,
25}
26
27impl SnapshotPin<'_> {
28    pub fn ts(&self) -> u64 {
29        self.ts
30    }
31
32    /// Keep the pin after this guard is forgotten (explicit txn, ADR-0028 / ADR-0038).
33    pub fn detach(self) -> usize {
34        let slot = self.slot;
35        std::mem::forget(self);
36        slot
37    }
38}
39
40impl Drop for SnapshotPin<'_> {
41    fn drop(&mut self) {
42        self.graph.unpin_slot(self.slot);
43    }
44}
45
46impl Graph {
47    /// Pin `commit_ts` so GC cannot drop versions this statement still sees.
48    ///
49    /// The slot protocol is lock-free (ADR-0038). When every slot is
50    /// occupied the wait is bounded: the array is retried a fixed number of
51    /// times and then acquisition fails with a typed
52    /// `Error::Execution("snapshot pin: …")` instead of spinning forever
53    /// (ADR-0111).
54    pub fn pin_now(&self) -> Result<SnapshotPin<'_>> {
55        self.pin_now_with_retry(std::thread::yield_now)
56    }
57
58    /// Run the callback once after each unsuccessful full-table scan.
59    pub(super) fn pin_now_with_retry(&self, mut retry: impl FnMut()) -> Result<SnapshotPin<'_>> {
60        let start = self.pin_cursor.fetch_add(1, Ordering::Relaxed) as usize;
61        for _ in 0..PIN_ACQUIRE_RETRIES {
62            for i in 0..PIN_SLOTS {
63                let slot = (start + i) % PIN_SLOTS;
64                if self.pins[slot]
65                    .compare_exchange(PIN_FREE, PIN_CLAIMING, Ordering::AcqRel, Ordering::Acquire)
66                    .is_ok()
67                {
68                    let ts = self.commit_ts();
69                    self.pins[slot].store(ts.saturating_add(1), Ordering::Release);
70                    return Ok(SnapshotPin {
71                        graph: self,
72                        ts,
73                        slot,
74                    });
75                }
76            }
77            retry();
78        }
79        Err(relate_core::Error::execution(format!(
80            "snapshot pin: all {PIN_SLOTS} slots are held"
81        )))
82    }
83
84    pub fn unpin_slot(&self, slot: usize) {
85        self.pins[slot].store(PIN_FREE, Ordering::Release);
86    }
87
88    /// True while any statement or explicit transaction holds a snapshot pin.
89    pub fn snapshot_pinned(&self) -> bool {
90        self.pins
91            .iter()
92            .any(|slot| slot.load(Ordering::Acquire) != PIN_FREE)
93    }
94
95    /// Lowest timestamp that may still be read. Dead iff `xmax != 0 && xmax <= horizon`.
96    pub fn gc_horizon(&self) -> u64 {
97        let commit = self.commit_ts();
98        let mut min_pin: Option<u64> = None;
99        for slot in self.pins.iter() {
100            let v = slot.load(Ordering::Acquire);
101            if v == PIN_CLAIMING {
102                return 0;
103            }
104            if v != PIN_FREE {
105                let ts = v - 1;
106                min_pin = Some(min_pin.map_or(ts, |m| m.min(ts)));
107            }
108        }
109        min_pin.unwrap_or(commit).min(commit)
110    }
111}