Skip to main content

cranpose_core/snapshot_v2/
mutable.rs

1use std::rc::Rc;
2
3use super::*;
4use crate::{
5    collections::map::HashMap,
6    state::{ObjectId, PREEXISTING_SNAPSHOT_ID, StateRecord},
7};
8
9enum ApplyOperation {
10    PromoteChild {
11        object_id: ObjectId,
12        state: Rc<dyn StateObject>,
13        writer_id: SnapshotId,
14    },
15    PromoteExisting {
16        object_id: ObjectId,
17        state: Rc<dyn StateObject>,
18        source_id: SnapshotId,
19        applied: Rc<StateRecord>,
20    },
21    CommitMerged {
22        object_id: ObjectId,
23        state: Rc<dyn StateObject>,
24        merged: Rc<StateRecord>,
25        applied: Rc<StateRecord>,
26    },
27}
28
29/// A mutable snapshot that allows isolated state changes.
30///
31/// Changes made in a mutable snapshot are isolated from other snapshots
32/// until `apply()` is called, at which point they become visible atomically.
33/// This is a root mutable snapshot (not nested).
34///
35/// # Thread Safety
36/// Contains `Cell<T>` which is not `Send`/`Sync`. This is safe because snapshots
37/// are stored in thread-local storage and never shared across threads. The `Rc`
38/// is used for cheap cloning within a single thread, not for cross-thread sharing.
39pub struct MutableSnapshot {
40    pub(super) state: SnapshotState,
41    base_parent_id: SnapshotId,
42    nested_count: Cell<usize>,
43    applied: Cell<bool>,
44}
45
46impl MutableSnapshot {
47    pub(crate) fn from_parts(
48        id: SnapshotId,
49        invalid: SnapshotIdSet,
50        read_observer: Option<ReadObserver>,
51        write_observer: Option<WriteObserver>,
52        base_parent_id: SnapshotId,
53        runtime_tracking: RuntimeTracking,
54    ) -> Rc<Self> {
55        Rc::new(Self {
56            state: SnapshotState::new(id, invalid, read_observer, write_observer, runtime_tracking),
57            base_parent_id,
58            nested_count: Cell::new(0),
59            applied: Cell::new(false),
60        })
61    }
62
63    /// Create a new root mutable snapshot.
64    pub fn new(
65        id: SnapshotId,
66        invalid: SnapshotIdSet,
67        read_observer: Option<ReadObserver>,
68        write_observer: Option<WriteObserver>,
69        base_parent_id: SnapshotId,
70    ) -> Rc<Self> {
71        Self::from_parts(
72            id,
73            invalid,
74            read_observer,
75            write_observer,
76            base_parent_id,
77            RuntimeTracking::Untracked,
78        )
79    }
80
81    fn validate_not_applied(&self) {
82        assert!(!self.applied.get(), "Snapshot has already been applied");
83    }
84
85    fn validate_not_disposed(&self) {
86        assert!(!self.state.disposed.get(), "Snapshot has been disposed");
87    }
88
89    /// Returns the id of this snapshot. Ids grow with every snapshot taken.
90    pub fn snapshot_id(&self) -> SnapshotId {
91        self.state.id.get()
92    }
93
94    /// Returns the ids of snapshots whose writes this snapshot does not see.
95    pub fn invalid(&self) -> SnapshotIdSet {
96        self.state.invalid.borrow().clone()
97    }
98
99    /// Returns `false`: this snapshot accepts writes.
100    pub fn read_only(&self) -> bool {
101        false
102    }
103
104    pub(crate) fn set_on_dispose<F>(&self, f: F)
105    where
106        F: FnOnce() + 'static,
107    {
108        self.state.set_on_dispose(f);
109    }
110
111    /// Returns this snapshot, which is its own root.
112    pub fn root_mutable(self: &Rc<Self>) -> Rc<Self> {
113        Rc::clone(self)
114    }
115
116    /// Runs `f` with this snapshot as the current snapshot of the thread and returns its result.
117    /// The previous current snapshot is restored when `f` returns.
118    pub fn enter<T>(self: &Rc<Self>, f: impl FnOnce() -> T) -> T {
119        enter_snapshot_scope(AnySnapshot::Mutable(Rc::clone(self)), f)
120    }
121
122    /// Takes a read-only snapshot of this snapshot's view of state. Reads inside the new snapshot
123    /// call both `read_observer` and this snapshot's own read observer. Panics if this snapshot was
124    /// applied or disposed.
125    pub fn take_nested_snapshot(
126        self: &Rc<Self>,
127        read_observer: Option<ReadObserver>,
128    ) -> Rc<ReadonlySnapshot> {
129        self.validate_not_disposed();
130        self.validate_not_applied();
131
132        let merged_observer =
133            merge_read_observers(read_observer, self.state.read_observer.borrow().clone());
134
135        let nested = ReadonlySnapshot::new(
136            self.state.id.get(),
137            self.state.invalid.borrow().clone(),
138            merged_observer,
139        );
140
141        self.nested_count.set(self.nested_count.get() + 1);
142
143        let parent_weak = Rc::downgrade(self);
144        nested.set_on_dispose(move || {
145            if let Some(parent) = parent_weak.upgrade() {
146                let cur = parent.nested_count.get();
147                if cur > 0 {
148                    parent.nested_count.set(cur - 1);
149                }
150            }
151        });
152        nested
153    }
154
155    /// Returns `true` when this snapshot recorded writes that were not applied yet.
156    pub fn has_pending_changes(&self) -> bool {
157        !self.state.modified.borrow().is_empty()
158    }
159
160    /// Returns the ids of nested mutable snapshots taken from this snapshot and not yet disposed.
161    pub fn pending_children(&self) -> Vec<SnapshotId> {
162        self.state.pending_children()
163    }
164
165    /// Returns `true` when a nested mutable snapshot taken from this snapshot is still open.
166    pub fn has_pending_children(&self) -> bool {
167        self.state.has_pending_children()
168    }
169
170    /// Discards the writes that were not applied and releases the snapshot. Does nothing while
171    /// nested snapshots taken from it are still open.
172    pub fn dispose(&self) {
173        if !self.state.disposed.get() && self.nested_count.get() == 0 {
174            self.state.dispose();
175        }
176    }
177
178    /// Calls the read observer, if any, with `state`.
179    pub fn record_read(&self, state: &dyn StateObject) {
180        self.state.record_read(state);
181    }
182
183    /// Records `state` as written in this snapshot. The write observer, if any, is called the first
184    /// time a state object is recorded. Panics if the snapshot was applied or disposed.
185    pub fn record_write(&self, state: Rc<dyn StateObject>) {
186        self.validate_not_applied();
187        self.validate_not_disposed();
188        self.state.record_write(state, self.state.id.get());
189    }
190
191    /// Returns `true` once the snapshot was disposed.
192    pub fn is_disposed(&self) -> bool {
193        self.state.disposed.get()
194    }
195
196    /// Makes the writes of this snapshot visible to the global state. Returns `Failure` if the
197    /// snapshot was already applied or disposed, or if a state object it wrote changed in the
198    /// global state in a way that cannot be merged. After a successful apply with writes, the apply
199    /// observers are called.
200    pub fn apply(&self) -> SnapshotApplyResult {
201        // Values the apply displaces drop once it has landed.
202        let _retiring = crate::state::RetiredValuesScope::enter();
203        if self.state.disposed.get() {
204            return SnapshotApplyResult::Failure;
205        }
206
207        if self.applied.get() {
208            return SnapshotApplyResult::Failure;
209        }
210
211        let modified = self.state.modified.borrow();
212        if modified.is_empty() {
213            self.applied.set(true);
214            self.state.dispose();
215            return SnapshotApplyResult::Success;
216        }
217
218        let this_id = self.state.id.get();
219        let mut modified_objects: Vec<(ObjectId, Rc<dyn StateObject>, SnapshotId)> =
220            Vec::with_capacity(modified.len());
221        for (&obj_id, (obj, writer_id)) in modified.iter() {
222            modified_objects.push((obj_id, Rc::clone(obj), *writer_id));
223        }
224
225        drop(modified);
226
227        let parent_snapshot = GlobalSnapshot::get_or_create();
228        let parent_snapshot_id = parent_snapshot.snapshot_id();
229        let parent_invalid = parent_snapshot.invalid();
230        drop(parent_snapshot);
231
232        let next_invalid = runtime::open_snapshots().clear(parent_snapshot_id);
233        let this_invalid_for_optimistic = self.state.invalid.borrow().clone();
234        let optimistic = optimistic_merges(
235            parent_snapshot_id,
236            self.base_parent_id,
237            &modified_objects,
238            &next_invalid,
239            &this_invalid_for_optimistic,
240        );
241
242        let mut operations: Vec<ApplyOperation> = Vec::with_capacity(modified_objects.len());
243
244        for (obj_id, state, writer_id) in &modified_objects {
245            let records = state.records();
246            let Some(applied) = records.live_at(*writer_id) else {
247                return SnapshotApplyResult::Failure;
248            };
249
250            let Some(current) = records
251                .readable(parent_snapshot_id, &next_invalid)
252                .or_else(|| state.try_readable_record(parent_snapshot_id, &parent_invalid))
253            else {
254                log::error!(
255                    "MutableSnapshot::apply missing parent readable record (object_id={obj_id:?}, parent_snapshot_id={parent_snapshot_id})"
256                );
257                return SnapshotApplyResult::Failure;
258            };
259            let this_invalid = self.state.invalid.borrow();
260            let (previous_opt, found_base) = records.previous(self.base_parent_id, &this_invalid);
261            drop(this_invalid);
262            let Some(previous) = previous_opt else {
263                return SnapshotApplyResult::Failure;
264            };
265
266            if !found_base || previous.snapshot_id() == PREEXISTING_SNAPSHOT_ID {
267                operations.push(ApplyOperation::PromoteChild {
268                    object_id: *obj_id,
269                    state: Rc::clone(state),
270                    writer_id: *writer_id,
271                });
272                continue;
273            }
274
275            if Rc::ptr_eq(&current, &previous) {
276                operations.push(ApplyOperation::PromoteChild {
277                    object_id: *obj_id,
278                    state: Rc::clone(state),
279                    writer_id: *writer_id,
280                });
281                continue;
282            }
283
284            let merged = if let Some(candidate) = optimistic
285                .as_ref()
286                .and_then(|map| map.get(&(Rc::as_ptr(&current) as usize)))
287                .cloned()
288            {
289                candidate
290            } else {
291                match state.merge_records(
292                    Rc::clone(&previous),
293                    Rc::clone(&current),
294                    Rc::clone(&applied),
295                ) {
296                    Some(record) => record,
297                    None => return SnapshotApplyResult::Failure,
298                }
299            };
300
301            if Rc::ptr_eq(&merged, &applied) {
302                operations.push(ApplyOperation::PromoteChild {
303                    object_id: *obj_id,
304                    state: Rc::clone(state),
305                    writer_id: *writer_id,
306                });
307            } else if Rc::ptr_eq(&merged, &current) {
308                operations.push(ApplyOperation::PromoteExisting {
309                    object_id: *obj_id,
310                    state: Rc::clone(state),
311                    source_id: current.snapshot_id(),
312                    applied: Rc::clone(&applied),
313                });
314            } else {
315                operations.push(ApplyOperation::CommitMerged {
316                    object_id: *obj_id,
317                    state: Rc::clone(state),
318                    merged: Rc::clone(&merged),
319                    applied: Rc::clone(&applied),
320                });
321            }
322        }
323
324        let mut applied_info: Vec<(ObjectId, Rc<dyn StateObject>, SnapshotId)> =
325            Vec::with_capacity(operations.len());
326
327        for operation in operations {
328            match operation {
329                ApplyOperation::PromoteChild {
330                    object_id,
331                    state,
332                    writer_id,
333                } => {
334                    if state.promote_record(writer_id).is_err() {
335                        return SnapshotApplyResult::Failure;
336                    }
337                    let new_head_id = state.records().head().snapshot_id();
338                    applied_info.push((object_id, state, new_head_id));
339                }
340                ApplyOperation::PromoteExisting {
341                    object_id,
342                    state,
343                    source_id,
344                    applied,
345                } => {
346                    if state.promote_record(source_id).is_err() {
347                        return SnapshotApplyResult::Failure;
348                    }
349                    applied.tombstone_retiring_value();
350                    let new_head_id = state.records().head().snapshot_id();
351                    applied_info.push((object_id, state, new_head_id));
352                }
353                ApplyOperation::CommitMerged {
354                    object_id,
355                    state,
356                    merged,
357                    applied,
358                } => {
359                    let Ok(new_head_id) = state.commit_merged_record(merged) else {
360                        return SnapshotApplyResult::Failure;
361                    };
362                    applied.tombstone_retiring_value();
363                    applied_info.push((object_id, state, new_head_id));
364                }
365            }
366        }
367
368        for (obj_id, _, head_id) in &applied_info {
369            set_last_write(*obj_id, *head_id);
370        }
371
372        self.applied.set(true);
373        self.state.dispose();
374
375        crate::thread_state::snapshots(|snapshots| {
376            let mut extra_state_objects = snapshots.extra_state_objects.borrow_mut();
377            for (_, state, _) in &applied_info {
378                extra_state_objects.add_trait_object(state);
379            }
380        });
381
382        let observer_states: Vec<Rc<dyn StateObject>> = applied_info
383            .iter()
384            .map(|(_, state, _)| Rc::clone(state))
385            .collect();
386        notify_apply_observers(&observer_states, this_id);
387        SnapshotApplyResult::Success
388    }
389
390    /// Takes a mutable snapshot nested in this one. Its `apply` moves the writes into this
391    /// snapshot. Panics if this snapshot was applied or disposed.
392    pub fn take_nested_mutable_snapshot(
393        self: &Rc<Self>,
394        read_observer: Option<ReadObserver>,
395        write_observer: Option<WriteObserver>,
396    ) -> Rc<NestedMutableSnapshot> {
397        self.validate_not_disposed();
398        self.validate_not_applied();
399
400        allocate_nested_mutable_snapshot(self, Rc::downgrade(self), read_observer, write_observer)
401    }
402
403    pub(crate) fn merge_child_modifications(
404        &self,
405        child_modified: &HashMap<ObjectId, (Rc<dyn StateObject>, SnapshotId)>,
406    ) -> Result<(), ()> {
407        {
408            let parent_mod = self.state.modified.borrow();
409            for key in child_modified.keys() {
410                if parent_mod.contains_key(key) {
411                    return Err(());
412                }
413            }
414        }
415
416        let mut parent_mod = self.state.modified.borrow_mut();
417        for (key, value) in child_modified {
418            parent_mod.entry(*key).or_insert_with(|| value.clone());
419        }
420        Ok(())
421    }
422}
423
424impl NestedMutableHost for MutableSnapshot {
425    fn snapshot_state(&self) -> &SnapshotState {
426        &self.state
427    }
428
429    fn nested_count(&self) -> &Cell<usize> {
430        &self.nested_count
431    }
432}
433
434#[cfg(test)]
435impl MutableSnapshot {
436    pub(crate) fn debug_modified_objects(
437        &self,
438    ) -> Vec<(ObjectId, Rc<dyn StateObject>, SnapshotId)> {
439        let modified = self.state.modified.borrow();
440        modified
441            .iter()
442            .map(|(&obj_id, (state, writer_id))| (obj_id, Rc::clone(state), *writer_id))
443            .collect()
444    }
445
446    pub(crate) fn debug_base_parent_id(&self) -> SnapshotId {
447        self.base_parent_id
448    }
449}
450
451#[cfg(test)]
452#[path = "tests/mutable_tests.rs"]
453mod tests;