Skip to main content

reddb_server/replication/
logical.rs

1//! Logical replication helpers shared by replica apply and point-in-time restore.
2
3use 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/// PLAN.md Phase 11.5 — counters the replica apply loop bumps when an
22/// invariant breaks. Surfaced via `reddb_replica_apply_errors_total`.
23/// Decode errors aren't strictly apply errors but they share the same
24/// observability lane so dashboards alert on "replica is ingesting
25/// trash from primary regardless of cause".
26#[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    /// Issue #814 — a delete (or other apply) that found no target on the
35    /// replica: a missing collection or a missing entity. Non-fatal (the
36    /// LSN chain still advances so idempotent re-pull converges, see
37    /// #813), but recorded so a missed delete that drives collection-count
38    /// drift leaves a trail instead of being swallowed by `let _ =`.
39    pub apply_miss_total: std::sync::atomic::AtomicU64,
40    /// Issue #835 — a record carrying a term *behind* the replica's current
41    /// term was fenced at the apply boundary (a returning ex-primary on a
42    /// stale term). Fail-closed: the record is rejected and the LSN/term
43    /// chain does not advance, so the deposed primary cannot move any
44    /// watermark until it re-syncs under the new term.
45    pub fenced_total: std::sync::atomic::AtomicU64,
46    /// Issue #1242 — entity-payload bytes from successfully applied WAL
47    /// records (entity_bytes for insert/update, refresh payload for
48    /// refresh; deletes carry no payload and contribute 0). Monotonic
49    /// within one process lifetime; reset-aware for readers after restart.
50    /// Surfaced via `reddb_replication_apply_bytes_total`.
51    pub bytes_applied_total: std::sync::atomic::AtomicU64,
52    /// Issue #1242 — count of WAL records successfully applied (Applied
53    /// outcome only; Idempotent and Skipped are excluded). Monotonic
54    /// within one process lifetime. Surfaced via
55    /// `reddb_replication_apply_records_total`.
56    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    /// Issue #1242 — throughput snapshot: `(bytes_applied_total,
103    /// records_applied_total)`. Both are monotonic within a process
104    /// lifetime and zero after restart, so callers that track rate must
105    /// detect a reset (new value < prior value) and treat it as a restart.
106    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    /// Issue #814 — apply ran against a missing target (delete on an
122    /// absent collection/entity). Non-fatal divergence signal.
123    Miss,
124    /// Issue #835 — a record from a term behind the replica's current term
125    /// was fenced at the apply boundary (a stale ex-primary). Fail-closed.
126    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/// Outcome of a single `apply` call. `Applied` advances the chain;
155/// `Idempotent` and `Skipped` are no-ops (we already saw an
156/// equal-or-newer LSN). `Gap` and `Divergence` (returned via
157/// `LogicalApplyError`) are fail-closed — callers (replica fetcher,
158/// restore loop) should mark the instance unhealthy and stop applying.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum ApplyOutcome {
161    /// Normal monotonic advance.
162    Applied,
163    /// Same LSN as last applied with same payload hash — log + skip.
164    Idempotent,
165    /// Older LSN than what we already have — log + skip.
166    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    /// Issue #835 — the record's term is behind the replica's current
187    /// term: a returning ex-primary streaming on a stale, superseded term.
188    /// Rejected at the apply boundary so the deposed primary cannot apply
189    /// or advance any watermark until it re-syncs under the new term.
190    StaleTermFenced {
191        record_term: u64,
192        current_term: u64,
193        lsn: u64,
194    },
195    /// Issue #991 — the record is stamped for a range whose authority
196    /// watermark has moved past it: a write from a deposed range owner
197    /// (stale ownership epoch) or a superseded timeline (stale term) for the
198    /// target range. Rejected at the apply boundary before the LSN state
199    /// machine runs — fail-closed, so a stale owner cannot apply or advance
200    /// the chain/watermark for that range. Shares the `Fenced` metrics lane
201    /// with the global stale-term fence.
202    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
293/// Shared logical change applier so replica replay and PITR converge on the
294/// same semantics. Stateful (PLAN.md Phase 11.5): tracks the last applied
295/// LSN + payload hash so duplicates / older LSNs / gaps / divergences are
296/// detected explicitly.
297pub 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    /// Issue #814 — metrics the apply path bumps when a record runs
306    /// against a missing target. The production replica loop shares the
307    /// runtime's `ReplicaApplyMetrics` here so `/metrics` surfaces misses;
308    /// other callers (PITR, tests) get a private default that no one reads.
309    metrics: std::sync::Arc<ReplicaApplyMetrics>,
310}
311
312impl LogicalChangeApplier {
313    /// Build a fresh applier. `starting_lsn` is the LSN already
314    /// covered by the snapshot (or `0` for an empty replica). The
315    /// next acceptable record is any positive LSN; from there the
316    /// chain advances by 1.
317    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    /// Build an applier that records apply misses / errors into a shared
325    /// `ReplicaApplyMetrics` (issue #814). The production replica loop
326    /// passes the runtime's metrics so a swallowed delete leaves a trail
327    /// on `reddb_replica_apply_errors_total{kind="apply_miss"}`.
328    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    /// The metrics handle this applier records misses/errors into.
342    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    /// Apply one logical change record. The state machine:
405    /// - first record after `starting_lsn == 0` → apply, anchor.
406    /// - `lsn == last + 1` → apply, advance.
407    /// - `lsn == last` && payload hash equal → idempotent skip.
408    /// - `lsn == last` && payload hash differs → `Divergence` (fail closed).
409    /// - `lsn < last` → older replay, skip with debug log.
410    /// - `lsn > last + 1` → `Gap` (fail closed; caller marks unhealthy).
411    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    /// Apply one record, first gating it against the target range's authority
421    /// watermark (issue #991). When `range_fence` is `Some`, a record stamped
422    /// for that range whose term or ownership epoch is behind the watermark is
423    /// rejected before the global term fence and the LSN state machine run —
424    /// fail-closed, so a deposed range owner cannot advance anything. Records
425    /// for a different range, or with no range identity (legacy /
426    /// non-range-replicated), pass the range fence untouched. `apply` is the
427    /// unfenced shorthand for callers that do not yet hold range authority.
428    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        // Serialize validation, publication and frontier advancement. Keep this
436        // separate from bookmark waits so their deadlines still work during I/O.
437        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        // Per-range authority fence (issue #991). Runs before the global
442        // term fence so a stale ownership epoch is rejected even when the
443        // record's term is otherwise current. Only records stamped for the
444        // fence's range are gated; the rest fall through.
445        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        // Stale-term fence (issue #835, ADR 0030). Run the shared primitive
457        // before the LSN state machine so a stale ex-primary can neither
458        // apply nor advance the chain/watermark. TermFence also adopts a
459        // higher term before admitting its record.
460        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        // Coordinate the predicate and notification with Condvar::wait_timeout.
514        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    /// Stateless apply — applies the record without monotonicity
536    /// checks. Kept for callers that don't yet thread the stateful
537    /// applier through. New code should prefer
538    /// `LogicalChangeApplier::new()` + `apply()`. Apply misses (delete
539    /// against a missing target) are recorded into a throwaway metrics
540    /// handle; use [`apply_record_with_metrics`] to surface them.
541    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    /// Stateless apply that records apply misses (issue #814) into
546    /// `metrics`. A delete against a missing collection or a missing
547    /// entity is a non-fatal divergence signal: it bumps
548    /// `ApplyErrorKind::Miss` and emits a structured warn line, but still
549    /// returns `Ok(())` so the LSN chain advances and idempotent re-pull
550    /// (#813) converges. A genuine (non-missing-target) store error on a
551    /// delete propagates as a real apply error — counted, fail-closed —
552    /// rather than being swallowed by the old `let _ =`.
553    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        // Issue #1242 — compute payload bytes before the apply so we can
577        // increment the throughput counter unconditionally at the end (early
578        // `return Err` paths skip the counter, correctly counting only
579        // successful applies).
580        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        // Transaction apply already holds this read guard. Recursive reads
603        // must not wait behind an index DDL writer waiting for the outer guard.
604        let _topology = topology.as_ref().map(|lock| lock.read_recursive());
605        let _storage_publication = store.vault_publication_lock.lock();
606        // Decode before changing either data or indexes. Collect only affected
607        // physical versions, except Refresh which replaces the whole collection.
608        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                // Runtime readers may still hold snapshots of this table row.
661                // Retain a durable tombstone until normal MVCC reclamation.
662                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                        // Target collection existed but no such entity —
694                        // the delete found nothing to remove.
695                        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                        // The whole collection is absent on the replica —
706                        // a missed delete that can drive count drift.
707                        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                        // A real store error is a genuine apply failure:
718                        // surface it instead of discarding it so the
719                        // caller counts it and the replica fails closed.
720                        return Err(RedDBError::Internal(err.to_string()));
721                    }
722                }
723            }
724            ChangeOperation::Refresh => {
725                // Issue #596 slice 9d — replica replay of
726                // `REFRESH MATERIALIZED VIEW v`. The primary
727                // emitted the serialized backing-collection
728                // contents in `refresh_records`; apply the
729                // atomic swap on the replica's local store
730                // (which also persists a `RefreshCollection`
731                // WAL action so the post-swap contents survive
732                // a replica restart).
733                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                    // Replaying a durable physical version after a lost ACK
760                    // cannot transfer its visibility to a new, abortable xid.
761                    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                        // Source and replica allocators are independent. A source
780                        // xid already in a local snapshot's past must not make a
781                        // newly arriving physical version visible retroactively.
782                        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                // Issue #813 — MVCC table-row supersession on the replica.
795                //
796                // A table-row UPDATE on the primary installs a NEW physical
797                // version (fresh `EntityId`) that shares the row's stable
798                // `logical_id`, and marks the prior version superseded
799                // (`xmax != 0`) so snapshot reads skip it. Only the new
800                // version travels on the wire — the prior version's `xmax`
801                // bump is implicit. Without reproducing it here the replica
802                // leaves every prior version LIVE, so each update to a row
803                // accumulates a stale live duplicate and a full re-pull
804                // replays them all (the observed 22× inflation). Before
805                // upserting the incoming version, mark any *other* live
806                // version of the same logical id superseded — mirroring
807                // `install_versioned_table_row_update` on the primary. This
808                // is idempotent under re-pull: re-applying a record updates
809                // its version in place (resetting its `xmax` from the
810                // serialized bytes), and the last writer per logical id in
811                // LSN order wins, converging on the primary's live set.
812                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                // Publish the visibility floor only after this record's WAL
875                // batch and metadata have become durable.
876                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 &current {
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                // A partially repaired index must never answer subsequent
927                // queries. Keep durable declarations for rebuild on restart.
928                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        // Issue #1242 — only reached on successful apply (all early `return
935        // Err` paths skip this). Fenced and error records never reach here.
936        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        // Reject malformed or recursive envelopes before mutating any member.
970        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    // Issue #991 — range authority participates in the payload hash so two
1070    // records at the same LSN that differ only in range identity or ownership
1071    // epoch are flagged divergent rather than silently treated as idempotent.
1072    // `u64::MAX` stands in for an absent field (a value real epochs/ids never
1073    // reach) so `None` and `Some(MAX)` stay distinguishable.
1074    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    // Issue #596 slice 9d — refresh payload participates in the
1080    // payload-hash so the same-LSN-idempotent / different-payload-
1081    // divergence state machine works for Refresh records too.
1082    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        // Initialize the durable result-cache format before the test pauses a
1112        // transaction while holding the publication lock. A real transaction
1113        // completes without this test-only barrier; letting the first read
1114        // create cache metadata inside the pause would deadlock the harness
1115        // rather than exercise transaction visibility.
1116        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    // Issue #814 — a delete against a missing collection must record an
1337    // apply miss (not a silent no-op) and still return Ok so the LSN
1338    // chain advances (idempotent re-pull, #813).
1339    #[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    // Issue #814 — a delete against an existing collection but absent
1362    // entity is likewise a recorded miss, not a swallowed no-op.
1363    #[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    // Issue #814 — the normal path (target present) deletes without
1386    // firing the miss signal. No behavioral regression.
1387    #[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    // Issue #814 — the shared-metrics handle on the stateful applier
1418    // surfaces the miss so `/metrics` (which reads the same Arc) sees it.
1419    #[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    // Issue #1242 — bytes_applied_total and records_applied_total must
1443    // reflect observed apply throughput: Applied increments both, Idempotent
1444    // and Skipped increment neither, and deletes contribute 0 bytes but 1
1445    // record.
1446    #[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        // Three insert records with payloads of different sizes.
1453        let r1 = record(1, b"hello");
1454        let r2 = record(2, b"world-longer-payload");
1455        let r3 = record(3, b"x");
1456
1457        // Compute expected bytes from the serialized entity_bytes (not the raw
1458        // payload, which goes through entity serialization before it lands in
1459        // entity_bytes).
1460        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        // Idempotent replay must not increment either counter.
1485        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        // A delete-miss (non-fatal) increments records by 1 but contributes
1501        // 0 bytes — deletes carry no entity payload.
1502        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    // Issue #835 — a record from a term behind the replica's adopted term
1622    // is fenced at the apply boundary: rejected, counted, and crucially the
1623    // LSN/term chain does NOT advance, so a returning ex-primary on a stale
1624    // term cannot move any watermark.
1625    #[test]
1626    fn apply_fences_stale_term_record() {
1627        let (db, path) = open_db();
1628        let applier = LogicalChangeApplier::new(0);
1629
1630        // Replica adopts term 5 from the legitimate primary at lsn 1.
1631        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        // A returning ex-primary streams the next record on the old term 4.
1638        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        // The fenced record advanced nothing — no apply, no watermark move.
1660        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    // The fence only bites a *behind* term. A record on the same term
1671    // applies normally, and a record on a higher term is the new primary's
1672    // timeline — adopted on apply.
1673    #[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        // Same term → admitted.
1682        applier
1683            .apply(&db, &record(2, b"b").with_term(3), ApplyMode::Replica)
1684            .unwrap();
1685        assert_eq!(applier.last_applied_term(), 3);
1686        // Higher term → adopted.
1687        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        // Now a record back on term 3 is fenced.
1694        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    // Issue #991 — a record stamped for the target range but carrying an
1705    // ownership epoch behind the range's accepted epoch is a write from a
1706    // deposed owner. It is fenced at the apply boundary: rejected, counted on
1707    // the Fenced lane, and the LSN/term chain does not advance.
1708    #[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    // Issue #991 — the same fence applies on the recovery/restore path: a
1752    // record on a stale term for the target range is rejected there too.
1753    #[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    // Issue #991 — a record current for the range applies through the fence,
1785    // and a record for a *different* range is not gated by this fence.
1786    #[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        // Current epoch for the fenced range → applies and advances.
1797        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        // A record stamped for a different (stale-looking) range is not this
1808        // fence's concern and still applies.
1809        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    // Issue #992 — end-to-end range-indexed catch-up over the single physical
1822    // WAL: a follower plans its range's work out of the shared stream, then
1823    // applies exactly that work through the same `apply_fenced` gate. The other
1824    // range's records and a deposed-owner write never reach apply.
1825    #[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        // One sequential WAL slice: range 7 at LSN 1..3 (epoch 5), range 9 at
1833        // 4..5, and a returning ex-owner of range 7 at LSN 6 on a stale epoch.
1834        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        // Range-7 follower resumes from origin, already knowing owner epoch 5.
1844        let position = RangeStreamPosition::new(7, 0, 1, 5);
1845        let plan = plan_range_catchup(&position, &stream);
1846
1847        // Only range 7's current records were selected; the stale-epoch write
1848        // is rejected, not selected.
1849        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        // Apply exactly the planned records through the per-range fence.
1863        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        // The deposed-owner record the plan refused is exactly what the apply
1872        // fence would also reject, never advancing the chain.
1873        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}