1use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::{Condvar, Mutex};
5
6use crate::api::{RedDBError, RedDBResult};
7use crate::application::entity::metadata_from_json;
8use crate::replication::cdc::{
9 change_record_from_entity, wire_json_to_server_json, ChangeOperation, ChangeRecord,
10 RangeAdmitError, RangeAuthority,
11};
12use crate::replication::fence::{FenceVerdict, MemoryTermStore, TermFence};
13use crate::storage::{EntityId, EntityKind, RedDB, UnifiedStore};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum ApplyMode {
17 Replica,
18 Restore,
19}
20
21#[derive(Debug, Default)]
27pub struct ReplicaApplyMetrics {
28 #[cfg(test)]
29 transaction_member_barrier: Mutex<Option<std::sync::Arc<std::sync::Barrier>>>,
30 pub gap_total: std::sync::atomic::AtomicU64,
31 pub divergence_total: std::sync::atomic::AtomicU64,
32 pub apply_error_total: std::sync::atomic::AtomicU64,
33 pub decode_error_total: std::sync::atomic::AtomicU64,
34 pub apply_miss_total: std::sync::atomic::AtomicU64,
40 pub fenced_total: std::sync::atomic::AtomicU64,
46 pub bytes_applied_total: std::sync::atomic::AtomicU64,
52 pub records_applied_total: std::sync::atomic::AtomicU64,
57}
58
59impl ReplicaApplyMetrics {
60 pub fn record(&self, kind: ApplyErrorKind) {
61 use std::sync::atomic::Ordering::Relaxed;
62 match kind {
63 ApplyErrorKind::Gap => {
64 self.gap_total.fetch_add(1, Relaxed);
65 }
66 ApplyErrorKind::Divergence => {
67 self.divergence_total.fetch_add(1, Relaxed);
68 }
69 ApplyErrorKind::Apply => {
70 self.apply_error_total.fetch_add(1, Relaxed);
71 }
72 ApplyErrorKind::Decode => {
73 self.decode_error_total.fetch_add(1, Relaxed);
74 }
75 ApplyErrorKind::Miss => {
76 self.apply_miss_total.fetch_add(1, Relaxed);
77 }
78 ApplyErrorKind::Fenced => {
79 self.fenced_total.fetch_add(1, Relaxed);
80 }
81 }
82 }
83
84 pub fn snapshot(&self) -> [(ApplyErrorKind, u64); 6] {
85 use std::sync::atomic::Ordering::Relaxed;
86 [
87 (ApplyErrorKind::Gap, self.gap_total.load(Relaxed)),
88 (
89 ApplyErrorKind::Divergence,
90 self.divergence_total.load(Relaxed),
91 ),
92 (ApplyErrorKind::Apply, self.apply_error_total.load(Relaxed)),
93 (
94 ApplyErrorKind::Decode,
95 self.decode_error_total.load(Relaxed),
96 ),
97 (ApplyErrorKind::Miss, self.apply_miss_total.load(Relaxed)),
98 (ApplyErrorKind::Fenced, self.fenced_total.load(Relaxed)),
99 ]
100 }
101
102 pub fn snapshot_throughput(&self) -> (u64, u64) {
107 use std::sync::atomic::Ordering::Relaxed;
108 (
109 self.bytes_applied_total.load(Relaxed),
110 self.records_applied_total.load(Relaxed),
111 )
112 }
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum ApplyErrorKind {
117 Gap,
118 Divergence,
119 Apply,
120 Decode,
121 Miss,
124 Fenced,
127}
128
129impl ApplyErrorKind {
130 pub fn label(self) -> &'static str {
131 match self {
132 Self::Gap => "gap",
133 Self::Divergence => "divergence",
134 Self::Apply => "apply",
135 Self::Decode => "decode",
136 Self::Miss => "apply_miss",
137 Self::Fenced => "fenced",
138 }
139 }
140}
141
142impl LogicalApplyError {
143 pub fn kind(&self) -> ApplyErrorKind {
144 match self {
145 Self::Gap { .. } => ApplyErrorKind::Gap,
146 Self::Divergence { .. } => ApplyErrorKind::Divergence,
147 Self::Apply { .. } => ApplyErrorKind::Apply,
148 Self::StaleTermFenced { .. } => ApplyErrorKind::Fenced,
149 Self::RangeFenced { .. } => ApplyErrorKind::Fenced,
150 }
151 }
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum ApplyOutcome {
161 Applied,
163 Idempotent,
165 Skipped,
167}
168
169#[derive(Debug)]
170pub enum LogicalApplyError {
171 Gap {
172 last: u64,
173 next: u64,
174 },
175 Divergence {
176 expected_term: u64,
177 got_term: u64,
178 lsn: u64,
179 expected: String,
180 got: String,
181 },
182 Apply {
183 lsn: u64,
184 source: RedDBError,
185 },
186 StaleTermFenced {
191 record_term: u64,
192 current_term: u64,
193 lsn: u64,
194 },
195 RangeFenced {
203 range_id: u64,
204 lsn: u64,
205 reason: RangeAdmitError,
206 },
207}
208
209impl std::fmt::Display for LogicalApplyError {
210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211 match self {
212 Self::Gap { last, next } => write!(f, "LSN gap on apply: last={last} next={next}"),
213 Self::StaleTermFenced {
214 record_term,
215 current_term,
216 lsn,
217 } => write!(
218 f,
219 "stale-term record fenced at lsn={lsn}: record term {record_term} is behind current term {current_term}"
220 ),
221 Self::RangeFenced {
222 range_id,
223 lsn,
224 reason,
225 } => match reason {
226 RangeAdmitError::StaleTerm {
227 record_term,
228 accepted_term,
229 } => write!(
230 f,
231 "range-stale record fenced at lsn={lsn} for range {range_id}: record term {record_term} is behind accepted term {accepted_term}"
232 ),
233 RangeAdmitError::StaleOwnershipEpoch {
234 record_epoch,
235 accepted_epoch,
236 } => write!(
237 f,
238 "range-stale record fenced at lsn={lsn} for range {range_id}: ownership epoch {record_epoch} is behind accepted epoch {accepted_epoch}"
239 ),
240 },
241 Self::Divergence {
242 expected_term,
243 got_term,
244 lsn,
245 expected,
246 got,
247 } => write!(
248 f,
249 "LSN divergence on apply at term/lsn=({got_term},{lsn}): expected term {expected_term} payload hash {expected}, got {got}"
250 ),
251 Self::Apply { lsn, source } => write!(f, "apply error at lsn={lsn}: {source}"),
252 }
253 }
254}
255
256impl std::error::Error for LogicalApplyError {}
257
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub enum BookmarkWaitError {
260 Timeout { target_lsn: u64, applied_lsn: u64 },
261 TermMismatch { target_term: u64, applied_term: u64 },
262}
263
264impl BookmarkWaitError {
265 pub fn is_timeout(&self) -> bool {
266 matches!(self, Self::Timeout { .. })
267 }
268}
269
270impl std::fmt::Display for BookmarkWaitError {
271 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
272 match self {
273 Self::Timeout {
274 target_lsn,
275 applied_lsn,
276 } => write!(
277 f,
278 "timed out waiting for causal bookmark lsn {target_lsn}; applied={applied_lsn}"
279 ),
280 Self::TermMismatch {
281 target_term,
282 applied_term,
283 } => write!(
284 f,
285 "causal bookmark term mismatch: target={target_term} applied={applied_term}"
286 ),
287 }
288 }
289}
290
291impl std::error::Error for BookmarkWaitError {}
292
293pub struct LogicalChangeApplier {
298 last_applied_term: AtomicU64,
299 term_fence: TermFence<MemoryTermStore>,
300 last_applied_lsn: AtomicU64,
301 received_frontier_lsn: AtomicU64,
302 last_payload_hash: Mutex<Option<[u8; 32]>>,
303 apply_wait: (Mutex<()>, Condvar),
304 apply_lock: Mutex<()>,
305 metrics: std::sync::Arc<ReplicaApplyMetrics>,
310}
311
312impl LogicalChangeApplier {
313 pub fn new(starting_lsn: u64) -> Self {
318 Self::with_metrics(
319 starting_lsn,
320 std::sync::Arc::new(ReplicaApplyMetrics::default()),
321 )
322 }
323
324 pub fn with_metrics(starting_lsn: u64, metrics: std::sync::Arc<ReplicaApplyMetrics>) -> Self {
329 Self {
330 last_applied_term: AtomicU64::new(crate::replication::DEFAULT_REPLICATION_TERM),
331 term_fence: TermFence::new(MemoryTermStore::new()),
332 last_applied_lsn: AtomicU64::new(starting_lsn),
333 received_frontier_lsn: AtomicU64::new(starting_lsn),
334 last_payload_hash: Mutex::new(None),
335 apply_wait: (Mutex::new(()), Condvar::new()),
336 apply_lock: Mutex::new(()),
337 metrics,
338 }
339 }
340
341 pub fn metrics(&self) -> &std::sync::Arc<ReplicaApplyMetrics> {
343 &self.metrics
344 }
345
346 pub fn last_applied_lsn(&self) -> u64 {
347 self.last_applied_lsn.load(Ordering::Acquire)
348 }
349
350 pub fn received_frontier_lsn(&self) -> u64 {
351 self.received_frontier_lsn.load(Ordering::Acquire)
352 }
353
354 pub fn last_applied_term(&self) -> u64 {
355 self.last_applied_term.load(Ordering::Acquire)
356 }
357
358 pub fn wait_for_bookmark(
359 &self,
360 bookmark: &crate::replication::CausalBookmark,
361 timeout: std::time::Duration,
362 ) -> Result<(), BookmarkWaitError> {
363 let deadline = std::time::Instant::now() + timeout;
364 let target_lsn = bookmark.commit_lsn();
365 let target_term = bookmark.term();
366
367 let mut guard = self.apply_wait.0.lock().expect("apply wait mutex");
368 loop {
369 let applied_lsn = self.last_applied_lsn();
370 let applied_term = self.last_applied_term();
371 if applied_lsn >= target_lsn {
372 if applied_term == target_term {
373 return Ok(());
374 }
375 return Err(BookmarkWaitError::TermMismatch {
376 target_term,
377 applied_term,
378 });
379 }
380
381 let now = std::time::Instant::now();
382 if now >= deadline {
383 return Err(BookmarkWaitError::Timeout {
384 target_lsn,
385 applied_lsn,
386 });
387 }
388 let remaining = deadline.saturating_duration_since(now);
389 let (next_guard, wait_result) = self
390 .apply_wait
391 .1
392 .wait_timeout(guard, remaining)
393 .expect("apply wait condvar");
394 guard = next_guard;
395 if wait_result.timed_out() {
396 return Err(BookmarkWaitError::Timeout {
397 target_lsn,
398 applied_lsn: self.last_applied_lsn(),
399 });
400 }
401 }
402 }
403
404 pub fn apply(
412 &self,
413 db: &RedDB,
414 record: &ChangeRecord,
415 mode: ApplyMode,
416 ) -> Result<ApplyOutcome, LogicalApplyError> {
417 self.apply_fenced(db, record, mode, None)
418 }
419
420 pub fn apply_fenced(
429 &self,
430 db: &RedDB,
431 record: &ChangeRecord,
432 mode: ApplyMode,
433 range_fence: Option<&RangeAuthority>,
434 ) -> Result<ApplyOutcome, LogicalApplyError> {
435 let _apply = self.apply_lock.lock().expect("apply mutex");
438 let last = self.last_applied_lsn.load(Ordering::Acquire);
439 let last_term = self.last_applied_term.load(Ordering::Acquire);
440
441 if let Some(fence) = range_fence {
446 if let Err(reason) = fence.admit(record) {
447 self.metrics.record(ApplyErrorKind::Fenced);
448 return Err(LogicalApplyError::RangeFenced {
449 range_id: fence.range_id,
450 lsn: record.lsn,
451 reason,
452 });
453 }
454 }
455
456 if let FenceVerdict::Fenced(rejection) = self
461 .term_fence
462 .admit_record(record.term)
463 .expect("in-memory term store")
464 {
465 self.metrics.record(ApplyErrorKind::Fenced);
466 return Err(LogicalApplyError::StaleTermFenced {
467 record_term: rejection.incoming_term,
468 current_term: rejection.current_term,
469 lsn: record.lsn,
470 });
471 }
472
473 let payload_hash = record_payload_hash(record);
474 self.received_frontier_lsn
475 .fetch_max(record.lsn, Ordering::AcqRel);
476
477 if last == 0 && record.lsn > 0 {
478 self.do_apply(db, record, mode)?;
479 self.publish_applied(record, payload_hash);
480 return Ok(ApplyOutcome::Applied);
481 }
482
483 if record.lsn == last {
484 let prior = *self.last_payload_hash.lock().expect("payload hash mutex");
485 return match prior {
486 Some(p) if p == payload_hash => Ok(ApplyOutcome::Idempotent),
487 Some(p) => Err(LogicalApplyError::Divergence {
488 expected_term: last_term,
489 got_term: record.term,
490 lsn: record.lsn,
491 expected: hex_digest(&p),
492 got: hex_digest(&payload_hash),
493 }),
494 None => Ok(ApplyOutcome::Idempotent),
495 };
496 }
497 if record.lsn < last {
498 return Ok(ApplyOutcome::Skipped);
499 }
500 if record.lsn > last + 1 {
501 return Err(LogicalApplyError::Gap {
502 last,
503 next: record.lsn,
504 });
505 }
506
507 self.do_apply(db, record, mode)?;
508 self.publish_applied(record, payload_hash);
509 Ok(ApplyOutcome::Applied)
510 }
511
512 fn publish_applied(&self, record: &ChangeRecord, payload_hash: [u8; 32]) {
513 let _wait = self.apply_wait.0.lock().expect("apply wait mutex");
515 self.last_applied_term.store(record.term, Ordering::Release);
516 self.last_applied_lsn.store(record.lsn, Ordering::Release);
517 *self.last_payload_hash.lock().expect("payload hash mutex") = Some(payload_hash);
518 self.apply_wait.1.notify_all();
519 }
520
521 fn do_apply(
522 &self,
523 db: &RedDB,
524 record: &ChangeRecord,
525 mode: ApplyMode,
526 ) -> Result<(), LogicalApplyError> {
527 Self::apply_record_with_metrics(db, record, mode, &self.metrics).map_err(|err| {
528 LogicalApplyError::Apply {
529 lsn: record.lsn,
530 source: err,
531 }
532 })
533 }
534
535 pub fn apply_record(db: &RedDB, record: &ChangeRecord, mode: ApplyMode) -> RedDBResult<()> {
542 Self::apply_record_with_metrics(db, record, mode, &ReplicaApplyMetrics::default())
543 }
544
545 pub fn apply_record_with_metrics(
554 db: &RedDB,
555 record: &ChangeRecord,
556 mode: ApplyMode,
557 metrics: &ReplicaApplyMetrics,
558 ) -> RedDBResult<()> {
559 if record.operation == ChangeOperation::Transaction {
560 return Self::apply_transaction(db, record, mode, metrics);
561 }
562 Self::apply_member(db, record, metrics, None)
563 }
564
565 fn apply_member(
566 db: &RedDB,
567 record: &ChangeRecord,
568 metrics: &ReplicaApplyMetrics,
569 transaction_xid: Option<u64>,
570 ) -> RedDBResult<()> {
571 if db.options().read_only {
572 return Err(RedDBError::InvalidOperation(
573 "cannot apply logical changes to a read-only database".into(),
574 ));
575 }
576 let payload_bytes: u64 = match record.operation {
581 ChangeOperation::Insert | ChangeOperation::Update => record
582 .entity_bytes
583 .as_ref()
584 .map(|b| b.len() as u64)
585 .unwrap_or(0),
586 ChangeOperation::Refresh => record
587 .refresh_records
588 .as_ref()
589 .map(|recs| recs.iter().map(|r| r.len() as u64).sum())
590 .unwrap_or(0),
591 ChangeOperation::Delete => 0,
592 ChangeOperation::Transaction => unreachable!("transaction members are validated"),
593 };
594 let store = db.store();
595 let runtime = db
596 .runtime
597 .get()
598 .and_then(crate::runtime::WeakRuntime::upgrade);
599 let indexes = runtime.as_ref().map(|runtime| runtime.index_store_ref());
600 let _publication = indexes.map(|indexes| indexes.begin_unscoped_indexed_mutation());
601 let topology = indexes.map(|indexes| indexes.collection_topology_lock(&record.collection));
602 let _topology = topology.as_ref().map(|lock| lock.read_recursive());
605 let _storage_publication = store.vault_publication_lock.lock();
606 let incoming = record
609 .entity_bytes
610 .as_ref()
611 .map(|bytes| {
612 UnifiedStore::deserialize_entity(bytes, store.format_version())
613 .map_err(|err| RedDBError::Internal(err.to_string()))
614 })
615 .transpose()?;
616 if incoming
617 .as_ref()
618 .is_some_and(|entity| entity.id.raw() != record.entity_id)
619 {
620 return Err(RedDBError::Internal(
621 "replication entity identity does not match its payload".into(),
622 ));
623 }
624 let metadata = record
625 .metadata
626 .as_ref()
627 .map(|json| metadata_from_json(&wire_json_to_server_json(json)))
628 .transpose()?;
629 let mut previous = match record.operation {
630 ChangeOperation::Refresh => store
631 .get_collection(&record.collection)
632 .map(|manager| manager.query_all(|_| true))
633 .unwrap_or_default(),
634 _ => store
635 .get(&record.collection, EntityId::new(record.entity_id))
636 .into_iter()
637 .collect(),
638 };
639 if let Some(entity) = &incoming {
640 if matches!(entity.kind, EntityKind::TableRow { .. }) {
641 previous.extend(
642 store
643 .table_row_versions_by_logical_id(&record.collection, entity.logical_id())
644 .into_iter()
645 .filter(|version| {
646 version.id != entity.id
647 && (version.xmax == 0
648 || runtime.as_ref().is_some_and(|runtime| {
649 runtime.snapshot_manager().is_aborted(version.xmax)
650 }))
651 }),
652 );
653 }
654 }
655 let capture = (!UnifiedStore::deferred_store_wal_capture_active())
656 .then(|| crate::storage::unified::store::StoreWalCaptureGuard::begin(None));
657 let mut replayed_xid = 0;
658 match record.operation {
659 ChangeOperation::Delete => {
660 let deletion = if let (Some(runtime), Some(entity)) = (
663 runtime.as_ref(),
664 previous
665 .first()
666 .filter(|entity| matches!(entity.kind, EntityKind::TableRow { .. })),
667 ) {
668 let mut tombstone = entity.clone();
669 if tombstone.xmax == 0 || runtime.snapshot_manager().is_aborted(tombstone.xmax)
670 {
671 tombstone.set_xmax(
672 transaction_xid.unwrap_or_else(|| {
673 runtime.snapshot_manager().allocate_replayed_xid()
674 }),
675 );
676 let manager = store
677 .get_collection(&record.collection)
678 .expect("existing row collection");
679 manager
680 .update(tombstone.clone())
681 .map_err(|error| RedDBError::Internal(error.to_string()))?;
682 store
683 .persist_entities_to_pager(&record.collection, &[tombstone])
684 .map_err(|error| RedDBError::Internal(error.to_string()))?;
685 }
686 Ok(true)
687 } else {
688 store.delete(&record.collection, EntityId::new(record.entity_id))
689 };
690 match deletion {
691 Ok(true) => {}
692 Ok(false) => {
693 metrics.record(ApplyErrorKind::Miss);
696 tracing::warn!(
697 target: "reddb::replication::apply",
698 lsn = record.lsn,
699 collection = %record.collection,
700 entity_id = record.entity_id,
701 "replica delete found no matching entity; recorded apply miss (non-fatal divergence signal)"
702 );
703 }
704 Err(crate::storage::StoreError::CollectionNotFound(name)) => {
705 metrics.record(ApplyErrorKind::Miss);
708 tracing::warn!(
709 target: "reddb::replication::apply",
710 lsn = record.lsn,
711 collection = %name,
712 entity_id = record.entity_id,
713 "replica delete against missing collection; recorded apply miss (non-fatal divergence signal)"
714 );
715 }
716 Err(err) => {
717 return Err(RedDBError::Internal(err.to_string()));
721 }
722 }
723 }
724 ChangeOperation::Refresh => {
725 let records = record.refresh_records.clone().ok_or_else(|| {
734 RedDBError::Internal(
735 "replication refresh record missing refresh_records payload".to_string(),
736 )
737 })?;
738 for bytes in &records {
739 let (entity, _) =
740 UnifiedStore::deserialize_entity_record(bytes, store.format_version())
741 .map_err(|err| RedDBError::Internal(err.to_string()))?;
742 replayed_xid = replayed_xid.max(entity.max_transaction_id());
743 }
744 store
745 .refresh_collection_from_records(&record.collection, records)
746 .map_err(|err| RedDBError::Internal(err.to_string()))?;
747 }
748 ChangeOperation::Insert | ChangeOperation::Update => {
749 let mut entity = incoming.clone().ok_or_else(|| {
750 RedDBError::Internal("replication record missing entity payload".to_string())
751 })?;
752 if let Some(xid) = transaction_xid {
753 let existing = previous.iter().find(|old| {
754 old.id == entity.id
755 && runtime.as_ref().is_some_and(|runtime| {
756 !runtime.snapshot_manager().is_aborted(old.xmin)
757 })
758 });
759 entity.set_xmin(existing.map(|old| old.xmin).unwrap_or(xid));
762 if entity.xmax != 0 {
763 entity.set_xmax(
764 existing
765 .filter(|old| {
766 old.xmax != 0
767 && runtime.as_ref().is_some_and(|runtime| {
768 !runtime.snapshot_manager().is_aborted(old.xmax)
769 })
770 })
771 .map(|old| old.xmax)
772 .unwrap_or(xid),
773 );
774 } else if let Some(existing) = existing {
775 entity.set_xmax(existing.xmax);
776 }
777 } else if matches!(entity.kind, EntityKind::TableRow { .. }) && entity.xmax == 0 {
778 if let Some(runtime) = &runtime {
779 if let Some(existing) = previous.iter().find(|old| old.id == entity.id) {
783 entity.set_xmin(existing.xmin);
784 } else {
785 entity.set_xmin(
786 entity
787 .xmin
788 .max(runtime.snapshot_manager().allocate_replayed_xid()),
789 );
790 }
791 }
792 }
793
794 if matches!(entity.kind, EntityKind::TableRow { .. }) {
813 let logical = entity.logical_id();
814 let new_id = entity.id;
815 let superseding_xid = if entity.xmin != 0 { entity.xmin } else { 1 };
816 let stale: Vec<_> = store
817 .table_row_versions_by_logical_id(&record.collection, logical)
818 .into_iter()
819 .filter(|version| {
820 version.id != new_id
821 && (version.xmax == 0
822 || runtime.as_ref().is_some_and(|runtime| {
823 runtime.snapshot_manager().is_aborted(version.xmax)
824 }))
825 })
826 .collect();
827 if !stale.is_empty() {
828 let manager = store
829 .get_collection(&record.collection)
830 .ok_or_else(|| RedDBError::NotFound(record.collection.clone()))?;
831 let mut changed = Vec::with_capacity(stale.len());
832 for mut version in stale {
833 version.set_xmax(superseding_xid);
834 manager
835 .update(version.clone())
836 .map_err(|err| RedDBError::Internal(err.to_string()))?;
837 changed.push(version);
838 }
839 store
840 .persist_entities_to_pager(&record.collection, &changed)
841 .map_err(|err| RedDBError::Internal(err.to_string()))?;
842 }
843 }
844
845 let exists = store
846 .get(&record.collection, EntityId::new(record.entity_id))
847 .is_some();
848 if exists {
849 let manager = store
850 .get_collection(&record.collection)
851 .ok_or_else(|| RedDBError::NotFound(record.collection.clone()))?;
852 manager
853 .update(entity.clone())
854 .map_err(|err| RedDBError::Internal(err.to_string()))?;
855 store
856 .persist_entities_to_pager(
857 &record.collection,
858 std::slice::from_ref(&entity),
859 )
860 .map_err(|err| RedDBError::Internal(err.to_string()))?;
861 } else {
862 store
863 .insert_auto(&record.collection, entity.clone())
864 .map_err(|err| RedDBError::Internal(err.to_string()))?;
865 }
866 if let Some(metadata) = metadata {
867 store
868 .set_metadata(&record.collection, entity.id, metadata)
869 .map_err(|err| RedDBError::Internal(err.to_string()))?;
870 }
871 store
872 .context_index()
873 .index_entity(&record.collection, &entity);
874 replayed_xid = entity.max_transaction_id();
877 }
878 ChangeOperation::Transaction => unreachable!("transaction members are validated"),
879 }
880 if let Some(capture) = capture {
881 store
882 .append_deferred_store_wal_actions(capture.finish())
883 .map_err(|error| RedDBError::Internal(error.to_string()))?;
884 }
885 if transaction_xid.is_none() {
886 if let Some(manager) = store.snapshot_manager.get() {
887 manager.observe_committed_xid(replayed_xid);
888 }
889 }
890 if let Some(indexes) = indexes {
891 let publish = (|| -> Result<(), String> {
892 for entity in &previous {
893 indexes.index_entity_delete(
894 &record.collection,
895 entity.id,
896 &crate::application::ports::entity_row_fields_snapshot(entity),
897 )?;
898 }
899 let current = match record.operation {
900 ChangeOperation::Refresh => store
901 .get_collection(&record.collection)
902 .map(|manager| manager.query_all(|entity| entity.xmax == 0))
903 .unwrap_or_default(),
904 ChangeOperation::Insert | ChangeOperation::Update => incoming
905 .into_iter()
906 .filter(|entity| entity.xmax == 0)
907 .collect(),
908 ChangeOperation::Delete => Vec::new(),
909 ChangeOperation::Transaction => {
910 unreachable!("transaction members are validated")
911 }
912 };
913 for entity in ¤t {
914 indexes.index_entity_insert(
915 &record.collection,
916 entity.id,
917 &crate::application::ports::entity_row_fields_snapshot(entity),
918 )?;
919 }
920 Ok(())
921 })();
922 if let Some(runtime) = &runtime {
923 runtime.invalidate_result_cache_for_table(&record.collection);
924 }
925 if let Err(error) = publish {
926 for index in indexes.list_indices(&record.collection) {
929 indexes.drop_index(&index.name, &record.collection);
930 }
931 return Err(RedDBError::Internal(error));
932 }
933 }
934 metrics
937 .bytes_applied_total
938 .fetch_add(payload_bytes, Ordering::Relaxed);
939 metrics
940 .records_applied_total
941 .fetch_add(1, Ordering::Relaxed);
942 Ok(())
943 }
944
945 fn apply_transaction(
946 db: &RedDB,
947 record: &ChangeRecord,
948 _mode: ApplyMode,
949 metrics: &ReplicaApplyMetrics,
950 ) -> RedDBResult<()> {
951 let encoded = record
952 .refresh_records
953 .as_ref()
954 .ok_or_else(|| RedDBError::Internal("replication transaction has no members".into()))?;
955 if encoded.is_empty()
956 || encoded.len() > 65_536
957 || encoded.iter().map(Vec::len).sum::<usize>() > 16 * 1024 * 1024
958 {
959 return Err(RedDBError::InvalidOperation(
960 "invalid replication transaction size".into(),
961 ));
962 }
963 let members = encoded
964 .iter()
965 .map(|bytes| ChangeRecord::decode(bytes))
966 .collect::<Result<Vec<_>, _>>()
967 .map_err(RedDBError::Internal)?;
968 let store = db.store();
969 for member in &members {
971 if !matches!(
972 member.operation,
973 ChangeOperation::Insert | ChangeOperation::Update | ChangeOperation::Delete
974 ) {
975 return Err(RedDBError::InvalidOperation(
976 "unsupported replication transaction member".into(),
977 ));
978 }
979 if let Some(bytes) = &member.entity_bytes {
980 let entity = UnifiedStore::deserialize_entity(bytes, store.format_version())
981 .map_err(|error| RedDBError::Internal(error.to_string()))?;
982 if entity.id.raw() != member.entity_id {
983 return Err(RedDBError::Internal(
984 "replication member identity mismatch".into(),
985 ));
986 }
987 } else if member.operation != ChangeOperation::Delete {
988 return Err(RedDBError::Internal(
989 "replication member missing entity".into(),
990 ));
991 }
992 if let Some(metadata) = &member.metadata {
993 metadata_from_json(&wire_json_to_server_json(metadata))?;
994 }
995 }
996 let runtime = db
997 .runtime
998 .get()
999 .and_then(crate::runtime::WeakRuntime::upgrade);
1000 let indexes = runtime.as_ref().map(|runtime| runtime.index_store_ref());
1001 let _indexes = indexes.map(|indexes| indexes.begin_unscoped_indexed_mutation());
1002 let mut collections: Vec<_> = members.iter().map(|member| &member.collection).collect();
1003 collections.sort_unstable();
1004 collections.dedup();
1005 let topology: Vec<_> = indexes
1006 .map(|indexes| {
1007 collections
1008 .iter()
1009 .map(|collection| indexes.collection_topology_lock(collection))
1010 .collect()
1011 })
1012 .unwrap_or_default();
1013 let _topology: Vec<_> = topology.iter().map(|lock| lock.read()).collect();
1014 let _storage = store.vault_publication_lock.lock();
1015 let manager = store.snapshot_manager.get();
1016 let xid = manager.map(|manager| manager.begin());
1017 let capture = crate::storage::unified::store::StoreWalCaptureGuard::begin(None);
1018 let applied = (|| -> RedDBResult<()> {
1019 for member in &members {
1020 Self::apply_member(db, member, metrics, xid)?;
1021 #[cfg(test)]
1022 if std::ptr::eq(member, &members[0]) {
1023 let barrier = metrics
1024 .transaction_member_barrier
1025 .lock()
1026 .expect("test barrier mutex")
1027 .clone();
1028 if let Some(barrier) = barrier {
1029 barrier.wait();
1030 barrier.wait();
1031 }
1032 }
1033 }
1034 store
1035 .append_deferred_store_wal_actions(capture.finish())
1036 .map_err(|error| RedDBError::Internal(error.to_string()))
1037 })();
1038 match applied {
1039 Ok(()) => {
1040 if let (Some(manager), Some(xid)) = (manager, xid) {
1041 manager.commit(xid);
1042 }
1043 Ok(())
1044 }
1045 Err(error) => {
1046 if let (Some(manager), Some(xid)) = (manager, xid) {
1047 manager.rollback(xid);
1048 }
1049 if let Some(indexes) = indexes {
1050 for member in &members {
1051 for index in indexes.list_indices(&member.collection) {
1052 indexes.drop_index(&index.name, &member.collection);
1053 }
1054 }
1055 }
1056 Err(error)
1057 }
1058 }
1059 }
1060}
1061
1062fn record_payload_hash(record: &ChangeRecord) -> [u8; 32] {
1063 let mut hasher = crate::crypto::sha256::Sha256::new();
1064 hasher.update(&record.term.to_le_bytes());
1065 hasher.update(&record.lsn.to_le_bytes());
1066 hasher.update(&[record.operation as u8]);
1067 hasher.update(record.collection.as_bytes());
1068 hasher.update(&record.entity_id.to_le_bytes());
1069 hasher.update(&record.range_id.unwrap_or(u64::MAX).to_le_bytes());
1075 hasher.update(&record.ownership_epoch.unwrap_or(u64::MAX).to_le_bytes());
1076 if let Some(bytes) = &record.entity_bytes {
1077 hasher.update(bytes);
1078 }
1079 if let Some(records) = &record.refresh_records {
1083 hasher.update(&(records.len() as u64).to_le_bytes());
1084 for r in records {
1085 hasher.update(&(r.len() as u64).to_le_bytes());
1086 hasher.update(r);
1087 }
1088 }
1089 hasher.finalize()
1090}
1091
1092fn hex_digest(bytes: &[u8; 32]) -> String {
1093 crate::utils::to_hex(bytes)
1094}
1095
1096#[cfg(test)]
1097mod tests {
1098 use super::*;
1099 use crate::replication::cdc::ChangeOperation;
1100 use crate::storage::{EntityData, EntityId, EntityKind, RedDB, RowData, UnifiedEntity};
1101 use reddb_types::Value;
1102 use std::sync::Arc;
1103
1104 #[test]
1105 fn transaction_members_become_visible_together() {
1106 let replica =
1107 crate::RedDBRuntime::with_options(crate::RedDBOptions::in_memory()).expect("replica");
1108 replica
1109 .execute_query("CREATE TABLE users (id INT, payload BLOB)")
1110 .expect("schema");
1111 assert!(replica
1117 .execute_query("SELECT id FROM users")
1118 .expect("initialize read metadata")
1119 .result
1120 .records
1121 .is_empty());
1122 let applier = Arc::new(LogicalChangeApplier::new(0));
1123 let barrier = Arc::new(std::sync::Barrier::new(2));
1124 *applier
1125 .metrics()
1126 .transaction_member_barrier
1127 .lock()
1128 .expect("barrier mutex") = Some(barrier.clone());
1129 let transaction =
1130 ChangeRecord::for_transaction(1, 1, vec![record(1, b"a"), record(2, b"b")]);
1131 let writer = replica.clone();
1132 let worker = std::thread::spawn(move || {
1133 applier.apply(writer.db().as_ref(), &transaction, ApplyMode::Replica)
1134 });
1135 barrier.wait();
1136 let during = replica.execute_query("SELECT id FROM users");
1137 barrier.wait();
1138 worker
1139 .join()
1140 .expect("apply worker")
1141 .expect("apply transaction");
1142 assert!(during.expect("concurrent query").result.records.is_empty());
1143 assert_eq!(
1144 replica
1145 .execute_query("SELECT id FROM users")
1146 .expect("query")
1147 .result
1148 .records
1149 .len(),
1150 2
1151 );
1152 }
1153
1154 #[test]
1155 fn transaction_retry_supersedes_versions_from_aborted_apply() {
1156 let replica = crate::RedDBRuntime::with_options(crate::RedDBOptions::in_memory())
1157 .expect("in-memory replica should open");
1158 replica
1159 .execute_query("CREATE TABLE users (id INT, payload BLOB)")
1160 .expect("users table should be created");
1161 let applier = LogicalChangeApplier::new(0);
1162 applier
1163 .apply(
1164 replica.db().as_ref(),
1165 &record(1, b"old"),
1166 ApplyMode::Replica,
1167 )
1168 .expect("initial record should apply");
1169 let mut update = record(2, b"new");
1170 let mut entity = UnifiedStore::deserialize_entity(
1171 update
1172 .entity_bytes
1173 .as_ref()
1174 .expect("update record should contain an entity"),
1175 crate::api::REDDB_FORMAT_VERSION,
1176 )
1177 .expect("update entity should deserialize");
1178 entity.set_logical_id(EntityId::new(1));
1179 update.entity_bytes = Some(UnifiedStore::serialize_entity(
1180 &entity,
1181 replica.db().store().format_version(),
1182 ));
1183 update.operation = ChangeOperation::Update;
1184 let transaction = ChangeRecord::for_transaction(2, 1, vec![update]);
1185 replica
1186 .db()
1187 .store()
1188 .test_fail_deferred_wal_append
1189 .store(true, Ordering::Release);
1190 assert!(applier
1191 .apply(replica.db().as_ref(), &transaction, ApplyMode::Replica)
1192 .is_err());
1193 assert_eq!(
1194 replica
1195 .execute_query("SELECT * FROM users")
1196 .expect("users query should succeed after failed apply")
1197 .result
1198 .records
1199 .len(),
1200 1
1201 );
1202 applier
1203 .apply(replica.db().as_ref(), &transaction, ApplyMode::Replica)
1204 .expect("transaction retry should apply");
1205 let versions = replica
1206 .db()
1207 .store()
1208 .get_collection("users")
1209 .expect("users collection should exist")
1210 .query_all(|_| true);
1211 assert_eq!(
1212 replica
1213 .execute_query("SELECT * FROM users")
1214 .expect("users query should succeed after retry")
1215 .result
1216 .records
1217 .len(),
1218 1,
1219 "versions: {:?}",
1220 versions
1221 .iter()
1222 .map(|row| (row.id, row.logical_id(), row.xmin, row.xmax))
1223 .collect::<Vec<_>>()
1224 );
1225 assert_eq!(applier.last_applied_lsn(), 2);
1226 }
1227
1228 #[test]
1229 fn failed_replay_cannot_hide_an_already_committed_transaction() {
1230 let replica = crate::RedDBRuntime::with_options(crate::RedDBOptions::in_memory())
1231 .expect("in-memory replica should open");
1232 replica
1233 .execute_query("CREATE TABLE users (id INT, payload BLOB)")
1234 .expect("users table should be created");
1235 let transaction =
1236 ChangeRecord::for_transaction(1, 1, vec![record(1, b"a"), record(2, b"b")]);
1237 LogicalChangeApplier::new(0)
1238 .apply(replica.db().as_ref(), &transaction, ApplyMode::Replica)
1239 .expect("transaction should apply initially");
1240 replica
1241 .db()
1242 .store()
1243 .test_fail_deferred_wal_append
1244 .store(true, Ordering::Release);
1245 assert!(LogicalChangeApplier::new(0)
1246 .apply(replica.db().as_ref(), &transaction, ApplyMode::Replica)
1247 .is_err());
1248 assert_eq!(
1249 replica
1250 .execute_query("SELECT * FROM users")
1251 .expect("users query should succeed after failed replay")
1252 .result
1253 .records
1254 .len(),
1255 2
1256 );
1257 }
1258
1259 fn open_db() -> (RedDB, std::path::PathBuf) {
1260 let path = std::env::temp_dir().join(format!(
1261 "reddb_logical_apply_{}_{}",
1262 std::process::id(),
1263 std::time::SystemTime::now()
1264 .duration_since(std::time::UNIX_EPOCH)
1265 .unwrap()
1266 .as_nanos()
1267 ));
1268 let _ = std::fs::remove_file(&path);
1269 let db = RedDB::open(&path).unwrap();
1270 (db, path)
1271 }
1272
1273 fn record(lsn: u64, payload: &[u8]) -> ChangeRecord {
1274 let timestamp = 100 + lsn;
1275 let mut entity = UnifiedEntity::new(
1276 EntityId::new(lsn),
1277 EntityKind::TableRow {
1278 table: Arc::from("users"),
1279 row_id: lsn,
1280 },
1281 EntityData::Row(RowData::with_names(
1282 vec![Value::UnsignedInteger(lsn), Value::Blob(payload.to_vec())],
1283 vec!["id".to_string(), "payload".to_string()],
1284 )),
1285 );
1286 entity.created_at = timestamp;
1287 entity.updated_at = timestamp;
1288 entity.sequence_id = lsn;
1289 change_record_from_entity(
1290 lsn,
1291 timestamp,
1292 ChangeOperation::Insert,
1293 "users",
1294 "row",
1295 &entity,
1296 crate::api::REDDB_FORMAT_VERSION,
1297 None,
1298 )
1299 }
1300
1301 fn delete_record(lsn: u64, collection: &str, entity_id: u64) -> ChangeRecord {
1302 ChangeRecord {
1303 term: crate::replication::DEFAULT_REPLICATION_TERM,
1304 lsn,
1305 timestamp: 100 + lsn,
1306 operation: ChangeOperation::Delete,
1307 collection: collection.to_string(),
1308 entity_id,
1309 entity_kind: "row".to_string(),
1310 entity_bytes: None,
1311 metadata: None,
1312 refresh_records: None,
1313 range_id: None,
1314 ownership_epoch: None,
1315 }
1316 }
1317
1318 fn table_row_entity(id: u64) -> UnifiedEntity {
1319 let mut entity = UnifiedEntity::new(
1320 EntityId::new(id),
1321 EntityKind::TableRow {
1322 table: Arc::from("users"),
1323 row_id: id,
1324 },
1325 EntityData::Row(RowData::with_names(
1326 vec![Value::UnsignedInteger(id)],
1327 vec!["id".to_string()],
1328 )),
1329 );
1330 entity.created_at = 100 + id;
1331 entity.updated_at = 100 + id;
1332 entity.sequence_id = id;
1333 entity
1334 }
1335
1336 #[test]
1340 fn delete_against_missing_collection_records_apply_miss() {
1341 let (db, path) = open_db();
1342 let metrics = ReplicaApplyMetrics::default();
1343 let before = metrics.apply_miss_total.load(Ordering::Relaxed);
1344
1345 LogicalChangeApplier::apply_record_with_metrics(
1346 &db,
1347 &delete_record(1, "no_such_collection", 42),
1348 ApplyMode::Replica,
1349 &metrics,
1350 )
1351 .expect("missing-target delete is non-fatal");
1352
1353 assert_eq!(
1354 metrics.apply_miss_total.load(Ordering::Relaxed),
1355 before + 1,
1356 "delete against a missing collection must bump the apply-miss signal"
1357 );
1358 let _ = std::fs::remove_file(path);
1359 }
1360
1361 #[test]
1364 fn delete_against_missing_entity_records_apply_miss() {
1365 let (db, path) = open_db();
1366 let _ = db.store().get_or_create_collection("users");
1367 let metrics = ReplicaApplyMetrics::default();
1368
1369 LogicalChangeApplier::apply_record_with_metrics(
1370 &db,
1371 &delete_record(1, "users", 9999),
1372 ApplyMode::Replica,
1373 &metrics,
1374 )
1375 .expect("missing-entity delete is non-fatal");
1376
1377 assert_eq!(
1378 metrics.apply_miss_total.load(Ordering::Relaxed),
1379 1,
1380 "delete of an absent entity must bump the apply-miss signal"
1381 );
1382 let _ = std::fs::remove_file(path);
1383 }
1384
1385 #[test]
1388 fn delete_of_present_target_records_no_apply_miss() {
1389 let (db, path) = open_db();
1390 let store = db.store();
1391 let _ = store.get_or_create_collection("users");
1392 let id = store
1393 .insert_auto("users", table_row_entity(1))
1394 .expect("insert entity");
1395 let metrics = ReplicaApplyMetrics::default();
1396
1397 LogicalChangeApplier::apply_record_with_metrics(
1398 &db,
1399 &delete_record(1, "users", id.raw()),
1400 ApplyMode::Replica,
1401 &metrics,
1402 )
1403 .expect("present-target delete applies");
1404
1405 assert_eq!(
1406 metrics.apply_miss_total.load(Ordering::Relaxed),
1407 0,
1408 "deleting a present target must not fire the apply-miss signal"
1409 );
1410 assert!(
1411 store.get("users", id).is_none(),
1412 "the entity must actually be removed on the normal path"
1413 );
1414 let _ = std::fs::remove_file(path);
1415 }
1416
1417 #[test]
1420 fn stateful_apply_surfaces_delete_miss_via_metrics_handle() {
1421 let (db, path) = open_db();
1422 let applier =
1423 LogicalChangeApplier::with_metrics(0, Arc::new(ReplicaApplyMetrics::default()));
1424
1425 applier
1426 .apply(&db, &delete_record(1, "ghost", 7), ApplyMode::Replica)
1427 .expect("missing-target delete advances the chain");
1428
1429 assert_eq!(
1430 applier.metrics().apply_miss_total.load(Ordering::Relaxed),
1431 1,
1432 "the applier's shared metrics handle must record the miss"
1433 );
1434 assert_eq!(
1435 applier.last_applied_lsn(),
1436 1,
1437 "a non-fatal miss still advances the LSN chain"
1438 );
1439 let _ = std::fs::remove_file(path);
1440 }
1441
1442 #[test]
1447 fn throughput_counters_reflect_applied_bytes_and_records() {
1448 let (db, path) = open_db();
1449 let metrics = Arc::new(ReplicaApplyMetrics::default());
1450 let applier = LogicalChangeApplier::with_metrics(0, Arc::clone(&metrics));
1451
1452 let r1 = record(1, b"hello");
1454 let r2 = record(2, b"world-longer-payload");
1455 let r3 = record(3, b"x");
1456
1457 let expected_bytes: u64 = [&r1, &r2, &r3]
1461 .iter()
1462 .map(|r| r.entity_bytes.as_ref().map(|b| b.len() as u64).unwrap_or(0))
1463 .sum();
1464 assert!(expected_bytes > 0, "test records must carry entity payload");
1465
1466 for r in [&r1, &r2, &r3] {
1467 assert_eq!(
1468 applier.apply(&db, r, ApplyMode::Replica).unwrap(),
1469 ApplyOutcome::Applied
1470 );
1471 }
1472
1473 assert_eq!(
1474 metrics.records_applied_total.load(Ordering::Relaxed),
1475 3,
1476 "three applied records must increment records counter by 3"
1477 );
1478 assert_eq!(
1479 metrics.bytes_applied_total.load(Ordering::Relaxed),
1480 expected_bytes,
1481 "bytes counter must match the sum of entity_bytes across applied records"
1482 );
1483
1484 assert_eq!(
1486 applier.apply(&db, &r3, ApplyMode::Replica).unwrap(),
1487 ApplyOutcome::Idempotent
1488 );
1489 assert_eq!(
1490 metrics.records_applied_total.load(Ordering::Relaxed),
1491 3,
1492 "idempotent replay must not increment the records counter"
1493 );
1494 assert_eq!(
1495 metrics.bytes_applied_total.load(Ordering::Relaxed),
1496 expected_bytes,
1497 "idempotent replay must not increment the bytes counter"
1498 );
1499
1500 let del = delete_record(4, "ghost_collection", 999);
1503 applier
1504 .apply(&db, &del, ApplyMode::Replica)
1505 .expect("delete miss is non-fatal and still advances the chain");
1506 assert_eq!(
1507 metrics.records_applied_total.load(Ordering::Relaxed),
1508 4,
1509 "a delete (including a miss) must increment the records counter"
1510 );
1511 assert_eq!(
1512 metrics.bytes_applied_total.load(Ordering::Relaxed),
1513 expected_bytes,
1514 "a delete contributes 0 bytes to the bytes counter"
1515 );
1516
1517 let _ = std::fs::remove_file(path);
1518 }
1519
1520 #[test]
1521 fn apply_advances_on_monotonic_lsn() {
1522 let (db, path) = open_db();
1523 let applier = LogicalChangeApplier::new(0);
1524 assert_eq!(
1525 applier
1526 .apply(&db, &record(1, b"a"), ApplyMode::Replica)
1527 .unwrap(),
1528 ApplyOutcome::Applied
1529 );
1530 assert_eq!(applier.last_applied_lsn(), 1);
1531 assert_eq!(
1532 applier
1533 .apply(&db, &record(2, b"b"), ApplyMode::Replica)
1534 .unwrap(),
1535 ApplyOutcome::Applied
1536 );
1537 assert_eq!(applier.last_applied_lsn(), 2);
1538 let _ = std::fs::remove_file(path);
1539 }
1540
1541 #[test]
1542 fn bookmark_timeout_does_not_wait_for_inflight_apply_lock() {
1543 let applier = std::sync::Arc::new(LogicalChangeApplier::new(0));
1544 let apply = applier.apply_lock.lock().expect("inflight apply");
1545 let reader = std::sync::Arc::clone(&applier);
1546 let (send, receive) = std::sync::mpsc::channel();
1547 let thread = std::thread::spawn(move || {
1548 send.send(reader.wait_for_bookmark(
1549 &crate::replication::CausalBookmark::new(1, 1),
1550 std::time::Duration::from_millis(20),
1551 ))
1552 .expect("send result");
1553 });
1554 let result = receive.recv_timeout(std::time::Duration::from_secs(2));
1555 drop(apply);
1556 thread.join().expect("waiter");
1557 assert!(matches!(
1558 result.expect("bookmark respects its deadline during apply"),
1559 Err(BookmarkWaitError::Timeout { .. })
1560 ));
1561 }
1562
1563 #[test]
1564 fn apply_idempotent_on_duplicate_lsn_same_payload() {
1565 let (db, path) = open_db();
1566 let applier = LogicalChangeApplier::new(0);
1567 let r = record(5, b"same");
1568 applier.apply(&db, &r, ApplyMode::Replica).unwrap();
1569 assert_eq!(
1570 applier.apply(&db, &r, ApplyMode::Replica).unwrap(),
1571 ApplyOutcome::Idempotent
1572 );
1573 assert_eq!(applier.last_applied_lsn(), 5);
1574 let _ = std::fs::remove_file(path);
1575 }
1576
1577 #[test]
1578 fn apply_fails_closed_on_lsn_collision_diff_payload() {
1579 let (db, path) = open_db();
1580 let applier = LogicalChangeApplier::new(0);
1581 applier
1582 .apply(&db, &record(7, b"first"), ApplyMode::Replica)
1583 .unwrap();
1584 let err = applier
1585 .apply(&db, &record(7, b"different"), ApplyMode::Replica)
1586 .unwrap_err();
1587 assert!(
1588 matches!(err, LogicalApplyError::Divergence { lsn: 7, .. }),
1589 "got {err:?}"
1590 );
1591 let _ = std::fs::remove_file(path);
1592 }
1593
1594 #[test]
1595 fn apply_fails_closed_on_same_lsn_different_term() {
1596 let (db, path) = open_db();
1597 let applier = LogicalChangeApplier::new(0);
1598 applier
1599 .apply(&db, &record(7, b"same").with_term(1), ApplyMode::Replica)
1600 .unwrap();
1601 let err = applier
1602 .apply(&db, &record(7, b"same").with_term(2), ApplyMode::Replica)
1603 .unwrap_err();
1604 assert!(
1605 matches!(
1606 err,
1607 LogicalApplyError::Divergence {
1608 lsn: 7,
1609 expected_term: 1,
1610 got_term: 2,
1611 ..
1612 }
1613 ),
1614 "got {err:?}"
1615 );
1616 assert_eq!(applier.last_applied_term(), 1);
1617 assert_eq!(applier.last_applied_lsn(), 7);
1618 let _ = std::fs::remove_file(path);
1619 }
1620
1621 #[test]
1626 fn apply_fences_stale_term_record() {
1627 let (db, path) = open_db();
1628 let applier = LogicalChangeApplier::new(0);
1629
1630 applier
1632 .apply(&db, &record(1, b"a").with_term(5), ApplyMode::Replica)
1633 .unwrap();
1634 assert_eq!(applier.last_applied_term(), 5);
1635 assert_eq!(applier.last_applied_lsn(), 1);
1636
1637 let before = applier.metrics().fenced_total.load(Ordering::Relaxed);
1639 let err = applier
1640 .apply(&db, &record(2, b"b").with_term(4), ApplyMode::Replica)
1641 .unwrap_err();
1642 assert!(
1643 matches!(
1644 err,
1645 LogicalApplyError::StaleTermFenced {
1646 record_term: 4,
1647 current_term: 5,
1648 lsn: 2,
1649 }
1650 ),
1651 "got {err:?}"
1652 );
1653 assert_eq!(err.kind(), ApplyErrorKind::Fenced);
1654 assert_eq!(
1655 applier.metrics().fenced_total.load(Ordering::Relaxed),
1656 before + 1,
1657 "the fence must leave a metrics trail"
1658 );
1659 assert_eq!(applier.last_applied_lsn(), 1, "watermark must not advance");
1661 assert_eq!(applier.last_applied_term(), 5);
1662 assert_eq!(
1663 applier.received_frontier_lsn(),
1664 1,
1665 "a fenced record must not even advance the received frontier"
1666 );
1667 let _ = std::fs::remove_file(path);
1668 }
1669
1670 #[test]
1674 fn apply_admits_same_term_and_adopts_higher_term() {
1675 let (db, path) = open_db();
1676 let applier = LogicalChangeApplier::new(0);
1677
1678 applier
1679 .apply(&db, &record(1, b"a").with_term(3), ApplyMode::Replica)
1680 .unwrap();
1681 applier
1683 .apply(&db, &record(2, b"b").with_term(3), ApplyMode::Replica)
1684 .unwrap();
1685 assert_eq!(applier.last_applied_term(), 3);
1686 applier
1688 .apply(&db, &record(3, b"c").with_term(7), ApplyMode::Replica)
1689 .unwrap();
1690 assert_eq!(applier.last_applied_term(), 7);
1691 assert_eq!(applier.last_applied_lsn(), 3);
1692
1693 let err = applier
1695 .apply(&db, &record(4, b"d").with_term(3), ApplyMode::Replica)
1696 .unwrap_err();
1697 assert!(
1698 matches!(err, LogicalApplyError::StaleTermFenced { .. }),
1699 "got {err:?}"
1700 );
1701 let _ = std::fs::remove_file(path);
1702 }
1703
1704 #[test]
1709 fn apply_fenced_rejects_stale_ownership_epoch() {
1710 let (db, path) = open_db();
1711 let applier = LogicalChangeApplier::new(0);
1712 let fence = RangeAuthority {
1713 range_id: 7,
1714 min_term: 1,
1715 min_ownership_epoch: 5,
1716 };
1717
1718 let stale = record(1, b"a").with_range_authority(7, 4);
1719 let before = applier.metrics().fenced_total.load(Ordering::Relaxed);
1720 let err = applier
1721 .apply_fenced(&db, &stale, ApplyMode::Replica, Some(&fence))
1722 .unwrap_err();
1723 assert!(
1724 matches!(
1725 err,
1726 LogicalApplyError::RangeFenced {
1727 range_id: 7,
1728 lsn: 1,
1729 reason: RangeAdmitError::StaleOwnershipEpoch {
1730 record_epoch: 4,
1731 accepted_epoch: 5,
1732 },
1733 }
1734 ),
1735 "got {err:?}"
1736 );
1737 assert_eq!(err.kind(), ApplyErrorKind::Fenced);
1738 assert_eq!(
1739 applier.metrics().fenced_total.load(Ordering::Relaxed),
1740 before + 1
1741 );
1742 assert_eq!(applier.last_applied_lsn(), 0, "watermark must not advance");
1743 assert_eq!(
1744 applier.received_frontier_lsn(),
1745 0,
1746 "a range-fenced record must not advance the received frontier"
1747 );
1748 let _ = std::fs::remove_file(path);
1749 }
1750
1751 #[test]
1754 fn apply_fenced_rejects_stale_range_term_on_restore() {
1755 let (db, path) = open_db();
1756 let applier = LogicalChangeApplier::new(0);
1757 let fence = RangeAuthority {
1758 range_id: 3,
1759 min_term: 6,
1760 min_ownership_epoch: 1,
1761 };
1762
1763 let stale = record(1, b"a").with_term(4).with_range_authority(3, 9);
1764 let err = applier
1765 .apply_fenced(&db, &stale, ApplyMode::Restore, Some(&fence))
1766 .unwrap_err();
1767 assert!(
1768 matches!(
1769 err,
1770 LogicalApplyError::RangeFenced {
1771 range_id: 3,
1772 reason: RangeAdmitError::StaleTerm {
1773 record_term: 4,
1774 accepted_term: 6,
1775 },
1776 ..
1777 }
1778 ),
1779 "got {err:?}"
1780 );
1781 let _ = std::fs::remove_file(path);
1782 }
1783
1784 #[test]
1787 fn apply_fenced_admits_current_and_ignores_other_ranges() {
1788 let (db, path) = open_db();
1789 let applier = LogicalChangeApplier::new(0);
1790 let fence = RangeAuthority {
1791 range_id: 7,
1792 min_term: 1,
1793 min_ownership_epoch: 5,
1794 };
1795
1796 applier
1798 .apply_fenced(
1799 &db,
1800 &record(1, b"a").with_range_authority(7, 5),
1801 ApplyMode::Replica,
1802 Some(&fence),
1803 )
1804 .expect("current record applies");
1805 assert_eq!(applier.last_applied_lsn(), 1);
1806
1807 applier
1810 .apply_fenced(
1811 &db,
1812 &record(2, b"b").with_range_authority(99, 1),
1813 ApplyMode::Replica,
1814 Some(&fence),
1815 )
1816 .expect("other-range record bypasses this fence");
1817 assert_eq!(applier.last_applied_lsn(), 2);
1818 let _ = std::fs::remove_file(path);
1819 }
1820
1821 #[test]
1826 fn range_catchup_plan_applies_only_its_range_through_the_fence() {
1827 use crate::replication::cdc::{plan_range_catchup, RangeStreamPosition, RangeStreamReject};
1828
1829 let (db, path) = open_db();
1830 let applier = LogicalChangeApplier::new(0);
1831
1832 let stream = vec![
1835 record(1, b"a").with_range_authority(7, 5),
1836 record(2, b"b").with_range_authority(7, 5),
1837 record(3, b"c").with_range_authority(7, 5),
1838 record(4, b"d").with_range_authority(9, 2),
1839 record(5, b"e").with_range_authority(9, 2),
1840 record(6, b"f").with_range_authority(7, 4),
1841 ];
1842
1843 let position = RangeStreamPosition::new(7, 0, 1, 5);
1845 let plan = plan_range_catchup(&position, &stream);
1846
1847 assert_eq!(plan.apply, vec![0, 1, 2]);
1850 assert_eq!(
1851 plan.rejected,
1852 vec![RangeStreamReject {
1853 lsn: 6,
1854 error: RangeAdmitError::StaleOwnershipEpoch {
1855 record_epoch: 4,
1856 accepted_epoch: 5,
1857 },
1858 }]
1859 );
1860 assert_eq!(plan.resume.applied_lsn, 3);
1861
1862 let fence = position.authority();
1864 for index in &plan.apply {
1865 applier
1866 .apply_fenced(&db, &stream[*index], ApplyMode::Replica, Some(&fence))
1867 .expect("planned record applies through the fence");
1868 }
1869 assert_eq!(applier.last_applied_lsn(), 3);
1870
1871 let stale = &stream[5];
1874 let err = applier
1875 .apply_fenced(&db, stale, ApplyMode::Replica, Some(&fence))
1876 .unwrap_err();
1877 assert!(
1878 matches!(err, LogicalApplyError::RangeFenced { range_id: 7, .. }),
1879 "got {err:?}"
1880 );
1881 assert_eq!(
1882 applier.last_applied_lsn(),
1883 3,
1884 "stale write must not advance"
1885 );
1886 let _ = std::fs::remove_file(path);
1887 }
1888
1889 #[test]
1890 fn apply_skips_older_lsn() {
1891 let (db, path) = open_db();
1892 let applier = LogicalChangeApplier::new(0);
1893 applier
1894 .apply(&db, &record(1, b"a"), ApplyMode::Replica)
1895 .unwrap();
1896 applier
1897 .apply(&db, &record(2, b"b"), ApplyMode::Replica)
1898 .unwrap();
1899 assert_eq!(
1900 applier
1901 .apply(&db, &record(1, b"a"), ApplyMode::Replica)
1902 .unwrap(),
1903 ApplyOutcome::Skipped
1904 );
1905 assert_eq!(applier.last_applied_lsn(), 2);
1906 let _ = std::fs::remove_file(path);
1907 }
1908
1909 #[test]
1910 fn apply_returns_gap_on_future_lsn() {
1911 let (db, path) = open_db();
1912 let applier = LogicalChangeApplier::new(0);
1913 applier
1914 .apply(&db, &record(1, b"a"), ApplyMode::Replica)
1915 .unwrap();
1916 let err = applier
1917 .apply(&db, &record(5, b"e"), ApplyMode::Replica)
1918 .unwrap_err();
1919 assert!(
1920 matches!(err, LogicalApplyError::Gap { last: 1, next: 5 }),
1921 "got {err:?}"
1922 );
1923 assert_eq!(applier.last_applied_lsn(), 1);
1924 let _ = std::fs::remove_file(path);
1925 }
1926}