cranpose_core/snapshot_v2/
mutable.rs1use 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
29pub 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 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 pub fn snapshot_id(&self) -> SnapshotId {
91 self.state.id.get()
92 }
93
94 pub fn invalid(&self) -> SnapshotIdSet {
96 self.state.invalid.borrow().clone()
97 }
98
99 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 pub fn root_mutable(self: &Rc<Self>) -> Rc<Self> {
113 Rc::clone(self)
114 }
115
116 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 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 pub fn has_pending_changes(&self) -> bool {
157 !self.state.modified.borrow().is_empty()
158 }
159
160 pub fn pending_children(&self) -> Vec<SnapshotId> {
162 self.state.pending_children()
163 }
164
165 pub fn has_pending_children(&self) -> bool {
167 self.state.has_pending_children()
168 }
169
170 pub fn dispose(&self) {
173 if !self.state.disposed.get() && self.nested_count.get() == 0 {
174 self.state.dispose();
175 }
176 }
177
178 pub fn record_read(&self, state: &dyn StateObject) {
180 self.state.record_read(state);
181 }
182
183 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 pub fn is_disposed(&self) -> bool {
193 self.state.disposed.get()
194 }
195
196 pub fn apply(&self) -> SnapshotApplyResult {
201 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(¤t, &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(¤t) as usize)))
287 .cloned()
288 {
289 candidate
290 } else {
291 match state.merge_records(
292 Rc::clone(&previous),
293 Rc::clone(¤t),
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, ¤t) {
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 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;