forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

pending_changes.rs942 lines, 37.2 KiBHistoryRawDownload
1use std::{
2 collections::{hash_map::Entry, BTreeMap},
3 ops::Deref,
4};
5
6use crate::{
7 change::Change,
8 version::{ImVersionVector, VersionRange},
9 OpLog, VersionVector,
10};
11use loro_common::{
12 Counter, CounterSpan, HasCounterSpan, HasIdSpan, IdSpan, LoroEncodeError, PeerID, ID,
13};
14use rle::{HasLength, Sliceable};
15use rustc_hash::FxHashMap;
16
17#[derive(Debug, Clone)]
18pub enum PendingChange {
19 // Retains the input's supplied Lamport, which cannot yet be resolved against
20 // the DAG. Resolve it when the change can be applied.
21 Unknown(Change),
22 // TODO: Refactor, remove this?
23 #[allow(unused)]
24 Known(Change),
25}
26
27impl Deref for PendingChange {
28 type Target = Change;
29 fn deref(&self) -> &Self::Target {
30 match self {
31 Self::Unknown(a) => a,
32 Self::Known(a) => a,
33 }
34 }
35}
36
37#[derive(Debug, Default)]
38pub(crate) struct PendingChanges {
39 changes: FxHashMap<PeerID, BTreeMap<Counter, Vec<PendingChange>>>,
40}
41
42impl PendingChanges {
43 /// Copy only the pending portions, excluding applied and duplicate operations.
44 /// Slots are indexed by the missing dependency, not by the pending change's ID.
45 pub(crate) fn export_changes(
46 &self,
47 vv: &VersionVector,
48 ) -> Result<Vec<Change>, LoroEncodeError> {
49 let mut pending: Vec<&Change> = self
50 .changes
51 .values()
52 .flat_map(|tree| tree.values())
53 .flatten()
54 .map(|change| &**change)
55 .collect();
56 pending.sort_by_key(|change| {
57 (
58 change.id.peer,
59 change.id.counter,
60 std::cmp::Reverse(change.ctr_end()),
61 )
62 });
63
64 let mut covered = vv.clone();
65 let mut changes = Vec::new();
66 for change in pending {
67 let start = change
68 .id
69 .counter
70 .max(covered.get(&change.id.peer).copied().unwrap_or(0));
71 if start >= change.ctr_end() {
72 continue;
73 }
74
75 // Unknown means the input's Lamport has not been verified against the
76 // DAG yet. Preserve it; ordinary import resolves it once deps arrive.
77 // JSON input can supply a value that cannot fit in a binary block.
78 if change
79 .lamport
80 .checked_add(change.atom_len() as u32)
81 .is_none()
82 {
83 return Err(LoroEncodeError::InternalError(
84 "pending change's supplied Lamport range cannot be encoded".into(),
85 ));
86 }
87 let offset = (start - change.id.counter) as usize;
88 let mut tail = change.slice(offset, change.atom_len());
89 if offset > 0 {
90 // Change::slice normally keeps only the own-peer predecessor.
91 // Pending input may still need explicit cross-peer dependencies.
92 for dep in change.deps.iter().filter(|dep| dep.peer != change.id.peer) {
93 tail.deps.push(dep);
94 }
95 }
96 covered.set_end(ID::new(tail.id.peer, tail.ctr_end()));
97 changes.push(tail);
98 }
99 Ok(changes)
100 }
101
102 pub(crate) fn has_import_rollback_ops(&self, detached: bool) -> bool {
103 self.changes.values().any(|tree| {
104 tree.values().any(|changes| {
105 changes.iter().any(|change| {
106 change
107 .ops
108 .iter()
109 .any(|op| super::import_op_can_reject(op, detached))
110 })
111 })
112 })
113 }
114
115 pub(crate) fn is_empty(&self) -> bool {
116 self.changes.is_empty()
117 }
118
119 /// Number of changes parked under `[peer][counter]`, or `None` if nothing is.
120 fn slot_len(&self, peer: PeerID, counter: Counter) -> Option<usize> {
121 Some(self.changes.get(&peer)?.get(&counter)?.len())
122 }
123
124 pub(crate) fn version_range(&self) -> VersionRange {
125 let mut range = VersionRange::default();
126 for tree in self.changes.values() {
127 for pending_changes in tree.values() {
128 for pending_change in pending_changes {
129 range.extends_to_include_id_span(pending_change.id_span());
130 }
131 }
132 }
133
134 range
135 }
136}
137
138#[cfg(test)]
139#[allow(dead_code)]
140impl PendingChanges {
141 pub(crate) fn len(&self) -> usize {
142 self.changes
143 .values()
144 .map(|tree| tree.values().map(Vec::len).sum::<usize>())
145 .sum()
146 }
147}
148
149/// What every `PendingChanges` slot this import-rollback scope touched held when the
150/// scope began, recorded on first touch and restored wholesale on rollback.
151///
152/// Snapshot-per-slot rather than a mutation log, for two reasons.
153///
154/// Correctness: one scope can park a change and later unlock it — `import_batch`
155/// opens a single scope across the whole batch, where later blobs routinely unlock
156/// what earlier blobs parked. Undoing individual mutations then depends on getting
157/// their relative order right, while restoring each slot to its pre-scope content is
158/// order-independent by construction.
159///
160/// Size: a slot created inside the scope only needs [`PendingSlot::Absent`], and a
161/// slot merely appended to only needs its original length. Cloning is limited to
162/// content that predates the scope, which is exactly what rollback cannot otherwise
163/// reconstruct — an out-of-order batch parks everything it later unlocks, so it
164/// clones nothing.
165#[derive(Debug, Default)]
166pub(crate) struct PendingChangesRollback {
167 slots: FxHashMap<(PeerID, Counter), PendingSlot>,
168}
169
170#[derive(Debug)]
171enum PendingSlot {
172 /// The slot did not exist when the scope began; rollback drops it.
173 Absent,
174 /// The slot held this many changes when the scope began and has only been
175 /// appended to since; rollback truncates it back.
176 Truncate(usize),
177 /// What the slot held when the scope began, kept because the slot was removed
178 /// wholesale and cannot be recovered from the live map.
179 Restore(Vec<PendingChange>),
180}
181
182impl PendingChangesRollback {
183 /// Record the slot before a change is pushed onto `[id.peer][id.counter]`.
184 /// `pre_len` is the slot's current length, or `None` if it does not exist yet.
185 fn record_added(&mut self, id: ID, pre_len: Option<usize>) {
186 self.slots
187 .entry((id.peer, id.counter))
188 .or_insert(match pre_len {
189 Some(len) => PendingSlot::Truncate(len),
190 None => PendingSlot::Absent,
191 });
192 }
193
194 /// Record the slot while `[peer][counter]` is removed wholesale.
195 fn record_removed(&mut self, peer: PeerID, counter: Counter, removed: &[PendingChange]) {
196 match self.slots.entry((peer, counter)) {
197 Entry::Vacant(e) => {
198 e.insert(PendingSlot::Restore(removed.to_vec()));
199 }
200 Entry::Occupied(mut e) => {
201 // `Absent` stays absent (nothing here predates the scope) and
202 // `Restore` already holds the pre-scope content. Only `Truncate`
203 // has to materialize, and just the prefix it was pointing at:
204 // everything past it was pushed inside the scope, so rollback
205 // drops it either way.
206 if let PendingSlot::Truncate(pre_len) = *e.get() {
207 debug_assert!(pre_len <= removed.len(), "slot shrank inside the scope");
208 e.insert(PendingSlot::Restore(removed[..pre_len].to_vec()));
209 }
210 }
211 }
212 }
213
214 pub(crate) fn rollback(self, pending_changes: &mut PendingChanges) {
215 for ((peer, counter), slot) in self.slots {
216 match slot {
217 PendingSlot::Absent => {
218 if let Some(tree) = pending_changes.changes.get_mut(&peer) {
219 tree.remove(&counter);
220 }
221 }
222 PendingSlot::Truncate(pre_len) => {
223 // The slot was never removed (that would have upgraded it to
224 // `Restore`), so it is still here with `pre_len` or more entries.
225 if let Some(changes) = pending_changes
226 .changes
227 .get_mut(&peer)
228 .and_then(|tree| tree.get_mut(&counter))
229 {
230 changes.truncate(pre_len);
231 }
232 }
233 PendingSlot::Restore(changes) => {
234 debug_assert!(!changes.is_empty(), "empty slots are never stored");
235 pending_changes
236 .changes
237 .entry(peer)
238 .or_default()
239 .insert(counter, changes);
240 }
241 }
242 }
243
244 pending_changes.changes.retain(|_, tree| !tree.is_empty());
245 }
246}
247
248impl OpLog {
249 fn push_pending_change(&mut self, missing_dep: ID, change: PendingChange) {
250 let Self {
251 pending_changes,
252 import_rollback,
253 ..
254 } = self;
255 if let Some(rollback) = import_rollback.as_mut() {
256 let pre_len = pending_changes.slot_len(missing_dep.peer, missing_dep.counter);
257 rollback.pending.record_added(missing_dep, pre_len);
258 }
259
260 pending_changes
261 .changes
262 .entry(missing_dep.peer)
263 .or_default()
264 .entry(missing_dep.counter)
265 .or_default()
266 .push(change);
267 }
268
269 /// Store or apply changes that could not get a lamport during the main import pass.
270 ///
271 /// These changes were deferred because some deps were missing from the DAG when
272 /// first seen. By the time this runs, `try_apply_pending` may already have unlocked
273 /// those deps (e.g. applying peer B unlocked previously pending peer A ops that a
274 /// later B change depended on). Treat that as normal: apply when possible, skip if
275 /// already present, and only park changes that are still waiting on a missing dep.
276 ///
277 /// Returns the version range of changes from `remote_changes` that remain pending.
278 pub(super) fn extend_pending_changes_with_unknown_lamport(
279 &mut self,
280 remote_changes: Vec<Change>,
281 mut would_affect: Option<&mut VersionRange>,
282 ) -> VersionRange {
283 let mut parked = Vec::new();
284 let mut newly_applied_ids = Vec::new();
285
286 for change in remote_changes {
287 let local_change = PendingChange::Unknown(change);
288 match remote_change_apply_state(self.vv(), self.shallow_since_vv(), &local_change) {
289 ChangeState::AwaitingMissingDependency(miss_dep) => {
290 parked.push(local_change.id_span());
291 self.push_pending_change(miss_dep, local_change);
292 }
293 ChangeState::Applied => {}
294 ChangeState::CanApplyDirectly => {
295 newly_applied_ids.push(local_change.id_last());
296 self.apply_change_from_remote(local_change, would_affect.as_deref_mut());
297 }
298 }
299 }
300
301 if !newly_applied_ids.is_empty() {
302 self.try_apply_pending(newly_applied_ids, would_affect);
303 }
304
305 // A parked change can already be partially covered by the oplog VV: a change whose
306 // span straddles the VV head is not `Applied`, and it still gets parked when one of
307 // its cross-peer deps is missing. Only the uncovered tail of such a span is pending.
308 //
309 // Trim each span on its own rather than merging first. `VersionRange` keeps a single
310 // (start, end) per peer, so trimming a merged range would attribute the gap between
311 // two disjoint parked spans to the covered one. That is defensive here — the input
312 // is lamport-ordered, so a parked change is unlikely to be unblocked by the
313 // `try_apply_pending` above — but it keeps the reported range honest regardless.
314 let mut still_pending = VersionRange::default();
315 for span in parked {
316 let vv_end = self.vv().get(&span.peer).copied().unwrap_or(0);
317 if vv_end < span.ctr_end() {
318 let start = span.counter.start.max(vv_end);
319 still_pending.extends_to_include_id_span(IdSpan::new(
320 span.peer,
321 start,
322 span.ctr_end(),
323 ));
324 }
325 }
326
327 still_pending
328 }
329}
330
331impl OpLog {
332 /// Try to apply pending changes.
333 ///
334 /// `new_ids` are the ID of the op that is just applied.
335 pub(crate) fn try_apply_pending(
336 &mut self,
337 mut new_ids: Vec<ID>,
338 mut would_affect: Option<&mut VersionRange>,
339 ) {
340 while let Some(id) = new_ids.pop() {
341 let Some(tree) = self.pending_changes.changes.get_mut(&id.peer) else {
342 continue;
343 };
344
345 let mut to_remove = Vec::new();
346 for (cnt, _) in tree.range_mut(0..=id.counter) {
347 to_remove.push(*cnt);
348 }
349
350 let mut pending_set = Vec::with_capacity(to_remove.len());
351 for cnt in to_remove {
352 let pending_changes = tree.remove(&cnt).unwrap();
353 if let Some(rollback) = self.import_rollback.as_mut() {
354 rollback
355 .pending
356 .record_removed(id.peer, cnt, &pending_changes);
357 }
358 pending_set.push(pending_changes);
359 }
360
361 if tree.is_empty() {
362 self.pending_changes.changes.remove(&id.peer);
363 }
364
365 for pending_changes in pending_set {
366 for pending_change in pending_changes {
367 match remote_change_apply_state(
368 self.dag.vv(),
369 self.dag.shallow_since_vv(),
370 &pending_change,
371 ) {
372 ChangeState::CanApplyDirectly => {
373 new_ids.push(pending_change.id_last());
374 self.apply_change_from_remote(
375 pending_change,
376 would_affect.as_deref_mut(),
377 );
378 }
379 ChangeState::Applied => {}
380 ChangeState::AwaitingMissingDependency(miss_dep) => {
381 self.push_pending_change(miss_dep, pending_change)
382 }
383 }
384 }
385 }
386 }
387 }
388
389 pub(super) fn apply_change_from_remote(
390 &mut self,
391 change: PendingChange,
392 would_affect: Option<&mut VersionRange>,
393 ) {
394 let change = match change {
395 PendingChange::Known(mut c) => {
396 self.dag.calc_unknown_lamport_change(&mut c).unwrap();
397 c
398 }
399 PendingChange::Unknown(mut c) => {
400 self.dag.calc_unknown_lamport_change(&mut c).unwrap();
401 c
402 }
403 };
404
405 let Some(change) = self.trim_the_known_part_of_change(change) else {
406 return;
407 };
408
409 if let Some(w) = would_affect {
410 w.extends_to_include_id_span(change.id_span());
411 }
412 self.insert_new_change(change, false);
413 }
414}
415
416enum ChangeState {
417 Applied,
418 CanApplyDirectly,
419 // The id of first missing dep
420 AwaitingMissingDependency(ID),
421}
422
423fn remote_change_apply_state(
424 vv: &VersionVector,
425 _shallow_vv: &ImVersionVector,
426 change: &Change,
427) -> ChangeState {
428 let peer = change.id.peer;
429 let CounterSpan { start, end } = change.ctr_span();
430 let vv_latest_ctr = vv.get(&peer).copied().unwrap_or(0);
431 if vv_latest_ctr >= end {
432 return ChangeState::Applied;
433 }
434
435 if vv_latest_ctr < start {
436 return ChangeState::AwaitingMissingDependency(change.id.inc(-1));
437 }
438
439 for dep in change.deps.iter() {
440 let dep_vv_latest_ctr = vv.get(&dep.peer).copied().unwrap_or(0);
441 if dep_vv_latest_ctr - 1 < dep.counter {
442 return ChangeState::AwaitingMissingDependency(dep);
443 }
444 }
445
446 ChangeState::CanApplyDirectly
447}
448
449#[cfg(test)]
450mod test {
451 use crate::handler::HandlerTrait;
452 use crate::{cursor::PosType, loro::ExportMode, LoroDoc, ToJson, VersionVector};
453
454 #[test]
455 fn pending_export_deduplicates_overlapping_slots_in_every_import_order() {
456 use loro_common::{HasCounterSpan, IdSpan};
457
458 let source = LoroDoc::new_auto_commit();
459 source.set_peer_id(1).unwrap();
460 source
461 .get_text("text")
462 .insert(0, "ABCDEFG", PosType::Unicode)
463 .unwrap();
464 let _ = source.export(ExportMode::all_updates()).unwrap();
465 assert_eq!(source.oplog().lock().len_changes(), 1);
466 let range = |start, end| {
467 source
468 .export(ExportMode::updates_in_range(vec![IdSpan::new(
469 1, start, end,
470 )]))
471 .unwrap()
472 };
473 let inputs = [range(1, 4), range(2, 5), range(6, 7)];
474 let a = range(0, 1);
475 let f = range(5, 6);
476
477 for order in [
478 [0, 1, 2],
479 [0, 2, 1],
480 [1, 0, 2],
481 [1, 2, 0],
482 [2, 0, 1],
483 [2, 1, 0],
484 ] {
485 let doc = LoroDoc::new_auto_commit();
486 for _ in 0..3 {
487 for index in order {
488 let status = doc.import(&inputs[index]).unwrap();
489 assert!(status.success.is_empty());
490 assert!(status.pending.is_some());
491 }
492 }
493 // Real repeated imports leave several copies under each missing-dep
494 // slot. Export must deduplicate across all of those slot vectors.
495 let pending_len = doc.oplog().lock().pending_changes_len();
496 assert_eq!(pending_len, 9);
497 let vv = doc.oplog_vv();
498 let frontiers = doc.oplog_frontiers();
499 let pending = doc.export_pending_updates().unwrap().unwrap();
500 assert!(doc.export_pending_updates().unwrap().is_some());
501 assert_eq!(doc.oplog().lock().pending_changes_len(), pending_len);
502 assert_eq!(doc.oplog_vv(), vv);
503 assert_eq!(doc.oplog_frontiers(), frontiers);
504 assert!(doc.get_text("text").to_string().is_empty());
505
506 let inspector = LoroDoc::new_auto_commit();
507 let parsed = crate::encoding::parse_header_and_body(&pending, true).unwrap();
508 let decoded = crate::encoding::fast_snapshot::decode_updates(
509 &mut inspector.oplog().lock(),
510 bytes::Bytes::copy_from_slice(parsed.body),
511 )
512 .unwrap();
513 let spans: Vec<_> = decoded
514 .iter()
515 .map(|change| (change.id.counter, change.ctr_end()))
516 .collect();
517 assert_eq!(spans, [(1, 4), (4, 5), (6, 7)], "{order:?}");
518 let counters: Vec<_> = decoded
519 .iter()
520 .flat_map(|change| change.id.counter..change.ctr_end())
521 .collect();
522 assert_eq!(counters, [1, 2, 3, 4, 6], "{order:?}");
523 // Check actual FastUpdates framing, not just a merged range summary:
524 // each disjoint/trimmed change has its own current-format block.
525 let mut body = parsed.body;
526 let mut block_count = 0;
527 while !body.is_empty() {
528 let len = leb128::read::unsigned(&mut body).unwrap() as usize;
529 body = &body[len..];
530 block_count += 1;
531 }
532 assert_eq!(block_count, 3);
533
534 let restored = LoroDoc::new_auto_commit();
535 restored
536 .import(&doc.export(ExportMode::Snapshot).unwrap())
537 .unwrap();
538 let status = restored.import(&pending).unwrap();
539 assert!(status.success.is_empty());
540 assert!(status.pending.is_some());
541 for target in [&doc, &restored] {
542 target.import(&a).unwrap();
543 assert_eq!(target.get_text("text").to_string(), "ABCDE");
544 assert_eq!(target.oplog_vv().get(&1), Some(&5));
545 assert!(target.export_pending_updates().unwrap().is_some());
546 target.import(&f).unwrap();
547 assert_eq!(target.get_text("text").to_string(), "ABCDEFG");
548 assert!(target.export_pending_updates().unwrap().is_none());
549 }
550 }
551 }
552
553 #[test]
554 fn pending_export_does_not_bypass_conflicting_history_rejection() {
555 use loro_common::{IdSpan, LoroError, ID};
556
557 let source = LoroDoc::new_auto_commit();
558 source.set_peer_id(1).unwrap();
559 for key in ["a", "b", "c"] {
560 source.get_map("map").insert(key, true).unwrap();
561 }
562 let prefix = source
563 .export(ExportMode::updates_in_range(vec![IdSpan::new(1, 0, 1)]))
564 .unwrap();
565 let mut json = source
566 .export_json_updates(&VersionVector::default(), &source.oplog_vv(), false)
567 .unwrap();
568 assert_eq!(json.changes.len(), 1);
569 // This rewrites the dependency of an already applied operation. Current
570 // import validation rejects the conflicting prefix instead of parking
571 // the tail as if it were a valid out-of-order change.
572 json.changes[0].deps = vec![ID::new(2, 0)];
573 json.changes[0].lamport = 0;
574 let doc = LoroDoc::new_auto_commit();
575 doc.import(&prefix).unwrap();
576 let before = doc.oplog_vv();
577 let state = doc.get_deep_value();
578 let err = doc.import_json_updates(json).unwrap_err();
579 assert!(matches!(err, LoroError::UsedOpID { id } if id == ID::new(1, 0)));
580 assert_eq!(doc.oplog_vv(), before);
581 assert_eq!(doc.get_deep_value(), state);
582 assert!(doc.export_pending_updates().unwrap().is_none());
583 // The rejected data did not poison the document or leave a sidecar;
584 // valid history with the same operation IDs still imports normally.
585 doc.import(&source.export(ExportMode::all_updates()).unwrap())
586 .unwrap();
587 assert_eq!(doc.get_deep_value(), source.get_deep_value());
588 assert!(doc.export_pending_updates().unwrap().is_none());
589 }
590
591 #[test]
592 fn pending_export_preserves_unresolved_input_lamport() {
593 let source = LoroDoc::new_auto_commit();
594 source.set_peer_id(1).unwrap();
595 source.get_map("map").insert("a", true).unwrap();
596 let a = source.export(ExportMode::all_updates()).unwrap();
597 let before_b = source.oplog_vv();
598 source.get_map("map").insert("b", true).unwrap();
599 let _ = source.export(ExportMode::all_updates()).unwrap();
600 let mut json = source
601 .export_json_updates(&before_b, &source.oplog_vv(), false)
602 .unwrap();
603 json.changes[0].lamport = 0;
604 let doc = LoroDoc::new_auto_commit();
605 assert!(doc.import_json_updates(json).unwrap().pending.is_some());
606 let bytes = doc.export_pending_updates().unwrap().unwrap();
607 let restored = LoroDoc::new_auto_commit();
608 restored
609 .import(&doc.export(ExportMode::Snapshot).unwrap())
610 .unwrap();
611 assert!(restored.import(&bytes).unwrap().pending.is_some());
612 doc.import(&a).unwrap();
613 restored.import(&a).unwrap();
614 assert!(restored.export_pending_updates().unwrap().is_none());
615 assert_eq!(restored.get_deep_value(), source.get_deep_value());
616 assert_eq!(restored.get_deep_value(), doc.get_deep_value());
617 assert_eq!(restored.oplog_vv(), doc.oplog_vv());
618 }
619
620 #[test]
621 fn pending_export_returns_error_for_unrepresentable_input_lamport() {
622 use loro_common::IdSpan;
623
624 let source = LoroDoc::new_auto_commit();
625 source.set_peer_id(1).unwrap();
626 source.get_map("map").insert("a", true).unwrap();
627 let a = source.export(ExportMode::all_updates()).unwrap();
628 let before_b = source.oplog_vv();
629 source.get_map("map").insert("b", true).unwrap();
630 let _ = source.export(ExportMode::all_updates()).unwrap();
631 let mut json = source
632 .export_json_updates(&before_b, &source.oplog_vv(), false)
633 .unwrap();
634 json.changes[0].lamport = u32::MAX;
635 let doc = LoroDoc::new_auto_commit();
636 assert!(doc.import_json_updates(json).unwrap().pending.is_some());
637 let before = doc.oplog_vv();
638 assert!(doc.export_pending_updates().is_err());
639 assert_eq!(doc.oplog_vv(), before);
640 // A failed export leaves the exact pending input in place.
641 assert_eq!(
642 doc.oplog().lock().pending_changes.version_range().get(&1),
643 Some(&(1, 2))
644 );
645 // Do not apply this deliberately unrepresentable input; a fresh valid
646 // import remains usable and does not inherit any exporter changes.
647 let clean = LoroDoc::new_auto_commit();
648 clean.import(&a).unwrap();
649 clean
650 .import(
651 &source
652 .export(ExportMode::updates_in_range(vec![IdSpan::new(1, 1, 2)]))
653 .unwrap(),
654 )
655 .unwrap();
656 assert_eq!(clean.get_deep_value(), source.get_deep_value());
657 }
658
659 #[test]
660 fn import_pending() {
661 let a = LoroDoc::new_auto_commit();
662 a.set_peer_id(1).unwrap();
663 let b = LoroDoc::new_auto_commit();
664 b.set_peer_id(2).unwrap();
665 let text_a = a.get_text("text");
666 text_a.insert(0, "a", PosType::Unicode).unwrap();
667 let update1 = a
668 .export(ExportMode::updates(&VersionVector::default()))
669 .unwrap();
670 let version1 = a.oplog_vv();
671 text_a.insert(0, "b", PosType::Unicode).unwrap();
672 let update2 = a.export(ExportMode::updates(&version1)).unwrap();
673 let version2 = a.oplog_vv();
674 text_a.insert(0, "c", PosType::Unicode).unwrap();
675 let update3 = a.export(ExportMode::updates(&version2)).unwrap();
676 let version3 = a.oplog_vv();
677 text_a.insert(0, "d", PosType::Unicode).unwrap();
678 let update4 = a.export(ExportMode::updates(&version3)).unwrap();
679 // let version4 = a.oplog_vv();
680 text_a.insert(0, "e", PosType::Unicode).unwrap();
681 let update3_5 = a.export(ExportMode::updates(&version2)).unwrap();
682 b.import(&update3_5).unwrap();
683 b.import(&update4).unwrap();
684 b.import(&update2).unwrap();
685 b.import(&update3).unwrap();
686 b.import(&update1).unwrap();
687 assert_eq!(a.get_deep_value(), b.get_deep_value());
688 }
689
690 #[test]
691 fn pending_import_snapshot() {
692 let a = LoroDoc::new_auto_commit();
693 a.set_peer_id(1).unwrap();
694 let b = LoroDoc::new_auto_commit();
695 b.set_peer_id(2).unwrap();
696 let text_a = a.get_text("text");
697 text_a.insert(0, "a", PosType::Unicode).unwrap();
698 let update1 = a.export(ExportMode::Snapshot).unwrap();
699 let version1 = a.oplog_vv();
700 text_a.insert(0, "b", PosType::Unicode).unwrap();
701 let update2 = a.export(ExportMode::updates(&version1)).unwrap();
702 let _version2 = a.oplog_vv();
703 b.import(&update2).unwrap();
704 // snapshot will be converted to updates
705 b.import(&update1).unwrap();
706 assert_eq!(a.get_deep_value(), b.get_deep_value());
707 }
708
709 /// A doc holding only pending changes is not empty: a snapshot import must
710 /// not replace its op log and drop them. Map ops leave the arena untouched,
711 /// which the emptiness check used to rely on.
712 #[test]
713 fn pending_map_change_survives_snapshot_import() {
714 let a = LoroDoc::new_auto_commit();
715 a.set_peer_id(1).unwrap();
716 let map = a.get_map("m");
717 map.insert("x", 1).unwrap();
718 let snapshot = a.export(ExportMode::Snapshot).unwrap();
719 let version1 = a.oplog_vv();
720 map.insert("y", 2).unwrap();
721 let update = a.export(ExportMode::updates(&version1)).unwrap();
722
723 let b = LoroDoc::new_auto_commit();
724 assert!(b.import(&update).unwrap().pending.is_some());
725 let status = b.import(&snapshot).unwrap();
726 assert!(status.pending.is_none());
727 assert_eq!(a.get_deep_value(), b.get_deep_value());
728 assert_eq!(a.oplog_vv(), b.oplog_vv());
729 }
730
731 #[test]
732 fn need_deps_pending_import() {
733 // a: a1 <--- a2
734 // \ /
735 // b: b1
736 let a = LoroDoc::new_auto_commit();
737 a.set_peer_id(1).unwrap();
738 let b = LoroDoc::new_auto_commit();
739 b.set_peer_id(2).unwrap();
740 let c = LoroDoc::new_auto_commit();
741 c.set_peer_id(3).unwrap();
742 let d = LoroDoc::new_auto_commit();
743 d.set_peer_id(4).unwrap();
744 let text_a = a.get_text("text");
745 let text_b = b.get_text("text");
746 text_a.insert(0, "a", PosType::Unicode).unwrap();
747 let version_a1 = a.oplog_vv();
748 let update_a1 = a
749 .export(ExportMode::updates(&VersionVector::default()))
750 .unwrap();
751 b.import(&update_a1).unwrap();
752 text_b.insert(1, "b", PosType::Unicode).unwrap();
753 let update_b1 = b.export(ExportMode::updates(&version_a1)).unwrap();
754 a.import(&update_b1).unwrap();
755 let version_a1b1 = a.oplog_vv();
756 text_a.insert(2, "c", PosType::Unicode).unwrap();
757 let update_a2 = a.export(ExportMode::updates(&version_a1b1)).unwrap();
758 c.import(&update_a2).unwrap();
759 assert_eq!(c.get_deep_value().to_json(), "{\"text\":\"\"}");
760 c.import(&update_a1).unwrap();
761 assert_eq!(c.get_deep_value().to_json(), "{\"text\":\"a\"}");
762 c.import(&update_b1).unwrap();
763 assert_eq!(a.get_deep_value(), c.get_deep_value());
764
765 d.import(&update_a2).unwrap();
766 assert_eq!(d.get_deep_value().to_json(), "{\"text\":\"\"}");
767 d.import(&update_b1).unwrap();
768 assert_eq!(d.get_deep_value().to_json(), "{\"text\":\"\"}");
769 d.import(&update_a1).unwrap();
770 assert_eq!(a.get_deep_value(), d.get_deep_value());
771 }
772
773 #[test]
774 fn should_activate_pending_change_when() {
775 // 0@a <- 0@b
776 // 0@a <- 1@a, where 0@a and 1@a will be merged
777 // In this case, c apply b's change first, then apply all the changes from a.
778 // C is expected to have the same content as a, after a imported b's change
779 let a = LoroDoc::new_auto_commit();
780 a.set_peer_id(1).unwrap();
781 let b = LoroDoc::new_auto_commit();
782 b.set_peer_id(2).unwrap();
783 let c = LoroDoc::new_auto_commit();
784 c.set_peer_id(3).unwrap();
785 let text_a = a.get_text("text");
786 let text_b = b.get_text("text");
787 text_a.insert(0, "1", PosType::Unicode).unwrap();
788 b.import(&a.export(ExportMode::Snapshot).unwrap()).unwrap();
789 text_b.insert(0, "1", PosType::Unicode).unwrap();
790 let b_change = b.export(ExportMode::updates(&a.oplog_vv())).unwrap();
791 text_a.insert(0, "1", PosType::Unicode).unwrap();
792 c.import(&b_change).unwrap();
793 c.import(&a.export(ExportMode::Snapshot).unwrap()).unwrap();
794 a.import(&b_change).unwrap();
795 assert_eq!(c.get_deep_value(), a.get_deep_value());
796 }
797
798 /// Regression: importing a blob can both apply ops that unlock previously pending
799 /// changes *and* contain later ops that depended on those pending changes.
800 ///
801 /// Sequence:
802 /// 1. D has A0.
803 /// 2. Import A1 (deps B0) → A1 parked as pending.
804 /// 3. Import a single blob with B0 (deps A0) + B1 (deps A1):
805 /// - B0 applies; B1 is deferred (A1 not yet in the DAG).
806 /// - `try_apply_pending` then applies A1 (unlocked by B0).
807 /// - B1 must now apply instead of hitting `unreachable!("can apply directly")`.
808 #[test]
809 fn pending_change_becomes_applicable_after_try_apply_pending() {
810 let (u_a0, u_a1_only, u_b0_b1, expected) = concurrent_pending_unlock_fixture();
811
812 let d = LoroDoc::new_auto_commit();
813 d.set_peer_id(3).unwrap();
814 d.import(&u_a0).unwrap();
815 let status_a1 = d.import(&u_a1_only).unwrap();
816 assert!(
817 status_a1.pending.is_some(),
818 "A1 should be pending without B0: {status_a1:?}"
819 );
820 assert!(status_a1.success.is_empty(), "{status_a1:?}");
821
822 // This used to panic with unreachable!("can apply directly").
823 let status_b = d.import(&u_b0_b1).unwrap();
824 assert!(status_b.pending.is_none(), "{status_b:?}");
825 assert_eq!(d.get_deep_value(), expected.get_deep_value());
826 assert_eq!(d.oplog_vv(), expected.oplog_vv());
827 }
828
829 /// Same causal pattern via `import_batch` (path that hit WASM `unreachable`
830 /// with the lody snapshot+updates fixture).
831 #[test]
832 fn import_batch_applies_pending_unlocked_within_blob() {
833 let (u_a0, u_a1_only, u_b0_b1, expected) = concurrent_pending_unlock_fixture();
834
835 let d = LoroDoc::new_auto_commit();
836 d.set_peer_id(3).unwrap();
837 d.import(&u_a0).unwrap();
838 d.import(&u_a1_only).unwrap();
839 d.import_batch(std::slice::from_ref(&u_b0_b1)).unwrap();
840 // `import_batch` force-detaches for the duration of the batch and reattaches
841 // after the loop; a panic inside used to unwind past the reattach and strand
842 // the doc detached, failing every later import and export.
843 assert!(!d.is_detached(), "import_batch must leave the doc attached");
844 assert_eq!(d.get_deep_value(), expected.get_deep_value());
845 assert_eq!(d.oplog_vv(), expected.oplog_vv());
846 }
847
848 /// Multi-blob `import_batch` (like lody drain): a large peer-A blob that
849 /// leaves pending ops, then a peer-B blob that both unlocks them and depends
850 /// on the previously pending range.
851 #[test]
852 fn import_batch_multi_blob_unlocks_and_applies_chained_pending() {
853 let (u_a0, u_a1_only, u_b0_b1, expected) = concurrent_pending_unlock_fixture();
854
855 let d = LoroDoc::new_auto_commit();
856 d.set_peer_id(3).unwrap();
857 d.import(&u_a0).unwrap();
858 // Sorted by change_num inside import_batch; either order must work.
859 d.import_batch(&[u_a1_only, u_b0_b1]).unwrap();
860 assert!(!d.is_detached(), "import_batch must leave the doc attached");
861 assert_eq!(d.get_deep_value(), expected.get_deep_value());
862 assert_eq!(d.oplog_vv(), expected.oplog_vv());
863 }
864
865 fn concurrent_pending_unlock_fixture() -> (Vec<u8>, Vec<u8>, Vec<u8>, LoroDoc) {
866 use loro_common::IdSpan;
867
868 let a = LoroDoc::new_auto_commit();
869 a.set_peer_id(1).unwrap();
870 let text_a = a.get_text("text");
871 text_a.insert(0, "A0", PosType::Unicode).unwrap();
872 let u_a0 = a
873 .export(ExportMode::updates(&VersionVector::default()))
874 .unwrap();
875 let vv_a0 = a.oplog_vv();
876 let a_counter_after_a0 = *vv_a0.get(&1).unwrap();
877
878 let b = LoroDoc::new_auto_commit();
879 b.set_peer_id(2).unwrap();
880 b.import(&u_a0).unwrap();
881 b.get_text("text")
882 .insert(2, "B0", PosType::Unicode)
883 .unwrap();
884 let u_b0 = b.export(ExportMode::updates(&vv_a0)).unwrap();
885
886 a.import(&u_b0).unwrap();
887 text_a.insert(4, "A1", PosType::Unicode).unwrap();
888 let a_counter_after_a1 = *a.oplog_vv().get(&1).unwrap();
889 // Peer-A ops only (A1), not B0 — so this stays pending on a doc that only has A0.
890 let u_a1_only = a
891 .export(ExportMode::updates_in_range(vec![IdSpan::new(
892 1,
893 a_counter_after_a0,
894 a_counter_after_a1,
895 )]))
896 .unwrap();
897
898 b.import(&u_a1_only).unwrap();
899 b.get_text("text")
900 .insert(6, "B1", PosType::Unicode)
901 .unwrap();
902 // Single blob containing B0 and B1. B1 depends on A1.
903 let u_b0_b1 = b.export(ExportMode::updates(&vv_a0)).unwrap();
904
905 (u_a0, u_a1_only, u_b0_b1, b)
906 }
907
908 // Change cannot be merged now
909 // #[test]
910 // fn pending_changes_may_deps_merged_change() {
911 // // a: (a1 <-- a2 <-- a3) <-- a4 a1~a3 is a merged change
912 // // \ /
913 // // b: b1
914 // let a = LoroDoc::new();
915 // a.set_peer_id(1);
916 // let b = LoroDoc::new();
917 // b.set_peer_id(2);
918 // let c = LoroDoc::new();
919 // c.set_peer_id(3);
920 // let text_a = a.get_text("text");
921 // let text_b = b.get_text("text");
922 // a.with_txn(|txn| text_a.insert(txn, 0, "a")).unwrap();
923 // a.with_txn(|txn| text_a.insert(txn, 1, "b")).unwrap();
924 // let version_a12 = a.oplog_vv();
925 // let updates_a12 = a.export(ExportMode::Snapshot);
926 // a.with_txn(|txn| text_a.insert(txn, 2, "c")).unwrap();
927 // let updates_a123 = a.export(ExportMode::Snapshot);
928 // b.import(&updates_a12).unwrap();
929 // b.with_txn(|txn| text_b.insert(txn, 2, "d")).unwrap();
930 // let update_b1 = b.export(ExportMode::updates(&version_a12)).unwrap();
931 // a.import(&update_b1).unwrap();
932 // let version_a123_b1 = a.oplog_vv();
933 // a.with_txn(|txn| text_a.insert(txn, 4, "e")).unwrap();
934 // let update_a4 = a.export(ExportMode::updates(&version_a123_b1)).unwrap();
935 // c.import(&update_b1).unwrap();
936 // assert_eq!(c.get_deep_value().to_json(), "{\"text\":\"\"}");
937 // c.import(&update_a4).unwrap();
938 // assert_eq!(c.get_deep_value().to_json(), "{\"text\":\"\"}");
939 // c.import(&updates_a123).unwrap();
940 // assert_eq!(c.get_deep_value(), a.get_deep_value());
941 // }
942}