Skip to main content

continuity_buffer/
snapshot.rs

1//! Cheap, send-able rope snapshots tagged with a revision.
2//!
3//! `RopeSnapshot` is the only buffer-shaped value that crosses thread
4//! boundaries: decoration workers, the persistence thread, and the search
5//! indexer all consume snapshots produced on the editor core thread.
6//!
7//! Every constructed snapshot registers a `Weak<Rope>` with the
8//! process-wide [`RopeSnapshotRegistry`] and deregisters on drop. The
9//! registry surfaces "how many live snapshots exist" and "how many
10//! distinct `Arc<Rope>` heads do they pin" — the two numbers Block 1.2
11//! of the memory optimization plan uses to detect divergent-rope
12//! generations held by long-lived workers.
13//!
14//! **Limitation.** We compare `Arc<Rope>` pointer identity, not the
15//! inner `Arc<Node>` head ropey uses for structural sharing. Two
16//! `RopeSnapshot`s built from independent `Arc::new(rope.clone())`
17//! calls count as two distinct generations even when the underlying
18//! ropey state is byte-identical. The metric therefore tracks
19//! "distinct snapshot rope handles" rather than the structurally-true
20//! "distinct rope generations"; a single distinct handle is still the
21//! healthy steady state we want to gate on.
22
23use std::collections::HashMap;
24use std::sync::atomic::{AtomicU64, Ordering};
25use std::sync::{Arc, Mutex, OnceLock, Weak};
26
27use ropey::Rope;
28
29use crate::Revision;
30
31/// Process-wide registry of live `RopeSnapshot`s. Entries are weak
32/// references; drops deregister explicitly so the map does not bloat
33/// with stale weaks during steady state.
34#[derive(Debug, Default)]
35pub struct RopeSnapshotRegistry {
36    by_id: Mutex<HashMap<u64, Weak<Rope>>>,
37}
38
39impl RopeSnapshotRegistry {
40    /// Borrow the process-wide registry.
41    #[must_use]
42    pub fn instance() -> &'static Self {
43        static INSTANCE: OnceLock<RopeSnapshotRegistry> = OnceLock::new();
44        INSTANCE.get_or_init(RopeSnapshotRegistry::default)
45    }
46
47    /// Number of currently-live `RopeSnapshot`s. Strong refs that have
48    /// already been dropped are excluded.
49    #[must_use]
50    pub fn live_snapshot_count(&self) -> usize {
51        match self.by_id.lock() {
52            Ok(map) => map.values().filter(|weak| weak.strong_count() > 0).count(),
53            Err(_) => 0,
54        }
55    }
56
57    /// Count of distinct `Arc<Rope>` heads across live snapshots. A
58    /// healthy editor with N snapshots all built from one source
59    /// returns 1; an N-distinct-generations leak returns N.
60    #[must_use]
61    pub fn distinct_arc_heads(&self) -> usize {
62        let Ok(map) = self.by_id.lock() else {
63            return 0;
64        };
65        let mut heads: Vec<*const Rope> = Vec::with_capacity(map.len());
66        for weak in map.values() {
67            if let Some(strong) = weak.upgrade() {
68                heads.push(Arc::as_ptr(&strong));
69            }
70        }
71        heads.sort_unstable();
72        heads.dedup();
73        heads.len()
74    }
75
76    fn register(&self, id: u64, rope: &Arc<Rope>) {
77        if let Ok(mut map) = self.by_id.lock() {
78            map.insert(id, Arc::downgrade(rope));
79        }
80    }
81
82    fn deregister(&self, id: u64) {
83        if let Ok(mut map) = self.by_id.lock() {
84            map.remove(&id);
85        }
86    }
87}
88
89fn next_snapshot_id() -> u64 {
90    static COUNTER: AtomicU64 = AtomicU64::new(1);
91    COUNTER.fetch_add(1, Ordering::Relaxed)
92}
93
94/// An immutable, ref-counted view of a buffer's contents at a specific
95/// revision.
96#[derive(Debug)]
97pub struct RopeSnapshot {
98    rope: Arc<Rope>,
99    revision: Revision,
100    /// Registry slot id; freed on drop.
101    registry_id: u64,
102}
103
104impl Clone for RopeSnapshot {
105    fn clone(&self) -> Self {
106        let registry_id = next_snapshot_id();
107        RopeSnapshotRegistry::instance().register(registry_id, &self.rope);
108        Self {
109            rope: Arc::clone(&self.rope),
110            revision: self.revision,
111            registry_id,
112        }
113    }
114}
115
116impl Drop for RopeSnapshot {
117    fn drop(&mut self) {
118        RopeSnapshotRegistry::instance().deregister(self.registry_id);
119    }
120}
121
122impl RopeSnapshot {
123    /// Construct a snapshot. Callers should prefer [`crate::Buffer::snapshot`].
124    #[must_use]
125    pub fn new(rope: Arc<Rope>, revision: Revision) -> Self {
126        let registry_id = next_snapshot_id();
127        RopeSnapshotRegistry::instance().register(registry_id, &rope);
128        Self {
129            rope,
130            revision,
131            registry_id,
132        }
133    }
134
135    /// Borrow the rope.
136    #[must_use]
137    pub fn rope(&self) -> &Rope {
138        &self.rope
139    }
140
141    /// Borrow the underlying `Arc<Rope>`. Lets consumers clone the
142    /// `Arc` to ship the rope across thread boundaries without
143    /// allocating a fresh refcounted wrapper.
144    #[must_use]
145    pub fn rope_arc(&self) -> &Arc<Rope> {
146        &self.rope
147    }
148
149    /// The revision this snapshot was taken at.
150    #[must_use]
151    pub fn revision(&self) -> Revision {
152        self.revision
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    fn count_snapshots_for_rope(registry: &RopeSnapshotRegistry, rope: &Arc<Rope>) -> usize {
161        registry
162            .by_id
163            .lock()
164            .expect("test registry lock should not be poisoned")
165            .values()
166            .filter_map(Weak::upgrade)
167            .filter(|registered| Arc::ptr_eq(registered, rope))
168            .count()
169    }
170
171    #[test]
172    fn snapshot_clone_shares_underlying_rope() {
173        let rope = Arc::new(Rope::from_str("hello"));
174        let s = RopeSnapshot::new(Arc::clone(&rope), Revision(5));
175        let s2 = s.clone();
176        assert_eq!(s.revision(), s2.revision());
177        // Cloning the snapshot must NOT clone the rope — both `&Rope`s point
178        // at the same allocation.
179        assert!(std::ptr::eq(s.rope(), s2.rope()));
180        assert_eq!(s.rope().to_string(), "hello");
181    }
182
183    #[test]
184    fn snapshot_is_send_and_sync() {
185        fn assert_send_sync<T: Send + Sync>() {}
186        assert_send_sync::<RopeSnapshot>();
187    }
188
189    #[test]
190    fn snapshot_registry_tracks_distinct_heads() {
191        // Two snapshots cloned from the same Arc share one head; a
192        // separately-constructed snapshot occupies another head. Inspect
193        // only this test's Arc identities because the registry is process-wide
194        // and other parallel tests legitimately create snapshots.
195        let registry = RopeSnapshotRegistry::instance();
196        let rope_a = Arc::new(Rope::from_str("alpha"));
197        let s1 = RopeSnapshot::new(Arc::clone(&rope_a), Revision(1));
198        let s2 = s1.clone();
199        assert_eq!(count_snapshots_for_rope(registry, &rope_a), 2);
200        let rope_b = Arc::new(Rope::from_str("beta"));
201        let s3 = RopeSnapshot::new(Arc::clone(&rope_b), Revision(2));
202        assert_eq!(count_snapshots_for_rope(registry, &rope_b), 1);
203        drop(s1);
204        drop(s2);
205        drop(s3);
206        assert_eq!(count_snapshots_for_rope(registry, &rope_a), 0);
207        assert_eq!(count_snapshots_for_rope(registry, &rope_b), 0);
208    }
209}