forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

oplog.rs1759 lines, 65.9 KiBHistoryRawDownload
1mod change_store;
2mod known_history;
3pub(crate) use known_history::ImportedValues;
4pub(crate) mod loro_dag;
5mod pending_changes;
6
7use crate::sync::{AtomicUsize, Mutex};
8use bytes::Bytes;
9use std::borrow::Cow;
10use std::cell::RefCell;
11use std::cmp::Ordering;
12use std::rc::Rc;
13use std::sync::Arc;
14use tracing::trace_span;
15
16use self::change_store::iter::MergedChangeIter;
17use self::pending_changes::{PendingChanges, PendingChangesRollback};
18use super::arena::{SharedArena, SharedArenaRollback};
19use crate::change::{get_sys_timestamp, Change, Lamport, Timestamp};
20use crate::configure::Configure;
21use crate::container::idx::ContainerIdx;
22use crate::container::list::list_op;
23use crate::dag::{Dag, DagUtils, MeetAsBase};
24use crate::diff_calc::DiffMode;
25use crate::encoding::decode_oplog;
26use crate::encoding::{ImportStatus, ParsedHeaderAndBody};
27use crate::history_cache::ContainerHistoryCache;
28use crate::id::{Counter, PeerID, ID};
29use crate::op::{FutureInnerContent, InnerContent, ListSlice, RawOpContent, RemoteOp, RichOp};
30use crate::span::{HasCounterSpan, HasLamportSpan};
31use crate::state::DocState;
32use crate::version::{Frontiers, ImVersionVector, VersionVector};
33use crate::LoroError;
34use change_store::{BlockOpRef, ChangeStoreRollback};
35use loro_common::{ContainerType, HasIdSpan, IdLp, IdSpan};
36use rle::{HasLength, RleVec, Sliceable};
37use rustc_hash::{FxHashMap, FxHashSet};
38use smallvec::SmallVec;
39
40pub use self::loro_dag::{AppDag, AppDagNode, FrontiersNotIncluded};
41pub(crate) use change_store::encode_change_block;
42pub use change_store::{BlockChangeRef, ChangeStore};
43
44/// [OpLog] store all the ops i.e. the history.
45/// It allows multiple [AppState] to attach to it.
46/// So you can derive different versions of the state from the [OpLog].
47/// It allows us to build a version control system.
48///
49/// The causal graph should always be a DAG and complete, so two versions always have a replay base (at worst the empty version).
50/// If deps are missing, we can't import the change. It will be put into the `pending_changes`.
51pub struct OpLog {
52 pub(crate) dag: AppDag,
53 pub(crate) arena: SharedArena,
54 visible_op_count: Arc<AtomicUsize>,
55 change_store: ChangeStore,
56 history_cache: Mutex<ContainerHistoryCache>,
57 /// Pending changes that haven't been applied to the dag.
58 /// A change can be imported only when all its deps are already imported.
59 /// Key is the ID of the missing dep
60 pub(crate) pending_changes: PendingChanges,
61 /// Whether we are importing a batch of changes.
62 /// If so the Dag's frontiers won't be updated until the batch is finished.
63 pub(crate) batch_importing: bool,
64 pub(crate) configure: Configure,
65 /// The uncommitted change, it's a placeholder for the change
66 /// that is being edited in pre-commit callback.
67 pub(crate) uncommitted_change: Option<Change>,
68 pub(crate) import_rollback: Option<ImportRollback>,
69}
70
71pub(crate) struct ImportRollback {
72 arena: SharedArenaRollback,
73 change_store: ChangeStoreRollback,
74 pending: PendingChangesRollback,
75 /// Movable-list `Move`/`Set` element references inserted in this scope and not
76 /// validated yet (`OpLog::validate_movable_list_elem_refs_in_import_scope`).
77 movable_list_refs: Vec<MovableListElemRef>,
78}
79
80#[derive(Clone, Copy)]
81struct ResolvedElem {
82 target: ID,
83 container: ContainerIdx,
84 is_insert: bool,
85}
86
87struct MovableListElemRef {
88 container: ContainerIdx,
89 op_id: ID,
90 op_lamport: Lamport,
91 elem_id: IdLp,
92}
93
94#[derive(Debug, Default, Clone, Copy)]
95pub(crate) struct ImportChangesPreflight {
96 pub applies_to_dag: bool,
97 pub has_deps_before_shallow_root: bool,
98 /// Attached: state apply can reject. Detached: element validation can reject.
99 pub needs_state_apply_rollback: bool,
100}
101
102impl std::fmt::Debug for OpLog {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 f.debug_struct("OpLog")
105 .field("dag", &self.dag)
106 .field("pending_changes", &self.pending_changes)
107 .finish()
108 }
109}
110
111#[cfg(test)]
112thread_local! {
113 /// Counts falls from the multi-head critical version search back to the
114 /// single-head whole-DAG descent. Test observability only; thread-local
115 /// so concurrently running tests cannot disturb each other's counts
116 /// (diff calc runs on the importing thread).
117 pub(crate) static CRITICAL_BASE_FALLBACK_COUNT: std::cell::Cell<u64> =
118 const { std::cell::Cell::new(0) };
119}
120
121/// Result of [`OpLog::latest_critical_version_below_meet`].
122#[derive(Debug, PartialEq, Eq)]
123pub(crate) enum CriticalVersionSearch {
124 /// The greatest critical version ≤ `meet(from, to)`.
125 Found(VersionVector),
126 /// Provably no non-empty critical version ≤ meet exists: the fixpoint
127 /// bottomed out at ∅, and every critical cut ≤ meet survives every
128 /// lowering step, so the single-head descent cannot find one either —
129 /// callers should skip its whole-DAG walk.
130 NoneBelowMeet,
131 /// A change's deps reach below trimmed history; nothing is known. Fall
132 /// back to the single-head descent.
133 Unknown,
134}
135
136/// The replay base [`OpLog::iter_from_replay_base_causally`] chose.
137#[derive(Debug)]
138pub(crate) struct ReplayBase {
139 pub vv: VersionVector,
140 pub diff_mode: DiffMode,
141 /// The base is a *critical version* of `ancestry(from) ∪ ancestry(to)`:
142 /// no event above it is concurrent with any event inside it. Calculators
143 /// that seed their CRDT state with one opaque "unknown" span for
144 /// everything below the base need exactly this property, because such a
145 /// span can never be retreated.
146 pub is_critical: bool,
147 /// `Some` when the import was proved register-only concurrent with
148 /// `from` and replays from it (see `OpLog::register_only_concurrency`):
149 /// every container with an op in the concurrent old history.
150 pub concurrent_containers: Option<FxHashSet<ContainerIdx>>,
151}
152
153/// Whether an imported op on a container of type `ty` can be rejected by
154/// `ContainerState::validate_diff` (e.g. a sequence position past the end), so
155/// the import needs a rollback scope to undo the op log on that error.
156pub(crate) fn state_apply_can_reject(ty: ContainerType) -> bool {
157 matches!(
158 ty,
159 ContainerType::List
160 | ContainerType::MovableList
161 | ContainerType::Text
162 | ContainerType::Tree
163 )
164}
165
166/// Detached imports do not apply state. Only Move/Set element validation can
167/// reject after adding history; an enclosing batch still owns its full scope.
168pub(super) fn import_op_can_reject(op: &crate::op::Op, detached: bool) -> bool {
169 if detached {
170 op.container.get_type() == ContainerType::MovableList
171 && matches!(
172 op.content,
173 InnerContent::List(
174 list_op::InnerListOp::Move { .. } | list_op::InnerListOp::Set { .. }
175 )
176 )
177 } else {
178 state_apply_can_reject(op.container.get_type())
179 }
180}
181
182impl OpLog {
183 #[inline]
184 pub(crate) fn new(visible_op_count: Arc<AtomicUsize>) -> Self {
185 let arena = SharedArena::new();
186 let cfg = Configure::default();
187 let change_store = ChangeStore::new_mem(&arena, cfg.merge_interval_in_s.clone());
188 arena.set_creator_resolver(change_store.creator_resolver());
189 Self {
190 visible_op_count,
191 history_cache: Mutex::new(ContainerHistoryCache::new(change_store.clone(), None)),
192 dag: AppDag::new(change_store.clone()),
193 change_store,
194 arena,
195 pending_changes: Default::default(),
196 batch_importing: false,
197 configure: cfg,
198 uncommitted_change: None,
199 import_rollback: None,
200 }
201 }
202
203 #[inline]
204 fn calc_visible_op_count(&self) -> usize {
205 let total = self.dag.vv().values().sum::<i32>() as usize;
206 let shallow = self
207 .dag
208 .shallow_since_vv()
209 .iter()
210 .map(|(_, ops)| *ops)
211 .sum::<i32>() as usize;
212 total - shallow
213 }
214
215 #[inline]
216 pub(crate) fn visible_op_count_exact(&self) -> usize {
217 self.calc_visible_op_count()
218 }
219
220 #[inline]
221 pub(crate) fn refresh_visible_op_count(&self) -> usize {
222 let count = self.calc_visible_op_count();
223 self.visible_op_count
224 .store(count, std::sync::atomic::Ordering::Release);
225 count
226 }
227
228 /// Incrementally bump the cached visible op count for newly applied *local*
229 /// ops. Local ops are always visible (never behind the shallow root), so the
230 /// visible count grows by exactly `delta`. This avoids a per-op full
231 /// recompute via [`Self::calc_visible_op_count`], which iterates the version
232 /// vectors and heap-allocates an `im::HashMap` iterator on every call.
233 #[inline]
234 pub(crate) fn inc_visible_op_count(&self, delta: usize) {
235 self.visible_op_count
236 .fetch_add(delta, std::sync::atomic::Ordering::Release);
237 }
238
239 #[cfg(test)]
240 pub(crate) fn cached_visible_op_count(&self) -> usize {
241 self.visible_op_count
242 .load(std::sync::atomic::Ordering::Acquire)
243 }
244
245 #[inline]
246 pub fn dag(&self) -> &AppDag {
247 &self.dag
248 }
249
250 pub fn change_store(&self) -> &ChangeStore {
251 &self.change_store
252 }
253
254 /// `Err` once a read of the history has hit a change block that cannot be parsed (see
255 /// `ChangeStore::corrupt_block_error`). Only public entry points that return a `Result`
256 /// check it: internal callers of the same code `unwrap` their results.
257 pub(crate) fn check_history_parsable(&self) -> Result<(), LoroError> {
258 self.change_store.corrupt_block_error()
259 }
260
261 /// Get the change with the given peer and lamport.
262 ///
263 /// If not found, return the change with the greatest lamport that is smaller than the given lamport.
264 pub fn get_change_with_lamport_lte(
265 &self,
266 peer: PeerID,
267 lamport: Lamport,
268 ) -> Option<BlockChangeRef> {
269 let ans = self
270 .change_store
271 .get_change_by_lamport_lte(IdLp::new(peer, lamport))?;
272 debug_assert!(ans.lamport <= lamport);
273 Some(ans)
274 }
275
276 pub fn try_get_change_with_lamport_lte(
277 &self,
278 peer: PeerID,
279 lamport: Lamport,
280 ) -> Result<Option<BlockChangeRef>, LoroError> {
281 self.check_history_parsable()?;
282 let change = self.get_change_with_lamport_lte(peer, lamport);
283 self.check_history_parsable()?;
284 Ok(change)
285 }
286
287 pub fn get_timestamp_of_version(&self, f: &Frontiers) -> Timestamp {
288 let mut timestamp = Timestamp::default();
289 for id in f.iter() {
290 if let Some(change) = self.lookup_change(id) {
291 timestamp = timestamp.max(change.timestamp);
292 }
293 }
294
295 timestamp
296 }
297
298 /// No history, not even pending changes: a snapshot import may replace
299 /// this op log wholesale.
300 #[inline]
301 pub fn is_empty(&self) -> bool {
302 self.dag.is_empty() && self.pending_changes.is_empty()
303 }
304
305 /// This is the **only** place to update the `OpLog.changes`
306 pub(crate) fn insert_new_change(&mut self, change: Change, from_local: bool) {
307 let s = trace_span!(
308 "insert_new_change",
309 id = ?change.id,
310 lamport = change.lamport,
311 deps = ?change.deps
312 );
313 let _enter = s.enter();
314 let rollback_old_vv = self
315 .import_rollback
316 .as_ref()
317 .map(|x| x.change_store.old_vv())
318 .filter(|vv| !vv.is_empty());
319 self.dag
320 .handle_new_change(&change, from_local, rollback_old_vv);
321 self.history_cache
322 .lock()
323 .insert_by_new_change(&change, true, true);
324 #[cfg(debug_assertions)]
325 if from_local {
326 crate::parent::assert_local_parent_links_registered(&self.arena, &change);
327 }
328 self.register_container_and_parent_link(&change);
329 if let Some(rollback) = self.import_rollback.as_mut() {
330 for op in change.ops.iter() {
331 if op.container.get_type() != ContainerType::MovableList {
332 continue;
333 }
334 if let InnerContent::List(
335 list_op::InnerListOp::Move { elem_id, .. }
336 | list_op::InnerListOp::Set { elem_id, .. },
337 ) = &op.content
338 {
339 rollback.movable_list_refs.push(MovableListElemRef {
340 container: op.container,
341 op_id: ID::new(change.id.peer, op.counter),
342 op_lamport: change.lamport + (op.counter - change.id.counter) as Lamport,
343 elem_id: *elem_id,
344 });
345 }
346 }
347 self.change_store.insert_change_with_rollback(
348 change,
349 true,
350 from_local,
351 &mut rollback.change_store,
352 );
353 } else {
354 self.change_store.insert_change(change, true, from_local);
355 }
356 self.refresh_visible_op_count();
357 }
358
359 pub(crate) fn begin_import_rollback(&mut self) {
360 let arena = self.arena.checkpoint_for_rollback();
361 self.begin_import_rollback_with_arena(arena);
362 }
363
364 pub(crate) fn begin_import_rollback_with_arena(&mut self, arena: SharedArenaRollback) {
365 let old_vv = Arc::new(self.vv().clone());
366 self.begin_import_rollback_with_version(arena, old_vv);
367 }
368
369 /// Share the attached import's existing version snapshot with both journals.
370 pub(crate) fn begin_import_rollback_with_version(
371 &mut self,
372 arena: SharedArenaRollback,
373 old_vv: Arc<VersionVector>,
374 ) {
375 debug_assert!(self.import_rollback.is_none());
376 self.dag.begin_import_rollback(old_vv.clone());
377 self.import_rollback = Some(ImportRollback {
378 arena,
379 change_store: ChangeStoreRollback::new(old_vv),
380 pending: Default::default(),
381 movable_list_refs: Vec::new(),
382 });
383 }
384
385 /// Whether an import rollback scope is currently open.
386 ///
387 /// Scopes cannot nest: [`Self::begin_import_rollback_with_arena`] overwrites the
388 /// journal, and the matching commit/rollback clears it. Callers that may run
389 /// inside another scope (e.g. a blob imported by `LoroDoc::import_batch`) must
390 /// check this first and leave the scope to its owner.
391 pub(crate) fn has_import_rollback(&self) -> bool {
392 self.import_rollback.is_some()
393 }
394
395 pub(crate) fn commit_import_rollback(&mut self) {
396 self.dag.commit_import_rollback();
397 self.import_rollback = None;
398 }
399
400 /// Commit an import rollback scope this caller owns. No-op when `owns` is false — the
401 /// scope then belongs to an outer owner such as `import_batch`.
402 pub(crate) fn commit_owned_import_rollback(&mut self, owns: bool) {
403 if owns {
404 self.commit_import_rollback();
405 }
406 }
407
408 /// Roll back an import rollback scope this caller owns (see [`Self::rollback_import`]).
409 /// No-op when `owns` is false — the scope then belongs to an outer owner such as
410 /// `import_batch`.
411 pub(crate) fn rollback_owned_import(&mut self, owns: bool, state: &mut DocState) {
412 if owns {
413 self.rollback_import(state);
414 }
415 }
416
417 pub(crate) fn preflight_import_changes(
418 &self,
419 changes: &[Change],
420 detached: bool,
421 ) -> Result<ImportChangesPreflight, LoroError> {
422 let mut ans = ImportChangesPreflight::default();
423 for change in changes {
424 if change.ctr_end() <= self.vv().get(&change.id.peer).copied().unwrap_or(0) {
425 continue;
426 }
427
428 if self.dag.try_import_deps_before_shallow_root(&change.deps)? {
429 ans.has_deps_before_shallow_root = true;
430 continue;
431 }
432
433 // Inspect the ops even when the deps are not in the DAG yet: they may be
434 // earlier changes of this same import, which then unlock this one.
435 if change
436 .ops
437 .iter()
438 .any(|op| import_op_can_reject(op, detached))
439 {
440 ans.needs_state_apply_rollback = true;
441 }
442
443 if self
444 .dag
445 .try_get_change_lamport_from_deps(&change.deps)?
446 .is_some()
447 {
448 ans.applies_to_dag = true;
449 }
450 }
451
452 // Any newly applied change can unlock pending changes whose ops are not
453 // visible in `changes`, so include pending in the rollback decision.
454 // Keep this narrow: map-only pending changes cannot return a
455 // state-apply error, and forcing rollback there adds lock traffic to
456 // small sync/import workloads.
457 //
458 // Scan pending last, and only when it can still change the answer:
459 // `has_import_rollback_ops` walks every parked change and every op in
460 // it, while a blob that only parks (deps not here yet) leaves
461 // `applies_to_dag` false. Evaluating it eagerly made a batch of N
462 // out-of-order blobs quadratic, since each blob re-scanned the pending set
463 // the earlier blobs had grown.
464 if ans.applies_to_dag
465 && !ans.needs_state_apply_rollback
466 && self.pending_changes.has_import_rollback_ops(detached)
467 {
468 ans.needs_state_apply_rollback = true;
469 }
470
471 #[cfg(test)]
472 if ans.applies_to_dag && !detached {
473 ans.needs_state_apply_rollback = true;
474 }
475
476 Ok(ans)
477 }
478
479 /// Undo the open import rollback scope, including the arena.
480 ///
481 /// `state` shows that the caller holds the state lock. A reader under that lock can
482 /// register containers through the creator resolver, which runs without the op log lock,
483 /// and resolve their parent links before it returns; the arena rollback must not drop
484 /// those links in between. See `context/arena-parent-links.md`. The state's caches that
485 /// depend on parent links are cleared as well
486 /// (`context/failed-import-arena-indices.md`).
487 pub(crate) fn rollback_import(&mut self, state: &mut DocState) {
488 let Some(rollback) = self.import_rollback.take() else {
489 return;
490 };
491 state.forget_parent_link_caches_after_failed_import();
492
493 // Also rolls back the arena; see `ChangeStore::rollback_import`.
494 self.change_store
495 .rollback_import(rollback.change_store, rollback.arena);
496 self.dag.rollback_import();
497 rollback.pending.rollback(&mut self.pending_changes);
498 self.history_cache.lock().free_all();
499 self.refresh_visible_op_count();
500 }
501
502 /// [`Self::rollback_import`] without the arena rollback, for a scope that only inserted a
503 /// discarded local transaction (`LoroDoc::rollback_apply_diff_scope`): its containers were
504 /// registered by the transaction, and undoing it from the state may register old
505 /// containers and create state for them. See `context/apply-diff-atomicity.md`.
506 pub(crate) fn rollback_import_keeping_arena(&mut self, _state: &DocState) {
507 let Some(rollback) = self.import_rollback.take() else {
508 return;
509 };
510
511 self.change_store
512 .rollback_import_keeping_arena(rollback.change_store);
513 self.dag.rollback_import();
514 rollback.pending.rollback(&mut self.pending_changes);
515 self.history_cache.lock().free_all();
516 self.refresh_visible_op_count();
517 }
518
519 /// Rolls the arena back to a checkpoint taken before an import that failed before its
520 /// import rollback scope began. See [`ChangeStore::rollback_arena`], and
521 /// [`Self::rollback_import`] for `state`.
522 pub(crate) fn rollback_arena(
523 &self,
524 arena_checkpoint: SharedArenaRollback,
525 state: &mut DocState,
526 ) {
527 state.forget_parent_link_caches_after_failed_import();
528 self.change_store.rollback_arena(arena_checkpoint);
529 }
530
531 /// See [`Self::rollback_import`] for `state`.
532 pub(crate) fn reset_to_empty_for_failed_snapshot_import(
533 &mut self,
534 arena_checkpoint: SharedArenaRollback,
535 state: &mut DocState,
536 ) {
537 state.forget_parent_link_caches_after_failed_import();
538 let arena = self.arena.clone();
539 let configure = self.configure.clone();
540 // Also rolls back the arena; see `ChangeStore::retire`.
541 self.change_store.retire(arena_checkpoint);
542 let change_store = ChangeStore::new_mem(&arena, configure.merge_interval_in_s.clone());
543 arena.set_creator_resolver(change_store.creator_resolver());
544 self.history_cache = Mutex::new(ContainerHistoryCache::new(change_store.clone(), None));
545 self.dag = AppDag::new(change_store.clone());
546 self.change_store = change_store;
547 self.pending_changes = Default::default();
548 self.batch_importing = false;
549 self.configure = configure;
550 self.uncommitted_change = None;
551 self.import_rollback = None;
552 self.visible_op_count
553 .store(0, std::sync::atomic::Ordering::Release);
554 }
555
556 #[inline(always)]
557 pub(crate) fn with_history_cache<F, R>(&self, f: F) -> R
558 where
559 F: FnOnce(&mut ContainerHistoryCache) -> R,
560 {
561 let mut history_cache = self.history_cache.lock();
562 f(&mut history_cache)
563 }
564
565 pub fn has_history_cache(&self) -> bool {
566 self.history_cache.lock().has_cache()
567 }
568
569 pub fn free_history_cache(&self) {
570 let mut history_cache = self.history_cache.lock();
571 history_cache.free();
572 }
573
574 #[cfg(test)]
575 #[allow(dead_code)]
576 pub(crate) fn pending_changes_len(&self) -> usize {
577 self.pending_changes.len()
578 }
579
580 /// Import a change.
581 ///
582 /// Pending changes that haven't been applied to the dag.
583 /// A change can be imported only when all its deps are already imported.
584 /// Key is the ID of the missing dep
585 ///
586 /// # Err
587 ///
588 /// - Return Err(LoroError::UsedOpID) when the change's id is occupied
589 /// - Return Err(LoroError::DecodeError) when the change's deps are missing
590 pub(crate) fn import_local_change(&mut self, change: Change) -> Result<(), LoroError> {
591 self.insert_new_change(change, true);
592 Ok(())
593 }
594
595 /// Trim the known part of change
596 pub(crate) fn trim_the_known_part_of_change(&self, change: Change) -> Option<Change> {
597 let Some(&end) = self.dag.vv().get(&change.id.peer) else {
598 return Some(change);
599 };
600
601 if change.id.counter >= end {
602 return Some(change);
603 }
604
605 if change.ctr_end() <= end {
606 return None;
607 }
608
609 let offset = (end - change.id.counter) as usize;
610 Some(change.slice(offset, change.atom_len()))
611 }
612
613 #[allow(unused)]
614 fn check_id_is_not_duplicated(&self, id: ID) -> Result<(), LoroError> {
615 let cur_end = self.dag.vv().get(&id.peer).cloned().unwrap_or(0);
616 if cur_end > id.counter {
617 return Err(LoroError::UsedOpID { id });
618 }
619
620 Ok(())
621 }
622
623 /// Ensure the new change is greater than the last peer's id and the counter is continuous.
624 ///
625 /// It can be false when users use detached editing mode and use a custom peer id.
626 // This method might be slow and can be optimized if needed in the future.
627 pub(crate) fn check_change_greater_than_last_peer_id(
628 &self,
629 peer: PeerID,
630 counter: Counter,
631 deps: &Frontiers,
632 ) -> Result<(), LoroError> {
633 if counter == 0 {
634 return Ok(());
635 }
636
637 if !self.configure.detached_editing() {
638 return Ok(());
639 }
640
641 let mut max_last_counter = -1;
642 for dep in deps.iter() {
643 let dep_vv = self
644 .dag
645 .get_vv(dep)
646 .ok_or(LoroError::FrontiersNotFound(dep))?;
647 max_last_counter = max_last_counter.max(dep_vv.get(&peer).cloned().unwrap_or(0) - 1);
648 }
649
650 if counter != max_last_counter + 1 {
651 return Err(LoroError::ConcurrentOpsWithSamePeerID {
652 peer,
653 last_counter: max_last_counter,
654 current: counter,
655 });
656 }
657
658 Ok(())
659 }
660
661 pub(crate) fn next_id(&self, peer: PeerID) -> ID {
662 let cnt = self.dag.vv().get(&peer).copied().unwrap_or(0);
663 ID::new(peer, cnt)
664 }
665
666 pub(crate) fn vv(&self) -> &VersionVector {
667 self.dag.vv()
668 }
669
670 pub(crate) fn frontiers(&self) -> &Frontiers {
671 self.dag.frontiers()
672 }
673
674 /// - Ordering::Less means self is less than target or parallel
675 /// - Ordering::Equal means versions equal
676 /// - Ordering::Greater means self's version is greater than target
677 pub fn cmp_with_frontiers(&self, other: &Frontiers) -> Ordering {
678 self.dag.cmp_with_frontiers(other)
679 }
680
681 /// Compare two [Frontiers] causally.
682 ///
683 /// If one of the [Frontiers] are not included, it will return [FrontiersNotIncluded].
684 #[inline]
685 pub fn cmp_frontiers(
686 &self,
687 a: &Frontiers,
688 b: &Frontiers,
689 ) -> Result<Option<Ordering>, FrontiersNotIncluded> {
690 self.dag.cmp_frontiers(a, b)
691 }
692
693 pub(crate) fn get_lamport_at(&self, id: ID) -> Option<Lamport> {
694 self.get_change_at(id)
695 .map(|c| c.lamport + (id.counter - c.id.counter) as Lamport)
696 }
697
698 pub(crate) fn iter_ops(&self, id_span: IdSpan) -> impl Iterator<Item = RichOp<'static>> + '_ {
699 let change_iter = self.change_store.iter_changes(id_span);
700 change_iter.flat_map(move |c| RichOp::new_iter_by_cnt_range(c, id_span.counter))
701 }
702
703 pub(crate) fn iter_changes(
704 &self,
705 id_span: IdSpan,
706 ) -> impl Iterator<Item = BlockChangeRef> + '_ {
707 self.change_store.iter_changes(id_span)
708 }
709
710 pub(crate) fn get_max_lamport_at(&self, id: ID) -> Lamport {
711 self.get_change_at(id)
712 .map(|c| {
713 let change_counter = c.id.counter as u32;
714 c.lamport + c.ops().last().map(|op| op.counter).unwrap_or(0) as u32 - change_counter
715 })
716 .unwrap_or(Lamport::MAX)
717 }
718
719 pub fn get_change_at(&self, id: ID) -> Option<BlockChangeRef> {
720 self.change_store.get_change(id)
721 }
722
723 pub fn try_get_change_at(&self, id: ID) -> Result<Option<BlockChangeRef>, LoroError> {
724 self.check_history_parsable()?;
725 let change = self.get_change_at(id);
726 self.check_history_parsable()?;
727 Ok(change)
728 }
729
730 pub(crate) fn set_uncommitted_change(&mut self, change: Change) {
731 self.uncommitted_change = Some(change);
732 }
733
734 pub(crate) fn get_uncommitted_change_in_span(
735 &self,
736 id_span: IdSpan,
737 ) -> Option<Cow<'_, Change>> {
738 self.uncommitted_change.as_ref().and_then(|c| {
739 if c.id_span() == id_span {
740 Some(Cow::Borrowed(c))
741 } else if let Some((start, end)) = id_span.get_slice_range_on(&c.id_span()) {
742 Some(Cow::Owned(c.slice(start, end)))
743 } else {
744 None
745 }
746 })
747 }
748
749 pub fn get_deps_of(&self, id: ID) -> Option<Frontiers> {
750 self.get_change_at(id).map(|c| {
751 if c.id.counter == id.counter {
752 c.deps.clone()
753 } else {
754 Frontiers::from_id(id.inc(-1))
755 }
756 })
757 }
758
759 pub fn get_remote_change_at(&self, id: ID) -> Option<Change<RemoteOp<'static>>> {
760 let change = self.get_change_at(id)?;
761 Some(convert_change_to_remote(&self.arena, &change))
762 }
763
764 pub fn try_get_remote_change_at(
765 &self,
766 id: ID,
767 ) -> Result<Option<Change<RemoteOp<'static>>>, LoroError> {
768 let change = self.try_get_change_at(id)?;
769 Ok(change.map(|change| convert_change_to_remote(&self.arena, &change)))
770 }
771
772 pub(crate) fn import_unknown_lamport_pending_changes(
773 &mut self,
774 remote_changes: Vec<Change>,
775 would_affect: Option<&mut crate::version::VersionRange>,
776 ) -> crate::version::VersionRange {
777 self.extend_pending_changes_with_unknown_lamport(remote_changes, would_affect)
778 }
779
780 /// lookup change by id.
781 ///
782 /// if id does not included in this oplog, return None
783 pub(crate) fn lookup_change(&self, id: ID) -> Option<BlockChangeRef> {
784 self.change_store.get_change(id)
785 }
786
787 #[inline(always)]
788 pub(crate) fn export_change_store_from(&self, vv: &VersionVector, f: &Frontiers) -> Bytes {
789 self.change_store
790 .export_from(vv, f, self.vv(), self.frontiers())
791 }
792
793 #[inline(always)]
794 pub(crate) fn export_change_store_in_range(
795 &self,
796 vv: &VersionVector,
797 f: &Frontiers,
798 to_vv: &VersionVector,
799 to_frontiers: &Frontiers,
800 ) -> Bytes {
801 self.change_store.export_from(vv, f, to_vv, to_frontiers)
802 }
803
804 #[inline(always)]
805 pub(crate) fn export_blocks_from<W: std::io::Write>(&self, vv: &VersionVector, w: &mut W) {
806 self.change_store
807 .export_blocks_from(vv, self.shallow_since_vv(), self.vv(), w)
808 }
809
810 #[inline(always)]
811 pub(crate) fn export_blocks_in_range<W: std::io::Write>(&self, spans: &[IdSpan], w: &mut W) {
812 self.change_store.export_blocks_in_range(spans, w)
813 }
814
815 pub(crate) fn fork_changes_up_to(
816 &self,
817 frontiers: &Frontiers,
818 ) -> Result<Option<Bytes>, LoroError> {
819 let Some(vv) = self.dag.try_frontiers_to_vv(frontiers)? else {
820 return Ok(None);
821 };
822 Ok(Some(self.change_store.fork_changes_up_to(
823 self.dag.shallow_since_vv(),
824 frontiers,
825 &vv,
826 )?))
827 }
828
829 #[inline(always)]
830 pub(crate) fn decode(
831 &mut self,
832 data: ParsedHeaderAndBody,
833 values: ImportedValues,
834 ) -> Result<ImportStatus, LoroError> {
835 decode_oplog(self, data, values)
836 }
837
838 /// Containers that have at least one op inside `spans`.
839 ///
840 /// Only `op.container` is needed, so this scans the borrowed changes
841 /// directly instead of materializing a cloned RichOp per op.
842 pub(crate) fn try_containers_in_spans(
843 &self,
844 spans: impl Iterator<Item = IdSpan>,
845 ) -> Result<FxHashSet<ContainerIdx>, LoroError> {
846 let mut containers = FxHashSet::default();
847 // Consecutive ops overwhelmingly share a container; skip the hash
848 // probe when it hasn't changed.
849 let mut last_container = None;
850 for span in spans {
851 for change in self.change_store.try_iter_changes(span)? {
852 let start_counter = span.counter.min().max(change.id.counter);
853 let end_counter = span.counter.norm_end();
854 let start = change
855 .ops
856 .binary_search_by(|op| op.ctr_last().cmp(&start_counter))
857 .unwrap_or_else(|e| e);
858 for op in &change.ops.vec()[start..] {
859 if op.counter >= end_counter {
860 break;
861 }
862
863 if last_container != Some(op.container) {
864 containers.insert(op.container);
865 last_container = Some(op.container);
866 }
867 }
868 }
869 }
870
871 Ok(containers)
872 }
873
874 /// For `to ⊇ from`: the old-parent frontiers of every entry change of the
875 /// new region `to − from` that does not causally cover all of `from`.
876 ///
877 /// An entry change is a new change (or the new suffix of a change that
878 /// straddles `from`) whose causal parents — explicit deps plus the
879 /// implicit same-peer predecessor — are all old. Every new event is a
880 /// descendant of some entry change, so `⋂ Events(parents)` over the
881 /// uncovered entries is causally before the whole new region and only
882 /// `Events(from)` outside it can be concurrent with a new op.
883 ///
884 /// This is the version-vector form of the DAG's
885 /// `new_region_uncovered_entry_parents` (see
886 /// `docs/critical-version-spec.md` L12): it only scans the new changes
887 /// and answers coverage with cached version vectors, so it costs
888 /// `O(|new changes|)` instead of a lamport-pruned ancestor walk. An empty
889 /// vector means the `ImportGreaterUpdates` contract holds outright;
890 /// `None` means trimmed history got in the way.
891 fn uncovered_entry_parents(
892 &self,
893 from: &VersionVector,
894 from_frontiers: &Frontiers,
895 to: &VersionVector,
896 ) -> Result<Option<Vec<Frontiers>>, LoroError> {
897 let mut uncovered = Vec::new();
898 for (peer, span) in from.diff(to).forward.iter() {
899 let id_span = IdSpan::new(*peer, span.start, span.end);
900 for change in self.change_store.try_iter_changes(id_span)? {
901 let start = change.id.counter.max(span.start);
902 let parents = if start > change.id.counter {
903 // The change straddles `from`; the new suffix only has
904 // the implicit predecessor as parent.
905 Frontiers::from_id(ID::new(*peer, start - 1))
906 } else {
907 let mut parents = change.deps().clone();
908 if change.id.counter > 0 {
909 let prev = ID::new(*peer, change.id.counter - 1);
910 if !parents.contains(&prev) {
911 parents.push(prev);
912 }
913 }
914 parents
915 };
916
917 // The everyday shape: the change depends on exactly the
918 // current frontiers. Covered without touching any version vector.
919 if &parents == from_frontiers {
920 continue;
921 }
922
923 if !parents.iter().all(|id| from.includes_id(id)) {
924 // Not an entry change; it inherits coverage through its
925 // new parents.
926 continue;
927 }
928
929 let Some(parents_vv) = self.dag.try_frontiers_to_vv(&parents)? else {
930 return Ok(None);
931 };
932 if !parents_vv.includes_vv(from) {
933 uncovered.push(parents);
934 }
935 }
936 }
937
938 Ok(Some(uncovered))
939 }
940
941 /// Decide whether an import whose new region `to − from` is concurrent
942 /// with part of `from` can still be replayed from `from`.
943 ///
944 /// `entry_parents` comes from [`OpLog::uncovered_entry_parents`]: the old
945 /// history that is causally before the *whole* new region is
946 /// `⋂ Events(parents)`, so the old ops that may be concurrent with a new op
947 /// are `Events(from) − ⋂ Events(parents)`.
948 ///
949 /// Sequence and tree containers need every concurrent op of the same
950 /// container as context, so a container with ops on both sides forces the
951 /// conservative replay. Map and counter are registers: a counter diff is
952 /// a commutative sum, and a map diff can be resolved per key from the
953 /// history cache without positional context, so concurrency on them is
954 /// harmless. (The map must NOT be resolved by comparing lamports against
955 /// the current state: persisted state drops metadata for deleted roots and
956 /// dead containers, so the diff calculator is told to use the history
957 /// cache for these containers, see `DiffCalculator::calc_diff_internal`.)
958 ///
959 /// Returns the containers touched by the concurrent old history when the
960 /// overlap is register-only, `None` otherwise.
961 fn register_only_concurrency(
962 &self,
963 from: &VersionVector,
964 to: &VersionVector,
965 entry_parents: &[Frontiers],
966 ) -> Result<Option<FxHashSet<ContainerIdx>>, LoroError> {
967 // ⋂ Events(parents) as a version vector: per-peer minimum.
968 let mut causal_past = from.clone();
969 for parents in entry_parents {
970 let Some(parents_vv) = self.dag.try_frontiers_to_vv(parents)? else {
971 return Ok(None);
972 };
973 causal_past.retain(|peer, end| {
974 let bound = parents_vv.get(peer).copied().unwrap_or(0);
975 *end = (*end).min(bound);
976 *end > 0
977 });
978 }
979
980 // A shallow snapshot may retain changes that are concurrent with its
981 // root (independent peer chains, for example), and `from` counts the
982 // trimmed ops below the root. If `concurrent_old` would reach into
983 // that trimmed history we cannot see which containers it touched, so
984 // the decision has to stay with the DAG.
985 if !causal_past.includes_vv(&self.dag.shallow_since_vv().to_vv()) {
986 return Ok(None);
987 }
988
989 let concurrent_old = causal_past.diff(from).forward;
990 let old_containers = self.try_containers_in_spans(
991 concurrent_old
992 .iter()
993 .map(|(peer, span)| IdSpan::new(*peer, span.start, span.end)),
994 )?;
995 if old_containers.is_empty() {
996 return Ok(Some(old_containers));
997 }
998
999 let new_region = from.diff(to).forward;
1000 let new_containers = self.try_containers_in_spans(
1001 new_region
1002 .iter()
1003 .map(|(peer, span)| IdSpan::new(*peer, span.start, span.end)),
1004 )?;
1005 let harmless = old_containers
1006 .iter()
1007 .filter(|idx| new_containers.contains(idx))
1008 .all(|idx| match idx.get_type() {
1009 ContainerType::Map => true,
1010 #[cfg(feature = "counter")]
1011 ContainerType::Counter => true,
1012 _ => false,
1013 });
1014 Ok(harmless.then_some(old_containers))
1015 }
1016
1017 /// The latest critical version below `from ∩ to`: the greatest causally
1018 /// closed `V ⊆ from ∩ to` such that every op in `(from ∪ to) − V` is
1019 /// causally after every op in `V`. "Causally after" is measured in the
1020 /// ancestry the replay hands the diff calculators — a change's recorded
1021 /// deps plus the author's own earlier ops — which is exactly what a
1022 /// calculator trusting the base relies on. Unlike
1023 /// `dag::latest_single_head_critical_version` the result may be
1024 /// multi-head, which is what makes it usable on the criss-cross DAG that
1025 /// continuous two-peer sync produces — there every merge point has two
1026 /// heads, so the single-head descent walks to genesis and returns nothing.
1027 ///
1028 /// Method: start at the meet `min(from, to)` — the largest candidate — and
1029 /// lower it to a fixpoint. `V` is critical iff for every change of the
1030 /// region above it, the context of the change's first op above `V`
1031 /// covers `V` (the change's later ops only add to that context). Each
1032 /// violating change lowers `V` to the intersection with that context,
1033 /// which preserves every critical cut below `V`, so the fixpoint is the
1034 /// greatest critical version ≤ the meet (spec L13). Lowering cannot
1035 /// change a verdict already reached — a context that covered `V` covers
1036 /// the smaller one, and the violator covers the lowered `V` by
1037 /// construction — it only exposes the spans between the old and the new
1038 /// `V`, which go on a worklist; a change is examined once per lowering
1039 /// that moves its peer's cut into it. The scan is thus bounded by the
1040 /// replay it enables, which walks the same region and computes the same
1041 /// contexts, so it needs no budget of its own.
1042 #[cfg(test)]
1043 pub(crate) fn latest_critical_version_below_meet(
1044 &self,
1045 from: &VersionVector,
1046 to: &VersionVector,
1047 merged: &VersionVector,
1048 ) -> CriticalVersionSearch {
1049 self.try_latest_critical_version_below_meet(from, to, merged)
1050 .unwrap()
1051 }
1052
1053 pub(crate) fn try_latest_critical_version_below_meet(
1054 &self,
1055 from: &VersionVector,
1056 to: &VersionVector,
1057 merged: &VersionVector,
1058 ) -> Result<CriticalVersionSearch, LoroError> {
1059 use CriticalVersionSearch::*;
1060
1061 // An intersection of two causally closed sets is causally closed, so
1062 // `min(from, to)` is a version, and it is the meet of the two.
1063 let mut v = from.intersection(to);
1064 if v.is_empty() {
1065 return Ok(NoneBelowMeet);
1066 }
1067
1068 let mut pending: Vec<IdSpan> = v.diff_iter(merged).1.collect();
1069 while let Some(span) = pending.pop() {
1070 for change in self.change_store.try_iter_changes(span)? {
1071 // The context of the change's first op above `v`, as
1072 // `iter_from_replay_base_causally` computes it for the
1073 // replay: the recorded deps plus the same-peer prefix.
1074 let Some(mut ctx) = self.dag.try_frontiers_to_vv(&change.deps)? else {
1075 // The deps reach below trimmed history; nothing can be
1076 // proved from here.
1077 return Ok(Unknown);
1078 };
1079 let cut = v.get(&change.id.peer).copied().unwrap_or(0);
1080 let first_above = change.id.counter.max(cut);
1081 ctx.extend_to_include_end_id(ID::new(change.id.peer, first_above));
1082
1083 if !ctx.includes_vv(&v) {
1084 let above = v.clone();
1085 v.intersect_with(&ctx);
1086 if v.is_empty() {
1087 return Ok(NoneBelowMeet);
1088 }
1089 pending.extend(v.diff_iter(&above).1);
1090 }
1091 }
1092 }
1093
1094 Ok(Found(v))
1095 }
1096
1097 /// Iterates causally over all changes between the replay base (the meet
1098 /// from `find_meet_and_mode` when it is valid for the diff mode, else a
1099 /// critical version below it in the Eg-walker sense, see
1100 /// `docs/critical-version-spec.md`) and the merged version of `from`/`to`.
1101 ///
1102 /// Tht iterator will include a version vector when the change is applied
1103 ///
1104 /// returns: (replay_base, iterator)
1105 ///
1106 /// Note: the change returned by the iterator may include redundant ops at the beginning, you should trim it by yourself.
1107 /// You can trim it by the provided counter value. It should start with the counter.
1108 ///
1109 /// If frontiers are provided, it will be faster (because we don't need to calculate it from version vector
1110 ///
1111 /// The third item is `Some(containers)` when part of the new region is
1112 /// concurrent with `from` but the oplog proved the concurrency
1113 /// register-only (see [`OpLog::register_only_concurrency`]); the replay
1114 /// then starts at `from` in `ImportGreaterUpdates` mode. The set lists
1115 /// every container with an op in the concurrent old history: the diff
1116 /// calculator resolves those from history and treats them as "source not
1117 /// in op context", and may trust `from` as the base for everything else.
1118 #[allow(clippy::type_complexity)]
1119 pub(crate) fn iter_from_replay_base_causally(
1120 &self,
1121 from: &VersionVector,
1122 from_frontiers: &Frontiers,
1123 to: &VersionVector,
1124 to_frontiers: &Frontiers,
1125 ) -> (
1126 ReplayBase,
1127 impl Iterator<
1128 Item = (
1129 BlockChangeRef,
1130 (Counter, Counter),
1131 Rc<RefCell<VersionVector>>,
1132 ),
1133 > + '_,
1134 ) {
1135 let (base, iter) = self
1136 .try_iter_from_replay_base_causally(from, from_frontiers, to, to_frontiers)
1137 .unwrap();
1138 (base, iter.map(Result::unwrap))
1139 }
1140
1141 #[allow(clippy::type_complexity)]
1142 pub(crate) fn try_iter_from_replay_base_causally(
1143 &self,
1144 from: &VersionVector,
1145 from_frontiers: &Frontiers,
1146 to: &VersionVector,
1147 to_frontiers: &Frontiers,
1148 ) -> Result<
1149 (
1150 ReplayBase,
1151 impl Iterator<
1152 Item = Result<
1153 (
1154 BlockChangeRef,
1155 (Counter, Counter),
1156 Rc<RefCell<VersionVector>>,
1157 ),
1158 LoroError,
1159 >,
1160 > + '_,
1161 ),
1162 LoroError,
1163 > {
1164 let mut merged_vv = from.clone();
1165 merged_vv.merge(to);
1166 loro_common::debug!("to_frontiers={:?} vv={:?}", &to_frontiers, to);
1167 let mut concurrent_containers = None;
1168 let mut register_only_base = None;
1169 if to > from {
1170 // `to ⊇ from`, but some new ops may be concurrent with part of
1171 // `from`. The DAG walk must then assume the worst and retreat
1172 // to a critical version; with container knowledge we can often
1173 // prove the concurrency harmless and replay from `from`
1174 // without touching the DAG at all.
1175 if let Some(entry_parents) = self.uncovered_entry_parents(from, from_frontiers, to)? {
1176 if !entry_parents.is_empty() {
1177 if let Some(containers) =
1178 self.register_only_concurrency(from, to, &entry_parents)?
1179 {
1180 concurrent_containers = Some(containers);
1181 register_only_base = Some(from_frontiers.clone());
1182 }
1183 }
1184 }
1185 }
1186
1187 let (meet, mut diff_mode) = if let Some(base) = register_only_base {
1188 (MeetAsBase::Valid(base), DiffMode::ImportGreaterUpdates)
1189 } else {
1190 self.dag
1191 .try_find_meet_and_mode(from_frontiers, to_frontiers)?
1192 };
1193 if diff_mode == DiffMode::Checkout && to > from {
1194 diff_mode = DiffMode::Import;
1195 }
1196
1197 let shallow_since_vv = self.dag.shallow_since_vv().to_vv();
1198 let mut replay_base_is_critical = false;
1199 let mut replay_base_frontiers = match meet {
1200 MeetAsBase::Valid(meet) => meet,
1201 MeetAsBase::NeedsCriticalRetreat => {
1202 // Some event above the meet is concurrent with it. Retreat to
1203 // a critical version — the latest *multi-head* one when we
1204 // can find it, because the single-head descent is both a
1205 // whole-DAG walk and, on the criss-cross DAG that continuous
1206 // two-peer sync produces, doomed to return the empty version.
1207 let descend = || {
1208 #[cfg(test)]
1209 CRITICAL_BASE_FALLBACK_COUNT.with(|c| c.set(c.get() + 1));
1210 self.dag
1211 .try_latest_single_head_critical_version(from_frontiers, to_frontiers)
1212 };
1213 match self.try_latest_critical_version_below_meet(from, to, &merged_vv)? {
1214 CriticalVersionSearch::Found(v) => {
1215 // Only replay from the version whose criticality was
1216 // proved. A shallow doc cannot replay from below its
1217 // seed version, and a cut assembled from recorded
1218 // deps plus the author's own prefix is causally
1219 // closed only when those deps cover that prefix
1220 // (spec axiom A6, which imported data is not checked
1221 // against) — a version that fails to round-trip
1222 // through frontiers is not one. Both are left to the
1223 // descent, as before.
1224 let f = self.dag.try_vv_to_frontiers(&v)?;
1225 let seed = self
1226 .dag
1227 .try_frontiers_to_vv(self.dag.shallow_since_frontiers())?
1228 .unwrap();
1229 if v.includes_vv(&seed)
1230 && self.dag.try_frontiers_to_vv(&f)?.as_ref() == Some(&v)
1231 {
1232 replay_base_is_critical = true;
1233 f
1234 } else {
1235 descend()?
1236 }
1237 }
1238 CriticalVersionSearch::NoneBelowMeet => {
1239 // ∅ is trivially critical (spec D8b), and the
1240 // single-head descent provably cannot find a better
1241 // cut (spec L13(ii); under A6, where its ancestry
1242 // coincides with the replay's) — skip its whole-DAG
1243 // walk.
1244 Frontiers::default()
1245 }
1246 CriticalVersionSearch::Unknown => descend()?,
1247 }
1248 }
1249 };
1250
1251 let mut replay_base_vv = self
1252 .dag
1253 .try_frontiers_to_vv(&replay_base_frontiers)?
1254 .unwrap();
1255 replay_base_is_critical |= replay_base_vv.is_empty();
1256 if !replay_base_vv.includes_vv(&shallow_since_vv) {
1257 // The replay base cannot point before shallow history because those
1258 // ops are no longer available to the causal iterator.
1259 replay_base_frontiers = self.dag.shallow_since_frontiers().clone();
1260 replay_base_vv = self
1261 .dag
1262 .try_frontiers_to_vv(&replay_base_frontiers)?
1263 .unwrap_or(shallow_since_vv);
1264 replay_base_is_critical = false;
1265 }
1266
1267 // go from the replay base to merged_vv
1268 let diff = replay_base_vv.diff(&merged_vv).forward;
1269 let mut iter = crate::dag::DagCausalIter::try_new(&self.dag, replay_base_frontiers, diff)?;
1270 let mut node = iter.next();
1271 let mut cur_cnt = 0;
1272 let vv = Rc::new(RefCell::new(VersionVector::default()));
1273 Ok((
1274 ReplayBase {
1275 vv: replay_base_vv.clone(),
1276 diff_mode,
1277 is_critical: replay_base_is_critical,
1278 concurrent_containers,
1279 },
1280 std::iter::from_fn(move || {
1281 let result = (|| -> Result<_, LoroError> {
1282 if let Some(inner) = &node {
1283 let mut inner_vv = vv.borrow_mut();
1284 // FIXME: PERF: it looks slow for large vv, like 10000+ entries
1285 inner_vv.clear();
1286 self.dag.try_ensure_vv_for(&inner.data)?;
1287 inner_vv.extend_to_include_vv(inner.data.vv.get().unwrap().iter());
1288 let peer = inner.data.peer;
1289 let cnt = inner
1290 .data
1291 .cnt
1292 .max(cur_cnt)
1293 .max(replay_base_vv.get(&peer).copied().unwrap_or(0));
1294 let dag_node_end = (inner.data.cnt + inner.data.len as Counter)
1295 .min(merged_vv.get(&peer).copied().unwrap_or(0));
1296 let change = match self.change_store.get_change(ID::new(peer, cnt)) {
1297 Some(change) => change,
1298 None => {
1299 self.check_history_parsable()?;
1300 panic!("DAG node must have a change");
1301 }
1302 };
1303
1304 if change.ctr_end() < dag_node_end {
1305 cur_cnt = change.ctr_end();
1306 } else {
1307 node = iter.next();
1308 cur_cnt = 0;
1309 }
1310
1311 inner_vv.extend_to_include_end_id(change.id);
1312
1313 Ok(Some((change, (cnt, dag_node_end), vv.clone())))
1314 } else {
1315 Ok(None)
1316 }
1317 })();
1318 match result {
1319 Ok(item) => item.map(Ok),
1320 Err(err) => {
1321 node = None;
1322 Some(Err(err))
1323 }
1324 }
1325 }),
1326 ))
1327 }
1328
1329 pub fn len_changes(&self) -> usize {
1330 self.change_store.change_num()
1331 }
1332
1333 pub fn diagnose_size(&self) -> SizeInfo {
1334 let mut total_changes = 0;
1335 let mut total_ops = 0;
1336 let mut total_atom_ops = 0;
1337 let total_dag_node = self.dag.total_parsed_dag_node();
1338 self.change_store.visit_all_changes(&mut |change| {
1339 total_changes += 1;
1340 total_ops += change.ops.len();
1341 total_atom_ops += change.atom_len();
1342 });
1343
1344 println!("total changes: {}", total_changes);
1345 println!("total ops: {}", total_ops);
1346 println!("total atom ops: {}", total_atom_ops);
1347 println!("total dag node: {}", total_dag_node);
1348 SizeInfo {
1349 total_changes,
1350 total_ops,
1351 total_atom_ops,
1352 total_dag_node,
1353 }
1354 }
1355
1356 pub(crate) fn iter_changes_peer_by_peer<'a>(
1357 &'a self,
1358 from: &VersionVector,
1359 to: &VersionVector,
1360 ) -> impl Iterator<Item = BlockChangeRef> + 'a {
1361 let spans: Vec<_> = from.diff_iter(to).1.collect();
1362 spans
1363 .into_iter()
1364 .flat_map(move |span| self.change_store.iter_changes(span))
1365 }
1366
1367 #[allow(dead_code)]
1368 pub(crate) fn iter_changes_causally_rev<'a>(
1369 &'a self,
1370 from: &VersionVector,
1371 to: &VersionVector,
1372 ) -> impl Iterator<Item = BlockChangeRef> + 'a {
1373 MergedChangeIter::new_change_iter_rev(self, from, to)
1374 }
1375
1376 pub fn get_timestamp_for_next_txn(&self) -> Timestamp {
1377 if self.configure.record_timestamp() {
1378 get_timestamp_now_txn()
1379 } else {
1380 0
1381 }
1382 }
1383
1384 #[inline(never)]
1385 pub(crate) fn idlp_to_id(&self, id: loro_common::IdLp) -> Option<ID> {
1386 let change = self.change_store.get_change_by_lamport_lte(id)?;
1387
1388 if change.lamport > id.lamport || change.lamport_end() <= id.lamport {
1389 return None;
1390 }
1391
1392 Some(ID::new(
1393 change.id.peer,
1394 (id.lamport - change.lamport) as Counter + change.id.counter,
1395 ))
1396 }
1397
1398 /// Reject the movable-list `Move`/`Set` ops inserted since the open import rollback
1399 /// scope began whose `elem_id` is not an element inserted into the same list within
1400 /// the op's causal history.
1401 ///
1402 /// Honest peers can only target elements they can see, and the movable-list diff
1403 /// calculator relies on it (`last_pos`/`last_value` lookups). The refs are recorded
1404 /// by `insert_new_change` while the scope is open, which covers directly imported
1405 /// changes, unlocked pending changes and every blob of an `import_batch`. See
1406 /// `context/movable-list-op-validation.md`.
1407 pub(crate) fn validate_movable_list_elem_refs_in_import_scope(
1408 &mut self,
1409 ) -> Result<(), LoroError> {
1410 let Some(rollback) = self.import_rollback.as_mut() else {
1411 return Ok(());
1412 };
1413 let refs = std::mem::take(&mut rollback.movable_list_refs);
1414 // Moves and sets keep hitting the same elements, and what an element id
1415 // resolves to does not depend on the op, so resolve each one once.
1416 let mut elems: FxHashMap<IdLp, Option<ResolvedElem>> = FxHashMap::default();
1417 for r in refs {
1418 let elem = *elems
1419 .entry(r.elem_id)
1420 .or_insert_with(|| self.resolve_movable_list_elem(r.elem_id));
1421 if elem.is_none() {
1422 self.check_history_parsable()?;
1423 }
1424 if !self.is_visible_movable_list_elem(&r, elem)? {
1425 return Err(LoroError::DecodeError(
1426 format!(
1427 "Movable list op {} targets element {}, which is not in the list's \
1428 causal history",
1429 r.op_id, r.elem_id
1430 )
1431 .into_boxed_str(),
1432 ));
1433 }
1434 }
1435
1436 Ok(())
1437 }
1438
1439 /// Where `elem_id`'s insert op lives, or `None` if its lamport is not in the stored
1440 /// history. The lookup searches both parsed and KV-only blocks of the peer, so
1441 /// `None` means the element never existed or was trimmed before a shallow root.
1442 fn resolve_movable_list_elem(&self, elem_id: IdLp) -> Option<ResolvedElem> {
1443 let change = self.change_store.get_change_by_lamport_lte(elem_id)?;
1444 if change.lamport_end() <= elem_id.lamport {
1445 return None;
1446 }
1447 let target = ID::new(
1448 change.id.peer,
1449 (elem_id.lamport - change.lamport) as Counter + change.id.counter,
1450 );
1451 let op = change.get_op_with_counter(target.counter)?;
1452 Some(ResolvedElem {
1453 target,
1454 container: op.container,
1455 is_insert: matches!(
1456 op.content,
1457 InnerContent::List(list_op::InnerListOp::Insert { .. })
1458 ),
1459 })
1460 }
1461
1462 fn is_visible_movable_list_elem(
1463 &self,
1464 r: &MovableListElemRef,
1465 elem: Option<ResolvedElem>,
1466 ) -> Result<bool, LoroError> {
1467 if r.elem_id.lamport >= r.op_lamport {
1468 return Ok(false);
1469 }
1470
1471 let Some(elem) = elem else {
1472 // History before a shallow root is trimmed. An op after the root can
1473 // only see pre-root elements that are still alive at the root.
1474 return Ok(!self.dag.shallow_since_vv().is_empty()
1475 && self.with_history_cache(|h| {
1476 h.shallow_root_has_movable_list_elem(r.container, r.elem_id)
1477 }));
1478 };
1479 if !elem.is_insert || elem.container != r.container {
1480 return Ok(false);
1481 }
1482
1483 // Earlier ops of the op's own DAG node are by the same peer, so the node's
1484 // start version covers every other peer's part of its causal history.
1485 let target = elem.target;
1486 if target.peer == r.op_id.peer && target.counter < r.op_id.counter {
1487 return Ok(true);
1488 }
1489 let Some(node) = self.dag.try_get(r.op_id)? else {
1490 return Ok(false);
1491 };
1492 Ok(self.dag.try_ensure_vv_for(&node)?.includes_id(target))
1493 }
1494
1495 #[allow(unused)]
1496 pub(crate) fn id_to_idlp(&self, id_start: ID) -> IdLp {
1497 let change = self.get_change_at(id_start).unwrap();
1498 let lamport = change.lamport + (id_start.counter - change.id.counter) as Lamport;
1499 let peer = id_start.peer;
1500 loro_common::IdLp { peer, lamport }
1501 }
1502
1503 /// NOTE: This may return a op that includes the given id, not necessarily start with the given id
1504 pub(crate) fn get_op_that_includes(&self, id: ID) -> Option<BlockOpRef> {
1505 let change = self.get_change_at(id)?;
1506 change.get_op_with_counter(id.counter)
1507 }
1508
1509 pub(crate) fn split_span_based_on_deps(&self, id_span: IdSpan) -> Vec<(IdSpan, Frontiers)> {
1510 let peer = id_span.peer;
1511 let mut counter = id_span.counter.min();
1512 let span_end = id_span.counter.norm_end();
1513 let mut ans = Vec::new();
1514
1515 while counter < span_end {
1516 let id = ID::new(peer, counter);
1517 let node = self.dag.get(id).unwrap();
1518
1519 let f = if node.cnt == counter {
1520 node.deps.clone()
1521 } else if counter > 0 {
1522 id.inc(-1).into()
1523 } else {
1524 unreachable!()
1525 };
1526
1527 let cur_end = node.cnt + node.len as Counter;
1528 let len = cur_end.min(span_end) - counter;
1529 ans.push((id.to_span(len as usize), f));
1530 counter += len;
1531 }
1532
1533 ans
1534 }
1535
1536 #[inline]
1537 pub fn compact_change_store(&mut self) {
1538 self.change_store
1539 .flush_and_compact(self.dag.vv(), self.dag.frontiers());
1540 }
1541
1542 #[inline]
1543 pub fn change_store_kv_size(&self) -> usize {
1544 self.change_store.kv_size()
1545 }
1546
1547 pub fn encode_change_store(&self) -> bytes::Bytes {
1548 self.change_store
1549 .encode_all(self.dag.vv(), self.dag.frontiers())
1550 }
1551
1552 pub fn check_dag_correctness(&self) {
1553 self.dag.check_dag_correctness();
1554 }
1555
1556 pub fn shallow_since_vv(&self) -> &ImVersionVector {
1557 self.dag.shallow_since_vv()
1558 }
1559
1560 pub fn shallow_since_frontiers(&self) -> &Frontiers {
1561 self.dag.shallow_since_frontiers()
1562 }
1563
1564 pub fn is_shallow(&self) -> bool {
1565 !self.dag.shallow_since_vv().is_empty()
1566 }
1567
1568 pub fn get_greatest_timestamp(&self, frontiers: &Frontiers) -> Timestamp {
1569 let mut max_timestamp = Timestamp::default();
1570 for id in frontiers.iter() {
1571 let change = self.get_change_at(id).unwrap();
1572 if change.timestamp > max_timestamp {
1573 max_timestamp = change.timestamp;
1574 }
1575 }
1576
1577 max_timestamp
1578 }
1579}
1580
1581#[derive(Debug)]
1582pub struct SizeInfo {
1583 pub total_changes: usize,
1584 pub total_ops: usize,
1585 pub total_atom_ops: usize,
1586 pub total_dag_node: usize,
1587}
1588
1589pub(crate) fn convert_change_to_remote(
1590 arena: &SharedArena,
1591 change: &Change,
1592) -> Change<RemoteOp<'static>> {
1593 let mut ops = RleVec::new();
1594 for op in change.ops.iter() {
1595 for op in local_op_to_remote(arena, op) {
1596 ops.push(op);
1597 }
1598 }
1599
1600 Change {
1601 ops,
1602 id: change.id,
1603 deps: change.deps.clone(),
1604 lamport: change.lamport,
1605 timestamp: change.timestamp,
1606 commit_msg: change.commit_msg.clone(),
1607 }
1608}
1609
1610pub(crate) fn local_op_to_remote(
1611 arena: &SharedArena,
1612 op: &crate::op::Op,
1613) -> SmallVec<[RemoteOp<'static>; 1]> {
1614 let container = arena.get_container_id(op.container).unwrap();
1615 let mut contents: SmallVec<[_; 1]> = SmallVec::new();
1616 match &op.content {
1617 crate::op::InnerContent::List(list) => match list {
1618 list_op::InnerListOp::Insert { slice, pos } => match container.container_type() {
1619 loro_common::ContainerType::List | loro_common::ContainerType::MovableList => {
1620 contents.push(RawOpContent::List(list_op::ListOp::Insert {
1621 slice: ListSlice::RawData(Cow::Owned(slice.as_slice().to_vec())),
1622 pos: *pos,
1623 }))
1624 }
1625 _ => unreachable!(),
1626 },
1627 list_op::InnerListOp::InsertText {
1628 slice,
1629 unicode_len: len,
1630 pos,
1631 } => match container.container_type() {
1632 loro_common::ContainerType::Text => {
1633 contents.push(RawOpContent::List(list_op::ListOp::Insert {
1634 slice: ListSlice::RawStr {
1635 unicode_len: *len as usize,
1636 str: Cow::Owned(std::str::from_utf8(slice).unwrap().to_owned()),
1637 },
1638 pos: *pos as usize,
1639 }));
1640 }
1641 _ => unreachable!(),
1642 },
1643 list_op::InnerListOp::Delete(del) => {
1644 contents.push(RawOpContent::List(list_op::ListOp::Delete(*del)))
1645 }
1646 list_op::InnerListOp::StyleStart {
1647 start,
1648 end,
1649 key,
1650 value,
1651 info,
1652 } => contents.push(RawOpContent::List(list_op::ListOp::StyleStart {
1653 start: *start,
1654 end: *end,
1655 key: key.clone(),
1656 value: value.clone(),
1657 info: *info,
1658 })),
1659 list_op::InnerListOp::StyleEnd => {
1660 contents.push(RawOpContent::List(list_op::ListOp::StyleEnd))
1661 }
1662 list_op::InnerListOp::Move {
1663 from,
1664 elem_id: from_id,
1665 to,
1666 } => contents.push(RawOpContent::List(list_op::ListOp::Move {
1667 from: *from,
1668 elem_id: *from_id,
1669 to: *to,
1670 })),
1671 list_op::InnerListOp::Set { elem_id, value } => {
1672 contents.push(RawOpContent::List(list_op::ListOp::Set {
1673 elem_id: *elem_id,
1674 value: value.clone(),
1675 }))
1676 }
1677 },
1678 crate::op::InnerContent::Map(map) => {
1679 let value = map.value.clone();
1680 contents.push(RawOpContent::Map(crate::container::map::MapSet {
1681 key: map.key.clone(),
1682 value,
1683 }))
1684 }
1685 crate::op::InnerContent::Tree(tree) => contents.push(RawOpContent::Tree(tree.clone())),
1686 crate::op::InnerContent::Future(f) => match f {
1687 #[cfg(feature = "counter")]
1688 crate::op::FutureInnerContent::Counter(c) => contents.push(RawOpContent::Counter(*c)),
1689 FutureInnerContent::Unknown { prop, value } => {
1690 contents.push(crate::op::RawOpContent::Unknown {
1691 prop: *prop,
1692 value: (**value).clone(),
1693 })
1694 }
1695 },
1696 };
1697
1698 let mut ans = SmallVec::with_capacity(contents.len());
1699 for content in contents {
1700 ans.push(RemoteOp {
1701 container: container.clone(),
1702 content,
1703 counter: op.counter,
1704 })
1705 }
1706 ans
1707}
1708
1709pub(crate) fn get_timestamp_now_txn() -> Timestamp {
1710 (get_sys_timestamp() as Timestamp + 500) / 1000
1711}
1712
1713#[cfg(test)]
1714mod visible_op_count_tests {
1715 use crate::{cursor::PosType, loro::ExportMode, LoroDoc};
1716
1717 /// The cached `visible_op_count` (bumped incrementally for local ops, and
1718 /// the only value read in release builds where `can_lock_in_this_thread`
1719 /// returns false) must always equal a from-scratch recompute.
1720 #[test]
1721 fn cached_visible_op_count_matches_exact() {
1722 let doc = LoroDoc::new();
1723 let text = doc.get_text("text");
1724 let mut txn = doc.txn().unwrap();
1725 for i in 0..50 {
1726 text.insert_with_txn(&mut txn, i, "a", PosType::Unicode)
1727 .unwrap();
1728 }
1729 txn.commit().unwrap();
1730 {
1731 let oplog = doc.oplog().lock();
1732 assert_eq!(
1733 oplog.cached_visible_op_count(),
1734 oplog.visible_op_count_exact(),
1735 "after local edits"
1736 );
1737 }
1738
1739 // Import keeps the cached count exact via full refresh; subsequent local
1740 // edits then increment from that exact base.
1741 let doc2 = LoroDoc::new();
1742 doc2.import(&doc.export(ExportMode::all_updates()).unwrap())
1743 .unwrap();
1744 let text2 = doc2.get_text("text");
1745 let mut txn2 = doc2.txn().unwrap();
1746 text2
1747 .insert_with_txn(&mut txn2, 0, "bbb", PosType::Unicode)
1748 .unwrap();
1749 txn2.commit().unwrap();
1750 {
1751 let oplog = doc2.oplog().lock();
1752 assert_eq!(
1753 oplog.cached_visible_op_count(),
1754 oplog.visible_op_count_exact(),
1755 "after import + local edits"
1756 );
1757 }
1758 }
1759}