Skip to main content

reddb_server/replication/
primary.rs

1//! Primary-side replication: WAL record production and snapshot serving.
2//!
3//! The logical WAL spool byte format is a `reddb-file` contract. This module
4//! owns runtime policy: appending after writes, syncing acknowledged records,
5//! serving replica pulls, and pruning once slots make records removable.
6
7use std::collections::{BTreeMap, VecDeque};
8use std::fs::{self, File, OpenOptions};
9use std::io::{self, Write};
10use std::path::{Path, PathBuf};
11use std::sync::{Arc, Condvar, Mutex, RwLock};
12use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
13
14use reddb_file::{ReplicationSlot, ReplicationSlotInvalidationCause};
15use tracing::warn;
16
17mod slots;
18use slots::{
19    load_replication_slot_catalog, load_replication_slots, persist_replication_slot_catalog,
20    persist_replication_slots,
21};
22
23fn term_from_payload(payload: &[u8]) -> u64 {
24    crate::replication::cdc::ChangeRecord::decode(payload)
25        .map(|record| record.term)
26        .unwrap_or(crate::replication::DEFAULT_REPLICATION_TERM)
27}
28
29fn authority_from_payload(payload: &[u8]) -> (u64, Option<u64>) {
30    crate::replication::cdc::ChangeRecord::decode(payload)
31        .map(|record| (record.term, record.ownership_epoch))
32        .unwrap_or((crate::replication::DEFAULT_REPLICATION_TERM, None))
33}
34
35/// In-memory WAL buffer for replication.
36/// Primary appends records here; replicas consume from it.
37///
38/// Each record payload is stored behind an `Arc<[u8]>` so fan-out to
39/// multiple replicas shares a single heap allocation per record
40/// (issue #832): a pull clones the `Arc` handle, never the bytes, so
41/// adding replicas does not multiply the primary's send-buffer memory.
42pub struct WalBuffer {
43    /// Circular buffer of (lsn, ref-counted serialized record) pairs.
44    records: RwLock<VecDeque<(u64, Arc<[u8]>)>>,
45    /// Current write LSN.
46    current_lsn: RwLock<u64>,
47}
48
49impl WalBuffer {
50    pub fn new(max_size: usize) -> Self {
51        Self {
52            records: RwLock::new(VecDeque::with_capacity(max_size)),
53            current_lsn: RwLock::new(0),
54        }
55    }
56
57    /// Append a WAL record. Called by the storage engine after each write.
58    pub fn append(&self, lsn: u64, data: Vec<u8>) {
59        let mut records = self.records.write().unwrap_or_else(|e| e.into_inner());
60        records.push_back((lsn, Arc::from(data.into_boxed_slice())));
61
62        let mut current = self.current_lsn.write().unwrap_or_else(|e| e.into_inner());
63        *current = (*current).max(lsn);
64    }
65
66    /// Read records since the given LSN (exclusive), copying each
67    /// payload into an owned `Vec<u8>`. Kept for callers (WAL
68    /// archiving, retention bookkeeping) that need owned bytes; the
69    /// per-replica fan-out path should prefer [`Self::read_since_shared`]
70    /// to avoid copying.
71    pub fn read_since(&self, since_lsn: u64, max_count: usize) -> Vec<(u64, Vec<u8>)> {
72        self.read_since_shared(since_lsn, max_count)
73            .into_iter()
74            .map(|(lsn, data)| (lsn, data.to_vec()))
75            .collect()
76    }
77
78    /// Read records since the given LSN (exclusive) sharing the stored
79    /// `Arc<[u8]>` payloads. Fan-out to N replicas clones only the
80    /// reference-counted handles, so the buffer's bytes are never
81    /// duplicated per replica (issue #832).
82    pub fn read_since_shared(&self, since_lsn: u64, max_count: usize) -> Vec<(u64, Arc<[u8]>)> {
83        let records = self.records.read().unwrap_or_else(|e| e.into_inner());
84        records
85            .iter()
86            .filter(|(lsn, _)| *lsn > since_lsn)
87            .take(max_count)
88            .cloned()
89            .collect()
90    }
91
92    /// Current LSN.
93    pub fn current_lsn(&self) -> u64 {
94        *self.current_lsn.read().unwrap_or_else(|e| e.into_inner())
95    }
96
97    pub fn set_current_lsn(&self, lsn: u64) {
98        let mut current = self.current_lsn.write().unwrap_or_else(|e| e.into_inner());
99        *current = (*current).max(lsn);
100    }
101
102    pub fn prune_through(&self, upto_lsn: u64) {
103        let mut records = self.records.write().unwrap_or_else(|e| e.into_inner());
104        while records
105            .front()
106            .map(|(lsn, _)| *lsn <= upto_lsn)
107            .unwrap_or(false)
108        {
109            records.pop_front();
110        }
111    }
112
113    /// Oldest available LSN (for gap detection).
114    pub fn oldest_lsn(&self) -> Option<u64> {
115        let records = self.records.read().unwrap_or_else(|e| e.into_inner());
116        records.front().map(|(lsn, _)| *lsn)
117    }
118}
119
120fn logical_wal_entry_term(entry: &reddb_file::LogicalWalEntry) -> u64 {
121    if entry.term == 0 {
122        term_from_payload(&entry.data)
123    } else {
124        entry.term
125    }
126}
127
128fn logical_wal_data_with_framing_term(entry: &reddb_file::LogicalWalEntry) -> Vec<u8> {
129    let term = logical_wal_entry_term(entry);
130    match crate::replication::cdc::ChangeRecord::decode(&entry.data) {
131        Ok(mut record)
132            if record.term != term || record.ownership_epoch != entry.ownership_epoch =>
133        {
134            record.term = term;
135            if entry.ownership_epoch.is_some() {
136                record.ownership_epoch = entry.ownership_epoch;
137            }
138            record.encode()
139        }
140        _ => entry.data.clone(),
141    }
142}
143
144/// One in every `SEEK_INDEX_INTERVAL` records is checkpointed into the
145/// spool's in-memory seek index. A briefly-disconnected replica
146/// resuming from its slot LSN binary-searches this sparse index and
147/// seeks straight to the nearest preceding checkpoint, then scans
148/// forward at most `SEEK_INDEX_INTERVAL` records — turning resume from
149/// an O(n) full-file scan into a sub-linear seek (issue #832). The
150/// index is rebuilt on `open` and extended on every `append`.
151#[derive(Debug, Default)]
152struct LogicalWalSpoolState {
153    current_lsn: u64,
154    /// Sparse, strictly LSN-ascending `(lsn, byte_offset)` checkpoints
155    /// into the spool file. `byte_offset` is the start of the record
156    /// whose LSN is `lsn`.
157    seek_index: Vec<(u64, u64)>,
158    /// Byte length of the spool file (offset at which the next append
159    /// lands). Tracked so `append` can record a checkpoint's offset
160    /// without an extra `stat`.
161    write_offset: u64,
162    /// Total records appended/recovered, used to space checkpoints
163    /// `SEEK_INDEX_INTERVAL` records apart.
164    record_count: u64,
165}
166
167impl LogicalWalSpoolState {
168    /// Push a checkpoint for the record at `offset` if it falls on a
169    /// `SEEK_INDEX_INTERVAL` boundary. `ordinal` is the record's
170    /// zero-based position in the spool.
171    fn note_record(&mut self, ordinal: u64, lsn: u64, offset: u64) {
172        if ordinal.is_multiple_of(reddb_file::LOGICAL_WAL_SEEK_INDEX_INTERVAL) {
173            // Keep the index strictly ascending even if LSNs repeat
174            // (they should not, but a defensive guard keeps the binary
175            // search total).
176            if self.seek_index.last().map(|(l, _)| *l) != Some(lsn) {
177                self.seek_index.push((lsn, offset));
178            }
179        }
180    }
181
182    /// Byte offset to start a forward scan from when resuming at
183    /// `since_lsn` (exclusive). Returns the offset of the latest
184    /// checkpoint whose LSN is `<= since_lsn`, or `0` when no such
185    /// checkpoint exists.
186    fn seek_floor_offset(&self, since_lsn: u64) -> u64 {
187        match self
188            .seek_index
189            .binary_search_by(|(lsn, _)| lsn.cmp(&since_lsn))
190        {
191            Ok(idx) => self.seek_index[idx].1,
192            Err(0) => 0,
193            Err(idx) => self.seek_index[idx - 1].1,
194        }
195    }
196}
197
198/// Durable append-only logical WAL spool kept beside the main `.rdb` file.
199///
200/// This is not the storage-engine WAL; it is a structured replication/PITR log.
201pub struct LogicalWalSpool {
202    path: PathBuf,
203    state: Mutex<LogicalWalSpoolState>,
204}
205
206impl LogicalWalSpool {
207    pub fn path_for(data_path: &Path) -> PathBuf {
208        reddb_file::layout::logical_wal_path(data_path)
209    }
210
211    pub fn open(data_path: &Path) -> io::Result<Self> {
212        let path = Self::path_for(data_path);
213        if let Some(parent) = path.parent() {
214            fs::create_dir_all(parent)?;
215        }
216        if !path.exists() {
217            File::create(&path)?;
218        }
219        // Recover-or-truncate to the longest valid prefix. A torn tail
220        // from the previous process exit (power loss, OOM kill, ENOSPC
221        // mid-write) is silently dropped; the warning surfaces to the
222        // operator log but the spool stays open.
223        let entries = reddb_file::read_and_repair_logical_wal_entries(&path)?;
224        let current_lsn = entries.last().map(|entry| entry.lsn).unwrap_or(0);
225        // Rebuild the sparse seek index from the (now repaired) file so
226        // a post-restart resume is sub-linear from the first pull.
227        let (seek_index, write_offset, record_count) =
228            reddb_file::build_logical_wal_seek_index(&path)?;
229        Ok(Self {
230            path,
231            state: Mutex::new(LogicalWalSpoolState {
232                current_lsn,
233                seek_index,
234                write_offset,
235                record_count,
236            }),
237        })
238    }
239
240    pub fn append(&self, lsn: u64, data: &[u8]) -> io::Result<()> {
241        let timestamp_ms = SystemTime::now()
242            .duration_since(UNIX_EPOCH)
243            .map(|d| d.as_millis() as u64)
244            .unwrap_or(0);
245        self.append_with_timestamp(lsn, timestamp_ms, data)
246    }
247
248    /// Append a record with an explicit framing timestamp. Used in
249    /// tests to produce deterministic timestamps; production callers
250    /// should use `append`.
251    pub fn append_with_timestamp(
252        &self,
253        lsn: u64,
254        timestamp_ms: u64,
255        data: &[u8],
256    ) -> io::Result<()> {
257        let (term, ownership_epoch) = authority_from_payload(data);
258        self.append_with_term_epoch_and_timestamp(term, ownership_epoch, lsn, timestamp_ms, data)
259    }
260
261    pub fn append_with_term_and_timestamp(
262        &self,
263        term: u64,
264        lsn: u64,
265        timestamp_ms: u64,
266        data: &[u8],
267    ) -> io::Result<()> {
268        let (_, ownership_epoch) = authority_from_payload(data);
269        self.append_with_term_epoch_and_timestamp(term, ownership_epoch, lsn, timestamp_ms, data)
270    }
271
272    pub fn append_with_term_epoch_and_timestamp(
273        &self,
274        term: u64,
275        ownership_epoch: Option<u64>,
276        lsn: u64,
277        timestamp_ms: u64,
278        data: &[u8],
279    ) -> io::Result<()> {
280        let mut file = OpenOptions::new()
281            .create(true)
282            .append(true)
283            .open(&self.path)?;
284        // Pre-build the record in memory so a single write_all keeps
285        // the on-disk record contiguous. Two side-effects:
286        //   (a) crash recovery sees either a complete record or a torn
287        //       header, never an interleaved partial frame from two
288        //       writers (the spool is not multi-writer today, but the
289        //       single-write semantics make that future-safe);
290        //   (b) crc32 is computed exactly once over the same bytes the
291        //       reader will checksum, with zero risk of header/payload
292        //       drift from a partial flush.
293        let frame =
294            reddb_file::encode_logical_wal_v3(term, ownership_epoch, lsn, timestamp_ms, data)?;
295
296        file.write_all(&frame)?;
297        // PLAN.md Phase 2 mandates `sync_all` for logical WAL durability.
298        // `flush()` only drains the std::io userspace buffer; without
299        // `sync_all` the kernel page cache may still be dirty when an
300        // acknowledged write supposedly committed.
301        file.sync_all()?;
302
303        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
304        state.current_lsn = state.current_lsn.max(lsn);
305        // The record we just wrote starts at the prior end-of-file.
306        // Checkpoint it into the seek index if it lands on an interval
307        // boundary, then advance the tracked write offset.
308        let record_start = state.write_offset;
309        let ordinal = state.record_count;
310        state.note_record(ordinal, lsn, record_start);
311        state.write_offset = record_start + frame.len() as u64;
312        state.record_count = ordinal + 1;
313        Ok(())
314    }
315
316    pub fn read_since(&self, since_lsn: u64, max_count: usize) -> io::Result<Vec<(u64, Vec<u8>)>> {
317        // Seek straight to the nearest indexed checkpoint at or before
318        // `since_lsn` instead of scanning the whole spool from offset 0
319        // (issue #832). The file was already repaired on `open`, so the
320        // forward scan from the checkpoint is non-repairing and simply
321        // stops at the first torn tail (left for the next `open` to fix).
322        let start_offset = {
323            let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
324            state.seek_floor_offset(since_lsn)
325        };
326        let entries = reddb_file::read_logical_wal_entries_from(&self.path, start_offset)?;
327        Ok(entries
328            .into_iter()
329            .filter(|entry| entry.lsn > since_lsn)
330            .take(max_count)
331            .map(|entry| (entry.lsn, logical_wal_data_with_framing_term(&entry)))
332            .collect())
333    }
334
335    /// Byte offset a resume at `since_lsn` would seek to before
336    /// forward-scanning. Exposed for tests asserting the resume is
337    /// sub-linear (starts past offset 0 for a mid-spool LSN).
338    #[cfg(test)]
339    fn seek_floor_offset(&self, since_lsn: u64) -> u64 {
340        self.state
341            .lock()
342            .unwrap_or_else(|e| e.into_inner())
343            .seek_floor_offset(since_lsn)
344    }
345
346    pub fn current_lsn(&self) -> u64 {
347        self.state
348            .lock()
349            .unwrap_or_else(|e| e.into_inner())
350            .current_lsn
351    }
352
353    pub fn oldest_lsn(&self) -> io::Result<Option<u64>> {
354        Ok(reddb_file::read_and_repair_logical_wal_entries(&self.path)?
355            .into_iter()
356            .next()
357            .map(|entry| entry.lsn))
358    }
359
360    pub fn prune_through(&self, upto_lsn: u64) -> io::Result<()> {
361        let previous_lsn = self.current_lsn();
362        let mut retained: Vec<_> = reddb_file::read_and_repair_logical_wal_entries(&self.path)?
363            .into_iter()
364            .filter(|entry| entry.lsn > upto_lsn)
365            .collect();
366        for entry in &mut retained {
367            entry.term = logical_wal_entry_term(entry);
368        }
369        let temp_path = reddb_file::layout::logical_wal_temp_path(&self.path);
370        for entry in &mut retained {
371            // Re-frame as v3 so the spool only ever contains current records
372            // after a prune. Legacy v1 records are upgraded by carrying
373            // their original LSN and default term forward; the framing timestamp is
374            // re-stamped to wall-clock-now because the original v1
375            // record didn't carry one — downstream consumers that need
376            // the operation's logical timestamp continue to use the
377            // payload's own ChangeRecord::timestamp field.
378            let timestamp_ms = if entry.timestamp_ms > 0 {
379                entry.timestamp_ms
380            } else {
381                SystemTime::now()
382                    .duration_since(UNIX_EPOCH)
383                    .map(|d| d.as_millis() as u64)
384                    .unwrap_or(0)
385            };
386            entry.timestamp_ms = timestamp_ms;
387        }
388        let current_lsn =
389            reddb_file::rewrite_logical_wal_entries(&self.path, &temp_path, &retained)?;
390
391        // The rewrite shifted every record's byte offset, so the old
392        // seek index is stale — rebuild it from the compacted file.
393        let (seek_index, write_offset, record_count) =
394            reddb_file::build_logical_wal_seek_index(&self.path)?;
395        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
396        state.current_lsn = previous_lsn.max(current_lsn).max(upto_lsn);
397        state.seek_index = seek_index;
398        state.write_offset = write_offset;
399        state.record_count = record_count;
400        Ok(())
401    }
402}
403
404/// State of a connected replica. PLAN.md Phase 11.4 fields:
405/// `last_seen_at_unix_ms` updates on every interaction (pull or ack);
406/// `last_sent_lsn` updates when the primary serves a `pull_wal_records`
407/// batch; `last_durable_lsn` updates when the replica reports its WAL
408/// is durably written via `ack_replica_lsn`.
409#[derive(Debug, Clone)]
410pub struct ReplicaState {
411    pub id: String,
412    pub last_acked_lsn: u64,
413    pub last_sent_lsn: u64,
414    pub last_durable_lsn: u64,
415    pub apply_error_count: u64,
416    pub divergence_count: u64,
417    pub connected_at_unix_ms: u128,
418    pub last_seen_at_unix_ms: u128,
419    /// Region identifier declared by the replica at handshake time
420    /// (Phase 2.6 multi-region PG parity). `None` until the replica
421    /// handshake extension lands in 2.6.2; the quorum coordinator's
422    /// region-binding map covers the in-process case meanwhile.
423    pub region: Option<String>,
424    /// `true` while this replica is re-bootstrapping — loading a fresh
425    /// snapshot to replace its current dataset (issue #837). It keeps
426    /// serving non-causal reads from the old data, but the advertiser
427    /// surfaces this flag so a causal reader routes bookmark reads
428    /// elsewhere: the replica's `last_acked_lsn` describes data it is
429    /// about to discard. Cleared atomically when the swap completes.
430    pub rebootstrapping: bool,
431}
432
433/// Primary-side replication progress derived from the replica registry.
434#[derive(Debug, Clone, Copy, PartialEq, Eq)]
435pub struct ReplicationProgress {
436    pub lag_lsn: u64,
437    pub safe_replay_lsn: u64,
438}
439
440impl ReplicationProgress {
441    pub fn from_replicas(replicas: &[ReplicaState]) -> Option<Self> {
442        let max_sent_lsn = replicas.iter().map(|replica| replica.last_sent_lsn).max()?;
443        let min_acked_lsn = replicas
444            .iter()
445            .map(|replica| replica.last_acked_lsn)
446            .min()?;
447        let safe_replay_lsn = replicas
448            .iter()
449            .map(|replica| replica.last_durable_lsn)
450            .min()?;
451
452        Some(Self {
453            lag_lsn: max_sent_lsn.saturating_sub(min_acked_lsn),
454            safe_replay_lsn,
455        })
456    }
457}
458
459/// Primary replication manager.
460pub struct PrimaryReplication {
461    pub wal_buffer: Arc<WalBuffer>,
462    pub logical_wal_spool: Option<Arc<LogicalWalSpool>>,
463    pub replicas: RwLock<Vec<ReplicaState>>,
464    wal_appended: (Mutex<u64>, Condvar),
465    metadata_store: Option<Arc<crate::storage::unified::UnifiedStore>>,
466    metadata_error: Mutex<Option<String>>,
467    slot_path: Option<PathBuf>,
468    slot_catalog_path: Option<PathBuf>,
469    primary_replica_file_plan: Option<reddb_file::PrimaryReplicaFilePlan>,
470    primary_replica_wal_lock: Mutex<()>,
471    slots: RwLock<BTreeMap<String, ReplicationSlot>>,
472    slot_retention_max_lag_lsn: u64,
473    slot_idle_timeout_ms: u64,
474    /// PLAN.md Phase 11.4 — ack-driven commit synchronization. Always
475    /// allocated so the policy enum can flip from `Local` to
476    /// `AckN`/`Quorum` without touching this struct's shape.
477    pub commit_waiter: Arc<crate::replication::commit_waiter::CommitWaiter>,
478    /// Monotonic registry-change counter consumed by the
479    /// `TopologyAdvertiser` (issue #167). Bumps on register,
480    /// unregister, and the periodic health sweep when a replica
481    /// flips between healthy/unhealthy. Clients use the epoch to
482    /// detect stale advertisements without comparing the full
483    /// replica list element-wise.
484    topology_epoch: std::sync::atomic::AtomicU64,
485    /// Count of pulls served as a partial resync — a replica resuming
486    /// incrementally from its retained slot position rather than
487    /// triggering a full re-bootstrap (issue #832). Surfaced as a
488    /// replication metric so a brief disconnect that recovers via
489    /// partial resync is observable.
490    partial_resync_count: std::sync::atomic::AtomicU64,
491    /// Count of pulls that forced a full re-bootstrap — the replica's
492    /// retained WAL no longer covers its requested position, so it must
493    /// discard its dataset and reload a fresh snapshot (issue #839).
494    /// This is the primary alert signal: a healthy cluster re-bootstraps
495    /// rarely, so any sustained rise means slots are being invalidated
496    /// faster than replicas can keep up.
497    full_resync_count: std::sync::atomic::AtomicU64,
498}
499
500/// How a replica's pull should be served, decided from its slot state.
501#[derive(Debug, Clone, Copy, PartialEq, Eq)]
502pub enum ResumeMode {
503    /// Resume incrementally from `resume_lsn` (the replica's slot
504    /// position, never behind it). The retained WAL still covers the
505    /// gap, so a brief disconnect costs only a partial resync.
506    PartialResync { resume_lsn: u64 },
507    /// The slot is past the retention cap (or otherwise invalidated);
508    /// the replica must discard and re-bootstrap from a fresh snapshot.
509    FullRebootstrap {
510        cause: ReplicationSlotInvalidationCause,
511    },
512}
513
514impl PrimaryReplication {
515    pub fn slot_path_for(data_path: &Path) -> PathBuf {
516        reddb_file::layout::legacy_logical_slots_path(data_path)
517    }
518
519    pub fn primary_replica_root_for(data_path: &Path) -> PathBuf {
520        reddb_file::layout::primary_replica_root(data_path)
521    }
522
523    pub fn slot_catalog_path_for(data_path: &Path) -> PathBuf {
524        Self::primary_replica_file_plan_for(data_path).slots_path()
525    }
526
527    fn primary_replica_file_plan_for(data_path: &Path) -> reddb_file::PrimaryReplicaFilePlan {
528        let root = Self::primary_replica_root_for(data_path);
529        let timeline =
530            Self::primary_replica_current_timeline_for_root(&root).unwrap_or_else(|err| {
531                warn!(
532                    target: "reddb::replication::primary",
533                    error = %err,
534                    "failed to read primary-replica timeline history; using initial timeline"
535                );
536                reddb_file::TimelineId::initial()
537            });
538        reddb_file::PrimaryReplicaFilePlan::new(root, timeline)
539    }
540
541    fn primary_replica_current_timeline_for_root(
542        root: &Path,
543    ) -> Result<reddb_file::TimelineId, reddb_file::RdbFileError> {
544        let path = reddb_file::PrimaryReplicaFilePlan::new(root, reddb_file::TimelineId::initial())
545            .timeline_history_path();
546        match reddb_file::TimelineHistory::read_from_path(&path) {
547            Ok(history) => Ok(history
548                .current()
549                .unwrap_or_else(reddb_file::TimelineId::initial)),
550            Err(reddb_file::RdbFileError::Io(err))
551                if err.kind() == std::io::ErrorKind::NotFound =>
552            {
553                Ok(reddb_file::TimelineId::initial())
554            }
555            Err(err) => Err(err),
556        }
557    }
558
559    pub fn new(data_path: Option<&Path>) -> Self {
560        Self::new_with_config(data_path, &crate::replication::ReplicationConfig::primary())
561    }
562
563    pub fn new_with_config(
564        data_path: Option<&Path>,
565        config: &crate::replication::ReplicationConfig,
566    ) -> Self {
567        let now_ms = crate::utils::now_unix_millis() as u128;
568        let slot_path = data_path.map(Self::slot_path_for);
569        let slot_catalog_path = data_path.map(Self::slot_catalog_path_for);
570        let primary_replica_file_plan = data_path.map(Self::primary_replica_file_plan_for);
571        let mut slots = load_replication_slot_catalog(slot_catalog_path.as_deref(), now_ms);
572        slots.extend(load_replication_slots(slot_path.as_deref(), now_ms));
573        let logical_wal_spool = data_path
574            .and_then(|path| LogicalWalSpool::open(path).ok())
575            .map(Arc::new);
576        let current_lsn = logical_wal_spool
577            .as_ref()
578            .map(|spool| spool.current_lsn())
579            .unwrap_or(0);
580        Self {
581            wal_buffer: Arc::new(WalBuffer::new(100_000)),
582            logical_wal_spool,
583            replicas: RwLock::new(Vec::new()),
584            wal_appended: (Mutex::new(current_lsn), Condvar::new()),
585            metadata_store: None,
586            metadata_error: Mutex::new(None),
587            slot_path,
588            slot_catalog_path,
589            primary_replica_file_plan,
590            primary_replica_wal_lock: Mutex::new(()),
591            slots: RwLock::new(slots),
592            slot_retention_max_lag_lsn: config.slot_retention_max_lag_lsn,
593            slot_idle_timeout_ms: config.slot_idle_timeout_ms,
594            commit_waiter: Arc::new(crate::replication::commit_waiter::CommitWaiter::new()),
595            topology_epoch: std::sync::atomic::AtomicU64::new(0),
596            partial_resync_count: std::sync::atomic::AtomicU64::new(0),
597            full_resync_count: std::sync::atomic::AtomicU64::new(0),
598        }
599    }
600
601    pub(crate) fn new_with_store(
602        data_path: Option<&Path>,
603        config: &crate::replication::ReplicationConfig,
604        store: Arc<crate::storage::unified::UnifiedStore>,
605    ) -> io::Result<Self> {
606        let mut primary = Self::new_with_config(data_path, config);
607        if let Some(bytes) = super::metadata::read(&store, super::metadata::SLOTS)? {
608            let catalog =
609                reddb_file::ReplicationSlotCatalog::decode(&bytes).map_err(io::Error::other)?;
610            primary.slots = RwLock::new(
611                catalog
612                    .slots
613                    .into_iter()
614                    .map(|slot| (slot.replica_id.clone(), slot))
615                    .collect(),
616            );
617        } else {
618            // Validate legacy sources before importing. An unreadable source
619            // must not silently become an empty authoritative catalog.
620            let mut valid_source = false;
621            let mut import_error = None;
622            for path in [&primary.slot_catalog_path, &primary.slot_path]
623                .into_iter()
624                .flatten()
625            {
626                if path.try_exists()? {
627                    let result = if primary.slot_catalog_path.as_ref() == Some(path) {
628                        reddb_file::ReplicationSlotCatalog::read_from_path(path)
629                    } else {
630                        reddb_file::ReplicationSlotCatalog::read_legacy_json_from_path(
631                            path,
632                            crate::utils::now_unix_millis() as u128,
633                        )
634                    };
635                    match result {
636                        Ok(_) => valid_source = true,
637                        Err(error) => import_error = Some(error),
638                    }
639                }
640            }
641            if !valid_source {
642                if let Some(error) = import_error {
643                    return Err(io::Error::other(error));
644                }
645            }
646            let slots = primary
647                .slots
648                .read()
649                .unwrap_or_else(|error| error.into_inner());
650            let bytes = slots::slot_catalog_from_map(&slots)
651                .and_then(|catalog| catalog.encode())
652                .map_err(io::Error::other)?;
653            super::metadata::write(&store, super::metadata::SLOTS, &bytes)?;
654        }
655        for path in [&primary.slot_catalog_path, &primary.slot_path]
656            .into_iter()
657            .flatten()
658        {
659            super::metadata::retire_legacy(path)?;
660        }
661        primary.metadata_store = Some(store);
662        Ok(primary)
663    }
664
665    fn current_timeline(
666        &self,
667        root: &Path,
668    ) -> Result<reddb_file::TimelineId, reddb_file::RdbFileError> {
669        if let Some(store) = &self.metadata_store {
670            let path =
671                reddb_file::PrimaryReplicaFilePlan::new(root, reddb_file::TimelineId::initial())
672                    .timeline_history_path();
673            return super::metadata::timeline(store, &path)
674                .map(|history| {
675                    history
676                        .current()
677                        .unwrap_or_else(reddb_file::TimelineId::initial)
678                })
679                .map_err(reddb_file::RdbFileError::Io);
680        }
681        Self::primary_replica_current_timeline_for_root(root)
682    }
683
684    pub fn append_logical_record(&self, lsn: u64, encoded: Vec<u8>) {
685        self.wal_buffer.append(lsn, encoded.clone());
686        if let Some(spool) = &self.logical_wal_spool {
687            let _ = spool.append(lsn, &encoded);
688        }
689        if let Some(plan) = &self.primary_replica_file_plan {
690            let _guard = self
691                .primary_replica_wal_lock
692                .lock()
693                .unwrap_or_else(|err| err.into_inner());
694            match self.current_timeline(&plan.root) {
695                Ok(timeline) => {
696                    let plan = reddb_file::PrimaryReplicaFilePlan::new(plan.root.clone(), timeline);
697                    if let Err(err) = plan.append_wal_record(lsn, &encoded) {
698                        warn!(
699                            target: "reddb::replication::primary",
700                            lsn,
701                            error = %err,
702                            "failed to append primary-replica WAL segment"
703                        );
704                    }
705                }
706                Err(err) => {
707                    warn!(
708                        target: "reddb::replication::primary",
709                        lsn,
710                        error = %err,
711                        "failed to read primary-replica timeline history; skipping WAL append"
712                    );
713                }
714            }
715        }
716        let (lock, cvar) = &self.wal_appended;
717        let mut latest = lock.lock().unwrap_or_else(|e| e.into_inner());
718        *latest = (*latest).max(lsn);
719        cvar.notify_all();
720    }
721
722    pub fn wait_for_logical_lsn_after(&self, since_lsn: u64, timeout: Duration) -> bool {
723        if self.current_logical_lsn() > since_lsn {
724            return true;
725        }
726        let deadline = Instant::now() + timeout;
727        let (lock, cvar) = &self.wal_appended;
728        let mut latest = lock.lock().unwrap_or_else(|e| e.into_inner());
729        while *latest <= since_lsn {
730            let now = Instant::now();
731            if now >= deadline {
732                return false;
733            }
734            let remaining = deadline.saturating_duration_since(now);
735            let (guard, result) = cvar
736                .wait_timeout(latest, remaining)
737                .unwrap_or_else(|e| e.into_inner());
738            latest = guard;
739            if result.timed_out() && *latest <= since_lsn {
740                return false;
741            }
742        }
743        true
744    }
745
746    pub fn register_replica(&self, id: String) -> u64 {
747        self.register_replica_with_region(id, None)
748    }
749
750    /// Register a replica with an explicit region tag (Phase 2.6 multi-region).
751    ///
752    /// Preferred when the replica handshake declares a region — the quorum
753    /// coordinator uses this field to decide whether the replica counts
754    /// toward a `QuorumMode::Regions` commit.
755    ///
756    /// Idempotent on reconnect (issue #812): if a replica with `id` is
757    /// already registered, the existing entry is *updated in place* rather
758    /// than duplicated — progress LSNs (`last_acked_lsn`, `last_sent_lsn`,
759    /// `last_durable_lsn`) are preserved so a reconnecting replica is not
760    /// rewound, only `last_seen_at_unix_ms` is refreshed (and `region` when
761    /// a non-`None` value is supplied). A re-registration is not a
762    /// registry-shape change, so it does **not** bump the topology epoch.
763    /// Returns the slot `restart_lsn` the replica should resume streaming from:
764    /// the current WAL LSN for a fresh registration, or the durable slot
765    /// restart point for a reconnect.
766    pub fn register_replica_with_region(&self, id: String, region: Option<String>) -> u64 {
767        self.register_replica_with_region_at(id, region, self.current_logical_lsn())
768    }
769
770    fn register_replica_with_region_at(
771        &self,
772        id: String,
773        region: Option<String>,
774        initial_lsn: u64,
775    ) -> u64 {
776        let now_ms = crate::utils::now_unix_millis() as u128;
777        let resume_lsn = self.ensure_slot(&id, initial_lsn);
778        let mut replicas = self.replicas.write().unwrap_or_else(|e| e.into_inner());
779        if let Some(existing) = replicas.iter_mut().find(|r| r.id == id) {
780            existing.last_seen_at_unix_ms = now_ms;
781            if region.is_some() {
782                existing.region = region;
783            }
784            return resume_lsn;
785        }
786        replicas.push(ReplicaState {
787            id,
788            last_acked_lsn: resume_lsn,
789            last_sent_lsn: resume_lsn,
790            last_durable_lsn: resume_lsn,
791            apply_error_count: 0,
792            divergence_count: 0,
793            connected_at_unix_ms: now_ms,
794            last_seen_at_unix_ms: now_ms,
795            region,
796            rebootstrapping: false,
797        });
798        drop(replicas);
799        self.bump_topology_epoch();
800        resume_lsn
801    }
802
803    /// Mark (or clear) a replica's re-bootstrap state (issue #837).
804    ///
805    /// While `rebootstrapping` is `true` the replica keeps serving
806    /// non-causal reads from its existing data, but the advertiser
807    /// surfaces the flag so causal (bookmark) reads route to a
808    /// caught-up peer instead — the rebuilding replica's applied
809    /// frontier describes data it is about to discard. The primary
810    /// flips this back to `false` when the replica reports its atomic
811    /// snapshot swap complete.
812    ///
813    /// A change to the flag is a registry-shape change for routing
814    /// purposes, so it bumps the topology epoch to force consumers to
815    /// re-read the advertisement. Returns `true` when a replica with
816    /// `id` was present and updated.
817    pub fn set_replica_rebootstrapping(&self, id: &str, rebootstrapping: bool) -> bool {
818        let mut replicas = self.replicas.write().unwrap_or_else(|e| e.into_inner());
819        let Some(state) = replicas.iter_mut().find(|r| r.id == id) else {
820            return false;
821        };
822        if state.rebootstrapping == rebootstrapping {
823            return true;
824        }
825        state.rebootstrapping = rebootstrapping;
826        drop(replicas);
827        self.bump_topology_epoch();
828        true
829    }
830
831    /// Ensure a replica identifying itself with `id` is present in the
832    /// registry (issue #812). This is the production self-registration hook
833    /// used by the `pull_wal_records` path: the first time a replica sends
834    /// its `replica_id` on a pull, the primary registers it so it is no
835    /// longer blind to that replica's existence; subsequent pulls are
836    /// idempotent no-ops. Returns `true` when a new registration was
837    /// created. A fresh slot starts at the replica's requested cursor rather
838    /// than the primary's current LSN, so an empty replica does not skip WAL
839    /// that was written before its first pull. Reconnects preserve existing
840    /// progress and do not bump the topology epoch.
841    pub fn ensure_replica_registered(&self, id: &str, requested_since_lsn: u64) -> bool {
842        let already = self
843            .replicas
844            .read()
845            .unwrap_or_else(|e| e.into_inner())
846            .iter()
847            .any(|r| r.id == id);
848        if already {
849            return false;
850        }
851        self.register_replica_with_region_at(id.to_string(), None, requested_since_lsn);
852        true
853    }
854
855    /// Unregister a replica by id. Returns `true` when the replica
856    /// was present (and removed). Bumps the topology epoch so a
857    /// pending advertisement reflects the new fleet size.
858    pub fn unregister_replica(&self, id: &str) -> bool {
859        let mut replicas = self.replicas.write().unwrap_or_else(|e| e.into_inner());
860        let before = replicas.len();
861        replicas.retain(|r| r.id != id);
862        let removed = replicas.len() != before;
863        drop(replicas);
864        if removed {
865            self.commit_waiter.drop_replica(id);
866            self.bump_topology_epoch();
867        }
868        removed
869    }
870
871    /// Current topology epoch. Strictly monotonic, bumps on every
872    /// registry-shape change consumed by `TopologyAdvertiser`.
873    pub fn topology_epoch(&self) -> u64 {
874        self.topology_epoch
875            .load(std::sync::atomic::Ordering::Relaxed)
876    }
877
878    /// Advance the topology epoch. Call sites: register, unregister,
879    /// and the health-sweep tick that flips a replica between
880    /// healthy/unhealthy. Wrapping is not a concern in practice
881    /// (`u64::MAX` events would take centuries at any realistic ack
882    /// rate) but `fetch_add` saturates implicitly via wrap-around;
883    /// the consumer treats epoch as opaque so a wrap is still
884    /// strictly "different" from the previous value.
885    pub fn bump_topology_epoch(&self) {
886        self.topology_epoch
887            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
888    }
889
890    pub fn ack_replica(&self, id: &str, lsn: u64) {
891        let now_ms = crate::utils::now_unix_millis() as u128;
892        let mut replicas = self.replicas.write().unwrap_or_else(|e| e.into_inner());
893        if let Some(r) = replicas.iter_mut().find(|r| r.id == id) {
894            r.last_acked_lsn = r.last_acked_lsn.max(lsn);
895            r.last_durable_lsn = r.last_durable_lsn.max(lsn);
896            r.last_seen_at_unix_ms = now_ms;
897        }
898        drop(replicas);
899        self.commit_waiter.record_replica_ack(id, lsn);
900    }
901
902    /// PLAN.md Phase 11.4 — replica reports applied + durable LSN
903    /// after persisting a batch. Idempotent: only advances LSNs
904    /// monotonically. `last_seen_at_unix_ms` always refreshes.
905    /// Also signals `commit_waiter` so any thread blocked on
906    /// `ack_n` / `quorum` can wake and re-check its threshold.
907    pub fn ack_replica_lsn(&self, id: &str, applied_lsn: u64, durable_lsn: u64) {
908        self.ack_replica_lsn_with_observability(id, applied_lsn, durable_lsn, 0, 0);
909    }
910
911    pub fn ack_replica_lsn_with_observability(
912        &self,
913        id: &str,
914        applied_lsn: u64,
915        durable_lsn: u64,
916        apply_error_count: u64,
917        divergence_count: u64,
918    ) {
919        let now_ms = crate::utils::now_unix_millis() as u128;
920        self.advance_slot(id, applied_lsn, durable_lsn, now_ms);
921        let mut replicas = self.replicas.write().unwrap_or_else(|e| e.into_inner());
922        if let Some(r) = replicas.iter_mut().find(|r| r.id == id) {
923            r.last_acked_lsn = r.last_acked_lsn.max(applied_lsn);
924            r.last_durable_lsn = r.last_durable_lsn.max(durable_lsn);
925            r.apply_error_count = r.apply_error_count.max(apply_error_count);
926            r.divergence_count = r.divergence_count.max(divergence_count);
927            r.last_seen_at_unix_ms = now_ms;
928        }
929        // Drop the write lock before signaling so a waiter that
930        // wakes immediately can read replica state without
931        // contending against us.
932        drop(replicas);
933        self.commit_waiter.record_replica_ack(id, durable_lsn);
934    }
935
936    /// PLAN.md Phase 11.4 — primary records the LSN it last sent to a
937    /// replica via pull_wal_records. Helpful for `lag_records =
938    /// last_sent_lsn - last_acked_lsn` to distinguish pull-side delay
939    /// from apply-side delay.
940    pub fn note_replica_pull(&self, id: &str, last_sent_lsn: u64) {
941        let now_ms = crate::utils::now_unix_millis() as u128;
942        self.touch_slot(id, now_ms);
943        let mut replicas = self.replicas.write().unwrap_or_else(|e| e.into_inner());
944        if let Some(r) = replicas.iter_mut().find(|r| r.id == id) {
945            r.last_sent_lsn = r.last_sent_lsn.max(last_sent_lsn);
946            r.last_seen_at_unix_ms = now_ms;
947        }
948    }
949
950    /// Snapshot of all currently registered replicas, for /metrics +
951    /// /admin/status. Returns owned clones so callers don't hold the
952    /// lock during serialization.
953    pub fn replica_snapshots(&self) -> Vec<ReplicaState> {
954        self.replicas
955            .read()
956            .unwrap_or_else(|e| e.into_inner())
957            .clone()
958    }
959
960    pub fn replication_progress(&self) -> Option<ReplicationProgress> {
961        let replicas = self.replicas.read().unwrap_or_else(|e| e.into_inner());
962        ReplicationProgress::from_replicas(&replicas)
963    }
964
965    pub fn slot_snapshots(&self) -> Vec<ReplicationSlot> {
966        self.slots
967            .read()
968            .unwrap_or_else(|e| e.into_inner())
969            .values()
970            .cloned()
971            .collect()
972    }
973
974    pub fn retention_floor_lsn(&self) -> Option<u64> {
975        // A slot update publishes its durability result while holding this lock.
976        // Check the error only after joining that same publication boundary.
977        let slots = self.slots.read().unwrap_or_else(|e| e.into_inner());
978        if self.ensure_slot_metadata_durable().is_err() {
979            return Some(0);
980        }
981        slots
982            .values()
983            .filter(|slot| slot.invalidation_reason.is_none())
984            .map(|slot| slot.restart_lsn)
985            .min()
986    }
987
988    pub fn prune_retained_wal_through(&self, archived_lsn: u64) -> io::Result<u64> {
989        self.enforce_retention_limits(crate::utils::now_unix_millis() as u128);
990        let prune_lsn = self
991            .retention_floor_lsn()
992            .map(|floor| floor.min(archived_lsn))
993            .unwrap_or(archived_lsn);
994        if prune_lsn > 0 {
995            if let Some(spool) = &self.logical_wal_spool {
996                spool.prune_through(prune_lsn)?;
997            }
998            self.wal_buffer.prune_through(prune_lsn);
999        }
1000        Ok(prune_lsn)
1001    }
1002
1003    pub fn replica_count(&self) -> usize {
1004        self.replicas
1005            .read()
1006            .unwrap_or_else(|e| e.into_inner())
1007            .len()
1008    }
1009
1010    /// Current primary write position (logical WAL LSN, falling back to
1011    /// the in-memory WAL buffer). Used as the reference point for
1012    /// per-replica lag — including issue #826 flow control.
1013    pub fn current_logical_lsn(&self) -> u64 {
1014        self.logical_wal_spool
1015            .as_ref()
1016            .map(|spool| spool.current_lsn())
1017            .unwrap_or_else(|| self.wal_buffer.current_lsn())
1018    }
1019
1020    fn ensure_slot(&self, id: &str, initial_lsn: u64) -> u64 {
1021        let now_ms = crate::utils::now_unix_millis() as u128;
1022        let _publication = self
1023            .metadata_store
1024            .as_ref()
1025            .map(|store| store.vault_publication_lock.lock());
1026        let mut slots = self.slots.write().unwrap_or_else(|e| e.into_inner());
1027        if let Some(slot) = slots.get_mut(id) {
1028            slot.last_seen_at_unix_ms = now_ms;
1029            let restart_lsn = slot.restart_lsn;
1030            self.persist_slots_locked(&slots);
1031            return restart_lsn;
1032        }
1033        let mut slot = ReplicationSlot::new(
1034            id.to_string(),
1035            reddb_file::TimelineId::initial(),
1036            initial_lsn,
1037        );
1038        slot.last_seen_at_unix_ms = now_ms;
1039        slots.insert(id.to_string(), slot);
1040        let restart_lsn = initial_lsn;
1041        self.persist_slots_locked(&slots);
1042        restart_lsn
1043    }
1044
1045    fn advance_slot(&self, id: &str, confirmed_lsn: u64, restart_lsn: u64, now_ms: u128) {
1046        let _publication = self
1047            .metadata_store
1048            .as_ref()
1049            .map(|store| store.vault_publication_lock.lock());
1050        let mut slots = self.slots.write().unwrap_or_else(|e| e.into_inner());
1051        let slot = slots.entry(id.to_string()).or_insert_with(|| {
1052            let mut slot =
1053                ReplicationSlot::new(id.to_string(), reddb_file::TimelineId::initial(), 0);
1054            slot.last_seen_at_unix_ms = now_ms;
1055            slot
1056        });
1057        if slot.invalidation_reason.is_some() {
1058            return;
1059        }
1060        slot.confirmed_write_lsn = slot.confirmed_lsn().max(confirmed_lsn).max(restart_lsn);
1061        slot.restart_lsn = slot.restart_lsn.max(restart_lsn);
1062        slot.confirmed_flush_lsn = slot.confirmed_flush_lsn.max(slot.restart_lsn);
1063        slot.confirmed_apply_lsn = slot.confirmed_apply_lsn.max(slot.restart_lsn);
1064        slot.last_seen_at_unix_ms = now_ms;
1065        self.persist_slots_locked(&slots);
1066    }
1067
1068    pub fn touch_slot(&self, id: &str, now_ms: u128) {
1069        let _publication = self
1070            .metadata_store
1071            .as_ref()
1072            .map(|store| store.vault_publication_lock.lock());
1073        let mut slots = self.slots.write().unwrap_or_else(|e| e.into_inner());
1074        let mut changed = false;
1075        if let Some(slot) = slots.get_mut(id) {
1076            if slot.invalidation_reason.is_none() {
1077                slot.last_seen_at_unix_ms = now_ms;
1078                changed = true;
1079            }
1080        }
1081        if changed {
1082            self.persist_slots_locked(&slots);
1083        }
1084    }
1085
1086    pub fn enforce_retention_limits(
1087        &self,
1088        now_ms: u128,
1089    ) -> Vec<(String, ReplicationSlotInvalidationCause)> {
1090        let current_lsn = self.current_logical_lsn();
1091        let mut invalidated = Vec::new();
1092        let _publication = self
1093            .metadata_store
1094            .as_ref()
1095            .map(|store| store.vault_publication_lock.lock());
1096        let mut slots = self.slots.write().unwrap_or_else(|e| e.into_inner());
1097        for slot in slots.values_mut() {
1098            if slot.invalidation_reason.is_some() {
1099                continue;
1100            }
1101            let reason = if self.slot_retention_max_lag_lsn > 0
1102                && current_lsn.saturating_sub(slot.restart_lsn) > self.slot_retention_max_lag_lsn
1103            {
1104                Some(ReplicationSlotInvalidationCause::Horizon)
1105            } else if self.slot_idle_timeout_ms > 0
1106                && now_ms.saturating_sub(slot.last_seen_at_unix_ms)
1107                    > u128::from(self.slot_idle_timeout_ms)
1108            {
1109                Some(ReplicationSlotInvalidationCause::IdleTimeout)
1110            } else {
1111                None
1112            };
1113            if let Some(reason) = reason {
1114                slot.invalidation_reason = Some(reason);
1115                slot.invalidated_at_unix_ms = Some(now_ms);
1116                invalidated.push((slot.replica_id.clone(), reason));
1117            }
1118        }
1119        if !invalidated.is_empty() {
1120            self.persist_slots_locked(&slots);
1121        }
1122        invalidated
1123    }
1124
1125    pub fn slot_rebootstrap_reason(
1126        &self,
1127        id: &str,
1128        requested_since_lsn: u64,
1129        oldest_available_lsn: Option<u64>,
1130    ) -> Option<ReplicationSlotInvalidationCause> {
1131        let now_ms = crate::utils::now_unix_millis() as u128;
1132        let _publication = self
1133            .metadata_store
1134            .as_ref()
1135            .map(|store| store.vault_publication_lock.lock());
1136        let mut slots = self.slots.write().unwrap_or_else(|e| e.into_inner());
1137        let slot = slots.get_mut(id)?;
1138        if let Some(reason) = slot.invalidation_reason {
1139            return Some(reason);
1140        }
1141        let slot_floor = slot.restart_lsn.max(requested_since_lsn);
1142        if oldest_available_lsn
1143            .map(|oldest| oldest > slot_floor.saturating_add(1))
1144            .unwrap_or(false)
1145        {
1146            slot.invalidation_reason = Some(ReplicationSlotInvalidationCause::WalRemoved);
1147            slot.invalidated_at_unix_ms = Some(now_ms);
1148            self.persist_slots_locked(&slots);
1149            return Some(ReplicationSlotInvalidationCause::WalRemoved);
1150        }
1151        None
1152    }
1153
1154    /// Decide how a reconnecting replica's pull should be served
1155    /// (issue #832). If the slot is invalidated or the requested
1156    /// position has fallen behind the retained WAL floor, the replica
1157    /// must re-bootstrap; otherwise it resumes via a partial resync
1158    /// from its slot position (never rewound behind it). Every
1159    /// partial-resync decision bumps the `partial_resync_count` metric
1160    /// so a brief disconnect that recovers without a full re-bootstrap
1161    /// is observable.
1162    pub fn plan_replica_resume(
1163        &self,
1164        id: &str,
1165        requested_since_lsn: u64,
1166        oldest_available_lsn: Option<u64>,
1167    ) -> ResumeMode {
1168        if let Some(cause) =
1169            self.slot_rebootstrap_reason(id, requested_since_lsn, oldest_available_lsn)
1170        {
1171            self.full_resync_count
1172                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1173            return ResumeMode::FullRebootstrap { cause };
1174        }
1175        let resume_lsn = self
1176            .slot_snapshots()
1177            .into_iter()
1178            .find(|slot| slot.replica_id == id)
1179            .map(|slot| requested_since_lsn.max(slot.restart_lsn))
1180            .unwrap_or(requested_since_lsn);
1181        self.partial_resync_count
1182            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1183        ResumeMode::PartialResync { resume_lsn }
1184    }
1185
1186    /// Number of pulls served as a partial resync since process start.
1187    /// Surfaced in the replication metrics/status payload (issue #832).
1188    pub fn partial_resync_count(&self) -> u64 {
1189        self.partial_resync_count
1190            .load(std::sync::atomic::Ordering::Relaxed)
1191    }
1192
1193    /// Number of pulls that forced a full re-bootstrap since process
1194    /// start (issue #839). Surfaced as `reddb_replication_full_resync_total`
1195    /// and in `/replication/status` — the primary operator alert signal.
1196    pub fn full_resync_count(&self) -> u64 {
1197        self.full_resync_count
1198            .load(std::sync::atomic::Ordering::Relaxed)
1199    }
1200
1201    fn persist_slots_locked(&self, slots: &BTreeMap<String, ReplicationSlot>) {
1202        if let Some(store) = &self.metadata_store {
1203            let result = slots::slot_catalog_from_map(slots)
1204                .and_then(|catalog| catalog.encode())
1205                .map_err(io::Error::other)
1206                .and_then(|bytes| super::metadata::write(store, super::metadata::SLOTS, &bytes));
1207            let mut last_error = self
1208                .metadata_error
1209                .lock()
1210                .unwrap_or_else(|error| error.into_inner());
1211            if let Err(error) = result {
1212                *last_error = Some(error.to_string());
1213                warn!(target: "reddb::replication::slots", %error,
1214                    "failed to persist replication slots inside database");
1215            } else {
1216                *last_error = None;
1217            }
1218            return;
1219        }
1220        if let Err(err) = persist_replication_slots(self.slot_path.as_deref(), slots) {
1221            warn!(
1222                target: "reddb::replication::slots",
1223                error = %err,
1224                "failed to persist replication slots"
1225            );
1226        }
1227        if let Err(err) = persist_replication_slot_catalog(self.slot_catalog_path.as_deref(), slots)
1228        {
1229            warn!(
1230                target: "reddb::replication::slots",
1231                error = %err,
1232                "failed to persist binary replication slot catalog"
1233            );
1234        }
1235    }
1236
1237    pub(crate) fn ensure_slot_metadata_durable(&self) -> io::Result<()> {
1238        match self
1239            .metadata_error
1240            .lock()
1241            .unwrap_or_else(|error| error.into_inner())
1242            .as_ref()
1243        {
1244            Some(error) => Err(io::Error::other(error.clone())),
1245            None => Ok(()),
1246        }
1247    }
1248}
1249
1250#[cfg(test)]
1251mod tests;