forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

loro.rs5041 lines, 195.5 KiBHistoryRawDownload
1use crate::encoding::json_schema::{encode_change, export_json_in_id_span};
2pub use crate::encoding::ExportMode;
3use crate::pre_commit::{FirstCommitFromPeerCallback, FirstCommitFromPeerPayload};
4pub use crate::state::analyzer::{ContainerAnalysisInfo, DocAnalysis};
5use crate::sync::{AtomicBool, AtomicUsize};
6pub(crate) use crate::LoroDocInner;
7use crate::{
8 arena::{SharedArena, SharedArenaRollback},
9 change::{Change, Timestamp},
10 configure::{Configure, DefaultRandom, SecureRandomGenerator, StyleConfig},
11 container::{
12 idx::ContainerIdx, list::list_op::InnerListOp, richtext::config::StyleConfigMap,
13 IntoContainerId,
14 },
15 cursor::{AbsolutePosition, CannotFindRelativePosition, Cursor, PosQueryResult},
16 dag::{Dag, DagUtils},
17 diff_calc::{DiffCalculator, DiffMode},
18 encoding::{
19 self, decode_snapshot, export_fast_snapshot, export_fast_updates,
20 export_fast_updates_in_range, export_shallow_snapshot, export_snapshot_at,
21 export_state_only_snapshot,
22 json_schema::{encode_change_to_json, json::JsonSchema},
23 parse_header_and_body, EncodeMode, ImportBlobMetadata, ImportStatus, ParsedHeaderAndBody,
24 },
25 event::{str_to_path, EventTriggerKind, Index, InternalDocDiff},
26 handler::{Handler, MovableListHandler, TextHandler, TreeHandler, ValueOrHandler},
27 id::PeerID,
28 json::JsonChange,
29 op::InnerContent,
30 oplog::{loro_dag::FrontiersNotIncluded, ImportedValues, OpLog},
31 state::DocState,
32 subscription::{LocalUpdateCallback, Observer, Subscriber},
33 undo::DiffBatch,
34 utils::subscription::{SubscriberSetWithQueue, Subscription},
35 version::{Frontiers, ImVersionVector, VersionRange, VersionVectorDiff},
36 ChangeMeta, DocDiff, HandlerTrait, InternalString, ListHandler, LoroDoc, LoroError, MapHandler,
37 VersionVector,
38};
39use crate::{change::ChangeRef, lock::LockKind};
40use crate::{lock::LoroMutexGuard, pre_commit::PreCommitCallback};
41use crate::{
42 lock::{LoroLockGroup, LoroMutex},
43 txn::Transaction,
44};
45use either::Either;
46
47#[cfg(test)]
48thread_local! {
49 pub(crate) static FAIL_APPLY_DIFF_AFTER_HANDLER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
50 pub(crate) static RUN_APPLY_DIFF_HOOK_AFTER_NATIVE_PLAN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
51 pub(crate) static FAIL_APPLY_DIFF_WITH_ARG_ERR: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
52 pub(crate) static AFTER_APPLY_DIFF_HANDLER: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
53}
54
55#[cfg(test)]
56fn after_apply_diff_handler() -> LoroResult<()> {
57 AFTER_APPLY_DIFF_HANDLER.with(|hook| {
58 if let Some(hook) = hook.borrow_mut().take() {
59 hook();
60 }
61 });
62 if FAIL_APPLY_DIFF_AFTER_HANDLER.with(|flag| flag.replace(false)) {
63 if FAIL_APPLY_DIFF_WITH_ARG_ERR.with(|flag| flag.replace(false)) {
64 return Err(LoroError::ArgErr("injected application error".into()));
65 }
66 Err(LoroError::OutOfBound {
67 pos: usize::MAX,
68 len: 0,
69 info: "injected apply failure".into(),
70 })
71 } else {
72 Ok(())
73 }
74}
75use loro_common::{
76 ContainerID, ContainerType, HasCounterSpan, HasIdSpan, HasLamportSpan, IdSpan, LoroEncodeError,
77 LoroResult, LoroValue, ID,
78};
79use rle::HasLength;
80use rustc_hash::{FxHashMap, FxHashSet};
81use std::{
82 borrow::Cow,
83 cmp::Ordering,
84 collections::{hash_map::Entry, BinaryHeap},
85 ops::ControlFlow,
86 sync::{
87 atomic::Ordering::{Acquire, Release},
88 Arc,
89 },
90};
91use tracing::{debug_span, info_span, instrument, warn};
92
93use crate::utils::subscription::DeferredPanic;
94
95impl Default for LoroDoc {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101#[cfg(test)]
102thread_local! {
103 /// Countdown of blobs `LoroDoc::import_batch` may import before panicking, standing
104 /// in for the decode/apply panics that malformed remote data can trigger.
105 static PANIC_AT_BATCH_IMPORT_BLOB: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
106}
107
108#[cfg(test)]
109pub(crate) fn panic_at_batch_import_blob_for_test(blobs_to_import_first: usize) {
110 PANIC_AT_BATCH_IMPORT_BLOB.with(|f| f.set(Some(blobs_to_import_first)));
111}
112
113#[cfg(test)]
114fn take_panic_at_batch_import_blob_for_test() {
115 PANIC_AT_BATCH_IMPORT_BLOB.with(|f| match f.get() {
116 Some(0) => {
117 f.set(None);
118 panic!("batch import failpoint");
119 }
120 Some(n) => f.set(Some(n - 1)),
121 None => {}
122 });
123}
124
125impl std::fmt::Debug for LoroDocInner {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 f.debug_struct("LoroDoc")
128 .field("config", &self.config)
129 .field("auto_commit", &self.auto_commit)
130 .field("detached", &self.detached)
131 .finish()
132 }
133}
134
135#[cfg(test)]
136thread_local! {
137 /// How many imports took the independent scalar-root fast path.
138 static ISOLATED_FAST_PATH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
139}
140
141#[cfg(test)]
142pub(crate) fn isolated_fast_path_hits_for_test() -> usize {
143 ISOLATED_FAST_PATH_HITS.with(|hits| hits.get())
144}
145
146impl LoroDoc {
147 /// Run the provided closure within a commit barrier.
148 ///
149 /// This finalizes any pending auto-commit transaction first (preserving
150 /// options across an empty txn), executes `f`, then renews the transaction
151 /// (carrying preserved options) if auto-commit is enabled. This is the
152 /// common implicit-commit pattern used by internal operations such as
153 /// import/export/checkouts.
154 #[inline]
155 pub fn with_barrier<F, R>(&self, f: F) -> R
156 where
157 F: FnOnce() -> R,
158 {
159 let (options, guard) = self.implicit_commit_then_stop();
160 // `f` may call user code, e.g. subscribers of an import's events. If it
161 // panics, release the txn lock first, so the panic does not poison it.
162 // A panic inside Loro may have poisoned another lock, which makes the
163 // renewal panic too; `DeferredPanic` keeps the first one.
164 let mut panic = DeferredPanic::default();
165 let result = panic.run(f);
166 drop(guard);
167 panic.run(|| self.renew_txn_if_auto_commit(options));
168 panic.resume();
169 result.unwrap()
170 }
171
172 pub fn new() -> Self {
173 let visible_op_count = Arc::new(AtomicUsize::new(0));
174 let oplog = OpLog::new(visible_op_count.clone());
175 let arena = oplog.arena.clone();
176 let config: Configure = oplog.configure.clone();
177 let lock_group = LoroLockGroup::new();
178 let global_txn = Arc::new(lock_group.new_lock(None, LockKind::Txn));
179 let inner = Arc::new_cyclic(|w| {
180 let state = DocState::new_arc(w.clone(), arena.clone(), config.clone(), &lock_group);
181 LoroDocInner {
182 oplog: Arc::new(lock_group.new_lock(oplog, LockKind::OpLog)),
183 state,
184 config,
185 visible_op_count,
186 detached: AtomicBool::new(false),
187 auto_commit: AtomicBool::new(false),
188 observer: Arc::new(Observer::new(arena.clone())),
189 diff_calculator: Arc::new(
190 lock_group.new_lock(DiffCalculator::new(true), LockKind::DiffCalculator),
191 ),
192 txn: global_txn,
193 arena,
194 local_update_subs: SubscriberSetWithQueue::new(),
195 peer_id_change_subs: SubscriberSetWithQueue::new(),
196 pre_commit_subs: SubscriberSetWithQueue::new(),
197 first_commit_from_peer_subs: SubscriberSetWithQueue::new(),
198 }
199 });
200 LoroDoc { inner }
201 }
202
203 pub fn fork(&self) -> Self {
204 if self.is_detached() {
205 return self
206 .fork_at_inner(&self.state_frontiers(), false)
207 .expect("fork_at on detached doc should not fail");
208 }
209
210 let snapshot = self
211 .with_barrier(|| encoding::fast_snapshot::encode_snapshot_inner_for_fork(self))
212 .expect("forking a valid document should encode a snapshot");
213 let doc = Self::new();
214 doc.with_barrier(|| {
215 encoding::fast_snapshot::decode_snapshot_inner(snapshot, &doc, Default::default())
216 })
217 .unwrap();
218 doc.set_config(&self.config);
219 if self.auto_commit.load(std::sync::atomic::Ordering::Relaxed) {
220 doc.start_auto_commit();
221 }
222 doc
223 }
224 /// Enables editing of the document in detached mode.
225 ///
226 /// By default, the document cannot be edited in detached mode (after calling
227 /// `detach` or checking out a version other than the latest). This method
228 /// allows editing in detached mode.
229 ///
230 /// # Important Notes:
231 ///
232 /// - After enabling this mode, the document will use a different PeerID. Each
233 /// time you call checkout, a new PeerID will be used.
234 /// - If you set a custom PeerID while this mode is enabled, ensure that
235 /// concurrent operations with the same PeerID are not possible.
236 /// - On detached mode, importing will not change the state of the document.
237 /// It also doesn't change the version of the [DocState]. The changes will be
238 /// recorded into [OpLog] only. You need to call `checkout` to make it take effect.
239 pub fn set_detached_editing(&self, enable: bool) {
240 self.config.set_detached_editing(enable);
241 if enable && self.is_detached() {
242 self.with_barrier(|| {
243 self.renew_peer_id();
244 });
245 }
246 }
247
248 /// Create a doc with auto commit enabled.
249 #[inline]
250 pub fn new_auto_commit() -> Self {
251 let doc = Self::new();
252 doc.start_auto_commit();
253 doc
254 }
255
256 #[inline(always)]
257 pub fn set_peer_id(&self, peer: PeerID) -> LoroResult<()> {
258 if peer == PeerID::MAX {
259 return Err(LoroError::InvalidPeerID);
260 }
261 let next_id = self.oplog.lock().next_id(peer);
262 if self.auto_commit.load(Acquire) {
263 let doc_state = self.state.lock();
264 doc_state
265 .peer
266 .store(peer, std::sync::atomic::Ordering::Relaxed);
267
268 if doc_state.is_in_txn() {
269 drop(doc_state);
270 // Use implicit-style barrier to avoid swallowing next-commit options
271 self.with_barrier(|| {});
272 }
273 self.peer_id_change_subs.emit(&(), next_id);
274 return Ok(());
275 }
276
277 let doc_state = self.state.lock();
278 if doc_state.is_in_txn() {
279 return Err(LoroError::TransactionError(
280 "Cannot change peer id during transaction"
281 .to_string()
282 .into_boxed_str(),
283 ));
284 }
285
286 doc_state
287 .peer
288 .store(peer, std::sync::atomic::Ordering::Relaxed);
289 drop(doc_state);
290 self.peer_id_change_subs.emit(&(), next_id);
291 Ok(())
292 }
293
294 /// Renews the PeerID for the document.
295 pub(crate) fn renew_peer_id(&self) {
296 let mut peer_id = DefaultRandom.next_u64();
297 while peer_id == PeerID::MAX {
298 peer_id = DefaultRandom.next_u64();
299 }
300 self.set_peer_id(peer_id).unwrap();
301 }
302
303 /// Implicitly commit the cumulative auto-commit transaction.
304 /// This method only has effect when `auto_commit` is true.
305 ///
306 /// Follow-ups: the caller is responsible for renewing the transaction
307 /// as needed (e.g., via `renew_txn_if_auto_commit`). Prefer using
308 /// `with_barrier(...)` for most internal flows to handle this safely.
309 ///
310 /// Empty-commit behavior: if the pending transaction is empty, the returned
311 /// `Some(CommitOptions)` preserves next-commit options such as message and
312 /// timestamp so they can carry into the renewed transaction. Transient
313 /// labels like `origin` do not carry across an empty commit.
314 #[inline]
315 #[must_use]
316 pub fn implicit_commit_then_stop(
317 &self,
318 ) -> (
319 Option<CommitOptions>,
320 LoroMutexGuard<'_, Option<Transaction>>,
321 ) {
322 // Implicit commit: preserve options on empty commit
323 let (a, b) = self.commit_internal(CommitOptions::new().immediate_renew(false), true);
324 (a, b.unwrap())
325 }
326
327 /// Commit the cumulative auto commit transaction.
328 /// It will start the next one immediately
329 ///
330 /// It only returns Some(options_of_the_empty_txn) when the txn is empty
331 #[inline]
332 pub fn commit_then_renew(&self) -> Option<CommitOptions> {
333 // Explicit commit: swallow options on empty commit
334 self.commit_internal(CommitOptions::new().immediate_renew(true), false)
335 .0
336 }
337
338 /// This method is called before the commit.
339 /// It can be used to modify the change before it is committed.
340 ///
341 /// It return Some(txn) if the txn is None
342 fn before_commit(&self) -> Option<LoroMutexGuard<'_, Option<Transaction>>> {
343 let mut txn_guard = self.txn.lock();
344 let Some(txn) = txn_guard.as_mut() else {
345 return Some(txn_guard);
346 };
347
348 if txn.is_peer_first_appearance {
349 txn.is_peer_first_appearance = false;
350 drop(txn_guard);
351 // First commit from a peer
352 self.first_commit_from_peer_subs.emit(
353 &(),
354 FirstCommitFromPeerPayload {
355 peer: self.peer_id(),
356 },
357 );
358 }
359
360 None
361 }
362
363 /// Core implementation for committing the cumulative auto-commit transaction.
364 ///
365 /// - When `preserve_on_empty` is true (implicit commits like export/checkout),
366 /// commit options from an empty transaction are carried over to the next transaction
367 /// (except `origin`, which never carries across an empty commit).
368 /// - When `preserve_on_empty` is false (explicit commits), commit options from an
369 /// empty transaction are swallowed and NOT carried over.
370 ///
371 /// A pre-commit callback that panics does not stop the commit; its panic is
372 /// raised after the txn lock is released, so the lock is not poisoned.
373 #[instrument(skip_all)]
374 fn commit_internal(
375 &self,
376 config: CommitOptions,
377 preserve_on_empty: bool,
378 ) -> (
379 Option<CommitOptions>,
380 Option<LoroMutexGuard<'_, Option<Transaction>>>,
381 ) {
382 let mut panic = DeferredPanic::default();
383 let ans = self.commit_internal_inner(config, preserve_on_empty, &mut panic);
384 if !panic.has_panic() {
385 return ans;
386 }
387 drop(ans);
388 panic.resume();
389 unreachable!("resume raises the deferred panic")
390 }
391
392 fn commit_internal_inner(
393 &self,
394 config: CommitOptions,
395 preserve_on_empty: bool,
396 panic: &mut DeferredPanic,
397 ) -> (
398 Option<CommitOptions>,
399 Option<LoroMutexGuard<'_, Option<Transaction>>>,
400 ) {
401 if !self.auto_commit.load(Acquire) {
402 let txn_guard = self.txn.lock();
403 // if not auto_commit, nothing should happen
404 // because the global txn is not used
405 return (None, Some(txn_guard));
406 }
407
408 loop {
409 if let Some(txn_guard) = self.before_commit() {
410 return (None, Some(txn_guard));
411 }
412
413 let mut txn_guard = self.txn.lock();
414 let txn = txn_guard.take();
415 let Some(mut txn) = txn else {
416 return (None, Some(txn_guard));
417 };
418 let on_commit = txn.take_on_commit();
419 if let Some(origin) = config.origin.clone() {
420 txn.set_origin(origin);
421 }
422
423 if let Some(timestamp) = config.timestamp {
424 txn.set_timestamp(timestamp);
425 }
426
427 if let Some(msg) = config.commit_msg.as_ref() {
428 txn.set_msg(Some(msg.clone()));
429 }
430
431 let id_span = txn.id_span();
432 let mut options = txn.commit_deferring_panic(panic).unwrap();
433 // Empty commit returns Some(options). We may preserve parts of it for implicit commits.
434 if let Some(opts) = options.as_mut() {
435 // `origin` is an event-only label and never carries across an empty commit
436 if config.origin.is_some() {
437 opts.set_origin(None);
438 }
439 // For explicit commits, swallow options from empty commit entirely
440 if !preserve_on_empty {
441 options = None;
442 }
443 }
444 if config.immediate_renew && self.can_edit() {
445 let mut t = self.txn().unwrap();
446 if let Some(options) = options.as_ref() {
447 t.set_options(options.clone());
448 }
449 *txn_guard = Some(t);
450 }
451
452 if let Some(on_commit) = on_commit {
453 drop(txn_guard);
454 on_commit(&self.state, &self.oplog, id_span);
455 txn_guard = self.txn.lock();
456 if !config.immediate_renew && txn_guard.is_some() {
457 // make sure that txn_guard is None when config.immediate_renew is false
458 continue;
459 }
460 }
461
462 return (
463 options,
464 if !config.immediate_renew {
465 Some(txn_guard)
466 } else {
467 None
468 },
469 );
470 }
471 }
472
473 /// Commit the cumulative auto commit transaction (explicit API).
474 ///
475 /// This is used by user-facing explicit commits. If the transaction is empty,
476 /// any provided commit options are swallowed and will NOT carry over.
477 #[instrument(skip_all)]
478 pub fn commit_with(
479 &self,
480 config: CommitOptions,
481 ) -> (
482 Option<CommitOptions>,
483 Option<LoroMutexGuard<'_, Option<Transaction>>>,
484 ) {
485 self.commit_internal(config, false)
486 }
487
488 /// Set the commit message of the next commit
489 pub fn set_next_commit_message(&self, message: &str) {
490 let mut binding = self.txn.lock();
491 let Some(txn) = binding.as_mut() else {
492 return;
493 };
494
495 if message.is_empty() {
496 txn.set_msg(None)
497 } else {
498 txn.set_msg(Some(message.into()))
499 }
500 }
501
502 /// Set the origin of the next commit
503 pub fn set_next_commit_origin(&self, origin: &str) {
504 let mut txn = self.txn.lock();
505 if let Some(txn) = txn.as_mut() {
506 txn.set_origin(origin.into());
507 }
508 }
509
510 /// Set the timestamp of the next commit
511 pub fn set_next_commit_timestamp(&self, timestamp: Timestamp) {
512 let mut txn = self.txn.lock();
513 if let Some(txn) = txn.as_mut() {
514 txn.set_timestamp(timestamp);
515 }
516 }
517
518 /// Set the options of the next commit
519 pub fn set_next_commit_options(&self, options: CommitOptions) {
520 let mut txn = self.txn.lock();
521 if let Some(txn) = txn.as_mut() {
522 txn.set_options(options);
523 }
524 }
525
526 /// Clear the options of the next commit
527 pub fn clear_next_commit_options(&self) {
528 let mut txn = self.txn.lock();
529 if let Some(txn) = txn.as_mut() {
530 txn.set_options(CommitOptions::new());
531 }
532 }
533
534 /// Set whether to record the timestamp of each change. Default is `false`.
535 ///
536 /// If enabled, the Unix timestamp will be recorded for each change automatically.
537 ///
538 /// You can also set each timestamp manually when you commit a change.
539 /// The timestamp manually set will override the automatic one.
540 ///
541 /// NOTE: Timestamps are forced to be in ascending order.
542 /// If you commit a new change with a timestamp that is less than the existing one,
543 /// the largest existing timestamp will be used instead.
544 #[inline]
545 pub fn set_record_timestamp(&self, record: bool) {
546 self.config.set_record_timestamp(record);
547 }
548
549 pub fn decoded_value_cache_limit(&self) -> usize {
550 self.config.decoded_value_cache_limit()
551 }
552
553 pub fn set_decoded_value_cache_limit(&self, limit: usize) {
554 self.state.lock().store.set_decoded_value_cache_limit(limit);
555 }
556
557 /// Set the interval of mergeable changes, in seconds.
558 ///
559 /// If two continuous local changes are within the interval, they will be merged into one change.
560 /// The default value is 1000 seconds.
561 #[inline]
562 pub fn set_change_merge_interval(&self, interval: i64) {
563 self.config.set_merge_interval(interval);
564 }
565
566 pub fn can_edit(&self) -> bool {
567 !self.is_detached() || self.config.detached_editing()
568 }
569
570 pub fn is_detached_editing_enabled(&self) -> bool {
571 self.config.detached_editing()
572 }
573
574 #[inline]
575 pub fn config_text_style(&self, text_style: StyleConfigMap) {
576 self.config.text_style_config.write().map = text_style.map;
577 }
578
579 #[inline]
580 pub fn config_default_text_style(&self, text_style: Option<StyleConfig>) {
581 self.config.text_style_config.write().default_style = text_style;
582 }
583 pub fn from_snapshot(bytes: &[u8]) -> LoroResult<Self> {
584 let doc = Self::new();
585 let ParsedHeaderAndBody { mode, body, .. } = parse_header_and_body(bytes, true)?;
586 if mode.is_snapshot() {
587 doc.with_barrier(|| -> Result<(), LoroError> {
588 decode_snapshot(&doc, mode, body, Default::default())?;
589 Ok(())
590 })?;
591 Ok(doc)
592 } else {
593 Err(LoroError::DecodeError(
594 "Invalid encode mode".to_string().into(),
595 ))
596 }
597 }
598
599 /// Is the document empty? (no ops)
600 #[inline(always)]
601 pub fn can_reset_with_snapshot(&self) -> bool {
602 let oplog = self.oplog.lock();
603 if oplog.batch_importing {
604 return false;
605 }
606
607 if self.is_detached() {
608 return false;
609 }
610
611 oplog.is_empty() && self.state.lock().can_import_snapshot()
612 }
613
614 /// Whether [OpLog] and [DocState] are detached.
615 ///
616 /// If so, the document is in readonly mode by default and importing will not change the state of the document.
617 /// It also doesn't change the version of the [DocState]. The changes will be recorded into [OpLog] only.
618 /// You need to call `checkout` to make it take effect.
619 #[inline(always)]
620 pub fn is_detached(&self) -> bool {
621 self.detached.load(Acquire)
622 }
623
624 pub(crate) fn set_detached(&self, detached: bool) {
625 self.detached.store(detached, Release);
626 }
627
628 #[inline(always)]
629 pub fn peer_id(&self) -> PeerID {
630 self.state
631 .lock()
632 .peer
633 .load(std::sync::atomic::Ordering::Relaxed)
634 }
635
636 #[inline(always)]
637 pub fn detach(&self) {
638 self.with_barrier(|| self.set_detached(true));
639 }
640
641 #[inline(always)]
642 pub fn attach(&self) {
643 self.checkout_to_latest()
644 }
645
646 /// Get the timestamp of the current state.
647 /// It's the last edit time of the [DocState].
648 pub fn state_timestamp(&self) -> Timestamp {
649 // Acquire locks in correct order: read frontiers first, then query OpLog.
650 let f = { self.state.lock().frontiers.clone() };
651 self.oplog.lock().get_timestamp_of_version(&f)
652 }
653
654 #[inline(always)]
655 pub fn app_state(&self) -> &Arc<LoroMutex<DocState>> {
656 &self.state
657 }
658
659 #[inline]
660 pub fn get_state_deep_value(&self) -> LoroValue {
661 self.state.lock().get_deep_value()
662 }
663
664 #[inline(always)]
665 pub fn oplog(&self) -> &Arc<LoroMutex<OpLog>> {
666 &self.oplog
667 }
668
669 #[inline(always)]
670 pub fn import(&self, bytes: &[u8]) -> Result<ImportStatus, LoroError> {
671 let s = debug_span!("import", peer = self.peer_id());
672 let _e = s.enter();
673 self.import_with(bytes, Default::default())
674 }
675
676 #[inline]
677 pub fn import_with(
678 &self,
679 bytes: &[u8],
680 origin: InternalString,
681 ) -> Result<ImportStatus, LoroError> {
682 self.import_with_history_mode(bytes, origin, false)
683 }
684
685 /// Import binary bytes. `json_lossy` accepts only the equivalences a JSON hop
686 /// can introduce; the default binary path passes `false`.
687 pub fn import_with_history_mode(
688 &self,
689 bytes: &[u8],
690 origin: InternalString,
691 json_lossy: bool,
692 ) -> Result<ImportStatus, LoroError> {
693 let values = if json_lossy {
694 ImportedValues::JsonLossy
695 } else {
696 ImportedValues::Exact
697 };
698 self.with_barrier(|| self._import_with(bytes, origin, values))
699 }
700
701 #[tracing::instrument(skip_all)]
702 fn _import_with(
703 &self,
704 bytes: &[u8],
705 origin: InternalString,
706 values: ImportedValues,
707 ) -> Result<ImportStatus, LoroError> {
708 let result = self.import_without_emitting(bytes, origin, values);
709 self.emit_events();
710 result
711 }
712
713 fn import_without_emitting(
714 &self,
715 bytes: &[u8],
716 origin: InternalString,
717 values: ImportedValues,
718 ) -> Result<ImportStatus, LoroError> {
719 ensure_cov::notify_cov("loro_internal::import");
720 let parsed = parse_header_and_body(bytes, true)?;
721 loro_common::info!("Importing with mode={:?}", &parsed.mode);
722 match parsed.mode {
723 EncodeMode::OutdatedRle => {
724 if self.state.lock().is_in_txn() {
725 return Err(LoroError::ImportWhenInTxn);
726 }
727
728 let s = tracing::span!(
729 tracing::Level::INFO,
730 "Import updates ",
731 peer = self.peer_id()
732 );
733 let _e = s.enter();
734 self.update_oplog_and_apply_delta_to_state_if_needed(
735 |oplog| oplog.decode(parsed, values),
736 origin,
737 )
738 }
739 EncodeMode::OutdatedSnapshot => {
740 if self.can_reset_with_snapshot() {
741 loro_common::info!("Init by snapshot {}", self.peer_id());
742 decode_snapshot(self, parsed.mode, parsed.body, origin)
743 } else {
744 self.update_oplog_and_apply_delta_to_state_if_needed(
745 |oplog| oplog.decode(parsed, values),
746 origin,
747 )
748 }
749 }
750 EncodeMode::FastSnapshot => {
751 if self.can_reset_with_snapshot() {
752 ensure_cov::notify_cov("loro_internal::import::snapshot");
753 loro_common::info!("Init by fast snapshot {}", self.peer_id());
754 decode_snapshot(self, parsed.mode, parsed.body, origin)
755 } else {
756 self.import_changes_and_apply_delta_to_state_if_needed(
757 |oplog| encoding::decode_oplog_changes(oplog, parsed, values),
758 values,
759 origin,
760 )
761
762 // let new_doc = LoroDoc::new();
763 // new_doc.import(bytes)?;
764 // let updates = new_doc.export(ExportMode::updates(&self.oplog_vv())).unwrap();
765 // return self.import_with(updates.as_slice(), origin);
766 }
767 }
768 EncodeMode::FastUpdates => self.import_changes_and_apply_delta_to_state_if_needed(
769 |oplog| encoding::decode_oplog_changes(oplog, parsed, values),
770 values,
771 origin,
772 ),
773 EncodeMode::Auto => {
774 unreachable!()
775 }
776 }
777 }
778
779 #[tracing::instrument(skip_all)]
780 pub(crate) fn update_oplog_and_apply_delta_to_state_if_needed(
781 &self,
782 f: impl FnOnce(&mut OpLog) -> Result<ImportStatus, LoroError>,
783 origin: InternalString,
784 ) -> Result<ImportStatus, LoroError> {
785 let mut oplog = self.oplog.lock();
786 // `import_batch` opens a rollback scope that spans the whole batch. Rollback
787 // scopes cannot nest (the inner `begin` would clobber the outer journal), so
788 // when one is already open we let the owner decide what to keep: the batch
789 // scope rolls the whole batch back if its final reattach fails, and commits
790 // everything otherwise.
791 let owns_rollback = !oplog.has_import_rollback();
792 if owns_rollback {
793 oplog.begin_import_rollback();
794 }
795 if !self.is_detached() {
796 let old_vv = oplog.vv().clone();
797 let old_frontiers = oplog.frontiers().clone();
798 let result = f(&mut oplog);
799 if &old_vv != oplog.vv() {
800 let mut diff = DiffCalculator::new(false);
801 let computed = diff.try_calc_diff_internal(
802 &oplog,
803 &old_vv,
804 &old_frontiers,
805 oplog.vv(),
806 oplog.dag.get_frontiers(),
807 None,
808 );
809 let (diff, diff_mode) = match computed {
810 Ok(diff) => diff,
811 Err(err) => {
812 oplog.rollback_owned_import(owns_rollback, &mut self.state.lock());
813 return Err(err);
814 }
815 };
816 let mut state = self.state.lock();
817 if let Err(e) = state.apply_diff(
818 InternalDocDiff {
819 origin,
820 diff: (diff).into(),
821 by: EventTriggerKind::Import,
822 new_version: Cow::Owned(oplog.frontiers().clone()),
823 },
824 diff_mode,
825 ) {
826 oplog.rollback_owned_import(owns_rollback, &mut state);
827 return Err(e);
828 }
829 }
830 match result {
831 Ok(result) => {
832 oplog.commit_owned_import_rollback(owns_rollback);
833 Ok(result)
834 }
835 Err(e) => {
836 // Some import errors are reported after a valid prefix has
837 // been inserted into the oplog. Keep that prefix if it was
838 // also applied to state; rollback is for failed state apply
839 // or decode errors that made no visible oplog progress.
840 let keep_prefix = &old_vv != oplog.vv();
841 if keep_prefix {
842 oplog.commit_owned_import_rollback(owns_rollback);
843 } else {
844 oplog.rollback_owned_import(owns_rollback, &mut self.state.lock());
845 }
846 Err(e)
847 }
848 }
849 } else {
850 match f(&mut oplog) {
851 Ok(result) => {
852 oplog.commit_owned_import_rollback(owns_rollback);
853 Ok(result)
854 }
855 Err(e) => {
856 oplog.rollback_owned_import(owns_rollback, &mut self.state.lock());
857 Err(e)
858 }
859 }
860 }
861 }
862
863 #[tracing::instrument(skip_all)]
864 pub(crate) fn import_changes_and_apply_delta_to_state_if_needed(
865 &self,
866 decode_changes: impl FnOnce(&mut OpLog) -> Result<Vec<Change>, LoroError>,
867 values: ImportedValues,
868 origin: InternalString,
869 ) -> Result<ImportStatus, LoroError> {
870 let mut oplog = self.oplog.lock();
871 oplog.check_history_parsable()?;
872 let arena_checkpoint = oplog.arena.checkpoint_for_rollback();
873 let changes = match decode_changes(&mut oplog)
874 .and_then(|changes| oplog.check_and_trim_known_part_of_changes(changes, values))
875 {
876 Ok(changes) => changes,
877 Err(e) => {
878 oplog.rollback_arena(arena_checkpoint, &mut self.state.lock());
879 return Err(e);
880 }
881 };
882
883 // Read once: attach/detach can change the flag without the oplog lock.
884 // The apply branch must use the same mode as preflight's rollback decision.
885 let detached = self.is_detached();
886 let preflight = match oplog.preflight_import_changes(&changes, detached) {
887 Ok(preflight) => preflight,
888 Err(err) => {
889 oplog.rollback_arena(arena_checkpoint, &mut self.state.lock());
890 return Err(err);
891 }
892 };
893 if preflight.has_deps_before_shallow_root && (detached || !preflight.applies_to_dag) {
894 oplog.rollback_arena(arena_checkpoint, &mut self.state.lock());
895 return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion);
896 }
897
898 if detached {
899 // An enclosing `import_batch` scope validates the whole batch before it
900 // reattaches (`BatchImportGuard::finish`).
901 let owns_rollback =
902 preflight.needs_state_apply_rollback && !oplog.has_import_rollback();
903 if owns_rollback {
904 oplog.begin_import_rollback_with_arena(arena_checkpoint);
905 }
906 let result = match encoding::apply_decoded_changes_to_oplog(&mut oplog, changes) {
907 Ok(result) => result,
908 Err(err) => {
909 if owns_rollback {
910 oplog.rollback_import(&mut self.state.lock());
911 }
912 return Err(err);
913 }
914 };
915 if owns_rollback {
916 if let Err(e) = oplog.validate_movable_list_elem_refs_in_import_scope() {
917 oplog.rollback_import(&mut self.state.lock());
918 return Err(e);
919 }
920 oplog.commit_import_rollback();
921 }
922 if result.has_deps_before_shallow_root {
923 return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion);
924 }
925
926 return Ok(result.status);
927 }
928
929 if !preflight.applies_to_dag {
930 let pending_root_containers =
931 match pending_root_containers_to_materialize(&oplog, &changes) {
932 Ok(ids) => ids,
933 Err(err) => {
934 oplog.rollback_arena(arena_checkpoint, &mut self.state.lock());
935 return Err(err);
936 }
937 };
938 let result = match encoding::apply_decoded_changes_to_oplog(&mut oplog, changes) {
939 Ok(result) => result,
940 Err(err) => {
941 if !oplog.has_import_rollback() {
942 oplog.rollback_arena(arena_checkpoint, &mut self.state.lock());
943 }
944 return Err(err);
945 }
946 };
947 if result.has_deps_before_shallow_root {
948 oplog.rollback_arena(arena_checkpoint, &mut self.state.lock());
949 return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion);
950 }
951
952 if !pending_root_containers.is_empty() {
953 let mut state = self.state.lock();
954 for id in pending_root_containers {
955 state.ensure_container(&id);
956 }
957 }
958
959 return Ok(result.status);
960 }
961
962 let old_vv = Arc::new(oplog.vv().clone());
963 let old_frontiers = oplog.frontiers().clone();
964 // Checked before the changes are applied, while the store still holds only old history.
965 let isolated_batch = isolated_scalar_root_batch(&oplog, &changes).filter(|(_, names)| {
966 let mut state = self.state.lock();
967 names.iter().all(|name| {
968 let id = ContainerID::new_root(name, ContainerType::Map);
969 !state.store.contains_id(&id)
970 })
971 });
972 let rollback_enabled =
973 preflight.needs_state_apply_rollback || oplog.change_store().may_have_unparsed_bodies();
974 if rollback_enabled {
975 oplog.begin_import_rollback_with_version(arena_checkpoint, old_vv.clone());
976 }
977
978 let result = match encoding::apply_decoded_changes_to_oplog(&mut oplog, changes) {
979 Ok(result) => result,
980 Err(err) => {
981 oplog.rollback_owned_import(rollback_enabled, &mut self.state.lock());
982 return Err(err);
983 }
984 };
985 if old_vv.as_ref() != oplog.vv() {
986 // The preflight enables rollback whenever the imported or unlocked
987 // pending changes hold movable-list ops, so other imports skip the scan.
988 if rollback_enabled {
989 if let Err(e) = oplog.validate_movable_list_elem_refs_in_import_scope() {
990 oplog.rollback_import(&mut self.state.lock());
991 return Err(e);
992 }
993 }
994 let mut calc = DiffCalculator::new(false);
995 // Applying may have unlocked pending changes; the isolated fast path is only valid
996 // when exactly the candidate batch was appended on top of the old version.
997 let isolated_batch = isolated_batch.filter(|(component_vv, _)| {
998 component_vv
999 .iter()
1000 .all(|(peer, end)| oplog.vv().get(peer) == Some(end))
1001 && oplog.vv().iter().all(|(peer, end)| {
1002 let old_end = old_vv.get(peer).copied().unwrap_or(0);
1003 let component_end = component_vv.get(peer).copied().unwrap_or(0);
1004 *end == old_end.max(component_end)
1005 })
1006 });
1007 let computed = (|| -> LoroResult<_> {
1008 let (diff, diff_mode) = if let Some((component_vv, _)) = isolated_batch {
1009 #[cfg(test)]
1010 ISOLATED_FAST_PATH_HITS.with(|hits| hits.set(hits.get() + 1));
1011 let component_frontiers = oplog.dag.try_vv_to_frontiers(&component_vv)?;
1012 let (diff, _) = calc.try_calc_diff_internal(
1013 &oplog,
1014 &VersionVector::default(),
1015 &Frontiers::default(),
1016 &component_vv,
1017 &component_frontiers,
1018 None,
1019 )?;
1020 (diff, DiffMode::Import)
1021 } else {
1022 calc.try_calc_diff_internal(
1023 &oplog,
1024 &old_vv,
1025 &old_frontiers,
1026 oplog.vv(),
1027 oplog.dag.get_frontiers(),
1028 None,
1029 )?
1030 };
1031 oplog.check_history_parsable()?;
1032 Ok((diff, diff_mode))
1033 })();
1034 let (diff, diff_mode) = match computed {
1035 Ok(diff) => diff,
1036 Err(err) => {
1037 oplog.rollback_owned_import(rollback_enabled, &mut self.state.lock());
1038 return Err(err);
1039 }
1040 };
1041 let mut state = self.state.lock();
1042 let diff = match recalc_in_checkout_mode_if_needed(
1043 &mut state,
1044 &oplog,
1045 &old_vv,
1046 &old_frontiers,
1047 diff,
1048 ) {
1049 Ok(diff) => diff,
1050 Err(err) => {
1051 oplog.rollback_owned_import(rollback_enabled, &mut state);
1052 return Err(err);
1053 }
1054 };
1055 if let Err(e) = state.apply_diff(
1056 InternalDocDiff {
1057 origin,
1058 diff: (diff).into(),
1059 by: EventTriggerKind::Import,
1060 new_version: Cow::Owned(oplog.frontiers().clone()),
1061 },
1062 diff_mode,
1063 ) {
1064 if rollback_enabled {
1065 oplog.rollback_import(&mut state);
1066 return Err(e);
1067 }
1068
1069 panic!("state apply returned Err for import without rollback guard: {e}");
1070 }
1071 materialize_touched_roots(&mut state, &calc, &oplog.arena);
1072 }
1073
1074 if result.has_deps_before_shallow_root {
1075 if rollback_enabled {
1076 oplog.commit_import_rollback();
1077 }
1078 return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion);
1079 }
1080
1081 if rollback_enabled {
1082 oplog.commit_import_rollback();
1083 }
1084 Ok(result.status)
1085 }
1086
1087 fn emit_events(&self) {
1088 // we should not hold the lock when emitting events
1089 let events = {
1090 let mut state = self.state.lock();
1091 state.take_events()
1092 };
1093 let mut panic = DeferredPanic::default();
1094 for event in events {
1095 panic.run(|| self.observer.emit(event));
1096 }
1097 panic.resume();
1098 }
1099
1100 pub(crate) fn drop_pending_events(&self) -> Vec<DocDiff> {
1101 let mut state = self.state.lock();
1102 state.take_events()
1103 }
1104
1105 /// Import the json schema updates.
1106 ///
1107 /// only supports backward compatibility but not forward compatibility.
1108 #[tracing::instrument(skip_all)]
1109 pub fn import_json_updates<T: TryInto<JsonSchema>>(&self, json: T) -> LoroResult<ImportStatus> {
1110 let json = json.try_into().map_err(|_| LoroError::InvalidJsonSchema)?;
1111 self.with_barrier(|| {
1112 let result = self.import_changes_and_apply_delta_to_state_if_needed(
1113 |oplog| crate::encoding::json_schema::decode_json_changes(json, &oplog.arena),
1114 ImportedValues::JsonLossy,
1115 Default::default(),
1116 );
1117 self.emit_events();
1118 result
1119 })
1120 }
1121
1122 pub fn export_json_updates(
1123 &self,
1124 start_vv: &VersionVector,
1125 end_vv: &VersionVector,
1126 with_peer_compression: bool,
1127 ) -> LoroResult<JsonSchema> {
1128 self.try_export_json_updates(start_vv, end_vv, with_peer_compression)
1129 }
1130
1131 pub fn try_export_json_updates(
1132 &self,
1133 start_vv: &VersionVector,
1134 end_vv: &VersionVector,
1135 with_peer_compression: bool,
1136 ) -> LoroResult<JsonSchema> {
1137 self.with_barrier(|| {
1138 let oplog = self.oplog.lock();
1139 let mut start_vv = start_vv;
1140 let _temp: Option<VersionVector>;
1141 if !oplog.dag.shallow_since_vv().is_empty() {
1142 // Make sure that start_vv >= shallow_since_vv
1143 let mut include_all = true;
1144 for (peer, counter) in oplog.dag.shallow_since_vv().iter() {
1145 if start_vv.get(peer).unwrap_or(&0) < counter {
1146 include_all = false;
1147 break;
1148 }
1149 }
1150 if !include_all {
1151 let mut vv = start_vv.clone();
1152 for (&peer, &counter) in oplog.dag.shallow_since_vv().iter() {
1153 vv.extend_to_include_end_id(ID::new(peer, counter));
1154 }
1155 _temp = Some(vv);
1156 start_vv = _temp.as_ref().unwrap();
1157 }
1158 }
1159
1160 crate::encoding::json_schema::try_export_json(
1161 &oplog,
1162 start_vv,
1163 end_vv,
1164 with_peer_compression,
1165 )
1166 })
1167 }
1168
1169 pub fn export_json_in_id_span(&self, id_span: IdSpan) -> Vec<JsonChange> {
1170 let oplog = self.oplog.lock();
1171 let mut changes = export_json_in_id_span(&oplog, id_span);
1172 if let Some(uncommit) = oplog.get_uncommitted_change_in_span(id_span) {
1173 let change_json = encode_change(ChangeRef::from_change(&uncommit), &self.arena, None);
1174 changes.push(change_json);
1175 }
1176 changes
1177 }
1178
1179 /// Get the version vector of the current OpLog
1180 #[inline]
1181 pub fn oplog_vv(&self) -> VersionVector {
1182 self.oplog.lock().vv().clone()
1183 }
1184
1185 /// Get the version vector of the current [DocState].
1186 ///
1187 /// When the state frontiers are the op-log frontiers, this clones the cached
1188 /// op-log version vector and does not parse change blocks. Otherwise it
1189 /// walks the frontiers.
1190 ///
1191 /// # Panics
1192 ///
1193 /// Panics if the state's version cannot be resolved from the document history.
1194 /// Use [`Self::try_state_vv`] to handle unreadable history as an error.
1195 #[inline]
1196 pub fn state_vv(&self) -> VersionVector {
1197 self.try_state_vv()
1198 .expect("Cannot resolve the state version vector")
1199 }
1200
1201 /// Get the version vector of the current state, returning a decode error
1202 /// when required history cannot be read.
1203 ///
1204 /// `Ok(None)` from the frontier walk (the frontiers are not in the dag) is
1205 /// [`LoroError::FrontiersNotFound`] for an id that can be named, not an empty
1206 /// version vector.
1207 pub fn try_state_vv(&self) -> LoroResult<VersionVector> {
1208 let oplog = self.oplog.lock();
1209 let frontiers = self.state.lock().frontiers.clone();
1210 if &frontiers == oplog.frontiers() {
1211 // `OpLog::vv` is the cached DAG version vector. It does not parse blocks.
1212 return Ok(oplog.vv().clone());
1213 }
1214 frontiers_to_vv_or_not_found(&oplog, &frontiers)
1215 }
1216
1217 pub fn get_by_path(&self, path: &[Index]) -> Option<ValueOrHandler> {
1218 let value: LoroValue = self.state.lock().get_value_by_path(path)?;
1219 if let LoroValue::Container(c) = value {
1220 Some(ValueOrHandler::Handler(Handler::new_attached(
1221 c.clone(),
1222 self.clone(),
1223 )))
1224 } else {
1225 Some(ValueOrHandler::Value(value))
1226 }
1227 }
1228
1229 /// Get the handler by the string path.
1230 pub fn get_by_str_path(&self, path: &str) -> Option<ValueOrHandler> {
1231 let path = str_to_path(path)?;
1232 self.get_by_path(&path)
1233 }
1234
1235 pub fn get_uncommitted_ops_as_json(&self) -> Option<JsonSchema> {
1236 let arena = &self.arena;
1237 let txn = self.txn.lock();
1238 let txn = txn.as_ref()?;
1239 let ops_ = txn.local_ops();
1240 let new_id = ID {
1241 peer: *txn.peer(),
1242 counter: ops_.first()?.counter,
1243 };
1244 let change = ChangeRef {
1245 id: &new_id,
1246 deps: txn.frontiers(),
1247 timestamp: &txn
1248 .timestamp()
1249 .as_ref()
1250 .copied()
1251 .unwrap_or_else(|| self.oplog.lock().get_timestamp_for_next_txn()),
1252 commit_msg: txn.msg(),
1253 ops: ops_,
1254 lamport: txn.lamport(),
1255 };
1256 let json = encode_change_to_json(change, arena);
1257 Some(json)
1258 }
1259
1260 #[inline]
1261 pub fn get_handler(&self, id: ContainerID) -> Option<Handler> {
1262 if self.has_container(&id) {
1263 self.ensure_root_container(&id);
1264 Some(Handler::new_attached(id, self.clone()))
1265 } else {
1266 None
1267 }
1268 }
1269
1270 #[inline]
1271 fn ensure_root_container(&self, id: &ContainerID) {
1272 // Mergeable roots stay lazily materialized: their existence is derived from the
1273 // parent map's child ref, and a store entry only appears once the child gets its
1274 // own ops (or via the shallow-export alive walk).
1275 if id.is_root() && !id.is_mergeable() {
1276 self.state.lock().ensure_container(id);
1277 }
1278 }
1279
1280 /// id can be a str, ContainerID, or ContainerIdRaw.
1281 /// if it's str it will use Root container, which will not be None
1282 #[inline]
1283 pub fn try_get_text<I: IntoContainerId>(&self, id: I) -> Option<TextHandler> {
1284 let id = id.into_container_id(&self.arena, ContainerType::Text);
1285 if !self.has_container(&id) {
1286 return None;
1287 }
1288 self.ensure_root_container(&id);
1289 Handler::new_attached(id, self.clone()).into_text().ok()
1290 }
1291
1292 /// id can be a str, ContainerID, or ContainerIdRaw.
1293 /// if it's str it will use Root container, which will not be None
1294 #[inline]
1295 pub fn get_text<I: IntoContainerId>(&self, id: I) -> TextHandler {
1296 self.try_get_text(id)
1297 .expect("The container does not exist in the document. Use `try_get_text` or `get_container` to check for existence.")
1298 }
1299
1300 /// id can be a str, ContainerID, or ContainerIdRaw.
1301 /// if it's str it will use Root container, which will not be None
1302 #[inline]
1303 pub fn try_get_list<I: IntoContainerId>(&self, id: I) -> Option<ListHandler> {
1304 let id = id.into_container_id(&self.arena, ContainerType::List);
1305 if !self.has_container(&id) {
1306 return None;
1307 }
1308 self.ensure_root_container(&id);
1309 Handler::new_attached(id, self.clone()).into_list().ok()
1310 }
1311
1312 /// id can be a str, ContainerID, or ContainerIdRaw.
1313 /// if it's str it will use Root container, which will not be None
1314 #[inline]
1315 pub fn get_list<I: IntoContainerId>(&self, id: I) -> ListHandler {
1316 self.try_get_list(id)
1317 .expect("The container does not exist in the document. Use `try_get_list` or `get_container` to check for existence.")
1318 }
1319
1320 /// id can be a str, ContainerID, or ContainerIdRaw.
1321 /// if it's str it will use Root container, which will not be None
1322 #[inline]
1323 pub fn try_get_movable_list<I: IntoContainerId>(&self, id: I) -> Option<MovableListHandler> {
1324 let id = id.into_container_id(&self.arena, ContainerType::MovableList);
1325 if !self.has_container(&id) {
1326 return None;
1327 }
1328 self.ensure_root_container(&id);
1329 Handler::new_attached(id, self.clone())
1330 .into_movable_list()
1331 .ok()
1332 }
1333
1334 /// id can be a str, ContainerID, or ContainerIdRaw.
1335 /// if it's str it will use Root container, which will not be None
1336 #[inline]
1337 pub fn get_movable_list<I: IntoContainerId>(&self, id: I) -> MovableListHandler {
1338 self.try_get_movable_list(id)
1339 .expect("The container does not exist in the document. Use `try_get_movable_list` or `get_container` to check for existence.")
1340 }
1341
1342 /// id can be a str, ContainerID, or ContainerIdRaw.
1343 /// if it's str it will use Root container, which will not be None
1344 #[inline]
1345 pub fn try_get_map<I: IntoContainerId>(&self, id: I) -> Option<MapHandler> {
1346 let id = id.into_container_id(&self.arena, ContainerType::Map);
1347 if !self.has_container(&id) {
1348 return None;
1349 }
1350 self.ensure_root_container(&id);
1351 Handler::new_attached(id, self.clone()).into_map().ok()
1352 }
1353
1354 /// id can be a str, ContainerID, or ContainerIdRaw.
1355 /// if it's str it will use Root container, which will not be None
1356 #[inline]
1357 pub fn get_map<I: IntoContainerId>(&self, id: I) -> MapHandler {
1358 self.try_get_map(id)
1359 .expect("The container does not exist in the document. Use `try_get_map` or `get_container` to check for existence.")
1360 }
1361
1362 /// id can be a str, ContainerID, or ContainerIdRaw.
1363 /// if it's str it will use Root container, which will not be None
1364 #[inline]
1365 pub fn try_get_tree<I: IntoContainerId>(&self, id: I) -> Option<TreeHandler> {
1366 let id = id.into_container_id(&self.arena, ContainerType::Tree);
1367 if !self.has_container(&id) {
1368 return None;
1369 }
1370 self.ensure_root_container(&id);
1371 Handler::new_attached(id, self.clone()).into_tree().ok()
1372 }
1373
1374 /// id can be a str, ContainerID, or ContainerIdRaw.
1375 /// if it's str it will use Root container, which will not be None
1376 #[inline]
1377 pub fn get_tree<I: IntoContainerId>(&self, id: I) -> TreeHandler {
1378 self.try_get_tree(id)
1379 .expect("The container does not exist in the document. Use `try_get_tree` or `get_container` to check for existence.")
1380 }
1381
1382 #[cfg(feature = "counter")]
1383 pub fn try_get_counter<I: IntoContainerId>(
1384 &self,
1385 id: I,
1386 ) -> Option<crate::handler::counter::CounterHandler> {
1387 let id = id.into_container_id(&self.arena, ContainerType::Counter);
1388 if !self.has_container(&id) {
1389 return None;
1390 }
1391 self.ensure_root_container(&id);
1392 Handler::new_attached(id, self.clone()).into_counter().ok()
1393 }
1394
1395 #[cfg(feature = "counter")]
1396 pub fn get_counter<I: IntoContainerId>(
1397 &self,
1398 id: I,
1399 ) -> crate::handler::counter::CounterHandler {
1400 self.try_get_counter(id)
1401 .expect("The container does not exist in the document. Use `try_get_counter` or `get_container` to check for existence.")
1402 }
1403
1404 #[must_use]
1405 pub fn has_container(&self, id: &ContainerID) -> bool {
1406 if id.is_root() && !id.is_mergeable() {
1407 return true;
1408 }
1409
1410 let exist = self.state.lock().does_container_exist(id);
1411 exist
1412 }
1413
1414 /// Undo the operations between the given id_span. It can be used even in a collaborative environment.
1415 ///
1416 /// This is an internal API. You should NOT use it directly.
1417 ///
1418 /// # Internal
1419 ///
1420 /// This method will use the diff calculator to calculate the diff required to time travel
1421 /// from the end of id_span to the beginning of the id_span. Then it will convert the diff to
1422 /// operations and apply them to the OpLog with a dep on the last id of the given id_span.
1423 ///
1424 /// This implementation is kinda slow, but it's simple and maintainable. We can optimize it
1425 /// further when it's needed. The time complexity is O(n + m), n is the ops in the id_span, m is the
1426 /// distance from id_span to the current latest version.
1427 ///
1428 /// Returns application errors after rolling back the inverse. Recreating
1429 /// an unknown container is rejected before application with an `ArgErr`.
1430 #[instrument(level = "info", skip_all)]
1431 pub fn undo_internal(
1432 &self,
1433 id_span: IdSpan,
1434 container_remap: &mut FxHashMap<ContainerID, ContainerID>,
1435 post_transform_base: Option<&DiffBatch>,
1436 before_diff: &mut dyn FnMut(&DiffBatch),
1437 ) -> LoroResult<CommitWhenDrop<'_>> {
1438 self.undo_internal_with(
1439 id_span,
1440 container_remap,
1441 post_transform_base,
1442 before_diff,
1443 &mut None,
1444 &mut Default::default(),
1445 )
1446 }
1447
1448 /// [`Self::undo_internal`]. When the step is rejected because it would
1449 /// recreate a container of an unknown type, `rejected_step` is set to the
1450 /// step's own changes, which stay in the doc: the undo manager treats them
1451 /// like remote changes for the steps before it.
1452 pub(crate) fn undo_internal_with(
1453 &self,
1454 id_span: IdSpan,
1455 container_remap: &mut FxHashMap<ContainerID, ContainerID>,
1456 post_transform_base: Option<&DiffBatch>,
1457 before_diff: &mut dyn FnMut(&DiffBatch),
1458 rejected_step: &mut Option<DiffBatch>,
1459 element_remap: &mut crate::undo::movable_list::ElementRemap,
1460 ) -> LoroResult<CommitWhenDrop<'_>> {
1461 let _exclusive = self.txn.lock_exclusive();
1462 if !self.can_edit() {
1463 return Err(LoroError::EditWhenDetached);
1464 }
1465
1466 let (options, mut txn) = self.implicit_commit_then_stop();
1467 if !self.oplog().lock().vv().includes_id(id_span.id_last()) {
1468 self.renew_txn_if_auto_commit(options);
1469 return Err(LoroError::UndoInvalidIdSpan(id_span.id_last()));
1470 }
1471
1472 let (was_recording, latest_frontiers) = {
1473 let mut state = self.state.lock();
1474 let was_recording = state.is_recording();
1475 state.stop_and_clear_recording();
1476 (was_recording, state.frontiers.clone())
1477 };
1478
1479 let spans = self.oplog.lock().split_span_based_on_deps(id_span);
1480 let (span_scopes, all_scopes) = match crate::undo::movable_list::scopes(self, &spans) {
1481 Ok(scopes) => scopes,
1482 Err(error) => {
1483 if was_recording {
1484 self.state.lock().start_recording();
1485 }
1486 drop(txn);
1487 self.renew_txn_if_auto_commit(options);
1488 return Err(error);
1489 }
1490 };
1491 let inverse_lists = std::cell::RefCell::new(Vec::new());
1492 let revived_lists = std::cell::RefCell::new(Default::default());
1493 let calc_diff = |from: &Frontiers, to: &Frontiers| {
1494 self._checkout_without_emitting(from, false, false).unwrap();
1495 let inverse_index = spans
1496 .iter()
1497 .position(|(span, deps)| Frontiers::from_id(span.id_last()) == *from && deps == to);
1498 let after_lists: Vec<_> = inverse_index.map_or_else(Vec::new, |i| {
1499 span_scopes[i]
1500 .iter()
1501 .map(|(cid, scope)| {
1502 (
1503 cid.clone(),
1504 crate::undo::movable_list::Snapshot::capture_span(
1505 self,
1506 cid,
1507 scope,
1508 &all_scopes[cid],
1509 false,
1510 ),
1511 )
1512 })
1513 .collect()
1514 });
1515 {
1516 let mut state = self.state.lock();
1517 state.start_recording();
1518 state.set_record_changes_only(true);
1519 }
1520 self._checkout_without_emitting(to, false, false).unwrap();
1521 for (cid, after) in after_lists {
1522 let i = inverse_index.unwrap();
1523 let before = crate::undo::movable_list::Snapshot::capture_span(
1524 self,
1525 &cid,
1526 &span_scopes[i][&cid],
1527 &all_scopes[&cid],
1528 true,
1529 );
1530 inverse_lists
1531 .borrow_mut()
1532 .push(crate::undo::movable_list::Inverse {
1533 span_index: inverse_index.unwrap(),
1534 cid,
1535 before,
1536 after,
1537 before_frontiers: to.clone(),
1538 });
1539 }
1540 let mut state = self.state.lock();
1541 state.set_record_changes_only(false);
1542 let e = state.take_events();
1543 state.stop_and_clear_recording();
1544 // Applied to this doc, which kept the state of re-activated mergeable children.
1545 let diff = DiffBatch::from_changes(e);
1546 drop(state);
1547 if let Some(i) = inverse_index {
1548 crate::undo::movable_list::capture_revivals(
1549 self,
1550 &diff,
1551 i,
1552 &mut revived_lists.borrow_mut(),
1553 );
1554 }
1555 diff
1556 };
1557 // `before_diff` rebases the undo manager's other steps over this one,
1558 // so it only runs once the step is accepted
1559 let mut last_event_a = None;
1560 let mut diff = crate::undo::undo(
1561 spans.clone(),
1562 match post_transform_base {
1563 Some(d) => Either::Right(d),
1564 None => Either::Left(&latest_frontiers),
1565 },
1566 calc_diff,
1567 &mut |d| last_event_a = Some(d.clone()),
1568 );
1569
1570 self._checkout_without_emitting(&latest_frontiers, false, false)?;
1571 self.set_detached(false);
1572 let mut inverse_lists = inverse_lists.take();
1573 crate::undo::movable_list::complete_anchors(
1574 self,
1575 &mut inverse_lists,
1576 &latest_frontiers,
1577 &all_scopes,
1578 element_remap,
1579 container_remap,
1580 )?;
1581 let mut movable_plans = crate::undo::movable_list::prepare(
1582 self,
1583 &mut diff,
1584 inverse_lists,
1585 revived_lists.take(),
1586 container_remap,
1587 element_remap,
1588 );
1589 // A step that would recreate an unknown container is rejected as a
1590 // whole, before anything is applied
1591 let rejected = self
1592 .check_apply_diff_creates_no_unknown_container(
1593 &diff,
1594 None,
1595 container_remap,
1596 true,
1597 &movable_plans,
1598 )
1599 .err();
1600 if rejected.is_some() {
1601 let mut changes = DiffBatch::default();
1602 for (span, deps) in spans.iter() {
1603 changes.compose(&calc_diff(deps, &span.id_last().into()));
1604 }
1605 self._checkout_without_emitting(&latest_frontiers, false, false)?;
1606 self.set_detached(false);
1607 *rejected_step = Some(changes);
1608 }
1609
1610 if was_recording {
1611 self.state.lock().start_recording();
1612 }
1613 // Native identity edits must use the same transaction lock that
1614 // protected capture/preparation. Releasing it here lets a waiting
1615 // writer delete elements or anchors before the plan uses them.
1616 let remap_before = container_remap.clone();
1617 let elements_before = element_remap.clone();
1618 let mut undo_scope = None;
1619 let native_result: LoroResult<()> = (|| {
1620 if rejected.is_some() {
1621 return Ok(());
1622 }
1623 *txn = Some(self.txn()?);
1624 let transaction = txn
1625 .as_mut()
1626 .ok_or_else(|| LoroError::TransactionError("undo transaction is missing".into()))?;
1627 // Keep the capture/preparation guard held while marking the scope
1628 // and applying native plans. Ordinary handlers later reuse this
1629 // same transaction and scope after the guard is released.
1630 undo_scope = Some(
1631 self.begin_apply_diff_scope_with_txn(transaction)
1632 .expect("undo must own its rollback scope"),
1633 );
1634 let ids: Vec<_> = diff
1635 .order
1636 .iter()
1637 .filter(|id| movable_plans.get(*id).is_some_and(|p| p.is_native()))
1638 .cloned()
1639 .collect();
1640 for cid in ids {
1641 let Some(plan) = movable_plans.remove(&cid) else {
1642 continue;
1643 };
1644 let (id, _) = resolve_container_remap(cid.clone(), container_remap);
1645 let list = self
1646 .get_handler(id)
1647 .and_then(|h| h.into_movable_list().ok())
1648 .ok_or_else(|| {
1649 LoroError::NotFoundError("MovableList undo container disappeared".into())
1650 })?;
1651 plan.apply_with_txn(&list, transaction, container_remap, element_remap)?;
1652 #[cfg(test)]
1653 if RUN_APPLY_DIFF_HOOK_AFTER_NATIVE_PLAN.with(|flag| flag.replace(false)) {
1654 after_apply_diff_handler()?;
1655 }
1656 diff.cid_to_events.remove(&cid);
1657 }
1658 diff.order.retain(|id| diff.cid_to_events.contains_key(id));
1659 Ok(())
1660 })();
1661 drop(txn);
1662 self.start_auto_commit();
1663 let applied = native_result.and_then(|()| {
1664 if rejected.is_none() {
1665 self.apply_diff_with_movable_undo(
1666 diff,
1667 container_remap,
1668 true,
1669 false,
1670 &mut movable_plans,
1671 element_remap,
1672 )
1673 } else {
1674 Ok(())
1675 }
1676 });
1677 if let Some(scope) = undo_scope {
1678 self.finish_undo_rollback(scope, applied.is_ok());
1679 }
1680
1681 if let Some(options) = options {
1682 self.set_next_commit_options(options);
1683 }
1684 if let Some(e) = rejected {
1685 return Err(e);
1686 }
1687 if let Err(e) = applied {
1688 *container_remap = remap_before;
1689 *element_remap = elements_before;
1690 return Err(e);
1691 }
1692 if let Some(event_a) = &last_event_a {
1693 before_diff(event_a);
1694 }
1695 Ok(CommitWhenDrop {
1696 doc: self,
1697 default_options: CommitOptions::new().origin("undo"),
1698 })
1699 }
1700
1701 /// Generate a series of local operations that can revert the current doc to the target
1702 /// version.
1703 ///
1704 /// Internally, it will calculate the diff between the current state and the target state,
1705 /// and apply the diff to the current state.
1706 pub fn revert_to(&self, target: &Frontiers) -> LoroResult<()> {
1707 // TODO: test when the doc is readonly
1708 // TODO: test when the doc is detached but enabled editing
1709 let f = self.state_frontiers();
1710 let diff = self.diff_events(&f, target, true)?;
1711 // This doc kept the state of the mergeable children the target re-activates, so apply
1712 // their actual changes rather than the full states `diff` reports.
1713 self.apply_diff_all_or_nothing(
1714 DiffBatch::from_changes(diff),
1715 &mut Default::default(),
1716 false,
1717 false,
1718 )
1719 }
1720
1721 /// Calculate the diff between two versions so that apply diff on a will make the state same as b.
1722 ///
1723 /// NOTE: This method will make the doc enter the **detached mode**.
1724 // FIXME: This method needs testing (no event should be emitted during processing this)
1725 pub fn diff(&self, a: &Frontiers, b: &Frontiers) -> LoroResult<DiffBatch> {
1726 self.diff_events(a, b, false).map(|e| DiffBatch {
1727 full_state: true,
1728 ..DiffBatch::new(e)
1729 })
1730 }
1731
1732 /// With `changes_only`, only [`DiffBatch::from_changes`] of the result is meaningful.
1733 // Both callers return a `Result`, so a history that cannot be parsed is rejected here.
1734 fn diff_events(
1735 &self,
1736 a: &Frontiers,
1737 b: &Frontiers,
1738 changes_only: bool,
1739 ) -> LoroResult<Vec<DocDiff>> {
1740 {
1741 // Check whether a and b are valid before checkout so this returns a normal error
1742 // instead of panicking on shallow docs.
1743 let oplog = self.oplog.lock();
1744 oplog.check_history_parsable()?;
1745 let validate_frontiers = |frontiers: &Frontiers| -> LoroResult<()> {
1746 for id in frontiers.iter() {
1747 if !oplog.dag.contains(id) {
1748 return Err(LoroError::FrontiersNotFound(id));
1749 }
1750 }
1751
1752 if oplog.dag.is_before_shallow_root(frontiers) {
1753 return Err(LoroError::SwitchToVersionBeforeShallowRoot);
1754 }
1755
1756 Ok(())
1757 };
1758
1759 validate_frontiers(a)?;
1760 validate_frontiers(b)?;
1761 }
1762
1763 let (options, txn) = self.implicit_commit_then_stop();
1764 let was_detached = self.is_detached();
1765 let old_frontiers = self.state_frontiers();
1766 let was_recording = {
1767 let mut state = self.state.lock();
1768 let is_recording = state.is_recording();
1769 state.stop_and_clear_recording();
1770 is_recording
1771 };
1772 let result = (|| {
1773 self._checkout_without_emitting(a, true, false)?;
1774 {
1775 let mut state = self.state.lock();
1776 state.start_recording();
1777 state.set_record_changes_only(changes_only);
1778 }
1779 let checkout = self._checkout_without_emitting(b, true, false);
1780 let mut state = self.state.lock();
1781 state.set_record_changes_only(false);
1782 checkout?;
1783 let e = state.take_events();
1784 state.stop_and_clear_recording();
1785 Ok::<_, LoroError>(e)
1786 })();
1787
1788 // Always restore state regardless of whether diff calculation succeeded
1789 self._checkout_without_emitting(&old_frontiers, false, false)
1790 .unwrap();
1791 drop(txn);
1792 if !was_detached {
1793 self.set_detached(false);
1794 self.renew_txn_if_auto_commit(options);
1795 }
1796 if was_recording {
1797 self.state.lock().start_recording();
1798 }
1799 result
1800 }
1801
1802 /// Apply a diff to the current state.
1803 #[inline(always)]
1804 ///
1805 /// A mergeable child that the batch re-activates is aligned with this doc's hidden state
1806 /// only if `diff.full_state` is set (batches from [`LoroDoc::diff`]); otherwise its entry
1807 /// is applied as an increment. See [`DiffBatch::full_state`].
1808 ///
1809 /// All or nothing: when it returns `Err`, the doc, its history and its subscribers are as
1810 /// before the call, and uncommitted edits made before it are kept. See
1811 /// `context/apply-diff-atomicity.md`.
1812 pub fn apply_diff(&self, diff: DiffBatch) -> LoroResult<()> {
1813 let align = diff.full_state;
1814 self.apply_diff_all_or_nothing(diff, &mut Default::default(), true, align)
1815 }
1816
1817 /// [`Self::_apply_diff`], rolled back when it fails (loro-dev/loro#1154).
1818 /// Undo uses the same scope with its identity plans; see `context/undo-atomicity.md`.
1819 pub(crate) fn apply_diff_all_or_nothing(
1820 &self,
1821 diff: DiffBatch,
1822 container_remap: &mut FxHashMap<ContainerID, ContainerID>,
1823 skip_unreachable: bool,
1824 align_revived_mergeable: bool,
1825 ) -> LoroResult<()> {
1826 if !self.can_edit() {
1827 return Err(LoroError::EditWhenDetached);
1828 }
1829
1830 // Rollback checks the state out through the current frontiers. If that
1831 // history cannot be read, refuse before the batch mutates anything.
1832 {
1833 let oplog = self.oplog.lock();
1834 let frontiers = self.state.lock().frontiers.clone();
1835 frontiers_to_vv_or_not_found(&oplog, &frontiers)?;
1836 }
1837
1838 let scope = self.begin_apply_diff_scope();
1839 let result = self._apply_diff(
1840 diff,
1841 container_remap,
1842 skip_unreachable,
1843 align_revived_mergeable,
1844 );
1845 if let Some(scope) = scope {
1846 if result.is_ok() {
1847 self.end_apply_diff_scope(scope);
1848 } else if let Err(err) = self.rollback_apply_diff_scope(scope) {
1849 return Err(err);
1850 }
1851 }
1852 result
1853 }
1854
1855 /// Undo owns the writer gate and a fresh transaction. Losing its rollback
1856 /// scope or failing to restore state is an invariant failure, not a normal
1857 /// error that callers could safely retry on a partly changed document.
1858 fn finish_undo_rollback(&self, scope: u64, succeeded: bool) {
1859 if succeeded {
1860 self.end_apply_diff_scope(scope);
1861 } else {
1862 assert!(
1863 self.txn
1864 .lock()
1865 .as_ref()
1866 .is_some_and(|txn| txn.rollback_scope_is_intact(scope)),
1867 "undo lost its exclusive rollback scope"
1868 );
1869 self.rollback_apply_diff_scope(scope)
1870 .expect("undo rollback must restore the document");
1871 }
1872 }
1873
1874 /// Marks where the batch starts in the transaction it will run in.
1875 ///
1876 /// Returns `None`, and the batch runs without a rollback, when there is no transaction
1877 /// to run it in (the batch then fails before it applies anything) or another thread's
1878 /// batch runs in it.
1879 fn begin_apply_diff_scope(&self) -> Option<u64> {
1880 let mut guard = self.txn.lock();
1881 if guard.is_none() && !cfg!(target_arch = "wasm32") && self.can_edit() {
1882 // Like the handlers' `with_txn`, which the batch's first op would call
1883 drop(guard);
1884 self.start_auto_commit();
1885 guard = self.txn.lock();
1886 }
1887 self.begin_apply_diff_scope_with_txn(guard.as_mut()?)
1888 }
1889
1890 /// Also used by undo while it holds the preparation transaction guard.
1891 fn begin_apply_diff_scope_with_txn(&self, txn: &mut Transaction) -> Option<u64> {
1892 static NEXT_SCOPE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1893 if txn.has_rollback_scope() {
1894 return None;
1895 }
1896 let id = NEXT_SCOPE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1897 txn.begin_rollback_scope(id);
1898 self.state.lock().begin_local_rollback(id);
1899 Some(id)
1900 }
1901
1902 fn end_apply_diff_scope(&self, scope: u64) {
1903 let mut guard = self.txn.lock();
1904 if let Some(txn) = guard.as_mut() {
1905 txn.end_rollback_scope(scope);
1906 }
1907 self.state.lock().end_local_rollback(scope);
1908 }
1909
1910 /// Undo the ops of a failed batch, keeping the ops the transaction held before it.
1911 /// Emits nothing.
1912 ///
1913 /// The transaction's ops are inserted into the op log as a change, under an import
1914 /// rollback scope, so that the diff calculator can compute the checkout from the batch's
1915 /// last op back to the version before the batch; then the scope is rolled back and the
1916 /// ops before the batch are put back into the DAG's version as pending local ops.
1917 fn rollback_apply_diff_scope(&self, scope: u64) -> LoroResult<()> {
1918 let mut guard = self.txn.lock();
1919 let Some(txn) = guard
1920 .as_mut()
1921 .filter(|txn| txn.rollback_scope_is_intact(scope))
1922 else {
1923 // Another thread committed the transaction or applied ops in it while the batch
1924 // ran. Undoing it would drop their edits, so the batch stays partly applied.
1925 warn!("apply_diff failed while another thread edited the doc; not rolled back");
1926 if let Some(txn) = guard.as_mut() {
1927 txn.end_rollback_scope(scope);
1928 }
1929 self.state.lock().end_local_rollback(scope);
1930 return Ok(());
1931 };
1932
1933 let batch = txn.roll_back_scope(scope);
1934 let mut oplog = self.oplog.lock();
1935 let mut state = self.state.lock();
1936 if batch.batch_start < batch.batch_end {
1937 let peer = batch.peer;
1938 let txn_ops_before = (batch.batch_start - batch.txn_start_counter) as usize;
1939 let before_batch = if txn_ops_before == 0 {
1940 batch.deps.clone()
1941 } else {
1942 Frontiers::from_id(ID::new(peer, batch.batch_start - 1))
1943 };
1944 #[cfg(debug_assertions)]
1945 {
1946 // Only the txn's ops changed the DAG's version since it began: anything else
1947 // (an import, a checkout) commits the txn first.
1948 let mut expected = batch.dag_frontiers_at_start.clone();
1949 expected.update_frontiers_on_new_change(
1950 ID::new(peer, batch.batch_end - 1),
1951 &batch.deps,
1952 );
1953 assert_eq!(&expected, oplog.dag.frontiers());
1954 assert_eq!(oplog.dag.vv().get(&peer), Some(&batch.batch_end));
1955 }
1956 oplog.dag.discard_pending_txn(
1957 batch.dag_frontiers_at_start,
1958 peer,
1959 batch.txn_start_counter,
1960 );
1961 oplog.begin_import_rollback();
1962 oplog.insert_new_change(
1963 Change {
1964 id: ID::new(peer, batch.txn_start_counter),
1965 lamport: batch.txn_start_lamport,
1966 deps: batch.deps.clone(),
1967 timestamp: batch.timestamp,
1968 commit_msg: None,
1969 ops: batch.ops,
1970 },
1971 false,
1972 );
1973
1974 let batch_last = state.frontiers.clone();
1975 debug_assert_eq!(
1976 batch_last,
1977 Frontiers::from_id(ID::new(peer, batch.batch_end - 1))
1978 );
1979 let undone = (|| -> LoroResult<()> {
1980 let from = frontiers_to_vv_or_not_found(&oplog, &batch_last)?;
1981 let to = frontiers_to_vv_or_not_found(&oplog, &before_batch)?;
1982 let (diff, diff_mode) = DiffCalculator::new(false).try_calc_diff_internal(
1983 &oplog,
1984 &from,
1985 &batch_last,
1986 &to,
1987 &before_batch,
1988 None,
1989 )?;
1990 // `DocState::apply_diff` refuses to run inside a transaction, and records nothing
1991 // without its event recorder.
1992 state.abort_txn();
1993 let recorder = state.take_event_recorder();
1994 let applied = state.apply_diff(
1995 InternalDocDiff {
1996 origin: Default::default(),
1997 by: EventTriggerKind::Checkout,
1998 diff: Cow::Owned(diff),
1999 new_version: Cow::Owned(before_batch.clone()),
2000 },
2001 diff_mode,
2002 );
2003 state.restore_event_recorder(recorder);
2004 state.resume_txn();
2005 applied
2006 })();
2007 // The temporary change must not stay in the op log if the checkout cannot be read.
2008 oplog.rollback_import_keeping_arena(&state);
2009 if txn_ops_before > 0 {
2010 oplog.dag.update_version_on_new_local_op(
2011 &batch.deps,
2012 ID::new(peer, batch.txn_start_counter),
2013 batch.txn_start_lamport,
2014 txn_ops_before,
2015 );
2016 oplog.refresh_visible_op_count();
2017 }
2018 undone?;
2019 }
2020 state.finish_local_rollback(scope, batch.peer, batch.batch_start);
2021 Ok(())
2022 }
2023
2024 /// Apply a diff to the current state.
2025 ///
2026 /// Regular containers are recreated with new [ContainerID]s. Reusing their
2027 /// original IDs could break several internal invariants:
2028 ///
2029 /// 1. Each container should appear only once in the document. Allowing containers with the same ID
2030 /// would result in multiple instances of the same container in the document.
2031 /// 2. Unreachable containers should be removable from the state when necessary.
2032 ///
2033 /// However, the diff may contain operations that depend on container IDs.
2034 /// Therefore, users need to provide a `container_remap` to record and retrieve the container ID remapping.
2035 /// This remapping applies to the diff/undo workflow, not to imported operations.
2036 /// Mergeable children instead restore a deterministic parent/key/type marker;
2037 /// their identity is preserved only when the parent identity is preserved.
2038 ///
2039 /// With `align_revived_mergeable` (a [`DiffBatch::full_state`] batch), a mergeable child the
2040 /// batch re-activates carries its full state (no entry means empty), which is aligned with
2041 /// whatever hidden state this doc has at its deterministic cid. Otherwise entries are
2042 /// increments; revert and undo pass batches of actual changes ([`DiffBatch::from_changes`]).
2043 /// See context/mergeable-containers.md.
2044 pub(crate) fn _apply_diff(
2045 &self,
2046 diff: DiffBatch,
2047 container_remap: &mut FxHashMap<ContainerID, ContainerID>,
2048 skip_unreachable: bool,
2049 align_revived_mergeable: bool,
2050 ) -> LoroResult<()> {
2051 self.apply_diff_with_movable_undo(
2052 diff,
2053 container_remap,
2054 skip_unreachable,
2055 align_revived_mergeable,
2056 &mut Default::default(),
2057 &mut Default::default(),
2058 )
2059 }
2060
2061 fn apply_diff_with_movable_undo(
2062 &self,
2063 diff: DiffBatch,
2064 container_remap: &mut FxHashMap<ContainerID, ContainerID>,
2065 skip_unreachable: bool,
2066 align_revived_mergeable: bool,
2067 movable_plans: &mut FxHashMap<ContainerID, crate::undo::movable_list::Plan>,
2068 element_remap: &mut crate::undo::movable_list::ElementRemap,
2069 ) -> LoroResult<()> {
2070 if !self.can_edit() {
2071 return Err(LoroError::EditWhenDetached);
2072 }
2073
2074 // When the batch holds unknown containers, its full states are aligned
2075 // before anything is applied, so the check sees what is applied; the
2076 // loop below then applies the planned edits. Otherwise the loop aligns
2077 // each full state itself.
2078 let mut plan =
2079 if align_revived_mergeable && diff.iter().any(|(_, d)| diff_has_unknown_value(d)) {
2080 self.plan_full_state_batch(&diff, container_remap)
2081 } else {
2082 FullStatePlan::default()
2083 };
2084 // Reject unsupported container recreation before touching the doc.
2085 let predicted_skips = self.check_apply_diff_creates_no_unknown_container(
2086 &diff,
2087 align_revived_mergeable.then_some(&plan),
2088 container_remap,
2089 skip_unreachable,
2090 movable_plans,
2091 )?;
2092
2093 let mut ans: LoroResult<()> = Ok(());
2094 let mut missing_containers: Vec<ContainerID> = Vec::new();
2095 // Containers whose diff in this batch is a full state while they keep an id that may
2096 // already hold state: re-activated mergeable children and, transitively, the children
2097 // of aligned containers that were kept.
2098 let mut full_state_targets: FxHashSet<ContainerID> = FxHashSet::default();
2099 let mut applied: FxHashSet<ContainerID> = FxHashSet::default();
2100 for (mut id, diff) in diff.into_iter() {
2101 let batch_id = id.clone();
2102 let mut remapped = false;
2103 while let Some(rid) = container_remap.get(&id) {
2104 remapped = true;
2105 id = rid.clone();
2106 }
2107
2108 let is_full_state = align_revived_mergeable && full_state_targets.remove(&id);
2109 if align_revived_mergeable {
2110 applied.insert(id.clone());
2111 }
2112
2113 if matches!(&id, ContainerID::Normal { .. }) && self.arena.id_to_idx(&id).is_none() {
2114 // Not in arena does not imply non-existent; consult state/kv and register lazily
2115 let exists = self.state.lock().does_container_exist(&id);
2116 if !exists {
2117 missing_containers.push(id);
2118 continue;
2119 }
2120 // Ensure registration so handlers can be created
2121 self.state.lock().ensure_container(&id);
2122 }
2123
2124 if skip_unreachable && !is_full_state {
2125 let mut state = self.state.lock();
2126 // A remapped target is normally recreated by this batch and is
2127 // applied even before it is attached. An earlier undo may have
2128 // recreated it, though, and it may have been deleted since:
2129 // writing to it would fail with `ContainerDeleted`, so skip it
2130 // like any other unreachable container.
2131 let skip = if remapped {
2132 self.arena
2133 .id_to_idx(&id)
2134 .is_some_and(|idx| state.is_deleted(idx))
2135 } else {
2136 !state.get_reachable(&id)
2137 };
2138 if skip {
2139 continue;
2140 }
2141 }
2142 debug_assert!(
2143 !predicted_skips.contains(&batch_id),
2144 "{batch_id} holds an unknown container and was predicted to be skipped"
2145 );
2146
2147 let Some(h) = self.get_handler(id.clone()) else {
2148 return Err(LoroError::ContainersNotFound {
2149 containers: Box::new(vec![id]),
2150 });
2151 };
2152 let planned = plan.aligned.remove(&batch_id);
2153 let diff = if is_full_state {
2154 match planned {
2155 // The plan aligned this entry against the same container
2156 Some(p) if p.target == id => {
2157 full_state_targets.extend(p.kept);
2158 match p.edit {
2159 Some(edit) => edit,
2160 None => continue,
2161 }
2162 }
2163 _ => {
2164 // Not planned (the batch holds no unknown container),
2165 // or a mergeable child of a container this batch
2166 // recreated: new and empty, which the plan checked as such
2167 debug_assert!(
2168 plan.fresh.contains(&batch_id) || !diff_has_unknown_value(&diff),
2169 "{batch_id} holds an unknown container and was not planned"
2170 );
2171 let current = self.state.lock().container_full_diff(h.container_idx());
2172 match crate::handler::align_full_state(
2173 &h,
2174 &diff,
2175 current,
2176 &mut full_state_targets,
2177 ) {
2178 Some(diff) => diff,
2179 None => continue,
2180 }
2181 }
2182 }
2183 } else {
2184 debug_assert!(
2185 planned.is_none() || !diff_has_unknown_value(&diff),
2186 "{batch_id} holds an unknown container and was planned as a full state"
2187 );
2188 diff
2189 };
2190 let result = if let Some(movable) = movable_plans.remove(&batch_id) {
2191 let Handler::MovableList(list) = &h else {
2192 unreachable!()
2193 };
2194 movable.apply(list, diff, container_remap, element_remap)
2195 } else {
2196 h.apply_diff(diff, container_remap, &mut full_state_targets)
2197 };
2198 // Fault injection after real operations exercises rollback.
2199 #[cfg(test)]
2200 let result = result.and_then(|()| after_apply_diff_handler());
2201 if let Err(e) = result {
2202 debug_assert!(
2203 !crate::handler::is_unknown_container_creation_err(&e),
2204 "the unknown container check missed {e:?} in {batch_id}"
2205 );
2206 ans = Err(e);
2207 }
2208 }
2209
2210 if align_revived_mergeable {
2211 // A full-state container without an entry in the batch is empty.
2212 for id in full_state_targets {
2213 if applied.contains(&id) {
2214 continue;
2215 }
2216 let Some(h) = self.get_handler(id) else {
2217 continue;
2218 };
2219 let is_empty = self
2220 .state
2221 .lock()
2222 .is_container_state_empty(h.container_idx());
2223 if !is_empty {
2224 if let Err(e) = h.clear() {
2225 ans = Err(e);
2226 }
2227 }
2228 }
2229 }
2230
2231 if !missing_containers.is_empty() {
2232 return Err(LoroError::ContainersNotFound {
2233 containers: Box::new(missing_containers),
2234 });
2235 }
2236
2237 ans
2238 }
2239
2240 /// How `_apply_diff` treats a full-state batch holding unknown containers,
2241 /// planned before anything is applied: which entries it aligns with the
2242 /// state this doc kept, and the edits they turn into. The loop applies
2243 /// these edits, so alignment is computed once, and the unknown container
2244 /// check sees what is applied.
2245 ///
2246 /// The loop still keeps its own `full_state_targets`, because it follows
2247 /// `container_remap` as it grows. It uses a planned edit only when it
2248 /// aligns the same container as the plan did.
2249 fn plan_full_state_batch(
2250 &self,
2251 diff: &DiffBatch,
2252 container_remap: &FxHashMap<ContainerID, ContainerID>,
2253 ) -> FullStatePlan {
2254 let mut plan = FullStatePlan::default();
2255 // The loop's `full_state_targets`
2256 let mut targets: FxHashSet<ContainerID> = FxHashSet::default();
2257 // Containers the loop may recreate under a new id: container values of
2258 // Map/List diffs and the metas of created or moved tree nodes. Errs
2259 // towards "recreated", which only makes the check stricter.
2260 let mut recreated: FxHashSet<ContainerID> = FxHashSet::default();
2261 // Mergeable children of recreated containers: the loop aligns them
2262 // against a new, empty container
2263 let mut fresh_targets: FxHashSet<ContainerID> = FxHashSet::default();
2264 for (id, diff) in diff.iter() {
2265 let (target, _) = resolve_container_remap(id.clone(), container_remap);
2266 match diff {
2267 crate::event::Diff::Map(map) => recreated.extend(
2268 map.updated
2269 .values()
2270 .filter_map(|v| v.value.as_ref().and_then(diff_value_container_id))
2271 .filter(|c| !c.is_mergeable()),
2272 ),
2273 crate::event::Diff::List(delta) => {
2274 recreated.extend(inserted_container_ids(delta));
2275 }
2276 crate::event::Diff::Tree(tree) => recreated.extend(
2277 tree.diff
2278 .iter()
2279 .filter(|item| {
2280 !matches!(item.action, crate::delta::TreeExternalDiff::Delete { .. })
2281 })
2282 .map(|item| item.target.associated_meta_container()),
2283 ),
2284 _ => {}
2285 }
2286
2287 let effective = if fresh_targets.remove(&target) {
2288 targets.remove(&target);
2289 plan.always_applied.insert(target.clone());
2290 plan.fresh.insert(id.clone());
2291 recreated.insert(target.clone());
2292 Some(diff)
2293 } else if targets.remove(&target) {
2294 plan.always_applied.insert(target.clone());
2295 let Some(h) = self.get_handler(target.clone()) else {
2296 // `_apply_diff` stops here with `ContainersNotFound`
2297 continue;
2298 };
2299 let current = self.state.lock().container_full_diff(h.container_idx());
2300 let mut kept = FxHashSet::default();
2301 let edit = crate::handler::align_full_state(&h, diff, current, &mut kept);
2302 targets.extend(kept.iter().cloned());
2303 let entry = plan.aligned.entry(id.clone()).or_insert(PlannedAlignment {
2304 target: target.clone(),
2305 edit,
2306 kept,
2307 });
2308 entry.edit.as_ref()
2309 } else if recreated.contains(&target)
2310 || container_remap.contains_key(id)
2311 || !self.has_container(&target)
2312 || self.state.lock().get_reachable(&target)
2313 {
2314 Some(diff)
2315 } else {
2316 // The loop skips an entry whose target is unreachable before the
2317 // batch, unless an earlier entry revived it, which would have
2318 // made it a target above. So its marker writes don't count (the
2319 // batch order is up to the caller).
2320 None
2321 };
2322
2323 // A mergeable marker written by a Map diff makes its child a target
2324 if let Some(crate::event::Diff::Map(map)) = effective {
2325 for (key, v) in map.updated.iter() {
2326 if let Some(c) = v.value.as_ref().and_then(diff_value_container_id) {
2327 if c.is_mergeable() {
2328 let child =
2329 ContainerID::new_mergeable(&target, key, c.container_type());
2330 if recreated.contains(&target) {
2331 fresh_targets.insert(child);
2332 } else {
2333 targets.insert(child);
2334 }
2335 }
2336 }
2337 }
2338 }
2339 }
2340 plan
2341 }
2342
2343 /// `_apply_diff` recreates the containers inserted by a diff, but this
2344 /// version cannot create a container whose type it doesn't know
2345 /// ([ContainerType::Unknown], e.g. `cid:0@1:Unknown(9)`). Such values may
2346 /// only appear where nothing is created: mergeable map children (only the
2347 /// marker is written), MovableList moves of an element already in the
2348 /// list, diffs targeting an unknown container (a no-op), and diffs that
2349 /// `_apply_diff` skips because their target is unreachable.
2350 ///
2351 /// With a full-state `plan`, the planned edits are checked instead of the
2352 /// full states. Nothing is applied here, but the apply loop changes its own
2353 /// inputs as it goes, so this predicts those changes from the whole batch:
2354 ///
2355 /// - fresh: container values of Map/List diffs, the metas of recreated
2356 /// tree nodes, and mergeable children of those are recreated under a new
2357 /// id (`container_remap`). Their diffs then apply to a new, empty
2358 /// container and are never skipped.
2359 /// - revived: writing a mergeable child's marker makes it and its
2360 /// descendants reachable again.
2361 /// - removed: a diff that deletes a child container makes it and its
2362 /// descendants unreachable for the diffs after it.
2363 ///
2364 /// Every prediction errs towards checking a diff (a false rejection),
2365 /// never towards skipping it, so an accepted batch cannot fail on an
2366 /// unknown container half way through. Returns the batch ids of the
2367 /// entries holding unknown containers that it predicted to be skipped;
2368 /// `_apply_diff` asserts that in debug builds.
2369 fn check_apply_diff_creates_no_unknown_container(
2370 &self,
2371 diff: &DiffBatch,
2372 plan: Option<&FullStatePlan>,
2373 container_remap: &FxHashMap<ContainerID, ContainerID>,
2374 skip_unreachable: bool,
2375 movable_plans: &FxHashMap<ContainerID, crate::undo::movable_list::Plan>,
2376 ) -> LoroResult<FxHashSet<ContainerID>> {
2377 let mut predicted_skips = FxHashSet::default();
2378 if !diff.iter().any(|(_, d)| diff_has_unknown_value(d)) {
2379 return Ok(predicted_skips);
2380 }
2381
2382 // The batch as the loop applies it
2383 let entries: Vec<(&ContainerID, &crate::event::Diff)> = diff
2384 .iter()
2385 .filter_map(|(id, d)| match plan.and_then(|p| p.aligned.get(id)) {
2386 Some(p) => p.edit.as_ref().map(|edit| (id, edit)),
2387 None => Some((id, d)),
2388 })
2389 .collect();
2390 let empty = FxHashSet::default();
2391 let always_applied = plan.map_or(&empty, |p| &p.always_applied);
2392
2393 // A handler for an existing container, without materializing roots
2394 // that have no state yet
2395 let existing = |id: &ContainerID| -> Option<Handler> {
2396 if id.is_root() && !id.is_mergeable() && self.arena.id_to_idx(id).is_none() {
2397 return None;
2398 }
2399 self.has_container(id)
2400 .then(|| Handler::new_attached(id.clone(), self.clone()))
2401 };
2402
2403 let mut fresh: FxHashSet<ContainerID> = plan.map(|p| p.fresh.clone()).unwrap_or_default();
2404 let mut revived: FxHashSet<ContainerID> = FxHashSet::default();
2405 // Container -> index of the first diff in the batch that removes it
2406 let mut removed: FxHashMap<ContainerID, usize> = FxHashMap::default();
2407 for (i, &(id, diff)) in entries.iter().enumerate() {
2408 let (target, _) = resolve_container_remap(id.clone(), container_remap);
2409 let handler = if fresh.contains(id) || target.is_unknown() {
2410 None
2411 } else {
2412 existing(&target)
2413 };
2414 match diff {
2415 crate::event::Diff::Map(map) => {
2416 let map_handler = handler.and_then(|h| h.into_map().ok());
2417 for (key, v) in map.updated.iter() {
2418 if let Some(LoroValue::Container(old)) =
2419 map_handler.as_ref().and_then(|m| m.get(key))
2420 {
2421 if !old.is_mergeable() {
2422 removed.entry(old).or_insert(i);
2423 }
2424 }
2425 if let Some(c) = v.value.as_ref().and_then(diff_value_container_id) {
2426 if c.is_mergeable() {
2427 // The loop writes the marker of `mergeable(target,
2428 // key)` and remaps `c` to it. Unless that is `c`
2429 // itself, the child is another container: new (under a
2430 // recreated map) or one this check can't see into (a
2431 // parent the undo manager already remapped, or a value
2432 // under another key). Check it as new and empty.
2433 let effective =
2434 ContainerID::new_mergeable(&target, key, c.container_type());
2435 if fresh.contains(id)
2436 || effective
2437 != resolve_container_remap(c.clone(), container_remap).0
2438 {
2439 fresh.insert(c.clone());
2440 }
2441 revived.insert(c);
2442 } else {
2443 fresh.insert(c);
2444 }
2445 }
2446 }
2447 }
2448 crate::event::Diff::List(delta) => {
2449 if let Some(native) = movable_plans.get(id).and_then(|p| p.preflight()) {
2450 fresh.extend(native.creates.iter().cloned());
2451 for child in &native.removes {
2452 removed.entry(child.clone()).or_insert(i);
2453 }
2454 continue;
2455 }
2456 let values: FxHashSet<ContainerID> = inserted_container_ids(delta)
2457 .map(|c| resolve_container_remap(c, container_remap).0)
2458 .collect();
2459 let get = |i: usize| match &handler {
2460 Some(Handler::List(l)) => l.get(i),
2461 Some(Handler::MovableList(l)) => l.get(i),
2462 _ => None,
2463 };
2464 if handler.is_some() {
2465 let movable = matches!(handler, Some(Handler::MovableList(_)));
2466 let mut index = 0;
2467 for item in delta.iter() {
2468 match item {
2469 loro_delta::DeltaItem::Retain { len, .. } => index += len,
2470 loro_delta::DeltaItem::Replace { delete, .. } => {
2471 for j in index..index + delete {
2472 if let Some(LoroValue::Container(old)) = get(j) {
2473 // A MovableList may move it instead
2474 if !movable || !values.contains(&old) {
2475 removed.entry(old).or_insert(i);
2476 }
2477 }
2478 }
2479 index += delete;
2480 }
2481 }
2482 }
2483 }
2484 // Moves are counted too, which can only check more
2485 fresh.extend(inserted_container_ids(delta));
2486 }
2487 crate::event::Diff::Tree(tree) => {
2488 for item in tree.diff.iter() {
2489 let meta = item.target.associated_meta_container();
2490 if matches!(item.action, crate::delta::TreeExternalDiff::Delete { .. }) {
2491 if handler.is_some() && !container_remap.contains_key(&meta) {
2492 removed.entry(meta).or_insert(i);
2493 }
2494 } else {
2495 fresh.insert(meta);
2496 }
2497 }
2498 }
2499 _ => {}
2500 }
2501 }
2502
2503 for (i, &(id, diff)) in entries.iter().enumerate() {
2504 if !diff_has_unknown_value(diff) {
2505 continue;
2506 }
2507 let (target, remapped) = resolve_container_remap(id.clone(), container_remap);
2508 if target.is_unknown() {
2509 // `Handler::Unknown` ignores diffs
2510 continue;
2511 }
2512
2513 let handler = if fresh.contains(id) {
2514 None
2515 } else {
2516 existing(&target)
2517 };
2518 if handler.is_some()
2519 && skip_unreachable
2520 && !remapped
2521 && !always_applied.contains(&target)
2522 {
2523 let chain = self.arena_ancestors_and_self(&target);
2524 let skipped = !chain.iter().any(|c| revived.contains(c))
2525 && (!self.state.lock().get_reachable(&target)
2526 || chain.iter().any(|c| removed.get(c).is_some_and(|&j| j < i)));
2527 if skipped {
2528 // `_apply_diff` skips this diff
2529 predicted_skips.insert(id.clone());
2530 continue;
2531 }
2532 }
2533
2534 let created = match diff {
2535 crate::event::Diff::Map(map) => map
2536 .updated
2537 .values()
2538 .filter_map(|v| v.value.as_ref().and_then(diff_value_container_id))
2539 .find(|c| c.is_unknown() && !c.is_mergeable()),
2540 crate::event::Diff::List(delta)
2541 if movable_plans.get(id).and_then(|p| p.preflight()).is_some() =>
2542 {
2543 let _ = delta;
2544 movable_plans[id]
2545 .preflight()
2546 .and_then(|p| p.creates.iter().find(|c| c.is_unknown()).cloned())
2547 }
2548 crate::event::Diff::List(delta) => match &handler {
2549 // Only an existing MovableList can move an element instead
2550 // of creating it
2551 Some(Handler::MovableList(list)) => {
2552 list.unknown_container_created_by_delta(delta, container_remap)?
2553 }
2554 _ => inserted_container_ids(delta).find(|c| c.is_unknown()),
2555 },
2556 _ => None,
2557 };
2558 if let Some(c) = created {
2559 return Err(crate::handler::unknown_container_creation_err(
2560 c.container_type(),
2561 ));
2562 }
2563 }
2564
2565 Ok(predicted_skips)
2566 }
2567
2568 /// `id` and its ancestors by arena parent, whether they are visible or
2569 /// not (a hidden mergeable child has no path from a root, but its
2570 /// descendants become reachable again when a batch revives it).
2571 fn arena_ancestors_and_self(&self, id: &ContainerID) -> Vec<ContainerID> {
2572 let mut ans = Vec::new();
2573 let idx = match self.arena.id_to_idx(id) {
2574 Some(idx) => Some(idx),
2575 None => {
2576 let mut state = self.state.lock();
2577 if state.does_container_exist(id) {
2578 state.ensure_container(id);
2579 }
2580 drop(state);
2581 self.arena.id_to_idx(id)
2582 }
2583 };
2584 if let Some(mut idx) = idx {
2585 while let Some(parent) = self.arena.get_parent(idx) {
2586 if let Some(parent_id) = self.arena.idx_to_id(parent) {
2587 ans.push(parent_id);
2588 }
2589 idx = parent;
2590 }
2591 }
2592 ans.push(id.clone());
2593 ans
2594 }
2595
2596 /// This is for debugging purpose. It will travel the whole oplog
2597 #[inline]
2598 pub fn diagnose_size(&self) {
2599 self.oplog().lock().diagnose_size();
2600 }
2601
2602 #[inline]
2603 pub fn oplog_frontiers(&self) -> Frontiers {
2604 self.oplog().lock().frontiers().clone()
2605 }
2606
2607 #[inline]
2608 pub fn state_frontiers(&self) -> Frontiers {
2609 self.state.lock().frontiers.clone()
2610 }
2611
2612 /// - Ordering::Less means self is less than target or parallel
2613 /// - Ordering::Equal means versions equal
2614 /// - Ordering::Greater means self's version is greater than target
2615 #[inline]
2616 pub fn cmp_with_frontiers(&self, other: &Frontiers) -> Ordering {
2617 self.oplog().lock().cmp_with_frontiers(other)
2618 }
2619
2620 /// Compare two [Frontiers] causally.
2621 ///
2622 /// If one of the [Frontiers] are not included, it will return [FrontiersNotIncluded].
2623 #[inline]
2624 pub fn cmp_frontiers(
2625 &self,
2626 a: &Frontiers,
2627 b: &Frontiers,
2628 ) -> Result<Option<Ordering>, FrontiersNotIncluded> {
2629 let oplog = self.oplog.lock();
2630 oplog
2631 .check_history_parsable()
2632 .map_err(FrontiersNotIncluded::unreadable)?;
2633 oplog.cmp_frontiers(a, b)
2634 }
2635
2636 pub fn subscribe_root(&self, callback: Subscriber) -> Subscription {
2637 let mut state = self.state.lock();
2638 if !state.is_recording() {
2639 state.start_recording();
2640 }
2641
2642 self.observer.subscribe_root(callback)
2643 }
2644
2645 pub fn subscribe(&self, container_id: &ContainerID, callback: Subscriber) -> Subscription {
2646 let mut state = self.state.lock();
2647 if !state.is_recording() {
2648 state.start_recording();
2649 }
2650
2651 self.observer.subscribe(container_id, callback)
2652 }
2653
2654 pub fn subscribe_local_update(&self, callback: LocalUpdateCallback) -> Subscription {
2655 let (sub, activate) = self.local_update_subs.inner().insert((), callback);
2656 activate();
2657 sub
2658 }
2659
2660 // PERF: opt
2661 #[tracing::instrument(skip_all)]
2662 pub fn import_batch(&self, bytes: &[Vec<u8>]) -> LoroResult<ImportStatus> {
2663 self.import_batch_with_history_mode(bytes, false)
2664 }
2665
2666 /// Like [`Self::import_batch`]. `json_lossy` is the same opt-in as
2667 /// [`Self::import_with_history_mode`].
2668 pub fn import_batch_with_history_mode(
2669 &self,
2670 bytes: &[Vec<u8>],
2671 json_lossy: bool,
2672 ) -> LoroResult<ImportStatus> {
2673 let values = if json_lossy {
2674 ImportedValues::JsonLossy
2675 } else {
2676 ImportedValues::Exact
2677 };
2678 if bytes.is_empty() {
2679 return Ok(ImportStatus::default());
2680 }
2681
2682 if bytes.len() == 1 {
2683 return self.import_with_history_mode(&bytes[0], Default::default(), json_lossy);
2684 }
2685
2686 let mut success = VersionRange::default();
2687 let mut meta_arr = bytes
2688 .iter()
2689 .map(|b| Ok((LoroDoc::decode_import_blob_meta(b, false)?, b)))
2690 .collect::<LoroResult<Vec<(ImportBlobMetadata, &Vec<u8>)>>>()?;
2691 meta_arr.sort_by(|a, b| {
2692 a.0.mode
2693 .cmp(&b.0.mode)
2694 .then(b.0.change_num.cmp(&a.0.change_num))
2695 });
2696
2697 let (options, txn) = self.implicit_commit_then_stop();
2698 // Why we should keep locking `txn` here
2699 //
2700 // In a multi-threaded environment, `import_batch` used to drop the txn lock
2701 // (via `commit_then_stop` + `drop(txn)`) and call `detach()`/`checkout_to_latest()`
2702 // around the batch import. That created a race where another thread could
2703 // start or renew the auto-commit txn and perform local edits while we were
2704 // importing and temporarily detached. Those interleaved local edits could
2705 // violate invariants between `OpLog` and `DocState` (e.g., state being
2706 // updated when we expect it not to, missed events, or inconsistent
2707 // frontiers), as exposed by the loom test `local_edits_during_batch_import`.
2708 //
2709 // The fix is to hold the txn mutex for the entire critical section:
2710 // - Stop the current txn and keep the mutex guard.
2711 // - Force-detach with `set_detached(true)` (avoids `detach()` side effects),
2712 // then run each `_import_with(...)` while detached so imports only touch
2713 // the `OpLog`.
2714 // - After importing, reattach by checking out to latest and renew the txn in
2715 // `BatchImportGuard::finish`, which keeps the mutex held while (re)starting
2716 // the auto-commit txn.
2717 //
2718 // Holding the lock ensures no concurrent thread can create/renew a txn and
2719 // do local edits in the middle of the batch import, making the whole
2720 // operation atomic with respect to local edits.
2721 //
2722 // The force-detach must be undone on *every* exit path. A blob that returns
2723 // `Err`, and just as importantly a panic out of decode/apply, used to skip the
2724 // reattach below and strand the document in detached mode, where it silently
2725 // stops reflecting later imports and local edits. `BatchImportGuard::finish`
2726 // owns that cleanup and the blob loop runs inside `catch_unwind` so it also
2727 // runs before a panic is re-raised.
2728 let was_attached = !self.is_detached();
2729 // A full snapshot can initialize state lazily, just as in `import`.
2730 // Pending-only history must not be replaced by the snapshot, either.
2731 // Keep the pre-snapshot arena checkpoint so a failed closing checkout
2732 // can discard the snapshot's state as well as the following updates.
2733 let snapshot_checkpoint = if was_attached
2734 && meta_arr[0].0.mode == encoding::EncodedBlobMode::Snapshot
2735 {
2736 let oplog = self.oplog.lock();
2737 let mut state = self.state.lock();
2738 (oplog.is_empty() && oplog.pending_changes.is_empty() && state.can_import_snapshot())
2739 .then(|| BatchSnapshotRollback {
2740 arena: oplog.arena.checkpoint_for_rollback(),
2741 empty_containers: state.store.iter_all_container_ids().collect(),
2742 })
2743 } else {
2744 None
2745 };
2746 self.set_detached(true);
2747 {
2748 let mut oplog = self.oplog.lock();
2749 oplog.batch_importing = true;
2750 // The history-only path touches just the `OpLog`, so a rollback
2751 // scope spanning the whole batch lets `BatchImportGuard::finish` restore
2752 // the pre-batch version if the closing reattach cannot apply the imported
2753 // changes to `DocState`. Without it the doc would be left detached at a
2754 // version it can never check out.
2755 if was_attached && snapshot_checkpoint.is_none() {
2756 oplog.begin_import_rollback();
2757 }
2758 }
2759
2760 let mut guard = BatchImportGuard {
2761 doc: self,
2762 was_attached,
2763 txn: Some(txn),
2764 options,
2765 snapshot_checkpoint,
2766 #[cfg(debug_assertions)]
2767 finished: false,
2768 };
2769
2770 // Catch here rather than in a `Drop`: releasing a mutex guard while a panic is
2771 // in flight poisons that mutex, so the reattach has to happen after unwinding
2772 // has stopped. Under `panic = "abort"` (e.g. wasm) a genuine panic still
2773 // terminates execution; only returned errors can be recovered there.
2774 let loop_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2775 let mut err = None;
2776 for (index, (_meta, data)) in meta_arr.into_iter().enumerate() {
2777 #[cfg(test)]
2778 take_panic_at_batch_import_blob_for_test();
2779 let result = if let Some(checkpoint) =
2780 guard.snapshot_checkpoint.as_ref().filter(|_| index == 0)
2781 {
2782 // Do not emit the snapshot event until the closing checkout
2783 // succeeds. Its state is part of the batch's rollback scope.
2784 let result = parse_header_and_body(data, true).and_then(|parsed| {
2785 decode_snapshot(guard.doc, parsed.mode, parsed.body, Default::default())
2786 });
2787 if result.is_err() {
2788 // The standalone decoder resets a failed snapshot to an
2789 // empty store. Restore pre-existing empty handles, too.
2790 let mut state = guard.doc.state.lock();
2791 for id in &checkpoint.empty_containers {
2792 state.ensure_container(id);
2793 }
2794 }
2795 let mut oplog = guard.doc.oplog.lock();
2796 // Snapshot decoding installs a new DAG; start the ordinary
2797 // suffix journal only after that installation (or its reset).
2798 oplog.batch_importing = true;
2799 oplog.begin_import_rollback();
2800 result
2801 } else {
2802 guard
2803 .doc
2804 .import_without_emitting(data, Default::default(), values)
2805 };
2806 match result {
2807 Ok(s) => {
2808 for (peer, (start, end)) in s.success.iter() {
2809 match success.0.entry(*peer) {
2810 Entry::Occupied(mut e) => {
2811 e.get_mut().1 = *end.max(&e.get().1);
2812 }
2813 Entry::Vacant(e) => {
2814 e.insert((*start, *end));
2815 }
2816 }
2817 }
2818 }
2819 Err(e) => {
2820 err = Some(e);
2821 }
2822 }
2823 }
2824 err
2825 }));
2826
2827 let err = match loop_result {
2828 Ok(err) => err,
2829 Err(payload) => {
2830 // Reattach first, then re-raise the original panic. `finish` can panic
2831 // itself when the interrupted blob poisoned a doc lock; that document
2832 // is unusable either way, so keep the original payload.
2833 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2834 let _ = guard.finish();
2835 }));
2836 std::panic::resume_unwind(payload);
2837 }
2838 };
2839
2840 let pending = guard.finish()?;
2841 if let Some(err) = err {
2842 return Err(err);
2843 }
2844
2845 Ok(ImportStatus {
2846 success,
2847 pending: if pending.is_empty() {
2848 None
2849 } else {
2850 Some(pending)
2851 },
2852 })
2853 }
2854
2855 /// Get shallow value of the document.
2856 #[inline]
2857 pub fn get_value(&self) -> LoroValue {
2858 self.state.lock().get_value()
2859 }
2860
2861 /// Get deep value of the document.
2862 #[inline]
2863 pub fn get_deep_value(&self) -> LoroValue {
2864 self.state.lock().get_deep_value()
2865 }
2866
2867 /// Get deep value of the document with container id
2868 #[inline]
2869 pub fn get_deep_value_with_id(&self) -> LoroValue {
2870 self.state.lock().get_deep_value_with_id()
2871 }
2872
2873 pub fn checkout_to_latest(&self) {
2874 let (options, _guard) = self.implicit_commit_then_stop();
2875 if !self.is_detached() {
2876 drop(_guard);
2877 self.renew_txn_if_auto_commit(options);
2878 return;
2879 }
2880
2881 self._checkout_to_latest_without_commit(true)
2882 .expect("checkout to oplog frontiers should succeed");
2883 self.emit_events();
2884 drop(_guard);
2885 self.renew_txn_if_auto_commit(options);
2886 }
2887
2888 /// NOTE: The caller of this method should ensure the txn is locked and set to None
2889 pub(crate) fn _checkout_to_latest_without_commit(
2890 &self,
2891 to_commit_then_renew: bool,
2892 ) -> LoroResult<()> {
2893 self._checkout_to_latest_without_commit_with_event(
2894 to_commit_then_renew,
2895 "checkout".into(),
2896 EventTriggerKind::Checkout,
2897 )
2898 }
2899
2900 pub(crate) fn _checkout_to_latest_without_commit_as_import(
2901 &self,
2902 to_commit_then_renew: bool,
2903 origin: InternalString,
2904 ) -> LoroResult<()> {
2905 self._checkout_to_latest_without_commit_with_event(
2906 to_commit_then_renew,
2907 origin,
2908 EventTriggerKind::Import,
2909 )
2910 }
2911
2912 fn _checkout_to_latest_without_commit_with_event(
2913 &self,
2914 to_commit_then_renew: bool,
2915 origin: InternalString,
2916 triggered_by: EventTriggerKind,
2917 ) -> LoroResult<()> {
2918 tracing::info_span!("CheckoutToLatest", peer = self.peer_id()).in_scope(|| {
2919 let f = self.oplog_frontiers();
2920 let this = &self;
2921 let frontiers = &f;
2922 this._checkout_without_emitting_with_event(
2923 frontiers,
2924 false,
2925 to_commit_then_renew,
2926 origin,
2927 triggered_by,
2928 )?;
2929 // We don't need to shrink frontiers because oplog's frontiers are already shrinked.
2930 this.emit_events();
2931 if this.config.detached_editing() {
2932 this.renew_peer_id();
2933 }
2934
2935 self.set_detached(false);
2936 Ok(())
2937 })
2938 }
2939
2940 /// Checkout [DocState] to a specific version.
2941 ///
2942 /// This will make the current [DocState] detached from the latest version of [OpLog].
2943 /// Any further import will not be reflected on the [DocState], until user call [LoroDoc::attach()]
2944 pub fn checkout(&self, frontiers: &Frontiers) -> LoroResult<()> {
2945 // Checked here and not in `_checkout_without_emitting`: undo, `checkout_to_latest`
2946 // and the exporters call that and cannot return this error.
2947 self.oplog.lock().check_history_parsable()?;
2948 let was_detached = self.is_detached();
2949 let (options, guard) = self.implicit_commit_then_stop();
2950 let result = self._checkout_without_emitting(frontiers, true, true);
2951 if result.is_ok() {
2952 self.emit_events();
2953 }
2954 drop(guard);
2955 if self.config.detached_editing() {
2956 if result.is_ok() {
2957 self.renew_peer_id();
2958 }
2959 self.renew_txn_if_auto_commit(options);
2960 } else if result.is_err() {
2961 if !was_detached {
2962 self.renew_txn_if_auto_commit(options);
2963 }
2964 } else if !self.is_detached() {
2965 self.renew_txn_if_auto_commit(options);
2966 }
2967
2968 result
2969 }
2970
2971 /// NOTE: The caller of this method should ensure the txn is locked and set to None
2972 #[instrument(level = "info", skip(self))]
2973 pub(crate) fn _checkout_without_emitting(
2974 &self,
2975 frontiers: &Frontiers,
2976 to_shrink_frontiers: bool,
2977 to_commit_then_renew: bool,
2978 ) -> Result<(), LoroError> {
2979 self._checkout_without_emitting_with_event(
2980 frontiers,
2981 to_shrink_frontiers,
2982 to_commit_then_renew,
2983 "checkout".into(),
2984 EventTriggerKind::Checkout,
2985 )
2986 }
2987
2988 fn _checkout_without_emitting_with_event(
2989 &self,
2990 frontiers: &Frontiers,
2991 to_shrink_frontiers: bool,
2992 _to_commit_then_renew: bool,
2993 origin: InternalString,
2994 triggered_by: EventTriggerKind,
2995 ) -> Result<(), LoroError> {
2996 if !self.txn.is_locked() {
2997 return Err(LoroError::TransactionError(
2998 "checkout requires the transaction mutex to be held"
2999 .to_string()
3000 .into_boxed_str(),
3001 ));
3002 }
3003 let from_frontiers = self.state_frontiers();
3004 loro_common::info!(
3005 "checkout from={:?} to={:?} cur_vv={:?}",
3006 from_frontiers,
3007 frontiers,
3008 self.oplog_vv()
3009 );
3010
3011 if &from_frontiers == frontiers {
3012 self.set_detached(frontiers != &self.oplog_frontiers());
3013 return Ok(());
3014 }
3015
3016 let oplog = self.oplog.lock();
3017 if oplog.dag.is_before_shallow_root(frontiers) {
3018 return Err(LoroError::SwitchToVersionBeforeShallowRoot);
3019 }
3020
3021 let frontiers = if to_shrink_frontiers {
3022 crate::version::try_shrink_frontiers(frontiers, &oplog.dag)?
3023 } else {
3024 frontiers.clone()
3025 };
3026
3027 if from_frontiers == frontiers {
3028 return Ok(());
3029 }
3030
3031 let mut state = self.state.lock();
3032 let mut calc = self.diff_calculator.lock();
3033 for i in frontiers.iter() {
3034 if !oplog.dag.contains(i) {
3035 return Err(LoroError::FrontiersNotFound(i));
3036 }
3037 }
3038
3039 let before = oplog
3040 .dag
3041 .try_frontiers_to_vv(&state.frontiers)?
3042 .ok_or_else(|| {
3043 LoroError::NotFoundError(
3044 format!(
3045 "Cannot find the current state version {:?}",
3046 state.frontiers
3047 )
3048 .into_boxed_str(),
3049 )
3050 })?;
3051 let Some(after) = &oplog.dag.try_frontiers_to_vv(&frontiers)? else {
3052 return Err(LoroError::NotFoundError(
3053 format!("Cannot find the specified version {:?}", frontiers).into_boxed_str(),
3054 ));
3055 };
3056
3057 let (diff, diff_mode) = calc.try_calc_diff_internal(
3058 &oplog,
3059 &before,
3060 &state.frontiers,
3061 after,
3062 &frontiers,
3063 None,
3064 )?;
3065 self.set_detached(true);
3066 state.apply_diff(
3067 InternalDocDiff {
3068 origin,
3069 diff: Cow::Owned(diff),
3070 by: triggered_by,
3071 new_version: Cow::Owned(frontiers.clone()),
3072 },
3073 diff_mode,
3074 )?;
3075 // Only at the latest version: every root the calculator has seen is then in
3076 // the history of the target version. Checking out an older version keeps
3077 // whatever roots the state already had.
3078 if after == oplog.vv() {
3079 materialize_touched_roots(&mut state, &calc, &oplog.arena);
3080 }
3081
3082 Ok(())
3083 }
3084
3085 #[inline]
3086 pub fn vv_to_frontiers(&self, vv: &VersionVector) -> Frontiers {
3087 self.oplog.lock().dag.vv_to_frontiers(vv)
3088 }
3089
3090 #[inline]
3091 pub fn frontiers_to_vv(&self, frontiers: &Frontiers) -> Option<VersionVector> {
3092 self.oplog.lock().dag.frontiers_to_vv(frontiers)
3093 }
3094
3095 /// Converts frontiers to a version vector, reporting unreadable history.
3096 pub fn try_frontiers_to_vv(&self, frontiers: &Frontiers) -> LoroResult<Option<VersionVector>> {
3097 let oplog = self.oplog.lock();
3098 oplog.check_history_parsable()?;
3099 oplog.dag.try_frontiers_to_vv(frontiers)
3100 }
3101
3102 /// Converts a version vector to frontiers, reporting unreadable history.
3103 pub fn try_vv_to_frontiers(&self, vv: &VersionVector) -> LoroResult<Frontiers> {
3104 let oplog = self.oplog.lock();
3105 oplog.check_history_parsable()?;
3106 oplog.dag.try_vv_to_frontiers(vv)
3107 }
3108
3109 /// Removes redundant frontiers, reporting unreadable history or an absent id.
3110 pub fn try_minimize_frontiers(&self, frontiers: &Frontiers) -> LoroResult<Frontiers> {
3111 let oplog = self.oplog.lock();
3112 oplog.check_history_parsable()?;
3113 crate::version::try_shrink_frontiers(frontiers, &oplog.dag)
3114 }
3115
3116 /// Reads change metadata, distinguishing unreadable history from an absent id.
3117 pub fn try_get_change(&self, id: ID) -> LoroResult<Option<ChangeMeta>> {
3118 let oplog = self.oplog.lock();
3119 let change = oplog.try_get_change_at(id)?;
3120 Ok(change.as_deref().map(ChangeMeta::from_change))
3121 }
3122
3123 /// Import ops from other doc.
3124 ///
3125 /// After `a.merge(b)` and `b.merge(a)`, `a` and `b` will have the same content if they are in attached mode.
3126 pub fn merge(&self, other: &Self) -> LoroResult<ImportStatus> {
3127 let updates = other
3128 .export(ExportMode::updates(&self.oplog_vv()))
3129 .map_err(LoroError::from)?;
3130 self.import(&updates)
3131 }
3132
3133 pub(crate) fn arena(&self) -> &SharedArena {
3134 &self.arena
3135 }
3136
3137 #[inline]
3138 pub fn len_ops(&self) -> usize {
3139 if self.oplog.can_lock_in_this_thread() {
3140 return self.oplog.lock().visible_op_count_exact();
3141 }
3142
3143 self.visible_op_count.load(Acquire)
3144 }
3145
3146 #[inline]
3147 pub fn len_changes(&self) -> usize {
3148 let oplog = self.oplog.lock();
3149 oplog.len_changes()
3150 }
3151
3152 pub fn config(&self) -> &Configure {
3153 &self.config
3154 }
3155
3156 /// This method compare the consistency between the current doc state
3157 /// and the state calculated by diff calculator from beginning.
3158 ///
3159 /// Panic when it's not consistent
3160 pub fn check_state_diff_calc_consistency_slow(&self) {
3161 // #[cfg(any(test, debug_assertions, feature = "test_utils"))]
3162 {
3163 static IS_CHECKING: std::sync::atomic::AtomicBool =
3164 std::sync::atomic::AtomicBool::new(false);
3165 if IS_CHECKING.load(std::sync::atomic::Ordering::Acquire) {
3166 return;
3167 }
3168
3169 IS_CHECKING.store(true, std::sync::atomic::Ordering::Release);
3170 let peer_id = self.peer_id();
3171 let s = info_span!("CheckStateDiffCalcConsistencySlow", ?peer_id);
3172 let _g = s.enter();
3173 let options = self.implicit_commit_then_stop().0;
3174 self.oplog.lock().check_dag_correctness();
3175 if self.is_shallow() {
3176 // For shallow documents, we cannot replay from the beginning as the history is not complete.
3177 //
3178 // Instead, we:
3179 // 1. Export the initial state from the GC snapshot.
3180 // 2. Create a new document and import the initial snapshot.
3181 // 3. Export updates from the shallow start version vector to the current version.
3182 // 4. Import these updates into the new document.
3183 // 5. Compare the states of the new document and the current document.
3184
3185 // Step 1: Export the initial state from the GC snapshot.
3186 let initial_snapshot = self
3187 .export(ExportMode::state_only(Some(
3188 &self.shallow_since_frontiers(),
3189 )))
3190 .unwrap();
3191
3192 // Step 2: Create a new document and import the initial snapshot.
3193 let doc = LoroDoc::new();
3194 doc.import(&initial_snapshot).unwrap();
3195 self.checkout(&self.shallow_since_frontiers()).unwrap();
3196 assert_eq!(self.get_deep_value(), doc.get_deep_value());
3197
3198 // Step 3: Export updates since the shallow start version vector to the current version.
3199 let updates = self.export(ExportMode::all_updates()).unwrap();
3200
3201 // Step 4: Import these updates into the new document.
3202 doc.import(&updates).unwrap();
3203 self.checkout_to_latest();
3204
3205 // Step 5: Checkout to the current state's frontiers and compare the states.
3206 // doc.checkout(&self.state_frontiers()).unwrap();
3207 assert_eq!(doc.get_deep_value(), self.get_deep_value());
3208 let mut calculated_state = doc.app_state().lock();
3209 let mut current_state = self.app_state().lock();
3210 current_state.check_is_the_same(&mut calculated_state);
3211 } else {
3212 let f = self.state_frontiers();
3213 let vv = self.oplog().lock().dag.frontiers_to_vv(&f).unwrap();
3214 let bytes = self.export(ExportMode::updates_till(&vv)).unwrap();
3215 let doc = Self::new();
3216 doc.import(&bytes).unwrap();
3217 let mut calculated_state = doc.app_state().lock();
3218 let mut current_state = self.app_state().lock();
3219 current_state.check_is_the_same(&mut calculated_state);
3220 }
3221
3222 self.renew_txn_if_auto_commit(options);
3223 IS_CHECKING.store(false, std::sync::atomic::Ordering::Release);
3224 }
3225 }
3226
3227 pub fn query_pos(&self, pos: &Cursor) -> Result<PosQueryResult, CannotFindRelativePosition> {
3228 match self.query_pos_internal(pos, true) {
3229 Ok(ans) => Ok(ans),
3230 Err(QueryPosError::Missing(err)) => Err(err),
3231 // `CannotFindRelativePosition` is `Copy` and has no room for the
3232 // decode error. `HistoryUnreadable` is the non-panicking mapping.
3233 Err(QueryPosError::History(_)) => Err(CannotFindRelativePosition::HistoryUnreadable),
3234 }
3235 }
3236
3237 /// [`query_pos`](Self::query_pos), preserving a decode error from unreadable history.
3238 pub fn try_get_cursor_pos(&self, pos: &Cursor) -> LoroResult<PosQueryResult> {
3239 match self.query_pos_internal(pos, true) {
3240 Ok(ans) => Ok(ans),
3241 Err(QueryPosError::History(err)) => Err(err),
3242 Err(QueryPosError::Missing(err)) => {
3243 Err(LoroError::NotFoundError(err.to_string().into_boxed_str()))
3244 }
3245 }
3246 }
3247
3248 /// Get position in a seq container
3249 pub(crate) fn query_pos_internal(
3250 &self,
3251 pos: &Cursor,
3252 ret_event_index: bool,
3253 ) -> Result<PosQueryResult, QueryPosError> {
3254 // Public construction and Serde can bypass Cursor::decode. Reject invalid
3255 // ids before taking document locks or tracing their history in the DAG.
3256 if pos.id.is_some_and(|id| id.counter < 0) {
3257 return Err(CannotFindRelativePosition::IdNotFound.into());
3258 }
3259
3260 if !self.has_container(&pos.container) {
3261 return Err(CannotFindRelativePosition::IdNotFound.into());
3262 }
3263
3264 // Cursors can only point into sequence containers
3265 if !matches!(
3266 pos.container.container_type(),
3267 ContainerType::Text | ContainerType::List | ContainerType::MovableList
3268 ) {
3269 return Err(CannotFindRelativePosition::IdNotFound.into());
3270 }
3271
3272 let mut state = self.state.lock();
3273 if let Some(ans) = state.get_relative_position(pos, ret_event_index) {
3274 Ok(PosQueryResult {
3275 update: None,
3276 current: AbsolutePosition {
3277 pos: ans,
3278 side: pos.side,
3279 },
3280 })
3281 } else {
3282 // We need to trace back to the version where the relative position is valid.
3283 // The optimal way to find that version is to have succ info like Automerge.
3284 //
3285 // But we don't have that info now, so an alternative way is to trace back
3286 // to version with frontiers of `[pos.id]`. But this may be very slow even if
3287 // the target is just deleted a few versions ago.
3288 //
3289 // What we need is to trace back to the latest version that deletes the target
3290 // id.
3291
3292 // commit the txn to make sure we can query the history correctly, preserving options
3293 drop(state);
3294 let result = self.with_barrier(|| {
3295 let oplog = self.oplog().lock();
3296 // TODO: assert pos.id is not unknown
3297 if let Some(id) = pos.id {
3298 // Ensure the container is registered if it exists lazily
3299 if oplog.arena.id_to_idx(&pos.container).is_none() {
3300 let mut s = self.state.lock();
3301 if !s.does_container_exist(&pos.container) {
3302 return Err(CannotFindRelativePosition::ContainerDeleted.into());
3303 }
3304 s.ensure_container(&pos.container);
3305 drop(s);
3306 }
3307 let idx = oplog.arena.id_to_idx(&pos.container).unwrap();
3308 // We know where the target id is when we trace back to the delete_op_id.
3309 let Some(delete_op_id) = find_last_delete_op(&oplog, id, idx)? else {
3310 if oplog.shallow_since_vv().includes_id(id) {
3311 return Err(CannotFindRelativePosition::HistoryCleared.into());
3312 }
3313
3314 tracing::error!("Cannot find id {}", id);
3315 return Err(CannotFindRelativePosition::IdNotFound.into());
3316 };
3317 // Should use persist mode so that it will force all the diff calculators to use the `checkout` mode
3318 let mut diff_calc = DiffCalculator::new(true);
3319 let before_frontiers: Frontiers = oplog.dag.find_deps_of_id(delete_op_id);
3320 let before = frontiers_to_vv_or_not_found(&oplog, &before_frontiers)?;
3321 // TODO: PERF: it doesn't need to calc the effects here
3322 diff_calc.try_calc_diff_internal(
3323 &oplog,
3324 &before,
3325 &before_frontiers,
3326 oplog.vv(),
3327 oplog.frontiers(),
3328 Some(&|target| idx == target),
3329 )?;
3330 // TODO: remove depth info
3331 let depth = self.arena.get_depth(idx);
3332 let (_, diff_calc) = &mut diff_calc.get_or_create_calc(idx, depth);
3333 match diff_calc {
3334 crate::diff_calc::ContainerDiffCalculator::Richtext(text) => {
3335 let c = text.get_id_latest_pos(id).unwrap();
3336 let new_pos = c.pos;
3337 let handler = self.get_text(&pos.container);
3338 let current_pos = handler.convert_entity_index_to_event_index(new_pos);
3339 Ok(PosQueryResult {
3340 update: handler.get_cursor(current_pos, c.side),
3341 current: AbsolutePosition {
3342 pos: current_pos,
3343 side: c.side,
3344 },
3345 })
3346 }
3347 crate::diff_calc::ContainerDiffCalculator::List(list) => {
3348 let c = list.get_id_latest_pos(id).unwrap();
3349 let new_pos = c.pos;
3350 let handler = self.get_list(&pos.container);
3351 Ok(PosQueryResult {
3352 update: handler.get_cursor(new_pos, c.side),
3353 current: AbsolutePosition {
3354 pos: new_pos,
3355 side: c.side,
3356 },
3357 })
3358 }
3359 crate::diff_calc::ContainerDiffCalculator::MovableList(list) => {
3360 let c = list.get_id_latest_pos(id).unwrap();
3361 let new_pos = c.pos;
3362 let handler = self.get_movable_list(&pos.container);
3363 let new_pos = handler.op_pos_to_user_pos(new_pos);
3364 Ok(PosQueryResult {
3365 update: handler.get_cursor(new_pos, c.side),
3366 current: AbsolutePosition {
3367 pos: new_pos,
3368 side: c.side,
3369 },
3370 })
3371 }
3372 crate::diff_calc::ContainerDiffCalculator::Tree(_) => unreachable!(),
3373 crate::diff_calc::ContainerDiffCalculator::Map(_) => unreachable!(),
3374 #[cfg(feature = "counter")]
3375 crate::diff_calc::ContainerDiffCalculator::Counter(_) => unreachable!(),
3376 crate::diff_calc::ContainerDiffCalculator::Unknown(_) => unreachable!(),
3377 }
3378 } else {
3379 match pos.container.container_type() {
3380 ContainerType::Text => {
3381 let text = self.get_text(&pos.container);
3382 Ok(PosQueryResult {
3383 update: Some(Cursor {
3384 id: None,
3385 container: text.id(),
3386 side: pos.side,
3387 origin_pos: text.len_unicode(),
3388 }),
3389 current: AbsolutePosition {
3390 pos: text.len_event(),
3391 side: pos.side,
3392 },
3393 })
3394 }
3395 ContainerType::List => {
3396 let list = self.get_list(&pos.container);
3397 Ok(PosQueryResult {
3398 update: Some(Cursor {
3399 id: None,
3400 container: list.id(),
3401 side: pos.side,
3402 origin_pos: list.len(),
3403 }),
3404 current: AbsolutePosition {
3405 pos: list.len(),
3406 side: pos.side,
3407 },
3408 })
3409 }
3410 ContainerType::MovableList => {
3411 let list = self.get_movable_list(&pos.container);
3412 Ok(PosQueryResult {
3413 update: Some(Cursor {
3414 id: None,
3415 container: list.id(),
3416 side: pos.side,
3417 origin_pos: list.len(),
3418 }),
3419 current: AbsolutePosition {
3420 pos: list.len(),
3421 side: pos.side,
3422 },
3423 })
3424 }
3425 ContainerType::Map | ContainerType::Tree | ContainerType::Unknown(_) => {
3426 unreachable!()
3427 }
3428 #[cfg(feature = "counter")]
3429 ContainerType::Counter => unreachable!(),
3430 }
3431 }
3432 });
3433 result
3434 }
3435 }
3436
3437 /// Free the history cache that is used for making checkout faster.
3438 ///
3439 /// If you use checkout that switching to an old/concurrent version, the history cache will be built.
3440 /// You can free it by calling this method.
3441 pub fn free_history_cache(&self) {
3442 self.oplog.lock().free_history_cache();
3443 }
3444
3445 /// Free the cached diff calculator that is used for checkout.
3446 pub fn free_diff_calculator(&self) {
3447 *self.diff_calculator.lock() = DiffCalculator::new(true);
3448 }
3449
3450 /// If you use checkout that switching to an old/concurrent version, the history cache will be built.
3451 /// You can free it by calling `free_history_cache`.
3452 pub fn has_history_cache(&self) -> bool {
3453 self.oplog.lock().has_history_cache()
3454 }
3455
3456 /// Encoded all ops and history cache to bytes and store them in the kv store.
3457 ///
3458 /// The parsed ops will be dropped
3459 #[inline]
3460 pub fn compact_change_store(&self) {
3461 self.with_barrier(|| {
3462 self.oplog.lock().compact_change_store();
3463 });
3464 }
3465
3466 /// Analyze the container info of the doc
3467 ///
3468 /// This is used for development and debugging
3469 #[inline]
3470 pub fn analyze(&self) -> DocAnalysis {
3471 DocAnalysis::analyze(self)
3472 }
3473
3474 /// Get the path from the root to the container
3475 pub fn get_path_to_container(&self, id: &ContainerID) -> Option<Vec<(ContainerID, Index)>> {
3476 let mut state = self.state.lock();
3477 if state.arena.id_to_idx(id).is_none() {
3478 if id.is_mergeable() {
3479 // Mergeable children can be logically active via the parent map marker
3480 // before they have their own encoded state. Register only the arena edge; do not
3481 // create container state or change `has_container` semantics.
3482 state.arena.register_container(id);
3483 } else if !state.does_container_exist(id) {
3484 return None;
3485 } else {
3486 state.ensure_container(id);
3487 }
3488 }
3489 // The registration above can already be gone: a failed import on another thread
3490 // rolls back every registration made since it began (loro-dev/loro#1164).
3491 let idx = state.arena.id_to_idx(id)?;
3492 state.get_path(idx)
3493 }
3494
3495 #[instrument(skip(self))]
3496 pub fn export(&self, mode: ExportMode) -> Result<Vec<u8>, LoroEncodeError> {
3497 self.export_inner(mode, true)
3498 }
3499
3500 /// With `reject_partial_history`, the export fails if a change block that cannot be
3501 /// parsed was found, before or during the export, instead of returning bytes that
3502 /// silently miss those changes. `fork` passes `false`: it has no error to return.
3503 pub(crate) fn export_inner(
3504 &self,
3505 mode: ExportMode,
3506 reject_partial_history: bool,
3507 ) -> Result<Vec<u8>, LoroEncodeError> {
3508 self.with_barrier(|| {
3509 if reject_partial_history {
3510 self.oplog.lock().check_history_parsable()?;
3511 }
3512 let ans = match mode {
3513 ExportMode::Snapshot => export_fast_snapshot(self)?,
3514 ExportMode::Updates { from } => export_fast_updates(self, &from),
3515 ExportMode::UpdatesInRange { spans } => {
3516 export_fast_updates_in_range(&self.oplog.lock(), spans.as_ref())
3517 }
3518 ExportMode::ShallowSnapshot(f) => export_shallow_snapshot(self, &f)?,
3519 ExportMode::StateOnly(f) => match f {
3520 Some(f) => export_state_only_snapshot(self, &f)?,
3521 None => export_state_only_snapshot(self, &self.oplog_frontiers())?,
3522 },
3523 ExportMode::SnapshotAt { version } => export_snapshot_at(self, &version)?,
3524 };
3525 if reject_partial_history {
3526 self.oplog.lock().check_history_parsable()?;
3527 }
3528 Ok(ans)
3529 })
3530 }
3531
3532 /// Export received remote changes waiting for causal dependencies, excluding
3533 /// local uncommitted operations. Returns `None` when nothing remains pending.
3534 /// This method does not commit, consume pending, emit events, or advance the
3535 /// applied version/frontiers. Ordinary snapshot/update exports omit pending.
3536 ///
3537 /// Capture snapshot and sidecar without concurrent document mutations/imports
3538 /// and persist them as one consistent checkpoint. `None` in a new checkpoint
3539 /// must clear its old sidecar; errors must not be treated as `None`. Restore
3540 /// snapshot then sidecar with ordinary `import`; actual missing dependencies
3541 /// must still arrive. This method cannot supply never-received predecessors
3542 /// and does not define cursor advancement or whether the document is synced.
3543 pub fn export_pending_updates(&self) -> Result<Option<Vec<u8>>, LoroEncodeError> {
3544 encoding::export_pending_updates(&self.oplog.lock())
3545 }
3546
3547 /// The doc only contains the history since the shallow history start version vector.
3548 ///
3549 /// This is empty if the doc is not shallow.
3550 ///
3551 /// The ops included by the shallow history start version vector are not in the doc.
3552 pub fn shallow_since_vv(&self) -> ImVersionVector {
3553 self.oplog().lock().shallow_since_vv().clone()
3554 }
3555
3556 pub fn shallow_since_frontiers(&self) -> Frontiers {
3557 self.oplog().lock().shallow_since_frontiers().clone()
3558 }
3559
3560 /// Check if the doc contains the full history.
3561 pub fn is_shallow(&self) -> bool {
3562 !self.oplog().lock().shallow_since_vv().is_empty()
3563 }
3564
3565 /// Get the number of operations in the pending transaction.
3566 ///
3567 /// The pending transaction is the one that is not committed yet. It will be committed
3568 /// after calling `doc.commit()`, `doc.export(mode)` or `doc.checkout(version)`.
3569 pub fn get_pending_txn_len(&self) -> usize {
3570 if let Some(txn) = self.txn.lock().as_ref() {
3571 txn.len()
3572 } else {
3573 0
3574 }
3575 }
3576
3577 #[inline]
3578 pub fn find_id_spans_between(&self, from: &Frontiers, to: &Frontiers) -> VersionVectorDiff {
3579 self.oplog().lock().dag.find_path(from, to)
3580 }
3581
3582 /// Finds operation spans between versions, reporting unreadable history.
3583 pub fn try_find_id_spans_between(
3584 &self,
3585 from: &Frontiers,
3586 to: &Frontiers,
3587 ) -> LoroResult<VersionVectorDiff> {
3588 let oplog = self.oplog.lock();
3589 oplog.check_history_parsable()?;
3590 for id in from.iter().chain(to.iter()) {
3591 if !oplog.vv().includes_id(id) {
3592 return Err(LoroError::FrontiersNotFound(id));
3593 }
3594 }
3595 oplog.dag.try_find_path(from, to)
3596 }
3597
3598 /// Subscribe to the first commit from a peer. Operations performed on the `LoroDoc` within this callback
3599 /// will be merged into the current commit.
3600 ///
3601 /// This is useful for managing the relationship between `PeerID` and user information.
3602 /// For example, you could store user names in a `LoroMap` using `PeerID` as the key and the `UserID` as the value.
3603 pub fn subscribe_first_commit_from_peer(
3604 &self,
3605 callback: FirstCommitFromPeerCallback,
3606 ) -> Subscription {
3607 let (s, enable) = self
3608 .first_commit_from_peer_subs
3609 .inner()
3610 .insert((), callback);
3611 enable();
3612 s
3613 }
3614
3615 /// Subscribe to the pre-commit event.
3616 ///
3617 /// The callback will be called when the changes are committed but not yet applied to the OpLog.
3618 /// You can modify the commit message and timestamp in the callback by [`ChangeModifier`].
3619 pub fn subscribe_pre_commit(&self, callback: PreCommitCallback) -> Subscription {
3620 let (s, enable) = self.pre_commit_subs.inner().insert((), callback);
3621 enable();
3622 s
3623 }
3624}
3625
3626/// A root container touched by any op in a doc's history is part of its value, even
3627/// when the ops add up to an empty value: the peer that wrote them created the root's
3628/// state with its first local op. A replay whose net diff for the root is empty never
3629/// creates that state, so create it here (loro-dev/loro#1156).
3630///
3631/// `calc` must have computed diffs whose ranges all lie in the history of the state's
3632/// new version.
3633fn materialize_touched_roots(state: &mut DocState, calc: &DiffCalculator, arena: &SharedArena) {
3634 for idx in calc.touched_containers() {
3635 if let Some(id) = arena.idx_to_id(idx) {
3636 if id.is_root() && !id.is_mergeable() && !state.store.contains_id(&id) {
3637 state.ensure_container(&id);
3638 }
3639 }
3640 }
3641}
3642
3643fn pending_root_containers_to_materialize(
3644 oplog: &OpLog,
3645 changes: &[Change],
3646) -> LoroResult<Vec<ContainerID>> {
3647 let mut roots = FxHashSet::default();
3648 for change in changes {
3649 if change.ctr_end() <= oplog.vv().get(&change.id.peer).copied().unwrap_or(0) {
3650 continue;
3651 }
3652
3653 if oplog.dag.is_before_shallow_root(&change.deps)
3654 || oplog
3655 .dag
3656 .try_get_change_lamport_from_deps(&change.deps)?
3657 .is_some()
3658 {
3659 continue;
3660 }
3661
3662 for op in change.ops.iter() {
3663 let id = oplog
3664 .arena
3665 .get_container_id(op.container)
3666 .expect("decoded op container should be registered");
3667 // Mergeable containers share the `ContainerID::Root` namespace but are logical
3668 // *children*: their existence is governed by their parent map's marker, and their
3669 // parent can be any (possibly not-yet-imported) map. Eagerly materializing one
3670 // while its causal dependencies are still pending has no valid parent edge to
3671 // resolve its depth against, which used to panic in `ContainerWrapper::new`.
3672 // They get materialized correctly through the normal diff path once the creating
3673 // change applies, so skip them here (mirrors the `!is_mergeable()` guard in
3674 // `ensure_root_container`). See the `mergeable_container::pending` regression test.
3675 if id.is_root() && !id.is_mergeable() {
3676 roots.insert(id);
3677 }
3678 }
3679 }
3680
3681 Ok(roots.into_iter().collect())
3682}
3683
3684/// Version vector of `frontiers`. `None` from the dag walk is a missing id, not
3685/// an empty vector and not a panic.
3686fn frontiers_to_vv_or_not_found(oplog: &OpLog, frontiers: &Frontiers) -> LoroResult<VersionVector> {
3687 match oplog.dag.try_frontiers_to_vv(frontiers)? {
3688 Some(vv) => Ok(vv),
3689 None => {
3690 for id in frontiers.iter() {
3691 if oplog.dag.try_get(id)?.is_none() {
3692 return Err(LoroError::FrontiersNotFound(id));
3693 }
3694 }
3695 Err(LoroError::NotFoundError(
3696 format!("Cannot find the specified version {frontiers:?}").into_boxed_str(),
3697 ))
3698 }
3699 }
3700}
3701
3702/// Identify a causally closed update component that can be applied without replaying unrelated
3703/// history. The first version is deliberately narrow: it accepts only scalar Map operations on
3704/// top-level roots that never appeared in the existing history.
3705fn isolated_scalar_root_batch(
3706 oplog: &OpLog,
3707 changes: &[Change],
3708) -> Option<(VersionVector, FxHashSet<InternalString>)> {
3709 if changes.is_empty() || !oplog.shallow_since_vv().is_empty() {
3710 return None;
3711 }
3712
3713 // Every peer in the batch must be brand new and contiguously covered from counter 0.
3714 // (`changes` is sorted by lamport, so one peer's changes appear in counter order.)
3715 let mut component_vv = VersionVector::new();
3716 let mut root_names = FxHashSet::default();
3717 for change in changes {
3718 let peer = change.id.peer;
3719 if oplog.vv().get(&peer).copied().unwrap_or(0) != 0 {
3720 return None;
3721 }
3722 let end = component_vv.entry(peer).or_insert(0);
3723 if change.id.counter != *end {
3724 return None;
3725 }
3726 *end = change.ctr_end();
3727
3728 for op in change.ops.iter() {
3729 let cid = oplog.arena.idx_to_id(op.container)?;
3730 if cid.is_mergeable() {
3731 return None;
3732 }
3733 let ContainerID::Root {
3734 name,
3735 container_type: ContainerType::Map,
3736 } = cid
3737 else {
3738 return None;
3739 };
3740 let InnerContent::Map(map) = &op.content else {
3741 return None;
3742 };
3743 if let Some(value) = &map.value {
3744 if value.is_container()
3745 || loro_common::parse_mergeable_marker(
3746 &ContainerID::new_root(&name, ContainerType::Map),
3747 &map.key,
3748 value,
3749 )
3750 .is_some()
3751 {
3752 return None;
3753 }
3754 }
3755 root_names.insert(name);
3756 }
3757 }
3758
3759 // The batch must be causally closed: every dependency points inside the batch itself.
3760 for change in changes {
3761 for dep in change.deps.iter() {
3762 if dep.counter >= component_vv.get(&dep.peer).copied().unwrap_or(0) {
3763 return None;
3764 }
3765 }
3766 }
3767
3768 if oplog
3769 .change_store()
3770 .old_history_may_touch_root_names(&root_names)
3771 {
3772 return None;
3773 }
3774
3775 Some((component_vv, root_names))
3776}
3777
3778#[derive(Debug, thiserror::Error)]
3779#[non_exhaustive]
3780pub enum ChangeTravelError {
3781 #[error(transparent)]
3782 HistoryUnreadable(#[from] LoroError),
3783 #[error("Target id not found {0:?}")]
3784 TargetIdNotFound(ID),
3785 #[error("The shallow history of the doc doesn't include the target version")]
3786 TargetVersionNotIncluded,
3787}
3788
3789impl LoroDoc {
3790 pub fn travel_change_ancestors(
3791 &self,
3792 ids: &[ID],
3793 f: &mut dyn FnMut(ChangeMeta) -> ControlFlow<()>,
3794 ) -> Result<(), ChangeTravelError> {
3795 let (options, guard) = self.implicit_commit_then_stop();
3796 drop(guard);
3797 struct PendingNode(ChangeMeta);
3798 impl PartialEq for PendingNode {
3799 fn eq(&self, other: &Self) -> bool {
3800 self.0.lamport_last() == other.0.lamport_last() && self.0.id.peer == other.0.id.peer
3801 }
3802 }
3803
3804 impl Eq for PendingNode {}
3805 impl PartialOrd for PendingNode {
3806 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3807 Some(self.cmp(other))
3808 }
3809 }
3810
3811 impl Ord for PendingNode {
3812 fn cmp(&self, other: &Self) -> Ordering {
3813 self.0
3814 .lamport_last()
3815 .cmp(&other.0.lamport_last())
3816 .then_with(|| self.0.id.peer.cmp(&other.0.id.peer))
3817 }
3818 }
3819
3820 let ans = (|| {
3821 for id in ids {
3822 let op_log = &self.oplog().lock();
3823 op_log.check_history_parsable()?;
3824 if !op_log.vv().includes_id(*id) {
3825 return Err(ChangeTravelError::TargetIdNotFound(*id));
3826 }
3827 if op_log.dag.shallow_since_vv().includes_id(*id) {
3828 return Err(ChangeTravelError::TargetVersionNotIncluded);
3829 }
3830 }
3831
3832 let mut visited = FxHashSet::default();
3833 let mut pending: BinaryHeap<PendingNode> = BinaryHeap::new();
3834 for id in ids {
3835 let change = self
3836 .oplog()
3837 .lock()
3838 .try_get_change_at(*id)?
3839 .ok_or(ChangeTravelError::TargetIdNotFound(*id))?;
3840 pending.push(PendingNode(ChangeMeta::from_change(&change)));
3841 }
3842 while let Some(PendingNode(node)) = pending.pop() {
3843 let deps = node.deps.clone();
3844 if f(node).is_break() {
3845 break;
3846 }
3847
3848 for dep in deps.iter() {
3849 let Some(dep_node) = self.oplog().lock().try_get_change_at(dep)? else {
3850 continue;
3851 };
3852 if visited.contains(&dep_node.id) {
3853 continue;
3854 }
3855
3856 visited.insert(dep_node.id);
3857 pending.push(PendingNode(ChangeMeta::from_change(&dep_node)));
3858 }
3859 }
3860
3861 Ok(())
3862 })();
3863 self.renew_txn_if_auto_commit(options);
3864 ans
3865 }
3866
3867 pub fn get_changed_containers_in(&self, id: ID, len: usize) -> FxHashSet<ContainerID> {
3868 self.with_barrier(|| {
3869 let mut set = FxHashSet::default();
3870 let len = i64::try_from(len).unwrap_or(i64::MAX);
3871 let start = i64::from(id.counter);
3872 let end = start.saturating_add(len);
3873 if end <= 0 {
3874 return set;
3875 }
3876
3877 let start = start.max(0).min(i64::from(i32::MAX));
3878 let end = end.max(0).min(i64::from(i32::MAX));
3879 if start >= end {
3880 return set;
3881 }
3882
3883 {
3884 let oplog = self.oplog().lock();
3885 let span = IdSpan::new(id.peer, start as i32, end as i32);
3886 for op in oplog.iter_ops(span) {
3887 let id = oplog.arena.get_container_id(op.container()).unwrap();
3888 set.insert(id);
3889 }
3890 }
3891 set
3892 })
3893 }
3894
3895 /// Gets modified container IDs, reporting unreadable history.
3896 pub fn try_get_changed_containers_in(
3897 &self,
3898 id: ID,
3899 len: usize,
3900 ) -> LoroResult<FxHashSet<ContainerID>> {
3901 self.oplog.lock().check_history_parsable()?;
3902 let containers = self.get_changed_containers_in(id, len);
3903 self.oplog.lock().check_history_parsable()?;
3904 Ok(containers)
3905 }
3906
3907 pub fn delete_root_container(&self, cid: ContainerID) {
3908 if !cid.is_root() {
3909 return;
3910 }
3911
3912 // Do not treat "not in arena" as non-existence; consult state/kv
3913 if !self.has_container(&cid) {
3914 return;
3915 }
3916
3917 let Some(h) = self.get_handler(cid.clone()) else {
3918 return;
3919 };
3920
3921 self.config
3922 .deleted_root_containers
3923 .lock()
3924 .insert(cid.clone());
3925 if let Err(e) = h.clear() {
3926 self.config.deleted_root_containers.lock().remove(&cid);
3927 eprintln!("Failed to clear handler: {:?}", e);
3928 }
3929 }
3930
3931 pub fn set_hide_empty_root_containers(&self, hide: bool) {
3932 self.config
3933 .hide_empty_root_containers
3934 .store(hide, std::sync::atomic::Ordering::Relaxed);
3935 }
3936}
3937
3938pub(crate) enum QueryPosError {
3939 Missing(CannotFindRelativePosition),
3940 History(LoroError),
3941}
3942
3943impl From<LoroError> for QueryPosError {
3944 fn from(err: LoroError) -> Self {
3945 QueryPosError::History(err)
3946 }
3947}
3948
3949impl From<CannotFindRelativePosition> for QueryPosError {
3950 fn from(err: CannotFindRelativePosition) -> Self {
3951 QueryPosError::Missing(err)
3952 }
3953}
3954
3955fn find_last_delete_op(oplog: &OpLog, id: ID, idx: ContainerIdx) -> LoroResult<Option<ID>> {
3956 // Any delete op that covers `id` must have observed it, so its peer's counter
3957 // at delete time was > id.counter. start_vv (the vv at `id`) is therefore a
3958 // valid lower bound: changes at or before start_vv[peer] predate `id` and can
3959 // be skipped. We scan peer-by-peer rather than using the DAG-ordered
3960 // iter_changes_causally_rev, which is O(total changes).
3961 //
3962 // We choose the matching delete op with the greatest (op_lamport, peer, counter)
3963 // ordering. op_lamport is the Lamport of the specific op within the change
3964 // (change.lamport + op offset), not just the change's starting Lamport, so
3965 // concurrent deletes with equal change Lamports are broken deterministically.
3966 let start_vv = match oplog.dag.try_frontiers_to_vv(&id.into())? {
3967 Some(vv) => vv,
3968 None => oplog.shallow_since_vv().to_vv(),
3969 };
3970
3971 // (op_lamport, peer) gives a deterministic total order for concurrent deletes.
3972 // A single peer cannot produce two ops with the same lamport, so peer suffices
3973 // as a tie-breaker.
3974 let mut best: Option<((loro_common::Lamport, loro_common::PeerID), ID)> = None;
3975
3976 for change in oplog.iter_changes_peer_by_peer(&start_vv, oplog.vv()) {
3977 let peer = change.peer();
3978 for op in change.ops.iter() {
3979 if op.container != idx {
3980 continue;
3981 }
3982 if let InnerContent::List(InnerListOp::Delete(d)) = &op.content {
3983 if d.id_start.to_span(d.atom_len()).contains(id) {
3984 debug_assert!(op.counter >= change.id().counter);
3985 let op_lamport =
3986 change.lamport + (op.counter - change.id().counter) as loro_common::Lamport;
3987 let key = (op_lamport, peer);
3988 if best.is_none_or(|(bk, _)| key > bk) {
3989 best = Some((key, ID::new(peer, op.counter)));
3990 }
3991 }
3992 }
3993 }
3994 }
3995
3996 // The legacy peer iterator records a bad block and skips it. A skipped
3997 // block may hold the delete, so that is a decode error, not a missing id.
3998 oplog.check_history_parsable()?;
3999 Ok(best.map(|(_, op_id)| op_id))
4000}
4001
4002/// Cleanup for the critical section of [`LoroDoc::import_batch`].
4003///
4004/// `import_batch` force-detaches the document so each blob only touches the `OpLog`,
4005/// then reattaches once at the end. Leaving that section without reattaching strands
4006/// the document in detached mode: further imports stop being reflected in `DocState`,
4007/// local edits branch off a stale version, and every later `attach()` re-runs the same
4008/// failing checkout. `finish` owns that reattach, and `import_batch` must call it
4009/// explicitly on every exit path — including after catching a panic, because cleanup
4010/// cannot run *while* unwinding (`MutexGuard::drop` poisons its mutex when a panic is
4011/// in flight, and a second panic during unwind aborts the process). A `Drop` impl
4012/// therefore cannot help; the debug-only one below only asserts the contract.
4013struct BatchImportGuard<'a> {
4014 doc: &'a LoroDoc,
4015 /// Whether the doc was attached before the batch and therefore owes a reattach.
4016 /// It also decides whether we own the batch-wide import rollback scope.
4017 was_attached: bool,
4018 /// Held for the whole batch so no other thread can renew the txn and edit while
4019 /// we are detached. `_checkout_to_latest_without_commit` requires it to be held.
4020 txn: Option<LoroMutexGuard<'a, Option<Transaction>>>,
4021 options: Option<CommitOptions>,
4022 /// A full snapshot initialized a previously empty document. On checkout
4023 /// failure both its lazy state and its history must be reset, not just the
4024 /// updates recorded in the suffix journal.
4025 snapshot_checkpoint: Option<BatchSnapshotRollback>,
4026 #[cfg(debug_assertions)]
4027 finished: bool,
4028}
4029
4030struct BatchSnapshotRollback {
4031 arena: SharedArenaRollback,
4032 // Even an empty doc may expose empty containers acquired through getters.
4033 empty_containers: Vec<ContainerID>,
4034}
4035
4036/// Forward import diffs of movable lists take untouched element fields from
4037/// `DocState`. When a (forged) op targets an element the state no longer holds,
4038/// recompute the diff in Checkout mode, which resolves elements from history the
4039/// same way `checkout`, `import_batch` and snapshot replay do.
4040/// See `context/movable-list-op-validation.md`.
4041fn recalc_in_checkout_mode_if_needed(
4042 state: &mut DocState,
4043 oplog: &OpLog,
4044 old_vv: &VersionVector,
4045 old_frontiers: &Frontiers,
4046 diff: Vec<crate::event::InternalContainerDiff>,
4047) -> LoroResult<Vec<crate::event::InternalContainerDiff>> {
4048 if !state.needs_checkout_diff(&diff) {
4049 return Ok(diff);
4050 }
4051
4052 Ok(DiffCalculator::new(true)
4053 .try_calc_diff_internal(
4054 oplog,
4055 old_vv,
4056 old_frontiers,
4057 oplog.vv(),
4058 oplog.dag.get_frontiers(),
4059 None,
4060 )?
4061 .0)
4062}
4063
4064impl BatchImportGuard<'_> {
4065 /// Leave batch-import mode, reattach if the doc was attached, and renew the txn.
4066 ///
4067 /// Returns the still-pending version range on success. If the accumulated changes
4068 /// cannot be applied to `DocState` (malformed remote ops reach state validation
4069 /// only here, because the blobs were imported while detached), the whole batch is
4070 /// rolled back out of the `OpLog` so the document stays attached and unchanged,
4071 /// and the state-apply error is returned.
4072 fn finish(&mut self) -> LoroResult<VersionRange> {
4073 #[cfg(debug_assertions)]
4074 {
4075 self.finished = true;
4076 }
4077 let doc = self.doc;
4078 let txn = self.txn.take().expect("finish called twice");
4079 let options = self.options.take();
4080
4081 let pending = {
4082 let mut oplog = doc.oplog.lock();
4083 oplog.batch_importing = false;
4084 oplog.pending_changes.version_range()
4085 };
4086
4087 // The txn guard must stay held across the checkout, and the renew below must
4088 // reuse it: dropping it first and re-locking would panic when this runs after
4089 // a caught panic, because releasing a `Mutex` guard while a panic is in
4090 // flight poisons the mutex.
4091 let mut checkout = Ok(());
4092 if self.was_attached {
4093 // The blobs were imported while detached inside this scope, so their
4094 // movable-list element references are validated here, once per batch.
4095 let validation = doc
4096 .oplog
4097 .lock()
4098 .validate_movable_list_elem_refs_in_import_scope();
4099 checkout = validation.and_then(|()| doc._checkout_to_latest_without_commit(true));
4100 if let Err(e) = &checkout {
4101 // Validation precedes mutation: state is still at its pre-batch
4102 // version, or at the bootstrapped snapshot. Restore the matching
4103 // baseline in both state and history before leaving attached.
4104 tracing::warn!("import_batch cannot reattach, rolling the batch back: {e}");
4105 let mut oplog = doc.oplog.lock();
4106 let mut state = doc.state.lock();
4107 if let Some(checkpoint) = self.snapshot_checkpoint.take() {
4108 state.reset_to_empty_for_failed_snapshot_import();
4109 oplog.reset_to_empty_for_failed_snapshot_import(checkpoint.arena, &mut state);
4110 for id in checkpoint.empty_containers {
4111 state.ensure_container(&id);
4112 }
4113 } else {
4114 oplog.rollback_import(&mut state);
4115 }
4116 drop(state);
4117 drop(oplog);
4118 // The shared diff calculator cached ranges against the rolled-back
4119 // history; drop that cache instead of reusing stale entries.
4120 *doc.diff_calculator.lock() = DiffCalculator::new(true);
4121 doc.set_detached(false);
4122 } else {
4123 doc.oplog.lock().commit_import_rollback();
4124 }
4125 }
4126
4127 doc._renew_txn_if_auto_commit_with_guard(options, txn);
4128 checkout.map(|()| pending)
4129 }
4130}
4131
4132/// Debug-only tripwire: `finish` must be called explicitly (see the struct docs for
4133/// why `Drop` cannot do the cleanup itself). Release builds compile this out.
4134#[cfg(debug_assertions)]
4135impl Drop for BatchImportGuard<'_> {
4136 fn drop(&mut self) {
4137 if !std::thread::panicking() {
4138 assert!(
4139 self.finished,
4140 "BatchImportGuard dropped without calling finish()"
4141 );
4142 }
4143 }
4144}
4145
4146#[derive(Debug)]
4147pub struct CommitWhenDrop<'a> {
4148 doc: &'a LoroDoc,
4149 default_options: CommitOptions,
4150}
4151
4152impl Drop for CommitWhenDrop<'_> {
4153 fn drop(&mut self) {
4154 {
4155 let mut guard = self.doc.txn.lock();
4156 if let Some(txn) = guard.as_mut() {
4157 txn.set_default_options(std::mem::take(&mut self.default_options));
4158 };
4159 }
4160
4161 self.doc.commit_then_renew();
4162 }
4163}
4164
4165/// Options for configuring a commit operation.
4166#[derive(Debug, Clone)]
4167pub struct CommitOptions {
4168 /// Origin identifier for the commit event, used to track the source of changes.
4169 /// It doesn't persist.
4170 pub origin: Option<InternalString>,
4171
4172 /// Whether to immediately start a new transaction after committing.
4173 /// Defaults to true.
4174 pub immediate_renew: bool,
4175
4176 /// Custom timestamp for the commit in seconds since Unix epoch.
4177 /// If None, the current time will be used.
4178 pub timestamp: Option<Timestamp>,
4179
4180 /// Optional commit message to attach to the changes. It will be persisted.
4181 pub commit_msg: Option<Arc<str>>,
4182}
4183
4184impl CommitOptions {
4185 /// Creates a new CommitOptions with default values.
4186 pub fn new() -> Self {
4187 Self {
4188 origin: None,
4189 immediate_renew: true,
4190 timestamp: None,
4191 commit_msg: None,
4192 }
4193 }
4194
4195 /// Sets the origin identifier for this commit.
4196 pub fn origin(mut self, origin: &str) -> Self {
4197 self.origin = Some(origin.into());
4198 self
4199 }
4200
4201 /// Sets whether to immediately start a new transaction after committing.
4202 pub fn immediate_renew(mut self, immediate_renew: bool) -> Self {
4203 self.immediate_renew = immediate_renew;
4204 self
4205 }
4206
4207 /// Set the timestamp of the commit.
4208 ///
4209 /// The timestamp is the number of **seconds** that have elapsed since 00:00:00 UTC on January 1, 1970.
4210 pub fn timestamp(mut self, timestamp: Timestamp) -> Self {
4211 self.timestamp = Some(timestamp);
4212 self
4213 }
4214
4215 /// Sets a commit message to be attached to the changes.
4216 pub fn commit_msg(mut self, commit_msg: &str) -> Self {
4217 self.commit_msg = Some(commit_msg.into());
4218 self
4219 }
4220
4221 /// Sets the origin identifier for this commit.
4222 pub fn set_origin(&mut self, origin: Option<&str>) {
4223 self.origin = origin.map(|x| x.into())
4224 }
4225
4226 /// Sets the timestamp for this commit.
4227 pub fn set_timestamp(&mut self, timestamp: Option<Timestamp>) {
4228 self.timestamp = timestamp;
4229 }
4230}
4231
4232impl Default for CommitOptions {
4233 fn default() -> Self {
4234 Self::new()
4235 }
4236}
4237
4238#[cfg(test)]
4239mod test {
4240 use std::{
4241 panic::AssertUnwindSafe,
4242 sync::{
4243 atomic::{AtomicUsize, Ordering},
4244 Arc,
4245 },
4246 };
4247
4248 use crate::{
4249 cursor::PosType,
4250 encoding::json_schema::json::{JsonOpContent, JsonSchema, ListOp},
4251 encoding::{fast_snapshot::EMPTY_MARK, EncodeMode},
4252 loro::ExportMode,
4253 version::{Frontiers, VersionVector},
4254 LoroDoc, ToJson, TreeParentId,
4255 };
4256 use bytes::{BufMut, Bytes};
4257 use loro_common::{ContainerID, ContainerType, ID};
4258 use loro_kv_store::{mem_store::MemKvConfig, MemKvStore};
4259
4260 const XXH_SEED: u32 = u32::from_le_bytes(*b"LORO");
4261
4262 fn encode_import_blob(mode: EncodeMode, body: &[u8]) -> Vec<u8> {
4263 let mut ans = Vec::new();
4264 ans.extend_from_slice(b"loro");
4265 ans.extend_from_slice(&[0; 16]);
4266 ans.extend_from_slice(&mode.to_bytes());
4267 ans.extend_from_slice(body);
4268 let checksum = xxhash_rust::xxh32::xxh32(&ans[20..], XXH_SEED);
4269 ans[16..20].copy_from_slice(&checksum.to_le_bytes());
4270 ans
4271 }
4272
4273 fn encode_fast_snapshot_import(oplog_bytes: &[u8]) -> Vec<u8> {
4274 let mut body = Vec::new();
4275 body.put_u32_le(oplog_bytes.len() as u32);
4276 body.extend_from_slice(oplog_bytes);
4277 body.put_u32_le(EMPTY_MARK.len() as u32);
4278 body.extend_from_slice(EMPTY_MARK);
4279 body.put_u32_le(0);
4280 encode_import_blob(EncodeMode::FastSnapshot, &body)
4281 }
4282
4283 fn sstable_with_huge_meta_block_count() -> Vec<u8> {
4284 let mut bytes = Vec::new();
4285 bytes.extend_from_slice(b"LORO");
4286 bytes.push(0);
4287 bytes.put_u32_le(10_000_000);
4288 bytes.put_u32_le(xxhash_rust::xxh32::xxh32(&[], XXH_SEED));
4289 bytes.put_u32_le(5);
4290 bytes
4291 }
4292
4293 fn snapshot_oplog_with_malformed_block() -> Vec<u8> {
4294 let peer = 1;
4295 let id = ID::new(peer, 0);
4296 let vv = VersionVector::from_iter([(peer, 1)]);
4297 let frontiers = Frontiers::from_id(id);
4298 let mut store = MemKvStore::new(MemKvConfig::default());
4299 store.set(b"vv", vv.encode().into());
4300 store.set(b"fr", frontiers.encode().into());
4301 store.set(&id.to_bytes(), Bytes::from_static(&[0]));
4302 store.export_all().to_vec()
4303 }
4304
4305 fn make_json_import_stress_doc(peer: u64) -> LoroDoc {
4306 let doc = LoroDoc::new_auto_commit();
4307 doc.set_peer_id(peer).unwrap();
4308
4309 let text = doc.get_text("text");
4310 let mut text_pos = 0;
4311 for i in 0..32 {
4312 let chunk = format!("segment-{i}-abcdefghijklmnopqrstuvwxyz;");
4313 text.insert_unicode(text_pos, &chunk).unwrap();
4314 text_pos += chunk.chars().count();
4315 }
4316
4317 let list = doc.get_list("list");
4318 for i in 0..32 {
4319 list.insert(i, format!("item-{i}")).unwrap();
4320 }
4321
4322 let map = doc.get_map("map");
4323 for i in 0..32 {
4324 let key = format!("key-{i}");
4325 map.insert(&key, format!("value-{i}")).unwrap();
4326 }
4327
4328 let tree = doc.get_tree("tree");
4329 let mut parent = TreeParentId::Root;
4330 for i in 0..16 {
4331 let node = tree.create(parent).unwrap();
4332 let meta = tree.get_meta(node).unwrap();
4333 meta.insert("name", format!("node-{i}")).unwrap();
4334 meta.insert("payload", format!("payload-{i}-{}", "x".repeat(16)))
4335 .unwrap();
4336 parent = TreeParentId::Node(node);
4337 }
4338
4339 doc
4340 }
4341
4342 fn make_json_list_update_with_four_ops(peer: u64) -> (LoroDoc, JsonSchema) {
4343 let doc = LoroDoc::new();
4344 doc.set_peer_id(peer).unwrap();
4345 let map = doc.get_map("map");
4346 let list = doc.get_list("list");
4347 let text = doc.get_text("text");
4348
4349 let mut txn = doc.txn().unwrap();
4350 map.insert_with_txn(&mut txn, "prefix", "map-value".into())
4351 .unwrap();
4352 list.insert_with_txn(&mut txn, 0, "seed".into()).unwrap();
4353 text.insert_with_txn(&mut txn, 0, "text-value", PosType::Unicode)
4354 .unwrap();
4355 list.insert_with_txn(&mut txn, 1, "tail".into()).unwrap();
4356 txn.commit().unwrap();
4357
4358 let json = doc
4359 .export_json_updates(&Default::default(), &doc.oplog_vv(), false)
4360 .unwrap();
4361 assert_eq!(json.changes.len(), 1);
4362 assert_eq!(json.changes[0].ops.len(), 4);
4363 (doc, json)
4364 }
4365
4366 fn move_last_list_insert_far_out_of_bounds(json: &mut JsonSchema) {
4367 let last_change = json.changes.last_mut().unwrap();
4368 let last_op = last_change.ops.last_mut().unwrap();
4369 match &mut last_op.content {
4370 JsonOpContent::List(ListOp::Insert { pos, .. }) => {
4371 *pos = 1_000;
4372 }
4373 other => panic!("expected list insert op, got {other:?}"),
4374 }
4375 }
4376
4377 #[test]
4378 fn test_sync() {
4379 fn is_send_sync<T: Send + Sync>(_v: T) {}
4380 let loro = super::LoroDoc::new();
4381 is_send_sync(loro)
4382 }
4383
4384 #[test]
4385 fn import_rejects_huge_sstable_meta_block_count_without_panic() {
4386 let bytes = encode_fast_snapshot_import(&sstable_with_huge_meta_block_count());
4387
4388 let result = std::panic::catch_unwind(AssertUnwindSafe(|| LoroDoc::new().import(&bytes)));
4389 assert!(result.is_ok(), "malformed import should not panic");
4390 assert!(result.unwrap().is_err());
4391 }
4392
4393 #[test]
4394 fn import_rejects_malformed_change_block_without_panic() {
4395 let bytes = encode_fast_snapshot_import(&snapshot_oplog_with_malformed_block());
4396
4397 let result = std::panic::catch_unwind(AssertUnwindSafe(|| LoroDoc::new().import(&bytes)));
4398 assert!(result.is_ok(), "malformed import should not panic");
4399 assert!(result.unwrap().is_err());
4400 }
4401
4402 #[test]
4403 fn failed_import_rolls_back_oplog_and_arena() {
4404 let src = LoroDoc::new();
4405 src.set_peer_id(1).unwrap();
4406 let text = src.get_text("text");
4407 let mut txn = src.txn().unwrap();
4408 text.insert_with_txn(&mut txn, 0, "hello", PosType::Unicode)
4409 .unwrap();
4410 txn.commit().unwrap();
4411 let update = src.export(ExportMode::all_updates()).unwrap();
4412
4413 let dst = LoroDoc::new();
4414 let vv_before_import = dst.oplog_vv();
4415 let state_before_import = dst.get_deep_value();
4416 let err = dst
4417 .import_with(&update, "__loro_fail_import_state_apply".into())
4418 .unwrap_err();
4419 assert!(err.to_string().contains("state apply failpoint"));
4420 assert_eq!(dst.oplog_vv(), vv_before_import);
4421 assert_eq!(dst.get_deep_value(), state_before_import);
4422 assert!(dst.oplog().lock().is_empty());
4423
4424 dst.import(&update).unwrap();
4425 assert_eq!(dst.get_deep_value(), src.get_deep_value());
4426 }
4427
4428 #[test]
4429 fn failed_incremental_import_restores_previous_change_store_block() {
4430 let src = LoroDoc::new();
4431 src.set_peer_id(1).unwrap();
4432 let text = src.get_text("text");
4433 let mut txn = src.txn().unwrap();
4434 text.insert_with_txn(&mut txn, 0, "a", PosType::Unicode)
4435 .unwrap();
4436 txn.commit().unwrap();
4437 let first_update = src.export(ExportMode::all_updates()).unwrap();
4438 let first_vv = src.oplog_vv();
4439
4440 let mut txn = src.txn().unwrap();
4441 text.insert_with_txn(&mut txn, 1, "b", PosType::Unicode)
4442 .unwrap();
4443 txn.commit().unwrap();
4444 let second_update = src.export(ExportMode::updates(&first_vv)).unwrap();
4445
4446 let dst = LoroDoc::new();
4447 dst.import(&first_update).unwrap();
4448 let vv_before_import = dst.oplog_vv();
4449 let state_before_import = dst.get_deep_value();
4450 dst.import_with(&second_update, "__loro_fail_import_state_apply".into())
4451 .unwrap_err();
4452 assert_eq!(dst.oplog_vv(), vv_before_import);
4453 assert_eq!(dst.get_deep_value(), state_before_import);
4454
4455 dst.import(&second_update).unwrap();
4456 assert_eq!(dst.get_deep_value(), src.get_deep_value());
4457 }
4458
4459 #[test]
4460 fn failed_import_json_updates_rolls_back_complex_empty_doc() {
4461 let src = make_json_import_stress_doc(11);
4462 let json = src
4463 .export_json_updates(&Default::default(), &src.oplog_vv(), false)
4464 .unwrap();
4465
4466 let dst = LoroDoc::new();
4467 let vv_before_import = dst.oplog_vv();
4468 let frontiers_before_import = dst.oplog_frontiers();
4469 let state_before_import = dst.get_deep_value();
4470 for _ in 0..3 {
4471 crate::state::fail_next_import_state_apply_for_test();
4472 let err = dst.import_json_updates(json.clone()).unwrap_err();
4473 assert!(err.to_string().contains("state apply failpoint"));
4474 assert_eq!(dst.oplog_vv(), vv_before_import);
4475 assert_eq!(dst.oplog_frontiers(), frontiers_before_import);
4476 assert_eq!(dst.get_deep_value(), state_before_import);
4477 assert!(dst.oplog().lock().is_empty());
4478 }
4479
4480 dst.import_json_updates(json).unwrap();
4481 assert_eq!(dst.oplog_vv(), src.oplog_vv());
4482 assert_eq!(dst.oplog_frontiers(), src.oplog_frontiers());
4483 assert_eq!(dst.get_deep_value(), src.get_deep_value());
4484 }
4485
4486 #[test]
4487 fn failed_incremental_import_json_updates_restores_previous_change_store_block() {
4488 let src = LoroDoc::new_auto_commit();
4489 src.set_peer_id(12).unwrap();
4490 let text = src.get_text("text");
4491 text.insert_unicode(0, "a").unwrap();
4492 let list = src.get_list("list");
4493 list.push("seed").unwrap();
4494 let map = src.get_map("map");
4495 map.insert("seed", "value").unwrap();
4496 let tree = src.get_tree("tree");
4497 let root = tree.create(TreeParentId::Root).unwrap();
4498 tree.get_meta(root).unwrap().insert("name", "root").unwrap();
4499
4500 let first_vv = src.oplog_vv();
4501 let first_json = src
4502 .export_json_updates(&Default::default(), &first_vv, false)
4503 .unwrap();
4504
4505 let mut text_pos = text.len_unicode();
4506 for i in 0..64 {
4507 let chunk = format!("chunk-{i};");
4508 text.insert_unicode(text_pos, &chunk).unwrap();
4509 text_pos += chunk.chars().count();
4510 }
4511 for i in 0..32 {
4512 list.push(format!("after-{i}")).unwrap();
4513 let key = format!("after-{i}");
4514 map.insert(&key, format!("value-{i}")).unwrap();
4515 }
4516 let child = tree.create(TreeParentId::Node(root)).unwrap();
4517 tree.get_meta(child)
4518 .unwrap()
4519 .insert("name", "child")
4520 .unwrap();
4521
4522 let second_json = src
4523 .export_json_updates(&first_vv, &src.oplog_vv(), false)
4524 .unwrap();
4525
4526 let dst = LoroDoc::new();
4527 dst.import_json_updates(first_json).unwrap();
4528 let vv_before_import = dst.oplog_vv();
4529 let frontiers_before_import = dst.oplog_frontiers();
4530 let state_before_import = dst.get_deep_value();
4531
4532 for _ in 0..2 {
4533 crate::state::fail_next_import_state_apply_for_test();
4534 let err = dst.import_json_updates(second_json.clone()).unwrap_err();
4535 assert!(err.to_string().contains("state apply failpoint"));
4536 assert_eq!(dst.oplog_vv(), vv_before_import);
4537 assert_eq!(dst.oplog_frontiers(), frontiers_before_import);
4538 assert_eq!(dst.get_deep_value(), state_before_import);
4539 }
4540
4541 dst.import_json_updates(second_json).unwrap();
4542 assert_eq!(dst.oplog_vv(), src.oplog_vv());
4543 assert_eq!(dst.oplog_frontiers(), src.oplog_frontiers());
4544 assert_eq!(dst.get_deep_value(), src.get_deep_value());
4545 }
4546
4547 #[test]
4548 fn malformed_later_import_json_update_rolls_back_after_valid_prefix_enters_oplog() {
4549 let peer = 13;
4550 let (src, good_json) = make_json_list_update_with_four_ops(peer);
4551 let mut bad_json = good_json.clone();
4552 move_last_list_insert_far_out_of_bounds(&mut bad_json);
4553
4554 let good_dst = LoroDoc::new();
4555 good_dst.import_json_updates(good_json.clone()).unwrap();
4556 assert_eq!(good_dst.get_deep_value(), src.get_deep_value());
4557
4558 let last_op_counter = good_json.changes[0].ops.last().unwrap().counter;
4559 let prefix_vv = VersionVector::from_iter([(peer, last_op_counter)]);
4560 let prefix_json = src
4561 .export_json_updates(&Default::default(), &prefix_vv, false)
4562 .unwrap();
4563 assert_eq!(
4564 prefix_json.changes[0].ops.len(),
4565 good_json.changes[0].ops.len() - 1
4566 );
4567 let good_suffix_json = src
4568 .export_json_updates(&prefix_vv, &src.oplog_vv(), false)
4569 .unwrap();
4570 assert_eq!(good_suffix_json.changes[0].ops.len(), 1);
4571 let mut bad_suffix_json = good_suffix_json.clone();
4572 move_last_list_insert_far_out_of_bounds(&mut bad_suffix_json);
4573
4574 let prefix_dst = LoroDoc::new();
4575 prefix_dst.import_json_updates(prefix_json.clone()).unwrap();
4576 let vv_before_bad_suffix = prefix_dst.oplog_vv();
4577 let frontiers_before_bad_suffix = prefix_dst.oplog_frontiers();
4578 let state_before_bad_suffix = prefix_dst.get_deep_value();
4579
4580 let bad_suffix_json = serde_json::to_string(&bad_suffix_json).unwrap();
4581 let err = prefix_dst
4582 .import_json_updates(&bad_suffix_json)
4583 .unwrap_err();
4584 assert!(
4585 err.to_string().contains("list diff"),
4586 "expected state list bounds validation, got {err:?}"
4587 );
4588 assert_eq!(prefix_dst.oplog_vv(), vv_before_bad_suffix);
4589 assert_eq!(prefix_dst.oplog_frontiers(), frontiers_before_bad_suffix);
4590 assert_eq!(prefix_dst.get_deep_value(), state_before_bad_suffix);
4591
4592 prefix_dst.import_json_updates(good_suffix_json).unwrap();
4593 assert_eq!(prefix_dst.get_deep_value(), src.get_deep_value());
4594 assert_eq!(prefix_dst.oplog_vv(), src.oplog_vv());
4595
4596 let dst = LoroDoc::new();
4597 let vv_before_import = dst.oplog_vv();
4598 let frontiers_before_import = dst.oplog_frontiers();
4599 let state_before_import = dst.get_deep_value();
4600 let bad_json = serde_json::to_string(&bad_json).unwrap();
4601 let err = dst.import_json_updates(&bad_json).unwrap_err();
4602 assert!(
4603 err.to_string().contains("list diff"),
4604 "expected state list bounds validation, got {err:?}"
4605 );
4606 assert_eq!(dst.oplog_vv(), vv_before_import);
4607 assert_eq!(dst.oplog_frontiers(), frontiers_before_import);
4608 assert_eq!(dst.get_deep_value(), state_before_import);
4609 assert!(dst.oplog().lock().is_empty());
4610 }
4611
4612 #[test]
4613 fn failed_import_restores_pending_changes_that_were_applied_during_import() {
4614 let src = LoroDoc::new();
4615 src.set_peer_id(14).unwrap();
4616 let text = src.get_text("text");
4617
4618 let mut txn = src.txn().unwrap();
4619 text.insert_with_txn(&mut txn, 0, "a", PosType::Unicode)
4620 .unwrap();
4621 txn.commit().unwrap();
4622 let first_update = src.export(ExportMode::all_updates()).unwrap();
4623 let first_vv = src.oplog_vv();
4624
4625 let mut txn = src.txn().unwrap();
4626 text.insert_with_txn(&mut txn, 1, "b", PosType::Unicode)
4627 .unwrap();
4628 txn.commit().unwrap();
4629 let second_update = src.export(ExportMode::updates(&first_vv)).unwrap();
4630
4631 let dst = LoroDoc::new();
4632 let status = dst.import(&second_update).unwrap();
4633 assert!(status.success.is_empty());
4634 assert!(status.pending.is_some());
4635 let vv_before_dependency = dst.oplog_vv();
4636 let frontiers_before_dependency = dst.oplog_frontiers();
4637 let state_before_dependency = dst.get_deep_value();
4638
4639 crate::state::fail_next_import_state_apply_for_test();
4640 let err = dst.import(&first_update).unwrap_err();
4641 assert!(err.to_string().contains("state apply failpoint"));
4642 assert_eq!(dst.oplog_vv(), vv_before_dependency);
4643 assert_eq!(dst.oplog_frontiers(), frontiers_before_dependency);
4644 assert_eq!(dst.get_deep_value(), state_before_dependency);
4645
4646 dst.import(&first_update).unwrap();
4647 assert_eq!(dst.oplog_vv(), src.oplog_vv());
4648 assert_eq!(dst.oplog_frontiers(), src.oplog_frontiers());
4649 assert_eq!(dst.get_deep_value(), src.get_deep_value());
4650 }
4651
4652 #[test]
4653 fn failed_import_json_updates_does_not_emit_or_leave_events() {
4654 let (src, good_json) = make_json_list_update_with_four_ops(15);
4655 let mut bad_json = good_json.clone();
4656 move_last_list_insert_far_out_of_bounds(&mut bad_json);
4657
4658 let dst = LoroDoc::new();
4659 let event_count = Arc::new(AtomicUsize::new(0));
4660 let event_count_cloned = event_count.clone();
4661 let _sub = dst.subscribe_root(Arc::new(move |_| {
4662 event_count_cloned.fetch_add(1, Ordering::SeqCst);
4663 }));
4664
4665 let bad_json = serde_json::to_string(&bad_json).unwrap();
4666 let err = dst.import_json_updates(&bad_json).unwrap_err();
4667 assert!(
4668 err.to_string().contains("list diff"),
4669 "expected state list bounds validation, got {err:?}"
4670 );
4671 assert_eq!(event_count.load(Ordering::SeqCst), 0);
4672 assert!(dst.drop_pending_events().is_empty());
4673 assert!(dst.oplog().lock().is_empty());
4674
4675 dst.import_json_updates(good_json).unwrap();
4676 assert_eq!(event_count.load(Ordering::SeqCst), 1);
4677 assert_eq!(dst.get_deep_value(), src.get_deep_value());
4678 }
4679
4680 #[test]
4681 fn test_checkout() {
4682 let loro = LoroDoc::new();
4683 loro.set_peer_id(1).unwrap();
4684 let text = loro.get_text("text");
4685 let map = loro.get_map("map");
4686 let list = loro.get_list("list");
4687 let mut txn = loro.txn().unwrap();
4688 for i in 0..10 {
4689 map.insert_with_txn(&mut txn, "key", i.into()).unwrap();
4690 text.insert_with_txn(&mut txn, 0, &i.to_string(), PosType::Unicode)
4691 .unwrap();
4692 list.insert_with_txn(&mut txn, 0, i.into()).unwrap();
4693 }
4694 txn.commit().unwrap();
4695 let b = LoroDoc::new();
4696 b.import(&loro.export(ExportMode::Snapshot).unwrap())
4697 .unwrap();
4698 loro.checkout(&Frontiers::default()).unwrap();
4699 {
4700 let json = &loro.get_deep_value();
4701 assert_eq!(
4702 json.to_json_value(),
4703 serde_json::json!({"text":"","list":[],"map":{}})
4704 );
4705 }
4706
4707 b.checkout(&ID::new(1, 2).into()).unwrap();
4708 {
4709 let json = &b.get_deep_value();
4710 assert_eq!(
4711 json.to_json_value(),
4712 serde_json::json!({"text":"0","list":[0],"map":{"key":0}})
4713 );
4714 }
4715
4716 loro.checkout(&ID::new(1, 3).into()).unwrap();
4717 {
4718 let json = &loro.get_deep_value();
4719 assert_eq!(
4720 json.to_json_value(),
4721 serde_json::json!({"text":"0","list":[0],"map":{"key":1}})
4722 );
4723 }
4724
4725 b.checkout(&ID::new(1, 29).into()).unwrap();
4726 {
4727 let json = &b.get_deep_value();
4728 assert_eq!(
4729 json.to_json_value(),
4730 serde_json::json!({"text":"9876543210","list":[9,8,7,6,5,4,3,2,1,0],"map":{"key":9}})
4731 );
4732 }
4733 }
4734
4735 #[test]
4736 fn import_batch_err_181() {
4737 let a = LoroDoc::new_auto_commit();
4738 let update_a = a.export(ExportMode::Snapshot);
4739 let b = LoroDoc::new_auto_commit();
4740 b.import_batch(&[update_a.unwrap()]).unwrap();
4741 b.get_text("text")
4742 .insert(0, "hello", PosType::Unicode)
4743 .unwrap();
4744 b.commit_then_renew();
4745 let oplog = b.oplog().lock();
4746 drop(oplog);
4747 b.export(ExportMode::all_updates()).unwrap();
4748 }
4749
4750 #[test]
4751 fn poisoned_mutex_keeps_follow_up_operations_failed() {
4752 let doc = LoroDoc::new();
4753 let oplog = doc.oplog.clone();
4754 let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
4755 let _guard = oplog.lock();
4756 panic!("poison oplog");
4757 }));
4758
4759 let err = std::panic::catch_unwind(AssertUnwindSafe(|| doc.oplog_vv()))
4760 .expect_err("poisoned lock should continue to fail fast");
4761 let msg = if let Some(msg) = err.downcast_ref::<&str>() {
4762 (*msg).to_string()
4763 } else if let Some(msg) = err.downcast_ref::<String>() {
4764 msg.clone()
4765 } else {
4766 String::new()
4767 };
4768 assert!(msg.contains("poisoned LoroMutex"), "{msg}");
4769 }
4770
4771 #[test]
4772 fn repeated_independent_scalar_root_imports_scan_history_once() {
4773 let base = LoroDoc::new_auto_commit();
4774 base.set_peer_id(1).unwrap();
4775 for i in 0..64 {
4776 base.get_map("existing")
4777 .insert(&format!("key-{i}"), i)
4778 .unwrap();
4779 base.commit_then_renew();
4780 }
4781
4782 let target = LoroDoc::new();
4783 target
4784 .import(&base.export(ExportMode::Snapshot).unwrap())
4785 .unwrap();
4786 assert!(!target.has_history_cache());
4787
4788 for i in 0_u64..8 {
4789 let remote = LoroDoc::new_auto_commit();
4790 remote.set_peer_id(2 + i).unwrap();
4791 remote
4792 .get_map(format!("isolated-{i}"))
4793 .insert("value", i as i32)
4794 .unwrap();
4795 let update = remote.export(ExportMode::all_updates()).unwrap();
4796 target.import(&update).unwrap();
4797 assert_eq!(
4798 target.get_map(format!("isolated-{i}")).get("value"),
4799 Some((i as i32).into())
4800 );
4801 }
4802
4803 assert!(!target.has_history_cache());
4804 assert_eq!(
4805 target
4806 .oplog
4807 .lock()
4808 .change_store()
4809 .root_history_scan_count_for_test(),
4810 1
4811 );
4812 }
4813
4814 #[test]
4815 fn independent_fast_path_rejects_root_present_only_in_snapshot_state() {
4816 fn snapshot_sections(doc: &LoroDoc) -> crate::encoding::fast_snapshot::Snapshot {
4817 let (_, txn_guard) = doc.implicit_commit_then_stop();
4818 drop(txn_guard);
4819 crate::encoding::fast_snapshot::encode_snapshot_inner(doc).unwrap()
4820 }
4821
4822 let base = LoroDoc::new_auto_commit();
4823 base.set_peer_id(1).unwrap();
4824 base.get_map("existing").insert("value", "base").unwrap();
4825 let base_sections = snapshot_sections(&base);
4826
4827 // The donor's value must lose the register comparison against the real
4828 // ops below (same lamport, lower peer), so both the general path and a
4829 // wrongly-taken fast path would end with "winner"; the fast-path
4830 // counter is what proves the rejection.
4831 let state_donor = LoroDoc::new_auto_commit();
4832 state_donor.set_peer_id(0).unwrap();
4833 state_donor
4834 .get_map("isolated")
4835 .insert("value", "stale")
4836 .unwrap();
4837 let donor_sections = snapshot_sections(&state_donor);
4838
4839 let target = LoroDoc::new();
4840 crate::encoding::fast_snapshot::decode_snapshot_inner(
4841 crate::encoding::fast_snapshot::Snapshot {
4842 oplog_bytes: base_sections.oplog_bytes,
4843 state_bytes: donor_sections.state_bytes,
4844 shallow_root_state_bytes: Bytes::new(),
4845 },
4846 &target,
4847 Default::default(),
4848 )
4849 .unwrap();
4850 assert!(!target.has_history_cache());
4851
4852 let left = LoroDoc::new_auto_commit();
4853 left.set_peer_id(2).unwrap();
4854 left.get_map("isolated").insert("value", "left").unwrap();
4855 let right = LoroDoc::new_auto_commit();
4856 right.set_peer_id(3).unwrap();
4857 right.get_map("isolated").insert("value", "winner").unwrap();
4858 let aggregate = LoroDoc::new();
4859 aggregate
4860 .import(&left.export(ExportMode::all_updates()).unwrap())
4861 .unwrap();
4862 aggregate
4863 .import(&right.export(ExportMode::all_updates()).unwrap())
4864 .unwrap();
4865
4866 let hits = super::isolated_fast_path_hits_for_test();
4867 target
4868 .import(&aggregate.export(ExportMode::all_updates()).unwrap())
4869 .unwrap();
4870
4871 assert_eq!(
4872 target.get_map("isolated").get("value"),
4873 Some("winner".into())
4874 );
4875 assert_eq!(super::isolated_fast_path_hits_for_test(), hits);
4876 }
4877
4878 #[test]
4879 fn independent_scalar_root_import_rolls_back_after_state_failure() {
4880 let base = LoroDoc::new_auto_commit();
4881 base.set_peer_id(1).unwrap();
4882 base.get_map("existing").insert("value", "base").unwrap();
4883
4884 let target = LoroDoc::new();
4885 target
4886 .import(&base.export(ExportMode::Snapshot).unwrap())
4887 .unwrap();
4888 let vv_before = target.oplog_vv();
4889 let state_before = target.get_deep_value();
4890
4891 let remote = LoroDoc::new_auto_commit();
4892 remote.set_peer_id(2).unwrap();
4893 remote.get_map("isolated").insert("value", 7).unwrap();
4894 let update = remote.export(ExportMode::all_updates()).unwrap();
4895
4896 crate::state::fail_next_import_state_apply_for_test();
4897 let err = target.import(&update).unwrap_err();
4898 assert!(err.to_string().contains("state apply failpoint"));
4899 assert_eq!(target.oplog_vv(), vv_before);
4900 assert_eq!(target.get_deep_value(), state_before);
4901 assert!(!target.has_history_cache());
4902
4903 target.import(&update).unwrap();
4904 assert_eq!(target.get_map("isolated").get("value"), Some(7.into()));
4905 }
4906
4907 #[test]
4908 fn independent_fast_path_rejects_root_name_seen_in_history() {
4909 let base = LoroDoc::new_auto_commit();
4910 base.set_peer_id(1).unwrap();
4911 base.get_map("shared").insert("value", "base").unwrap();
4912
4913 let target = LoroDoc::new();
4914 target
4915 .import(&base.export(ExportMode::Snapshot).unwrap())
4916 .unwrap();
4917 assert!(!target.has_history_cache());
4918
4919 let remote = LoroDoc::new_auto_commit();
4920 remote.set_peer_id(999).unwrap();
4921 remote.get_map("shared").insert("value", "remote").unwrap();
4922 let hits = super::isolated_fast_path_hits_for_test();
4923 target
4924 .import(&remote.export(ExportMode::all_updates()).unwrap())
4925 .unwrap();
4926
4927 assert_eq!(target.get_map("shared").get("value"), Some("remote".into()));
4928 assert_eq!(super::isolated_fast_path_hits_for_test(), hits);
4929 }
4930
4931 #[test]
4932 fn independent_fast_path_rejects_deleted_root_name() {
4933 let base = LoroDoc::new_auto_commit();
4934 base.set_peer_id(1).unwrap();
4935 let root_id = ContainerID::new_root("deleted", ContainerType::Map);
4936 base.get_map("deleted").insert("value", "base").unwrap();
4937 base.delete_root_container(root_id);
4938
4939 let target = LoroDoc::new();
4940 target
4941 .import(&base.export(ExportMode::Snapshot).unwrap())
4942 .unwrap();
4943 assert!(!target.has_history_cache());
4944
4945 let remote = LoroDoc::new_auto_commit();
4946 remote.set_peer_id(2).unwrap();
4947 remote.get_map("deleted").insert("value", "remote").unwrap();
4948 let hits = super::isolated_fast_path_hits_for_test();
4949 target
4950 .import(&remote.export(ExportMode::all_updates()).unwrap())
4951 .unwrap();
4952
4953 assert_eq!(super::isolated_fast_path_hits_for_test(), hits);
4954 // The root's clearing ops outrank the remote write, so the map stays
4955 // empty; `deleted_root_containers` only affects root visibility, so
4956 // compare the container value with a doc that saw the other order.
4957 let reference = LoroDoc::new();
4958 reference
4959 .import(&remote.export(ExportMode::all_updates()).unwrap())
4960 .unwrap();
4961 reference
4962 .import(&base.export(ExportMode::all_updates()).unwrap())
4963 .unwrap();
4964 use crate::handler::HandlerTrait;
4965 assert_eq!(
4966 target.get_map("deleted").get_deep_value(),
4967 reference.get_map("deleted").get_deep_value()
4968 );
4969 assert!(target.get_map("deleted").is_empty());
4970 }
4971}
4972
4973// Helpers of `LoroDoc::check_apply_diff_creates_no_unknown_container`
4974
4975fn resolve_container_remap(
4976 mut id: ContainerID,
4977 container_remap: &FxHashMap<ContainerID, ContainerID>,
4978) -> (ContainerID, bool) {
4979 let mut remapped = false;
4980 while let Some(rid) = container_remap.get(&id) {
4981 remapped = true;
4982 id = rid.clone();
4983 }
4984 (id, remapped)
4985}
4986
4987fn diff_value_container_id(v: &ValueOrHandler) -> Option<ContainerID> {
4988 match v {
4989 ValueOrHandler::Value(LoroValue::Container(id)) => Some(id.clone()),
4990 ValueOrHandler::Handler(h) => Some(h.id()),
4991 ValueOrHandler::Value(_) => None,
4992 }
4993}
4994
4995fn inserted_container_ids(
4996 delta: &crate::event::ListDiff,
4997) -> impl Iterator<Item = ContainerID> + '_ {
4998 delta
4999 .iter()
5000 .flat_map(|item| match item {
5001 loro_delta::DeltaItem::Replace { value, .. } => {
5002 Some(value.iter().filter_map(diff_value_container_id))
5003 }
5004 loro_delta::DeltaItem::Retain { .. } => None,
5005 })
5006 .flatten()
5007}
5008
5009fn diff_has_unknown_value(diff: &crate::event::Diff) -> bool {
5010 match diff {
5011 crate::event::Diff::Map(map) => map.updated.values().any(|v| {
5012 v.value
5013 .as_ref()
5014 .and_then(diff_value_container_id)
5015 .is_some_and(|c| c.is_unknown())
5016 }),
5017 crate::event::Diff::List(delta) => inserted_container_ids(delta).any(|c| c.is_unknown()),
5018 _ => false,
5019 }
5020}
5021
5022/// See `LoroDoc::plan_full_state_batch`.
5023#[derive(Default)]
5024struct FullStatePlan {
5025 /// Batch id -> how the loop applies that full-state entry
5026 aligned: FxHashMap<ContainerID, PlannedAlignment>,
5027 /// Targets the loop applies even when they are unreachable before the batch
5028 always_applied: FxHashSet<ContainerID>,
5029 /// Batch ids of mergeable children of containers this batch recreates.
5030 /// They are new and empty when the loop reaches them.
5031 fresh: FxHashSet<ContainerID>,
5032}
5033
5034struct PlannedAlignment {
5035 /// The container the full state was aligned with
5036 target: ContainerID,
5037 /// `None` when there is nothing to do
5038 edit: Option<crate::event::Diff>,
5039 /// Children kept by the alignment, whose own entries are full states too
5040 kept: FxHashSet<ContainerID>,
5041}