project_note
Clone
https://git.tahinli.com/Tahinli/project_note.git
0 watching·0 forks·Rust·3.6 MiB·c49f5e7·Tahinli·1 month ago·2 commits
| 1 | use std::sync::{ |
| 2 | atomic::{AtomicUsize, Ordering}, |
| 3 | Arc, |
| 4 | }; |
| 5 | |
| 6 | use crate::{ |
| 7 | cursor::PosType, |
| 8 | encoding::json_schema::json::{JsonOpContent, JsonSchema, ListOp}, |
| 9 | loro::ExportMode, |
| 10 | state::fail_next_import_state_apply_for_test, |
| 11 | version::{Frontiers, VersionVector}, |
| 12 | LoroDoc, LoroError, TreeParentId, |
| 13 | }; |
| 14 | |
| 15 | fn pending_len(doc: &LoroDoc) -> usize { |
| 16 | doc.oplog().lock().pending_changes_len() |
| 17 | } |
| 18 | |
| 19 | #[test] |
| 20 | fn import_batch_snapshot_keeps_untouched_state_lazy() { |
| 21 | use crate::HandlerTrait; |
| 22 | let source = LoroDoc::new_auto_commit(); |
| 23 | source.set_peer_id(1).unwrap(); |
| 24 | for i in 0..64 { |
| 25 | source |
| 26 | .get_text(format!("text-{i}")) |
| 27 | .insert_unicode(0, "snapshot text") |
| 28 | .unwrap(); |
| 29 | } |
| 30 | let snapshot = source.export(ExportMode::Snapshot).unwrap(); |
| 31 | let vv = source.oplog_vv(); |
| 32 | source |
| 33 | .get_text("text-0") |
| 34 | .insert_unicode(0, "edit ") |
| 35 | .unwrap(); |
| 36 | let update = source.export(ExportMode::updates(&vv)).unwrap(); |
| 37 | |
| 38 | let split = LoroDoc::new(); |
| 39 | split.import(&snapshot).unwrap(); |
| 40 | split.import(&update).unwrap(); |
| 41 | let batch = LoroDoc::new(); |
| 42 | // Sorting must still put the full snapshot first. |
| 43 | let status = batch.import_batch(&[update, snapshot]).unwrap(); |
| 44 | assert!(status.pending.is_none()); |
| 45 | assert_eq!( |
| 46 | status.success, |
| 47 | crate::version::VersionRange::from_vv(&source.oplog_vv()) |
| 48 | ); |
| 49 | for doc in [&split, &batch] { |
| 50 | let untouched = doc.get_text("text-63").idx(); |
| 51 | assert!( |
| 52 | !doc.app_state().lock().store.has_decoded_state(untouched), |
| 53 | "snapshot bootstrap must not replay untouched container state" |
| 54 | ); |
| 55 | } |
| 56 | assert_eq!(batch.oplog_vv(), split.oplog_vv()); |
| 57 | assert_eq!(batch.state_frontiers(), split.state_frontiers()); |
| 58 | assert_eq!(batch.get_deep_value(), split.get_deep_value()); |
| 59 | } |
| 60 | |
| 61 | #[test] |
| 62 | fn import_batch_snapshot_checkout_failure_resets_state_and_history() { |
| 63 | let source = LoroDoc::new_auto_commit(); |
| 64 | source |
| 65 | .get_text("text") |
| 66 | .insert_unicode(0, "snapshot") |
| 67 | .unwrap(); |
| 68 | let snapshot = source.export(ExportMode::Snapshot).unwrap(); |
| 69 | let target = LoroDoc::new_auto_commit(); |
| 70 | // Existing handles and subscriptions must remain usable after rollback. |
| 71 | let text = target.get_text("text"); |
| 72 | let before = target.get_deep_value(); |
| 73 | let events = Arc::new(AtomicUsize::new(0)); |
| 74 | let counter = events.clone(); |
| 75 | let _sub = target.subscribe_root(Arc::new(move |_| { |
| 76 | counter.fetch_add(1, Ordering::SeqCst); |
| 77 | })); |
| 78 | let err = target |
| 79 | .import_batch(&[snapshot.clone(), malformed_binary_update(91)]) |
| 80 | .unwrap_err(); |
| 81 | assert!(err.to_string().contains("list diff"), "{err:?}"); |
| 82 | assert!(!target.is_detached()); |
| 83 | assert!(!target.oplog().lock().batch_importing); |
| 84 | assert_eq!(target.oplog_vv(), VersionVector::default()); |
| 85 | assert_eq!(target.state_frontiers(), Frontiers::default()); |
| 86 | assert_eq!(target.get_deep_value(), before); |
| 87 | assert_eq!(pending_len(&target), 0); |
| 88 | assert_eq!(events.load(Ordering::SeqCst), 0); |
| 89 | assert!(target.drop_pending_events().is_empty()); |
| 90 | text.insert_unicode(0, "still usable").unwrap(); |
| 91 | target.commit_then_renew(); |
| 92 | assert_eq!(text.to_string(), "still usable"); |
| 93 | target.import(&snapshot).unwrap(); |
| 94 | assert_eq!(target.state_frontiers(), target.oplog_frontiers()); |
| 95 | } |
| 96 | |
| 97 | #[test] |
| 98 | fn import_batch_snapshot_preserves_preexisting_pending_changes() { |
| 99 | let remote = LoroDoc::new_auto_commit(); |
| 100 | remote.set_peer_id(72).unwrap(); |
| 101 | remote.get_map("remote").insert("first", 1).unwrap(); |
| 102 | let base = remote.export(ExportMode::all_updates()).unwrap(); |
| 103 | let vv = remote.oplog_vv(); |
| 104 | remote.get_map("remote").insert("later", 2).unwrap(); |
| 105 | let pending = remote.export(ExportMode::updates(&vv)).unwrap(); |
| 106 | |
| 107 | let source = LoroDoc::new_auto_commit(); |
| 108 | source.set_peer_id(73).unwrap(); |
| 109 | source.get_map("source").insert("snapshot", 1).unwrap(); |
| 110 | let snapshot = source.export(ExportMode::Snapshot).unwrap(); |
| 111 | let vv = source.oplog_vv(); |
| 112 | source.get_map("source").insert("update", 2).unwrap(); |
| 113 | let update = source.export(ExportMode::updates(&vv)).unwrap(); |
| 114 | |
| 115 | let target = LoroDoc::new(); |
| 116 | target.import(&pending).unwrap(); |
| 117 | assert_eq!(pending_len(&target), 1); |
| 118 | let status = target.import_batch(&[snapshot, update]).unwrap(); |
| 119 | assert!(status.pending.is_some()); |
| 120 | assert_eq!(pending_len(&target), 1); |
| 121 | target.import(&base).unwrap(); |
| 122 | source.import(&base).unwrap(); |
| 123 | source.import(&pending).unwrap(); |
| 124 | assert_eq!(pending_len(&target), 0); |
| 125 | assert_eq!(target.get_deep_value(), source.get_deep_value()); |
| 126 | assert_eq!(target.oplog_vv(), source.oplog_vv()); |
| 127 | } |
| 128 | |
| 129 | #[test] |
| 130 | fn import_batch_snapshot_panic_keeps_prefix_attached() { |
| 131 | let source = LoroDoc::new_auto_commit(); |
| 132 | source.get_map("map").insert("snapshot", 1).unwrap(); |
| 133 | let snapshot = source.export(ExportMode::Snapshot).unwrap(); |
| 134 | let vv = source.oplog_vv(); |
| 135 | source.get_map("map").insert("update", 2).unwrap(); |
| 136 | let update = source.export(ExportMode::updates(&vv)).unwrap(); |
| 137 | let blobs = [snapshot.clone(), update]; |
| 138 | let target = LoroDoc::new_auto_commit(); |
| 139 | crate::loro::panic_at_batch_import_blob_for_test(1); |
| 140 | assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 141 | let _ = target.import_batch(&blobs); |
| 142 | })) |
| 143 | .is_err()); |
| 144 | assert!(!target.is_detached()); |
| 145 | assert!(!target.oplog().lock().batch_importing); |
| 146 | assert_eq!(target.oplog_vv(), vv); |
| 147 | assert_eq!(target.state_frontiers(), target.oplog_frontiers()); |
| 148 | let expected = LoroDoc::new(); |
| 149 | expected.import(&snapshot).unwrap(); |
| 150 | assert_eq!(target.get_deep_value(), expected.get_deep_value()); |
| 151 | target.import_batch(&blobs).unwrap(); |
| 152 | assert_eq!(target.get_deep_value(), source.get_deep_value()); |
| 153 | target.get_map("map").insert("local", 3).unwrap(); |
| 154 | } |
| 155 | |
| 156 | #[test] |
| 157 | fn import_batch_snapshot_into_detached_empty_doc_only_updates_history() { |
| 158 | let source = LoroDoc::new_auto_commit(); |
| 159 | source |
| 160 | .get_text("text") |
| 161 | .insert_unicode(0, "snapshot") |
| 162 | .unwrap(); |
| 163 | let snapshot = source.export(ExportMode::Snapshot).unwrap(); |
| 164 | let vv = source.oplog_vv(); |
| 165 | source.get_text("text").insert_unicode(0, "update").unwrap(); |
| 166 | let update = source.export(ExportMode::updates(&vv)).unwrap(); |
| 167 | let target = LoroDoc::new(); |
| 168 | target.detach(); |
| 169 | target.import_batch(&[snapshot, update]).unwrap(); |
| 170 | assert!(target.is_detached()); |
| 171 | assert_eq!(target.state_frontiers(), Frontiers::default()); |
| 172 | assert_eq!(target.oplog_vv(), source.oplog_vv()); |
| 173 | assert_eq!(target.get_text("text").to_string(), ""); |
| 174 | target.attach(); |
| 175 | assert_eq!(target.get_deep_value(), source.get_deep_value()); |
| 176 | } |
| 177 | |
| 178 | fn corrupt_snapshot_state_bytes(snapshot: &mut [u8]) { |
| 179 | let body_start = 22; |
| 180 | let oplog_len = |
| 181 | u32::from_le_bytes(snapshot[body_start..body_start + 4].try_into().unwrap()) as usize; |
| 182 | let state_len_pos = body_start + 4 + oplog_len; |
| 183 | let state_len = u32::from_le_bytes( |
| 184 | snapshot[state_len_pos..state_len_pos + 4] |
| 185 | .try_into() |
| 186 | .unwrap(), |
| 187 | ) as usize; |
| 188 | assert!(state_len > 0); |
| 189 | let state_start = state_len_pos + 4; |
| 190 | snapshot[state_start] ^= 0xff; |
| 191 | |
| 192 | refresh_snapshot_checksum(snapshot); |
| 193 | } |
| 194 | |
| 195 | #[derive(Clone, Copy, Debug)] |
| 196 | enum SnapshotKvSection { |
| 197 | OpLog, |
| 198 | State, |
| 199 | } |
| 200 | |
| 201 | fn corrupt_snapshot_sstable_block(snapshot: &mut [u8], section: SnapshotKvSection) { |
| 202 | let body_start = 22; |
| 203 | let oplog_len = |
| 204 | u32::from_le_bytes(snapshot[body_start..body_start + 4].try_into().unwrap()) as usize; |
| 205 | let oplog_start = body_start + 4; |
| 206 | let state_len_pos = oplog_start + oplog_len; |
| 207 | let state_len = u32::from_le_bytes( |
| 208 | snapshot[state_len_pos..state_len_pos + 4] |
| 209 | .try_into() |
| 210 | .unwrap(), |
| 211 | ) as usize; |
| 212 | let state_start = state_len_pos + 4; |
| 213 | let (section_start, section_len) = match section { |
| 214 | SnapshotKvSection::OpLog => (oplog_start, oplog_len), |
| 215 | SnapshotKvSection::State => (state_start, state_len), |
| 216 | }; |
| 217 | |
| 218 | // SSTable layout starts with four magic bytes and one schema byte. Corrupt the first block |
| 219 | // payload while leaving its embedded checksum stale, then refresh only the outer envelope. |
| 220 | assert!(section_len > 9); |
| 221 | snapshot[section_start + 5] ^= 0xff; |
| 222 | refresh_snapshot_checksum(snapshot); |
| 223 | } |
| 224 | |
| 225 | fn refresh_snapshot_checksum(snapshot: &mut [u8]) { |
| 226 | let checksum = xxhash_rust::xxh32::xxh32(&snapshot[20..], u32::from_le_bytes(*b"LORO")); |
| 227 | snapshot[16..20].copy_from_slice(&checksum.to_le_bytes()); |
| 228 | } |
| 229 | |
| 230 | fn make_json_list_update_with_four_ops(peer: u64) -> (LoroDoc, JsonSchema) { |
| 231 | let doc = LoroDoc::new(); |
| 232 | doc.set_peer_id(peer).unwrap(); |
| 233 | let map = doc.get_map("map"); |
| 234 | let list = doc.get_list("list"); |
| 235 | let text = doc.get_text("text"); |
| 236 | |
| 237 | let mut txn = doc.txn().unwrap(); |
| 238 | map.insert_with_txn(&mut txn, "prefix", "map-value".into()) |
| 239 | .unwrap(); |
| 240 | list.insert_with_txn(&mut txn, 0, "seed".into()).unwrap(); |
| 241 | text.insert_with_txn(&mut txn, 0, "text-value", PosType::Unicode) |
| 242 | .unwrap(); |
| 243 | list.insert_with_txn(&mut txn, 1, "tail".into()).unwrap(); |
| 244 | txn.commit().unwrap(); |
| 245 | |
| 246 | let json = doc |
| 247 | .export_json_updates(&Default::default(), &doc.oplog_vv(), false) |
| 248 | .unwrap(); |
| 249 | assert_eq!(json.changes.len(), 1); |
| 250 | assert_eq!(json.changes[0].ops.len(), 4); |
| 251 | (doc, json) |
| 252 | } |
| 253 | |
| 254 | fn move_last_list_insert_far_out_of_bounds(json: &mut JsonSchema) { |
| 255 | let last_change = json.changes.last_mut().unwrap(); |
| 256 | let last_op = last_change.ops.last_mut().unwrap(); |
| 257 | match &mut last_op.content { |
| 258 | JsonOpContent::List(ListOp::Insert { pos, .. }) => { |
| 259 | *pos = 1_000; |
| 260 | } |
| 261 | other => panic!("expected list insert op, got {other:?}"), |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | fn make_multi_peer_frontier_doc() -> LoroDoc { |
| 266 | let base = LoroDoc::new_auto_commit(); |
| 267 | base.set_peer_id(1).unwrap(); |
| 268 | base.get_map("map").insert("base", 0).unwrap(); |
| 269 | base.get_text("text").insert_unicode(0, "base").unwrap(); |
| 270 | let tree = base.get_tree("tree"); |
| 271 | let root = tree.create(TreeParentId::Root).unwrap(); |
| 272 | tree.get_meta(root).unwrap().insert("base", 0).unwrap(); |
| 273 | |
| 274 | let base_updates = base.export(ExportMode::all_updates()).unwrap(); |
| 275 | |
| 276 | let peer2 = base.fork(); |
| 277 | peer2.set_peer_id(2).unwrap(); |
| 278 | peer2.get_map("map").insert("p2", 2).unwrap(); |
| 279 | peer2.get_text("text").insert_unicode(0, "p2").unwrap(); |
| 280 | peer2.commit_then_renew(); |
| 281 | let peer2_updates = peer2.export(ExportMode::updates(&base.oplog_vv())).unwrap(); |
| 282 | |
| 283 | let peer3 = base.fork(); |
| 284 | peer3.set_peer_id(3).unwrap(); |
| 285 | peer3.get_map("map").insert("p3", 3).unwrap(); |
| 286 | let peer3_tree = peer3.get_tree("tree"); |
| 287 | let node = peer3_tree.create(TreeParentId::Root).unwrap(); |
| 288 | peer3_tree.get_meta(node).unwrap().insert("p3", 3).unwrap(); |
| 289 | peer3.commit_then_renew(); |
| 290 | let peer3_updates = peer3.export(ExportMode::updates(&base.oplog_vv())).unwrap(); |
| 291 | |
| 292 | let target = LoroDoc::new(); |
| 293 | target.import(&base_updates).unwrap(); |
| 294 | target.import(&peer2_updates).unwrap(); |
| 295 | target.import(&peer3_updates).unwrap(); |
| 296 | target |
| 297 | } |
| 298 | |
| 299 | fn assert_doc_unchanged( |
| 300 | doc: &LoroDoc, |
| 301 | vv: &VersionVector, |
| 302 | frontiers: &Frontiers, |
| 303 | state: &crate::LoroValue, |
| 304 | ) { |
| 305 | assert_eq!(&doc.oplog_vv(), vv); |
| 306 | assert_eq!(&doc.oplog_frontiers(), frontiers); |
| 307 | assert_eq!(&doc.get_deep_value(), state); |
| 308 | } |
| 309 | |
| 310 | #[test] |
| 311 | fn failed_dependency_import_rolls_back_single_pending_change() { |
| 312 | let src = LoroDoc::new_auto_commit(); |
| 313 | src.set_peer_id(1).unwrap(); |
| 314 | let map = src.get_map("map"); |
| 315 | map.insert("seed", "base").unwrap(); |
| 316 | let update_base = src |
| 317 | .export(ExportMode::updates(&VersionVector::default())) |
| 318 | .unwrap(); |
| 319 | let version_base = src.oplog_vv(); |
| 320 | |
| 321 | map.insert("later", "value").unwrap(); |
| 322 | let update_later = src.export(ExportMode::updates(&version_base)).unwrap(); |
| 323 | |
| 324 | let dst = LoroDoc::new(); |
| 325 | dst.import(&update_later).unwrap(); |
| 326 | assert_eq!(pending_len(&dst), 1); |
| 327 | let vv_before_import = dst.oplog_vv(); |
| 328 | let frontiers_before_import = dst.oplog_frontiers(); |
| 329 | let state_before_import = dst.get_deep_value(); |
| 330 | |
| 331 | fail_next_import_state_apply_for_test(); |
| 332 | let err = dst.import(&update_base).unwrap_err(); |
| 333 | assert!( |
| 334 | err.to_string().contains("state apply failpoint"), |
| 335 | "unexpected error: {err:?}" |
| 336 | ); |
| 337 | assert_eq!(pending_len(&dst), 1); |
| 338 | assert_eq!(dst.oplog_vv(), vv_before_import); |
| 339 | assert_eq!(dst.oplog_frontiers(), frontiers_before_import); |
| 340 | assert_eq!(dst.get_deep_value(), state_before_import); |
| 341 | |
| 342 | dst.import(&update_base).unwrap(); |
| 343 | assert_eq!(pending_len(&dst), 0); |
| 344 | assert_eq!(dst.oplog_vv(), src.oplog_vv()); |
| 345 | assert_eq!(dst.oplog_frontiers(), src.oplog_frontiers()); |
| 346 | assert_eq!(dst.get_deep_value(), src.get_deep_value()); |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn failed_dependency_import_rolls_back_multiple_pending_changes() { |
| 351 | let base = LoroDoc::new_auto_commit(); |
| 352 | base.set_peer_id(1).unwrap(); |
| 353 | let map = base.get_map("map"); |
| 354 | map.insert("seed", "base").unwrap(); |
| 355 | let update_base = base |
| 356 | .export(ExportMode::updates(&VersionVector::default())) |
| 357 | .unwrap(); |
| 358 | let version_base = base.oplog_vv(); |
| 359 | |
| 360 | let peer2 = LoroDoc::new_auto_commit(); |
| 361 | peer2.set_peer_id(2).unwrap(); |
| 362 | peer2.import(&update_base).unwrap(); |
| 363 | peer2.get_map("map").insert("p2", "B").unwrap(); |
| 364 | let update_peer2 = peer2.export(ExportMode::updates(&version_base)).unwrap(); |
| 365 | |
| 366 | let peer3 = LoroDoc::new_auto_commit(); |
| 367 | peer3.set_peer_id(3).unwrap(); |
| 368 | peer3.import(&update_base).unwrap(); |
| 369 | peer3.get_map("map").insert("p3", "C").unwrap(); |
| 370 | let update_peer3 = peer3.export(ExportMode::updates(&version_base)).unwrap(); |
| 371 | |
| 372 | let expected = LoroDoc::new(); |
| 373 | expected.import(&update_base).unwrap(); |
| 374 | expected.import(&update_peer2).unwrap(); |
| 375 | expected.import(&update_peer3).unwrap(); |
| 376 | |
| 377 | let dst = LoroDoc::new(); |
| 378 | dst.import(&update_peer2).unwrap(); |
| 379 | dst.import(&update_peer3).unwrap(); |
| 380 | assert_eq!(pending_len(&dst), 2); |
| 381 | |
| 382 | let vv_before_import = dst.oplog_vv(); |
| 383 | let frontiers_before_import: Frontiers = dst.oplog_frontiers(); |
| 384 | let state_before_import = dst.get_deep_value(); |
| 385 | |
| 386 | fail_next_import_state_apply_for_test(); |
| 387 | let err = dst.import(&update_base).unwrap_err(); |
| 388 | assert!( |
| 389 | err.to_string().contains("state apply failpoint"), |
| 390 | "unexpected error: {err:?}" |
| 391 | ); |
| 392 | assert_eq!(pending_len(&dst), 2); |
| 393 | assert_eq!(dst.oplog_vv(), vv_before_import); |
| 394 | assert_eq!(dst.oplog_frontiers(), frontiers_before_import); |
| 395 | assert_eq!(dst.get_deep_value(), state_before_import); |
| 396 | |
| 397 | dst.import(&update_base).unwrap(); |
| 398 | assert_eq!(pending_len(&dst), 0); |
| 399 | assert_eq!(dst.oplog_vv(), expected.oplog_vv()); |
| 400 | assert_eq!(dst.oplog_frontiers(), expected.oplog_frontiers()); |
| 401 | assert_eq!(dst.get_deep_value(), expected.get_deep_value()); |
| 402 | } |
| 403 | |
| 404 | #[test] |
| 405 | fn failed_import_keeps_multi_peer_frontiers_intact() { |
| 406 | let target = make_multi_peer_frontier_doc(); |
| 407 | let vv_before_import = target.oplog_vv(); |
| 408 | assert!(vv_before_import.iter().count() >= 3); |
| 409 | let frontiers_before_import = target.oplog_frontiers(); |
| 410 | let state_before_import = target.get_deep_value(); |
| 411 | |
| 412 | let (_, mut bad_json) = make_json_list_update_with_four_ops(4); |
| 413 | move_last_list_insert_far_out_of_bounds(&mut bad_json); |
| 414 | let bad_json = serde_json::to_string(&bad_json).unwrap(); |
| 415 | |
| 416 | let err = target.import_json_updates(&bad_json).unwrap_err(); |
| 417 | assert!( |
| 418 | err.to_string().contains("list diff"), |
| 419 | "expected state list bounds validation, got {err:?}" |
| 420 | ); |
| 421 | assert_eq!(target.oplog_vv(), vv_before_import); |
| 422 | assert_eq!(target.oplog_frontiers(), frontiers_before_import); |
| 423 | assert_eq!(target.get_deep_value(), state_before_import); |
| 424 | } |
| 425 | |
| 426 | #[test] |
| 427 | fn malformed_json_import_returns_error_without_mutating_doc() { |
| 428 | let doc = make_multi_peer_frontier_doc(); |
| 429 | let vv_before_import = doc.oplog_vv(); |
| 430 | let frontiers_before_import = doc.oplog_frontiers(); |
| 431 | let state_before_import = doc.get_deep_value(); |
| 432 | |
| 433 | let err = doc |
| 434 | .import_json_updates("[3,{ \"(' k\" :\n\n42222 }]") |
| 435 | .unwrap_err(); |
| 436 | assert_eq!(err, LoroError::InvalidJsonSchema); |
| 437 | assert_doc_unchanged( |
| 438 | &doc, |
| 439 | &vv_before_import, |
| 440 | &frontiers_before_import, |
| 441 | &state_before_import, |
| 442 | ); |
| 443 | } |
| 444 | |
| 445 | #[test] |
| 446 | fn failed_import_does_not_emit_events() { |
| 447 | let doc = LoroDoc::new(); |
| 448 | let hit = Arc::new(AtomicUsize::new(0)); |
| 449 | let hit_cloned = hit.clone(); |
| 450 | let _sub = doc.subscribe_root(Arc::new(move |_event| { |
| 451 | hit_cloned.fetch_add(1, Ordering::SeqCst); |
| 452 | })); |
| 453 | |
| 454 | let (_, mut bad_json) = make_json_list_update_with_four_ops(7); |
| 455 | move_last_list_insert_far_out_of_bounds(&mut bad_json); |
| 456 | let bad_json = serde_json::to_string(&bad_json).unwrap(); |
| 457 | let err = doc.import_json_updates(&bad_json).unwrap_err(); |
| 458 | assert!( |
| 459 | err.to_string().contains("list diff"), |
| 460 | "expected state list bounds validation, got {err:?}" |
| 461 | ); |
| 462 | assert_eq!(hit.load(Ordering::SeqCst), 0); |
| 463 | assert!(doc.drop_pending_events().is_empty()); |
| 464 | |
| 465 | let (_, good_json) = make_json_list_update_with_four_ops(8); |
| 466 | let good_json = serde_json::to_string(&good_json).unwrap(); |
| 467 | doc.import_json_updates(&good_json).unwrap(); |
| 468 | assert!(hit.load(Ordering::SeqCst) > 0); |
| 469 | } |
| 470 | |
| 471 | /// Build a binary update blob that decodes into the `OpLog` fine but whose ops are |
| 472 | /// rejected by `DocState` validation (list insert far out of bounds). |
| 473 | fn malformed_binary_update(peer: u64) -> Vec<u8> { |
| 474 | let (_, mut bad_json) = make_json_list_update_with_four_ops(peer); |
| 475 | move_last_list_insert_far_out_of_bounds(&mut bad_json); |
| 476 | |
| 477 | // A detached doc records changes into the OpLog without applying them to state, |
| 478 | // so the malformed op survives into the exported binary updates. |
| 479 | let carrier = LoroDoc::new(); |
| 480 | carrier.detach(); |
| 481 | carrier |
| 482 | .import_json_updates(serde_json::to_string(&bad_json).unwrap()) |
| 483 | .unwrap(); |
| 484 | carrier.export(ExportMode::all_updates()).unwrap() |
| 485 | } |
| 486 | |
| 487 | fn doc_with_snapshot_and_pending_updates() -> (LoroDoc, Vec<Vec<u8>>, LoroDoc) { |
| 488 | let base = LoroDoc::new_auto_commit(); |
| 489 | base.set_peer_id(1).unwrap(); |
| 490 | base.get_text("text").insert_unicode(0, "base").unwrap(); |
| 491 | base.get_list("list").push("base").unwrap(); |
| 492 | base.commit_then_renew(); |
| 493 | let snapshot = base.export(ExportMode::Snapshot).unwrap(); |
| 494 | let base_vv = base.oplog_vv(); |
| 495 | |
| 496 | // A chain of updates from a second peer. Imported out of order, all but the |
| 497 | // first land in `pending_changes` until their deps arrive. |
| 498 | let peer2 = base.fork(); |
| 499 | peer2.set_peer_id(2).unwrap(); |
| 500 | let mut chain = Vec::new(); |
| 501 | let mut from = base_vv.clone(); |
| 502 | for i in 0..5 { |
| 503 | peer2.get_map("map").insert(&format!("k{i}"), i).unwrap(); |
| 504 | peer2.commit_then_renew(); |
| 505 | chain.push(peer2.export(ExportMode::updates(&from)).unwrap()); |
| 506 | from = peer2.oplog_vv(); |
| 507 | } |
| 508 | // Latest first: everything but the last blob stays pending while the batch runs. |
| 509 | chain.reverse(); |
| 510 | |
| 511 | let dst = LoroDoc::new_auto_commit(); |
| 512 | dst.set_peer_id(3).unwrap(); |
| 513 | dst.import(&snapshot).unwrap(); |
| 514 | (dst, chain, peer2) |
| 515 | } |
| 516 | |
| 517 | /// A blob whose ops only fail when they reach `DocState` used to panic inside the |
| 518 | /// batch reattach (`checkout to oplog frontiers should succeed`), unwinding past the |
| 519 | /// reattach and leaving the document detached — and every later import/export broken. |
| 520 | #[test] |
| 521 | fn import_batch_with_unappliable_update_stays_attached_and_rolls_back() { |
| 522 | let (dst, mut blobs, _) = doc_with_snapshot_and_pending_updates(); |
| 523 | blobs.insert(0, malformed_binary_update(21)); |
| 524 | |
| 525 | let vv_before = dst.oplog_vv(); |
| 526 | let frontiers_before = dst.oplog_frontiers(); |
| 527 | let state_before = dst.get_deep_value(); |
| 528 | |
| 529 | let err = dst |
| 530 | .import_batch(&blobs) |
| 531 | .expect_err("a state-rejected op must fail the batch"); |
| 532 | assert!( |
| 533 | err.to_string().contains("list diff"), |
| 534 | "expected state list bounds validation, got {err:?}" |
| 535 | ); |
| 536 | |
| 537 | assert!( |
| 538 | !dst.is_detached(), |
| 539 | "import_batch must leave the doc attached" |
| 540 | ); |
| 541 | assert!(!dst.oplog().lock().batch_importing); |
| 542 | assert_doc_unchanged(&dst, &vv_before, &frontiers_before, &state_before); |
| 543 | // The chain blobs were parked and then unlocked *within* the batch; its rollback |
| 544 | // must not resurrect them. A resurrected entry would carry `ContainerIdx` |
| 545 | // registrations the arena rollback just truncated. |
| 546 | assert_eq!( |
| 547 | pending_len(&dst), |
| 548 | 0, |
| 549 | "changes the batch itself parked must not survive its rollback" |
| 550 | ); |
| 551 | |
| 552 | // Still fully usable afterwards. |
| 553 | dst.get_text("text").insert_unicode(0, "after").unwrap(); |
| 554 | dst.commit_then_renew(); |
| 555 | assert_eq!(dst.state_frontiers(), dst.oplog_frontiers()); |
| 556 | } |
| 557 | |
| 558 | /// A batch can unlock changes that were parked *before* it started. If the batch is |
| 559 | /// rolled back, those changes must be re-parked, or the document would silently drop |
| 560 | /// them and diverge once their deps finally arrive. |
| 561 | #[test] |
| 562 | fn failed_import_batch_reparks_prebatch_pending_changes() { |
| 563 | let src = LoroDoc::new_auto_commit(); |
| 564 | src.set_peer_id(1).unwrap(); |
| 565 | src.get_map("map").insert("seed", "base").unwrap(); |
| 566 | let update_base = src |
| 567 | .export(ExportMode::updates(&VersionVector::default())) |
| 568 | .unwrap(); |
| 569 | let version_base = src.oplog_vv(); |
| 570 | src.get_map("map").insert("later", "value").unwrap(); |
| 571 | let update_later = src.export(ExportMode::updates(&version_base)).unwrap(); |
| 572 | |
| 573 | let dst = LoroDoc::new(); |
| 574 | dst.import(&update_later).unwrap(); |
| 575 | assert_eq!(pending_len(&dst), 1); |
| 576 | let vv_before = dst.oplog_vv(); |
| 577 | let frontiers_before = dst.oplog_frontiers(); |
| 578 | let state_before = dst.get_deep_value(); |
| 579 | |
| 580 | // `update_base` unlocks the pre-batch pending change mid-batch; the malformed |
| 581 | // blob then makes the closing reattach fail and rolls the whole batch back. |
| 582 | let err = dst |
| 583 | .import_batch(&[update_base.clone(), malformed_binary_update(31)]) |
| 584 | .expect_err("the malformed blob must fail the whole batch"); |
| 585 | assert!(err.to_string().contains("list diff"), "{err:?}"); |
| 586 | assert!(!dst.is_detached()); |
| 587 | assert_eq!( |
| 588 | pending_len(&dst), |
| 589 | 1, |
| 590 | "the pending change the batch unlocked must be re-parked" |
| 591 | ); |
| 592 | assert_doc_unchanged(&dst, &vv_before, &frontiers_before, &state_before); |
| 593 | |
| 594 | // Retrying without the bad blob applies base and unlocks the re-parked change. |
| 595 | dst.import(&update_base).unwrap(); |
| 596 | assert_eq!(pending_len(&dst), 0); |
| 597 | assert_eq!(dst.oplog_vv(), src.oplog_vv()); |
| 598 | assert_eq!(dst.get_deep_value(), src.get_deep_value()); |
| 599 | } |
| 600 | |
| 601 | /// Changes are parked under the ID of the dep they are missing, so two peers waiting |
| 602 | /// on the same change share one pending slot. When a batch appends to a slot that |
| 603 | /// already held a pre-batch change, rollback has to trim its own entry off and keep |
| 604 | /// the older one — dropping the slot loses a change the document still needs, and |
| 605 | /// keeping both resurrects a change whose arena registrations were just truncated. |
| 606 | #[test] |
| 607 | fn failed_import_batch_trims_only_its_own_entry_from_a_shared_pending_slot() { |
| 608 | let p1 = LoroDoc::new_auto_commit(); |
| 609 | p1.set_peer_id(1).unwrap(); |
| 610 | p1.get_map("map").insert("seed", "v").unwrap(); |
| 611 | p1.commit_then_renew(); |
| 612 | // Never shipped to `dst`, so everything below stays parked on it. |
| 613 | let u_seed = p1 |
| 614 | .export(ExportMode::updates(&VersionVector::default())) |
| 615 | .unwrap(); |
| 616 | let vv_seed = p1.oplog_vv(); |
| 617 | |
| 618 | let waiter = |peer: u64, key: &str| { |
| 619 | let d = LoroDoc::new_auto_commit(); |
| 620 | d.set_peer_id(peer).unwrap(); |
| 621 | d.import(&u_seed).unwrap(); |
| 622 | d.get_map("map").insert(key, "v").unwrap(); |
| 623 | d.commit_then_renew(); |
| 624 | d.export(ExportMode::updates(&vv_seed)).unwrap() |
| 625 | }; |
| 626 | let u_p2 = waiter(2, "p2"); |
| 627 | let u_p3 = waiter(3, "p3"); |
| 628 | |
| 629 | let dst = LoroDoc::new_auto_commit(); |
| 630 | dst.set_peer_id(9).unwrap(); |
| 631 | dst.import(&u_p2).unwrap(); |
| 632 | assert_eq!(pending_len(&dst), 1, "p2 waits on the seed change"); |
| 633 | let vv_before = dst.oplog_vv(); |
| 634 | let frontiers_before = dst.oplog_frontiers(); |
| 635 | let state_before = dst.get_deep_value(); |
| 636 | |
| 637 | // `u_p3` parks in the same slot as `u_p2`; the malformed blob then fails the |
| 638 | // closing reattach and rolls the whole batch back. |
| 639 | let err = dst |
| 640 | .import_batch(&[u_p3.clone(), malformed_binary_update(41)]) |
| 641 | .expect_err("the malformed blob must fail the whole batch"); |
| 642 | assert!(err.to_string().contains("list diff"), "{err:?}"); |
| 643 | assert!(!dst.is_detached()); |
| 644 | assert_eq!( |
| 645 | pending_len(&dst), |
| 646 | 1, |
| 647 | "rollback must keep the pre-batch change and drop only the batch's own" |
| 648 | ); |
| 649 | assert_doc_unchanged(&dst, &vv_before, &frontiers_before, &state_before); |
| 650 | |
| 651 | // The kept change is still the right one, and the doc converges on a retry. |
| 652 | dst.import(&u_seed).unwrap(); |
| 653 | assert_eq!(pending_len(&dst), 0, "the seed unlocks the kept p2 change"); |
| 654 | dst.import(&u_p3).unwrap(); |
| 655 | |
| 656 | let expected = LoroDoc::new_auto_commit(); |
| 657 | expected.set_peer_id(8).unwrap(); |
| 658 | expected.import(&u_seed).unwrap(); |
| 659 | expected.import(&u_p2).unwrap(); |
| 660 | expected.import(&u_p3).unwrap(); |
| 661 | assert_eq!(dst.oplog_vv(), expected.oplog_vv()); |
| 662 | assert_eq!(dst.get_deep_value(), expected.get_deep_value()); |
| 663 | } |
| 664 | |
| 665 | /// One blob can both park a change and unlock it in the same import: B1 parks while |
| 666 | /// A1 is missing, B0 unlocks A1, and the cascade then applies B1. If that import's |
| 667 | /// state apply fails, rollback must re-park only what was pending *before* the |
| 668 | /// import — resurrecting the import's own parked changes would leave pending entries |
| 669 | /// whose arena registrations were just rolled back. |
| 670 | #[test] |
| 671 | fn failed_import_reparks_only_preexisting_pending_changes() { |
| 672 | use loro_common::IdSpan; |
| 673 | |
| 674 | let a = LoroDoc::new_auto_commit(); |
| 675 | a.set_peer_id(1).unwrap(); |
| 676 | a.get_text("text").insert_unicode(0, "A0").unwrap(); |
| 677 | let u_a0 = a |
| 678 | .export(ExportMode::updates(&VersionVector::default())) |
| 679 | .unwrap(); |
| 680 | let vv_a0 = a.oplog_vv(); |
| 681 | let a_counter_after_a0 = *vv_a0.get(&1).unwrap(); |
| 682 | |
| 683 | let b = LoroDoc::new_auto_commit(); |
| 684 | b.set_peer_id(2).unwrap(); |
| 685 | b.import(&u_a0).unwrap(); |
| 686 | b.get_text("text").insert_unicode(2, "B0").unwrap(); |
| 687 | let u_b0 = b.export(ExportMode::updates(&vv_a0)).unwrap(); |
| 688 | |
| 689 | a.import(&u_b0).unwrap(); |
| 690 | a.get_text("text").insert_unicode(4, "A1").unwrap(); |
| 691 | let a_counter_after_a1 = *a.oplog_vv().get(&1).unwrap(); |
| 692 | // Peer-A ops only (A1), without B0 — pending on a doc that only has A0. |
| 693 | let u_a1_only = a |
| 694 | .export(ExportMode::updates_in_range(vec![IdSpan::new( |
| 695 | 1, |
| 696 | a_counter_after_a0, |
| 697 | a_counter_after_a1, |
| 698 | )])) |
| 699 | .unwrap(); |
| 700 | |
| 701 | b.import(&u_a1_only).unwrap(); |
| 702 | b.get_text("text").insert_unicode(6, "B1").unwrap(); |
| 703 | // Single blob with B0 and B1; B1 depends on A1. |
| 704 | let u_b0_b1 = b.export(ExportMode::updates(&vv_a0)).unwrap(); |
| 705 | |
| 706 | let d = LoroDoc::new_auto_commit(); |
| 707 | d.set_peer_id(3).unwrap(); |
| 708 | d.import(&u_a0).unwrap(); |
| 709 | d.import(&u_a1_only).unwrap(); |
| 710 | assert_eq!(pending_len(&d), 1); |
| 711 | let vv_before = d.oplog_vv(); |
| 712 | let frontiers_before = d.oplog_frontiers(); |
| 713 | let state_before = d.get_deep_value(); |
| 714 | |
| 715 | fail_next_import_state_apply_for_test(); |
| 716 | let err = d.import(&u_b0_b1).unwrap_err(); |
| 717 | assert!(err.to_string().contains("state apply failpoint"), "{err:?}"); |
| 718 | assert_eq!( |
| 719 | pending_len(&d), |
| 720 | 1, |
| 721 | "only the pre-import pending change may be re-parked" |
| 722 | ); |
| 723 | assert_doc_unchanged(&d, &vv_before, &frontiers_before, &state_before); |
| 724 | |
| 725 | // Retrying converges. |
| 726 | d.import(&u_b0_b1).unwrap(); |
| 727 | assert_eq!(pending_len(&d), 0); |
| 728 | assert_eq!(d.oplog_vv(), b.oplog_vv()); |
| 729 | assert_eq!(d.get_deep_value(), b.get_deep_value()); |
| 730 | } |
| 731 | |
| 732 | /// The same guarantee for a panic (malformed remote data reaching an `unreachable!` |
| 733 | /// in decode/apply is the shape that originally stranded the document). The blobs |
| 734 | /// imported before the panic must still be applied to `DocState`. |
| 735 | #[test] |
| 736 | fn import_batch_panic_leaves_doc_attached() { |
| 737 | let (dst, blobs, expected) = doc_with_snapshot_and_pending_updates(); |
| 738 | assert!(blobs.len() > 2); |
| 739 | |
| 740 | crate::loro::panic_at_batch_import_blob_for_test(2); |
| 741 | let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 742 | let _ = dst.import_batch(&blobs); |
| 743 | })); |
| 744 | assert!(panicked.is_err(), "the failpoint should have panicked"); |
| 745 | |
| 746 | assert!( |
| 747 | !dst.is_detached(), |
| 748 | "import_batch must leave the doc attached" |
| 749 | ); |
| 750 | assert!(!dst.oplog().lock().batch_importing); |
| 751 | assert_eq!(dst.state_frontiers(), dst.oplog_frontiers()); |
| 752 | |
| 753 | // The document still accepts the updates it missed. |
| 754 | dst.import_batch(&blobs).unwrap(); |
| 755 | assert!(!dst.is_detached()); |
| 756 | assert_eq!(dst.oplog_vv(), expected.oplog_vv()); |
| 757 | assert_eq!(dst.get_deep_value(), expected.get_deep_value()); |
| 758 | } |
| 759 | |
| 760 | /// A doc that was already detached must stay detached: the batch is only allowed to |
| 761 | /// restore the pre-batch mode, not to silently attach. |
| 762 | #[test] |
| 763 | fn import_batch_keeps_explicitly_detached_doc_detached() { |
| 764 | let (dst, blobs, _) = doc_with_snapshot_and_pending_updates(); |
| 765 | dst.detach(); |
| 766 | let state_frontiers = dst.state_frontiers(); |
| 767 | |
| 768 | dst.import_batch(&blobs).unwrap(); |
| 769 | assert!(dst.is_detached()); |
| 770 | assert_eq!(dst.state_frontiers(), state_frontiers); |
| 771 | assert!(!dst.oplog().lock().batch_importing); |
| 772 | } |
| 773 | |
| 774 | #[test] |
| 775 | fn corrupt_snapshot_import_rolls_back_empty_doc() { |
| 776 | let src = LoroDoc::new_auto_commit(); |
| 777 | src.set_peer_id(9).unwrap(); |
| 778 | src.get_text("text").insert_unicode(0, "snapshot").unwrap(); |
| 779 | src.get_list("list").push("value").unwrap(); |
| 780 | let snapshot = src.export(ExportMode::Snapshot).unwrap(); |
| 781 | let mut corrupt_snapshot = snapshot.clone(); |
| 782 | corrupt_snapshot_state_bytes(&mut corrupt_snapshot); |
| 783 | |
| 784 | let dst = LoroDoc::new(); |
| 785 | let vv_before_import = dst.oplog_vv(); |
| 786 | let frontiers_before_import = dst.oplog_frontiers(); |
| 787 | let state_before_import = dst.get_deep_value(); |
| 788 | let err = dst.import(&corrupt_snapshot).unwrap_err(); |
| 789 | assert!( |
| 790 | err.to_string().contains("decode_snapshot") |
| 791 | || err.to_string().contains("Decode") |
| 792 | || err.to_string().contains("snapshot"), |
| 793 | "unexpected error: {err:?}" |
| 794 | ); |
| 795 | assert_eq!(dst.oplog_vv(), vv_before_import); |
| 796 | assert_eq!(dst.oplog_frontiers(), frontiers_before_import); |
| 797 | assert_eq!(dst.get_deep_value(), state_before_import); |
| 798 | assert!(dst.oplog().lock().is_empty()); |
| 799 | |
| 800 | dst.import(&snapshot).unwrap(); |
| 801 | assert_eq!(dst.get_deep_value(), src.get_deep_value()); |
| 802 | } |
| 803 | |
| 804 | #[test] |
| 805 | fn corrupt_snapshot_batch_preserves_empty_handles() { |
| 806 | let source = LoroDoc::new_auto_commit(); |
| 807 | source |
| 808 | .get_text("text") |
| 809 | .insert_unicode(0, "snapshot") |
| 810 | .unwrap(); |
| 811 | let mut snapshot = source.export(ExportMode::Snapshot).unwrap(); |
| 812 | corrupt_snapshot_state_bytes(&mut snapshot); |
| 813 | let empty_update = LoroDoc::new().export(ExportMode::all_updates()).unwrap(); |
| 814 | let target = LoroDoc::new_auto_commit(); |
| 815 | let text = target.get_text("existing"); |
| 816 | let before = target.get_deep_value(); |
| 817 | assert!(target.import_batch(&[snapshot, empty_update]).is_err()); |
| 818 | assert!(!target.is_detached()); |
| 819 | assert_eq!(target.get_deep_value(), before); |
| 820 | assert_eq!(target.oplog_vv(), VersionVector::default()); |
| 821 | text.insert_unicode(0, "usable").unwrap(); |
| 822 | assert_eq!(text.to_string(), "usable"); |
| 823 | } |
| 824 | |
| 825 | #[test] |
| 826 | fn snapshot_import_rejects_corrupt_inner_sstable_with_valid_envelope_checksum() { |
| 827 | let src = LoroDoc::new_auto_commit(); |
| 828 | src.set_peer_id(9).unwrap(); |
| 829 | src.get_map("map").insert("key", "value").unwrap(); |
| 830 | let snapshot = src.export(ExportMode::Snapshot).unwrap(); |
| 831 | |
| 832 | for section in [SnapshotKvSection::OpLog, SnapshotKvSection::State] { |
| 833 | let mut corrupted = snapshot.clone(); |
| 834 | corrupt_snapshot_sstable_block(&mut corrupted, section); |
| 835 | |
| 836 | let dst = LoroDoc::new(); |
| 837 | let err = dst |
| 838 | .import(&corrupted) |
| 839 | .expect_err("invalid inner SSTable checksum must fail during import"); |
| 840 | assert!( |
| 841 | err.to_string().contains("checksum") || err.to_string().contains("Checksum"), |
| 842 | "unexpected {section:?} import error: {err:?}" |
| 843 | ); |
| 844 | assert!(dst.oplog().lock().is_empty()); |
| 845 | assert!(dst |
| 846 | .get_deep_value() |
| 847 | .as_map() |
| 848 | .is_some_and(|value| value.is_empty())); |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | /// A change whose deps are before the shallow root is rejected AND dropped: |
| 853 | /// it must not linger in the pending store, where it could never be unlocked. |
| 854 | /// Locks in the "dropped, not pending" guarantee documented by |
| 855 | /// `loro/tests/shallow_snapshot_concurrency.rs`. |
| 856 | #[test] |
| 857 | fn outdated_update_on_shallow_doc_is_dropped_not_pending() { |
| 858 | let a = LoroDoc::new_auto_commit(); |
| 859 | a.set_peer_id(1).unwrap(); |
| 860 | a.get_map("m").insert("a", 1).unwrap(); |
| 861 | a.commit_then_renew(); |
| 862 | let v_vv = a.oplog_vv(); |
| 863 | let v_frontiers = a.oplog_frontiers(); |
| 864 | a.get_map("m").insert("b", 2).unwrap(); |
| 865 | a.commit_then_renew(); |
| 866 | let f = a.oplog_frontiers(); |
| 867 | a.get_map("m").insert("c", 3).unwrap(); |
| 868 | a.commit_then_renew(); |
| 869 | |
| 870 | // B is bootstrapped from the shallow snapshot at F. |
| 871 | let b = LoroDoc::new(); |
| 872 | b.import(&a.export(ExportMode::shallow_snapshot(&f)).unwrap()) |
| 873 | .unwrap(); |
| 874 | assert_eq!(pending_len(&b), 0); |
| 875 | |
| 876 | // C holds full history up to V and edits on top of it, concurrent with F. |
| 877 | let c = LoroDoc::new(); |
| 878 | c.import(&a.export(ExportMode::snapshot_at(&v_frontiers)).unwrap()) |
| 879 | .unwrap(); |
| 880 | c.set_peer_id(2).unwrap(); |
| 881 | c.get_map("m").insert("from_c", true).unwrap(); |
| 882 | c.commit_then_renew(); |
| 883 | let updates = c.export(ExportMode::updates(&v_vv)).unwrap(); |
| 884 | |
| 885 | let err = b.import(&updates).unwrap_err(); |
| 886 | assert!(matches!( |
| 887 | err, |
| 888 | LoroError::ImportUpdatesThatDependsOnOutdatedVersion |
| 889 | )); |
| 890 | assert_eq!( |
| 891 | pending_len(&b), |
| 892 | 0, |
| 893 | "outdated changes must be dropped, not parked as pending" |
| 894 | ); |
| 895 | } |
| 896 | |
| 897 | /// Binary update whose movable-list move targets an element that never existed. |
| 898 | /// The public import paths reject it, so the carrier inserts the decoded change |
| 899 | /// straight into its oplog to obtain the bytes. |
| 900 | fn binary_update_moving_unknown_movable_list_elem() -> (LoroDoc, Vec<u8>) { |
| 901 | let doc = LoroDoc::new_auto_commit(); |
| 902 | doc.set_peer_id(1).unwrap(); |
| 903 | let list = doc.get_movable_list("list"); |
| 904 | list.insert(0, "a").unwrap(); |
| 905 | list.insert(1, "b").unwrap(); |
| 906 | doc.commit_then_renew(); |
| 907 | |
| 908 | let json = serde_json::json!({ |
| 909 | "schema_version": 1, |
| 910 | "start_version": {}, |
| 911 | "peers": ["1"], |
| 912 | "changes": [{ |
| 913 | "id": "2@0", "timestamp": 0, "deps": ["1@0"], "lamport": 2, "msg": null, |
| 914 | "ops": [{ |
| 915 | "container": "cid:root-list:MovableList", |
| 916 | "content": {"type": "move", "from": 0, "to": 1, "elem_id": "L99@0"}, |
| 917 | "counter": 2 |
| 918 | }] |
| 919 | }] |
| 920 | }); |
| 921 | let bytes = binary_update_bypassing_validation(&doc, json); |
| 922 | (doc, bytes) |
| 923 | } |
| 924 | |
| 925 | /// Encode the JSON `changes` on top of `doc` as a binary update. The carrier inserts |
| 926 | /// the decoded changes straight into its oplog, so no import validation runs. |
| 927 | fn binary_update_bypassing_validation(doc: &LoroDoc, json: serde_json::Value) -> Vec<u8> { |
| 928 | let carrier = LoroDoc::new(); |
| 929 | carrier |
| 930 | .import(&doc.export(ExportMode::all_updates()).unwrap()) |
| 931 | .unwrap(); |
| 932 | let json: JsonSchema = serde_json::from_value(json).unwrap(); |
| 933 | { |
| 934 | let mut oplog = carrier.oplog().lock(); |
| 935 | let changes = |
| 936 | crate::encoding::json_schema::decode_json_changes(json, &oplog.arena).unwrap(); |
| 937 | crate::encoding::apply_decoded_changes_to_oplog(&mut oplog, changes).unwrap(); |
| 938 | } |
| 939 | carrier |
| 940 | .export(ExportMode::updates(&doc.oplog_vv())) |
| 941 | .unwrap() |
| 942 | } |
| 943 | |
| 944 | /// Peer 2 edits a map, and peer 3 moves an unknown element in a change that depends on |
| 945 | /// peer 2's. The import preflight used to skip peer 3's ops because its deps were not |
| 946 | /// in the DAG yet, so the blob was imported without a rollback scope or validation. |
| 947 | #[test] |
| 948 | fn binary_forged_move_behind_same_blob_dependency_is_rejected() { |
| 949 | let (doc, _) = binary_update_moving_unknown_movable_list_elem(); |
| 950 | let json = serde_json::json!({ |
| 951 | "schema_version": 1, |
| 952 | "start_version": {}, |
| 953 | "peers": ["1", "2", "3"], |
| 954 | "changes": [ |
| 955 | { |
| 956 | "id": "0@1", "timestamp": 0, "deps": ["1@0"], "lamport": 2, "msg": null, |
| 957 | "ops": [{ |
| 958 | "container": "cid:root-meta:Map", |
| 959 | "content": {"type": "insert", "key": "k", "value": 1}, |
| 960 | "counter": 0 |
| 961 | }] |
| 962 | }, |
| 963 | { |
| 964 | "id": "0@2", "timestamp": 0, "deps": ["0@1"], "lamport": 3, "msg": null, |
| 965 | "ops": [{ |
| 966 | "container": "cid:root-list:MovableList", |
| 967 | "content": {"type": "move", "from": 0, "to": 1, "elem_id": "L99@0"}, |
| 968 | "counter": 0 |
| 969 | }] |
| 970 | } |
| 971 | ] |
| 972 | }); |
| 973 | let bad = binary_update_bypassing_validation(&doc, json); |
| 974 | let vv_before = doc.oplog_vv(); |
| 975 | let frontiers_before = doc.oplog_frontiers(); |
| 976 | let state_before = doc.get_deep_value(); |
| 977 | |
| 978 | let err = doc.import(&bad).unwrap_err(); |
| 979 | assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); |
| 980 | assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); |
| 981 | |
| 982 | let err = doc.import_batch(std::slice::from_ref(&bad)).unwrap_err(); |
| 983 | assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); |
| 984 | assert!(!doc.is_detached()); |
| 985 | assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); |
| 986 | |
| 987 | doc.detach(); |
| 988 | let err = doc.import(&bad).unwrap_err(); |
| 989 | assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); |
| 990 | doc.attach(); |
| 991 | assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); |
| 992 | |
| 993 | doc.get_movable_list("list").mov(0, 1).unwrap(); |
| 994 | doc.commit_then_renew(); |
| 995 | assert_eq!(doc.state_frontiers(), doc.oplog_frontiers()); |
| 996 | } |
| 997 | |
| 998 | #[test] |
| 999 | fn binary_move_of_unknown_movable_list_elem_is_rejected_atomically() { |
| 1000 | let (doc, bad) = binary_update_moving_unknown_movable_list_elem(); |
| 1001 | let vv_before = doc.oplog_vv(); |
| 1002 | let frontiers_before = doc.oplog_frontiers(); |
| 1003 | let state_before = doc.get_deep_value(); |
| 1004 | |
| 1005 | let err = doc.import(&bad).unwrap_err(); |
| 1006 | assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); |
| 1007 | assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); |
| 1008 | |
| 1009 | doc.detach(); |
| 1010 | let err = doc.import(&bad).unwrap_err(); |
| 1011 | assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); |
| 1012 | doc.attach(); |
| 1013 | assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); |
| 1014 | |
| 1015 | doc.get_movable_list("list").mov(0, 1).unwrap(); |
| 1016 | doc.commit_then_renew(); |
| 1017 | assert_eq!(doc.state_frontiers(), doc.oplog_frontiers()); |
| 1018 | } |
| 1019 | |
| 1020 | /// Blobs inside an attached `import_batch` are imported detached, so their element |
| 1021 | /// references are validated once in `BatchImportGuard::finish`. |
| 1022 | #[test] |
| 1023 | fn import_batch_with_move_of_unknown_movable_list_elem_rolls_back() { |
| 1024 | let (doc, bad) = binary_update_moving_unknown_movable_list_elem(); |
| 1025 | let valid = LoroDoc::new_auto_commit(); |
| 1026 | valid.set_peer_id(2).unwrap(); |
| 1027 | valid |
| 1028 | .import(&doc.export(ExportMode::all_updates()).unwrap()) |
| 1029 | .unwrap(); |
| 1030 | valid.get_movable_list("list").push("v".into()).unwrap(); |
| 1031 | valid.commit_then_renew(); |
| 1032 | let valid_update = valid.export(ExportMode::updates(&doc.oplog_vv())).unwrap(); |
| 1033 | |
| 1034 | let vv_before = doc.oplog_vv(); |
| 1035 | let frontiers_before = doc.oplog_frontiers(); |
| 1036 | let state_before = doc.get_deep_value(); |
| 1037 | |
| 1038 | let err = doc.import_batch(&[valid_update, bad]).unwrap_err(); |
| 1039 | assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); |
| 1040 | assert!(!doc.is_detached()); |
| 1041 | assert!(!doc.oplog().lock().batch_importing); |
| 1042 | assert_doc_unchanged(&doc, &vv_before, &frontiers_before, &state_before); |
| 1043 | |
| 1044 | doc.get_movable_list("list").mov(0, 1).unwrap(); |
| 1045 | doc.commit_then_renew(); |
| 1046 | assert_eq!(doc.state_frontiers(), doc.oplog_frontiers()); |
| 1047 | } |
| 1048 | |
| 1049 | #[test] |
| 1050 | fn detached_text_import_that_unlocks_invalid_movable_list_ops_rolls_back() { |
| 1051 | let (doc, _) = binary_update_moving_unknown_movable_list_elem(); |
| 1052 | let text_peer = LoroDoc::new_auto_commit(); |
| 1053 | text_peer.set_peer_id(2).unwrap(); |
| 1054 | text_peer |
| 1055 | .import(&doc.export(ExportMode::all_updates()).unwrap()) |
| 1056 | .unwrap(); |
| 1057 | text_peer |
| 1058 | .get_text("t") |
| 1059 | .insert(0, "unlock", PosType::Unicode) |
| 1060 | .unwrap(); |
| 1061 | text_peer.commit_then_renew(); |
| 1062 | let text_update = text_peer |
| 1063 | .export(ExportMode::updates(&doc.oplog_vv())) |
| 1064 | .unwrap(); |
| 1065 | let bad = binary_update_bypassing_validation( |
| 1066 | &text_peer, |
| 1067 | serde_json::json!({ |
| 1068 | "schema_version": 1, "start_version": {}, "peers": ["2", "3"], |
| 1069 | "changes": [{ |
| 1070 | "id": "0@1", "timestamp": 0, "deps": ["0@0"], "lamport": 8, "msg": null, |
| 1071 | "ops": [{ |
| 1072 | "container": "cid:root-list:MovableList", "counter": 0, |
| 1073 | "content": {"type": "move", "from": 0, "to": 1, "elem_id": "L99@0"} |
| 1074 | }] |
| 1075 | }] |
| 1076 | }), |
| 1077 | ); |
| 1078 | let vv = doc.oplog_vv(); |
| 1079 | let frontiers = doc.oplog_frontiers(); |
| 1080 | let state = doc.get_deep_value(); |
| 1081 | doc.detach(); |
| 1082 | doc.import(&bad).unwrap(); |
| 1083 | let pending_before = doc.oplog().lock().pending_changes_len(); |
| 1084 | assert!(pending_before > 0); |
| 1085 | let err = doc.import(&text_update).unwrap_err(); |
| 1086 | assert!(matches!(err, LoroError::DecodeError(_)), "{err:?}"); |
| 1087 | assert!(doc.is_detached()); |
| 1088 | assert_eq!(doc.oplog().lock().pending_changes_len(), pending_before); |
| 1089 | doc.attach(); |
| 1090 | assert_doc_unchanged(&doc, &vv, &frontiers, &state); |
| 1091 | } |