1use std::sync::Arc;
59#[cfg(test)]
60use std::sync::atomic::AtomicU64;
61use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
62
63use melin_journal::{BufferedWriter, JournalWrite};
64
65use melin_app::Application;
66use melin_transport_core::pipeline::{InputSlot, OutputSlot};
67use melin_transport_core::replication::archive::{ArchiveReason, archive_local_lineage};
68use melin_transport_core::replication::protocol::{MAX_CONTROL_FRAME, decode_primary_message};
69
70mod auth;
71#[cfg(feature = "dpdk")]
72mod dpdk;
73mod receiver_transport;
74mod tcp_receiver;
75mod tcp_sender;
76#[cfg(any(feature = "dpdk", test))]
81mod validation_worker;
82
83use receiver_transport::{ControlFrameSource, SessionExit, StreamingResult, receive_chunked_body};
84
85pub(crate) struct ReplicaGate<'a> {
98 count: &'a AtomicU32,
99}
100
101impl<'a> ReplicaGate<'a> {
102 pub(crate) fn new(count: &'a AtomicU32) -> Self {
103 Self { count }
104 }
105
106 pub(crate) fn lift(&self) {
109 self.count.fetch_add(1, Ordering::Release);
110 }
111
112 pub(crate) fn lower(&self) -> bool {
119 let was_last = self.count.fetch_sub(1, Ordering::Release) == 1;
120 if was_last {
121 tracing::warn!("all replicas disconnected — halted, refusing client writes");
122 }
123 was_last
124 }
125}
126
127pub use melin_transport_core::replication::ack_queue::{
134 PendingAck, PendingAckQueue, try_flush_dual_track, wait_for_journal_cursor,
135};
136pub use melin_transport_core::replication::protocol::{
137 Ack, Handshake, PrimaryMessage, ReplicaMessage,
138};
139pub use melin_transport_core::replication::{ReplicaCursors, ReplicationMetrics, SentHighWater};
140
141#[cfg(feature = "dpdk")]
142pub(crate) use dpdk::REPL_DISPATCH_BURST;
143#[cfg(feature = "dpdk")]
144pub use dpdk::{DpdkReplicationDriver, run_receiver_dpdk};
145pub use tcp_receiver::{ReceiverResult, run_receiver};
146pub use tcp_sender::{ReplicationListener, Sender, run_sender};
147
148#[derive(Clone)]
155pub struct ReplicaControlPlane {
156 pub promote: crate::promotion::PromotionRequest,
159 pub tip_ready: std::sync::Arc<AtomicBool>,
163 pub journal_tip: melin_transport_core::AdvertisedJournalTip,
166 pub primary_link_up: std::sync::Arc<AtomicBool>,
173 pub primary_ack_policy: std::sync::Arc<std::sync::atomic::AtomicU8>,
183 pub pipeline_healthy: std::sync::Arc<AtomicBool>,
191}
192
193impl ReplicaControlPlane {
194 pub fn new() -> Self {
198 Self {
199 promote: crate::promotion::PromotionRequest::new(),
200 tip_ready: std::sync::Arc::new(AtomicBool::new(false)),
201 journal_tip: melin_transport_core::AdvertisedJournalTip::new(
202 melin_transport_core::WireSeq::new(0),
203 ),
204 primary_link_up: std::sync::Arc::new(AtomicBool::new(false)),
205 primary_ack_policy: std::sync::Arc::new(std::sync::atomic::AtomicU8::new(
206 crate::ack_policy::ACK_POLICY_UNKNOWN,
207 )),
208 pipeline_healthy: std::sync::Arc::new(AtomicBool::new(true)),
209 }
210 }
211}
212
213impl Default for ReplicaControlPlane {
214 fn default() -> Self {
215 Self::new()
216 }
217}
218
219pub(super) fn log_tcp_info(fd: std::os::unix::io::RawFd, tag: &str, slot: usize) {
228 if !tracing::enabled!(tracing::Level::DEBUG) {
229 return;
230 }
231 let mut info: libc::tcp_info = unsafe { std::mem::zeroed() };
235 let mut len = std::mem::size_of::<libc::tcp_info>() as libc::socklen_t;
236 let rc = unsafe {
237 libc::getsockopt(
238 fd,
239 libc::IPPROTO_TCP,
240 libc::TCP_INFO,
241 &mut info as *mut _ as *mut libc::c_void,
242 &mut len,
243 )
244 };
245 if rc != 0 {
246 tracing::debug!(
247 slot,
248 tag,
249 errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0),
250 "tcp_info getsockopt failed"
251 );
252 return;
253 }
254 tracing::debug!(
255 slot,
256 tag,
257 state = info.tcpi_state,
258 ca_state = info.tcpi_ca_state,
259 rtt_us = info.tcpi_rtt,
260 rttvar_us = info.tcpi_rttvar,
261 snd_cwnd = info.tcpi_snd_cwnd,
262 snd_ssthresh = info.tcpi_snd_ssthresh,
263 snd_mss = info.tcpi_snd_mss,
264 rcv_mss = info.tcpi_rcv_mss,
265 unacked = info.tcpi_unacked,
266 retrans = info.tcpi_retrans,
267 total_retrans = info.tcpi_total_retrans,
268 lost = info.tcpi_lost,
269 rcv_space = info.tcpi_rcv_space,
270 rto_us = info.tcpi_rto,
271 "tcp_info"
272 );
273}
274
275pub(super) fn sleep_checking_flags(
279 duration: std::time::Duration,
280 shutdown: &AtomicBool,
281 promote: &crate::promotion::PromotionRequest,
282) {
283 let deadline = std::time::Instant::now() + duration;
284 while std::time::Instant::now() < deadline {
285 if shutdown.load(Ordering::Relaxed) || promote.is_requested() {
286 return;
287 }
288 std::thread::sleep(std::time::Duration::from_millis(100));
289 }
290}
291
292pub(super) fn sleep_then_double_backoff(
299 backoff: &mut std::time::Duration,
300 shutdown: &AtomicBool,
301 promote: &crate::promotion::PromotionRequest,
302) {
303 sleep_checking_flags(*backoff, shutdown, promote);
304 *backoff = (*backoff * 2).min(MAX_BACKOFF);
305}
306
307pub(super) enum TeardownOutcome<A, W> {
311 Clean(A, W),
314 JournalFailed(melin_journal::JournalError),
320 Panicked,
322}
323
324pub(super) fn shutdown_pipeline<A: Send + 'static, W: Send + 'static>(
339 shutdown_flag: &AtomicBool,
340 journal_handle: std::thread::JoinHandle<Result<W, melin_journal::JournalError>>,
341 matching_handle: std::thread::JoinHandle<A>,
342 drain_handle: std::thread::JoinHandle<()>,
343 shadow_handle: Option<std::thread::JoinHandle<()>>,
344) -> TeardownOutcome<A, W> {
345 shutdown_flag.store(true, Ordering::Release);
359 let journal_result = journal_handle.join();
364 let matching_result = matching_handle.join();
365 let _ = drain_handle.join();
366 if let Some(h) = shadow_handle {
367 let _ = h.join();
368 }
369 let writer = match journal_result {
370 Ok(Ok(w)) => w,
371 Ok(Err(e)) => return TeardownOutcome::JournalFailed(e),
373 Err(_) => return TeardownOutcome::Panicked,
374 };
375 match matching_result {
376 Ok(app) => TeardownOutcome::Clean(app, writer),
377 Err(_) => TeardownOutcome::Panicked,
378 }
379}
380
381pub(super) struct ReplicaPipelineHandles<A: Application, W: Send + 'static> {
390 pub(super) input_producer: melin_pipeline::ring::Producer<InputSlot<A::Event>>,
391 pub(super) journal_cursor: Arc<melin_pipeline::padding::Sequence>,
392 pub(super) last_seq: melin_transport_core::DurableWireSeqCursor,
398 pub(super) chain_hash_lock:
402 Option<melin_pipeline::seqlock::SeqLockReader<melin_transport_core::pipeline::FsyncState>>,
403 pub(super) stream_marks: melin_transport_core::pipeline::StreamMarkQueue,
408 pub(super) journal_failed: Arc<AtomicBool>,
415 pub(super) pipeline_shutdown: Arc<AtomicBool>,
418 pub(super) journal_handle: std::thread::JoinHandle<Result<W, melin_journal::JournalError>>,
419 pub(super) matching_handle: std::thread::JoinHandle<A>,
420 pub(super) drain_handle: std::thread::JoinHandle<()>,
421 pub(super) shadow_handle: Option<std::thread::JoinHandle<()>>,
422}
423
424pub(super) type ReplicaHandles<A> =
429 ReplicaPipelineHandles<A, BufferedWriter<<A as Application>::Event>>;
430
431#[allow(clippy::too_many_arguments)]
435pub(super) fn build_replica_pipeline_with_threads<A>(
436 mut app: A,
437 writer: BufferedWriter<A::Event>,
438 cores: crate::layout::PipelineCores,
439 staging_mode: melin_journal::StagingMode,
444 snapshot_interval_ms: u64,
445 snapshot_path: std::path::PathBuf,
446 group_commit_delay: std::time::Duration,
447 fence_state: Arc<melin_transport_core::fence::FenceState>,
448 pipeline_healthy: Arc<AtomicBool>,
454 sizing: &A::Sizing,
457) -> Result<ReplicaHandles<A>, Box<dyn std::error::Error>>
458where
459 A: Application + Send + 'static,
460 A::Event: Send + Sync + 'static,
461 A::Report: Send + 'static,
462 A::QueryResponse: Send + 'static,
463{
464 <A as Application>::prefault(&mut app, sizing);
469 let shadow_app = <A as Application>::clone_via_snapshot(&app)?;
470
471 let enable_shadow = snapshot_interval_ms > 0;
472 let shadow_initial_epoch = fence_state.epoch();
475 let pipeline = melin_transport_core::pipeline::build_replica_pipeline(
476 app,
477 writer,
478 4096, group_commit_delay,
480 cores.stage_waits(),
481 enable_shadow,
482 fence_state,
483 );
484
485 let pipeline_shutdown = Arc::new(AtomicBool::new(false));
486
487 let ps = Arc::clone(&pipeline_shutdown);
488 let journal_core = cores.journal_seq.core;
489 let mut journal_stage = pipeline.journal_stage;
490 let stream_marks: melin_transport_core::pipeline::StreamMarkQueue =
495 Arc::new(std::sync::Mutex::new(std::collections::VecDeque::new()));
496 journal_stage.set_stream_marks(Arc::clone(&stream_marks));
497 cores.place_journal_children(&mut journal_stage);
498 journal_stage.set_staging_mode(staging_mode);
499 let journal_failed = Arc::new(AtomicBool::new(false));
500 let journal_failed_latch = Arc::clone(&journal_failed);
501 let sequencer = journal_stage.start()?;
505 pipeline_healthy.store(true, Ordering::Release);
508 let journal_handle = std::thread::Builder::new()
509 .name("journal-seq".into())
510 .spawn(move || {
511 melin_app::affinity::pin_thread("journal-seq", journal_core);
512 let result = sequencer.run(&ps);
513 if let Err(ref e) = result {
514 journal_failed_latch.store(true, Ordering::Release);
521 pipeline_healthy.store(false, Ordering::Release);
524 tracing::error!(error = %e, "replica journal stage failed — session teardown");
525 }
526 result
527 })
528 .expect("spawn journal thread");
529
530 let ps = Arc::clone(&pipeline_shutdown);
531 let matching_core = cores.matching.core;
532 let matching_stage = pipeline.matching_stage;
533 let matching_handle = std::thread::Builder::new()
534 .name("matching".into())
535 .spawn(move || {
536 melin_app::affinity::pin_thread("matching", matching_core);
537 matching_stage.run(&ps)
538 })
539 .expect("spawn matching thread");
540
541 let ps = Arc::clone(&pipeline_shutdown);
544 let drain = cores.response;
545 let drain_consumer = pipeline.drain_consumer;
546 let drain_handle = std::thread::Builder::new()
547 .name("drain".into())
548 .spawn(move || {
549 melin_app::affinity::pin_thread("drain", drain.core);
550 let mut consumer = drain_consumer;
551 let mut batch = vec![OutputSlot::<A::Report, A::QueryResponse>::default(); 256];
552 let mut waiter = drain.wait.waiter();
553 loop {
554 if ps.load(Ordering::Relaxed) {
555 return;
556 }
557 let count = consumer.consume_batch(&mut batch, 256);
558 if count == 0 {
559 waiter.idle();
560 } else {
561 waiter.reset();
562 }
563 }
564 })
565 .expect("spawn drain thread");
566
567 let shadow_handle = if let Some(shadow_cons) = pipeline.shadow_consumer {
568 let snap_path = snapshot_path;
569 let chain_lock = pipeline
570 .chain_hash_lock
571 .as_ref()
572 .expect("chain hash lock with shadow")
573 .clone();
574 let ps = Arc::clone(&pipeline_shutdown);
575 let shadow = cores.shadow;
576 Some(
577 std::thread::Builder::new()
578 .name("replica-shadow".into())
579 .spawn(move || {
580 melin_app::affinity::pin_thread("replica-shadow", shadow.core);
581 melin_transport_core::shadow::run(
582 shadow_cons,
583 shadow_app,
584 snap_path,
585 std::time::Duration::from_millis(snapshot_interval_ms),
586 chain_lock,
587 &ps,
588 shadow.wait,
589 shadow_initial_epoch,
590 );
591 })
592 .expect("spawn shadow thread"),
593 )
594 } else {
595 None
596 };
597
598 Ok(ReplicaPipelineHandles {
599 input_producer: pipeline.input_producer,
600 journal_cursor: pipeline.cursors.journal_ring_arc(),
601 last_seq: pipeline.cursors.durable_wire_seq(),
602 chain_hash_lock: pipeline.chain_hash_lock,
603 stream_marks,
604 journal_failed,
605 pipeline_shutdown,
606 journal_handle,
607 matching_handle,
608 drain_handle,
609 shadow_handle,
610 })
611}
612
613pub(super) fn teardown_replica_pipeline<A: Application + Send + 'static, W: Send + 'static>(
618 mut handles: ReplicaPipelineHandles<A, W>,
619) -> TeardownOutcome<A, W> {
620 while !handles.journal_failed.load(Ordering::Acquire) {
637 match handles
638 .input_producer
639 .try_publish(InputSlot::<A::Event>::shutdown_sentinel())
640 {
641 Ok(_) => break,
642 Err(_) => std::thread::yield_now(),
644 }
645 }
646 shutdown_pipeline::<A, W>(
647 &handles.pipeline_shutdown,
648 handles.journal_handle,
649 handles.matching_handle,
650 handles.drain_handle,
651 handles.shadow_handle,
652 )
653}
654
655pub(super) const MAX_INPROCESS_DIVERGENCE_RESYNCS: u32 = 1;
666
667#[allow(clippy::type_complexity)]
684pub(super) fn recover_replica_state<A, W>(
685 journal_path: &std::path::Path,
686 snapshot_path: &std::path::Path,
687 fence_state: &melin_transport_core::fence::FenceState,
688 sizing: &A::Sizing,
691) -> Result<(Option<A>, Option<W>, u64, [u8; 32]), Box<dyn std::error::Error>>
692where
693 A: Application,
694 W: melin_journal::JournalWrite<A::Event>,
695{
696 let lineage_exists =
697 journal_path.exists() || !melin_journal::segment::list_archives(journal_path)?.is_empty();
698 if !lineage_exists {
699 return Ok((None, None, 0u64, [0u8; 32]));
700 }
701 let engine = if snapshot_path.exists() {
702 tracing::info!("recovering replica from snapshot + journal");
703 melin_transport_core::JournaledApp::<A, W>::recover_from_snapshot(
704 snapshot_path,
705 journal_path,
706 )?
707 } else {
708 let mut app = A::default();
709 <A as Application>::prefault(&mut app, sizing);
710 melin_transport_core::JournaledApp::<A, W>::recover(app, journal_path)?
711 };
712 let next = engine.next_sequence();
713 let last = next.saturating_sub(1);
714 let hash = engine.chain_hash().unwrap_or([0u8; 32]);
715 fence_state.observe_epoch(engine.recovered_epoch());
718 let (app, writer) = engine.into_parts();
719 Ok((Some(app), Some(writer), last, hash))
720}
721
722pub(super) const MAX_BACKOFF: std::time::Duration = std::time::Duration::from_secs(30);
728
729pub(in crate::replication) enum AfterSession<A, W> {
733 Return(ReceiverResult<A, W>),
737 Resync {
742 app: Option<A>,
743 journal_writer: Option<W>,
744 last_sequence: u64,
745 chain_hash: [u8; 32],
746 },
747 Reconnect,
751}
752
753#[allow(clippy::too_many_arguments)]
774pub(in crate::replication) fn handle_session_exit<A, W>(
775 result: StreamingResult,
776 pipeline: &mut Option<ReplicaPipelineHandles<A, W>>,
777 divergence_resyncs: &mut u32,
778 backoff: &mut std::time::Duration,
779 last_sequence: u64,
780 journal_path: &std::path::Path,
781 snapshot_path: &std::path::Path,
782 fence_state: &melin_transport_core::fence::FenceState,
783 shutdown: &AtomicBool,
784 promote: &crate::promotion::PromotionRequest,
785 mut close: impl FnMut(),
786 sizing: &A::Sizing,
789) -> AfterSession<A, W>
790where
791 A: Application + Send + 'static,
792 W: JournalWrite<A::Event> + Send + 'static,
793{
794 let StreamingResult {
795 exit,
796 heard_from_primary,
797 } = result;
798
799 match exit {
800 SessionExit::Shutdown => {
801 if let Some(p) = pipeline.take() {
802 let _ = teardown_replica_pipeline::<A, W>(p);
803 }
804 AfterSession::Return(Ok(None))
805 }
806
807 SessionExit::Promote => AfterSession::Return(match pipeline.take() {
808 Some(p) => match teardown_replica_pipeline::<A, W>(p) {
809 TeardownOutcome::Clean(ex, wr) => Ok(Some((ex, wr))),
810 _ => Err("pipeline failed during promotion".into()),
811 },
812 None => Err("pipeline missing on promote".into()),
813 }),
814
815 SessionExit::Fatal(e) => {
816 let outcome = match pipeline.take() {
817 Some(p) => teardown_replica_pipeline::<A, W>(p),
818 None => return AfterSession::Return(Err(e)),
821 };
822 let TeardownOutcome::JournalFailed(
832 je @ melin_journal::JournalError::ReplicaChainDivergence { .. },
833 ) = outcome
834 else {
835 return AfterSession::Return(Err(e));
836 };
837
838 *divergence_resyncs += 1;
839 let attempt = *divergence_resyncs;
840 if attempt > MAX_INPROCESS_DIVERGENCE_RESYNCS {
841 return AfterSession::Return(Err(format!(
842 "mid-stream chain divergence recurred {attempt} times — giving up on \
843 in-process resync (each cycle archives the local journal and re-seeds \
844 from the primary; recurrence at this rate means the primary keeps \
845 streaming history that forks from what it announces): {je}"
846 )
847 .into()));
848 }
849 tracing::warn!(
850 error = %je,
851 attempt,
852 max_attempts = MAX_INPROCESS_DIVERGENCE_RESYNCS,
853 "mid-stream chain divergence — re-deriving local state for in-process resync"
854 );
855 close();
857 match recover_replica_state::<A, W>(journal_path, snapshot_path, fence_state, sizing) {
858 Ok((app, journal_writer, seq, hash)) => AfterSession::Resync {
859 app,
860 journal_writer,
861 last_sequence: seq,
862 chain_hash: hash,
863 },
864 Err(e) => AfterSession::Return(Err(e)),
865 }
866 }
867
868 SessionExit::StreamGap(e) => {
869 close();
878 *backoff = std::time::Duration::from_secs(1);
879 tracing::warn!(
880 error = %e,
881 last_sequence,
882 "replication stream broke contiguity — reconnecting from the durable position"
883 );
884 sleep_then_double_backoff(backoff, shutdown, promote);
885 AfterSession::Reconnect
886 }
887
888 SessionExit::Disconnected => {
889 close();
892 if heard_from_primary {
901 *backoff = std::time::Duration::from_secs(1);
902 }
903 tracing::warn!(
904 last_sequence,
905 heard_from_primary,
906 backoff_secs = backoff.as_secs(),
907 "reconnecting to primary"
908 );
909 sleep_then_double_backoff(backoff, shutdown, promote);
910 AfterSession::Reconnect
911 }
912 }
913}
914
915pub(in crate::replication) fn take_pipeline_for_promotion<A, W>(
925 pipeline: &mut Option<ReplicaPipelineHandles<A, W>>,
926 app: &mut Option<A>,
927 journal_writer: &mut Option<W>,
928) -> ReceiverResult<A, W>
929where
930 A: Application + Send + 'static,
931 W: JournalWrite<A::Event> + Send + 'static,
932{
933 if let Some(p) = pipeline.take()
934 && let TeardownOutcome::Clean(e, w) = teardown_replica_pipeline::<A, W>(p)
935 {
936 *app = Some(e);
937 *journal_writer = Some(w);
938 }
939 match (app.take(), journal_writer.take()) {
940 (Some(e), Some(w)) => Ok(Some((e, w))),
941 _ => Err("promotion requested but no local state available".into()),
942 }
943}
944
945type ResyncTransfer<A> = (A, u64, [u8; 32], u64);
948
949pub(in crate::replication) enum ResyncDecision {
952 Ready {
957 segment_start_sequence: u64,
958 anchor_hash: [u8; 32],
959 resume_sequence: u64,
960 },
961 Retry,
965}
966
967fn receive_resync_transfer<A, S>(
977 source: &mut S,
978 snapshot_path: &std::path::Path,
979 journal_path: &std::path::Path,
980 fence_state: &melin_transport_core::fence::FenceState,
981) -> Result<ResyncTransfer<A>, Box<dyn std::error::Error + Send + Sync>>
982where
983 A: Application,
984 S: ControlFrameSource,
985{
986 let (snap_len, snap_sequence, snap_chain_hash) =
987 match decode_primary_message(&source.next_frame(MAX_CONTROL_FRAME)?)? {
988 PrimaryMessage::SnapshotBegin {
989 snapshot_len,
990 snap_sequence,
991 snap_chain_hash,
992 } => (snapshot_len, snap_sequence, snap_chain_hash),
993 other => return Err(format!("expected SnapshotBegin, got {other:?}").into()),
994 };
995
996 tracing::info!(snap_sequence, snap_len, "receiving snapshot");
997 let tmp_path = snapshot_path.with_extension("snapshot.tmp");
998 receive_chunked_body(source, &tmp_path, snap_len, "snapshot")?;
999 std::fs::rename(&tmp_path, snapshot_path)?;
1000 tracing::info!(snap_sequence, snap_len, "snapshot received and verified");
1001
1002 let (snap_app, _snap_seq, snap_hash, snap_epoch) =
1003 melin_transport_core::snapshot::load::<A>(snapshot_path)?;
1004 if snap_hash != snap_chain_hash {
1005 return Err(format!(
1006 "snapshot chain hash mismatch: primary sent {snap_chain_hash:02x?}, \
1007 loaded snapshot has {snap_hash:02x?}"
1008 )
1009 .into());
1010 }
1011 fence_state.observe_epoch(snap_epoch);
1014
1015 let seed_len = match decode_primary_message(&source.next_frame(MAX_CONTROL_FRAME)?)? {
1020 PrimaryMessage::SegmentSeedBegin { seed_len } => seed_len,
1021 other => {
1022 return Err(format!("expected SegmentSeedBegin after snapshot, got {other:?}").into());
1023 }
1024 };
1025 let seed_tmp = journal_path.with_extension("seed.tmp");
1026 receive_chunked_body(source, &seed_tmp, seed_len, "segment seed")?;
1027 if let Err(e) =
1033 melin_journal::segment::verify_segment_prefix(&seed_tmp, snap_sequence, seed_len)
1034 {
1035 let _ = std::fs::remove_file(&seed_tmp);
1036 return Err(format!("segment seed failed structural verification: {e}").into());
1037 }
1038 std::fs::rename(&seed_tmp, journal_path)?;
1039 melin_journal::segment::fsync_parent_dir(journal_path)?;
1040 Ok((snap_app, snap_sequence, snap_chain_hash, seed_len))
1041}
1042
1043#[allow(clippy::too_many_arguments)]
1056pub(in crate::replication) fn handle_resync_verdict<A, W, S>(
1057 divergent: bool,
1058 source: &mut S,
1059 pipeline: &mut Option<ReplicaPipelineHandles<A, W>>,
1060 app: &mut Option<A>,
1061 journal_writer: &mut Option<W>,
1062 journal_path: &std::path::Path,
1063 snapshot_path: &std::path::Path,
1064 fence_state: &melin_transport_core::fence::FenceState,
1065 control: &ReplicaControlPlane,
1066 last_sequence: &mut u64,
1067 chain_hash: &mut [u8; 32],
1068) -> Result<ResyncDecision, Box<dyn std::error::Error + Send + Sync>>
1069where
1070 A: Application + Send + 'static,
1071 W: JournalWrite<A::Event> + Send + 'static,
1072 S: ControlFrameSource,
1073{
1074 if divergent {
1079 tracing::warn!(
1080 last_sequence = *last_sequence,
1081 "primary reports chain divergence — archiving local journal, resyncing from snapshot"
1082 );
1083 } else {
1084 tracing::info!("primary requires snapshot transfer — receiving snapshot");
1085 }
1086
1087 if let Some(p) = pipeline.take() {
1088 let _ = teardown_replica_pipeline::<A, W>(p);
1089 }
1090
1091 *app = None;
1098 *journal_writer = None;
1099
1100 let reason = if divergent {
1104 ArchiveReason::Divergent
1105 } else {
1106 ArchiveReason::Resync
1107 };
1108 archive_local_lineage(journal_path, snapshot_path, reason)?;
1109 *last_sequence = 0;
1111 *chain_hash = [0u8; 32];
1112 control
1117 .journal_tip
1118 .reset(melin_transport_core::WireSeq::new(0));
1119
1120 let (snap_app, snap_sequence, snap_chain_hash, seed_len) =
1121 match receive_resync_transfer::<A, S>(source, snapshot_path, journal_path, fence_state) {
1122 Ok(v) => v,
1123 Err(e) => {
1124 tracing::warn!(error = %e, "snapshot transfer failed — retrying");
1125 let _ = std::fs::remove_file(snapshot_path);
1129 return Ok(ResyncDecision::Retry);
1130 }
1131 };
1132 *app = Some(snap_app);
1133
1134 let writer = W::open_append(journal_path, snap_sequence, seed_len)?;
1141 let seeded_chain = writer.chain_hash().unwrap_or(snap_chain_hash);
1142 if snap_chain_hash != [0u8; 32] && seeded_chain != snap_chain_hash {
1143 return Err(format!(
1144 "segment seed chain at {snap_sequence} disagrees with the transferred snapshot's \
1145 hash — inconsistent primary"
1146 )
1147 .into());
1148 }
1149 let seeded_info = melin_journal::segment::read_header_info(journal_path)?;
1150 *journal_writer = Some(writer);
1151
1152 match decode_primary_message(&source.next_frame(MAX_CONTROL_FRAME)?)? {
1155 PrimaryMessage::StreamStart {
1156 start_sequence,
1157 segment_start_sequence,
1158 anchor_hash,
1159 epoch,
1160 ack_policy,
1161 } => {
1162 if segment_start_sequence != seeded_info.starting_sequence
1163 || anchor_hash != seeded_info.anchor_hash
1164 {
1165 return Err(format!(
1166 "post-snapshot StreamStart lineage (start {segment_start_sequence}) \
1167 disagrees with the transferred segment seed (start {}) — inconsistent \
1168 primary",
1169 seeded_info.starting_sequence
1170 )
1171 .into());
1172 }
1173 fence_state.observe_epoch(epoch);
1177 control
1178 .primary_ack_policy
1179 .store(ack_policy, Ordering::Release);
1180 tracing::info!(
1181 start_sequence,
1182 epoch,
1183 ack_policy,
1184 "streaming resumed after snapshot transfer"
1185 );
1186 control
1189 .journal_tip
1190 .reset(melin_transport_core::WireSeq::new(snap_sequence));
1191 Ok(ResyncDecision::Ready {
1192 segment_start_sequence,
1193 anchor_hash,
1194 resume_sequence: snap_sequence,
1195 })
1196 }
1197 other => Err(format!("expected StreamStart after snapshot, got {other:?}").into()),
1198 }
1199}
1200
1201#[cfg(test)]
1202mod tests {
1203 use std::io::Write;
1204 use std::sync::Arc;
1205
1206 use super::auth::{authenticate_replica, authenticate_with_primary};
1207 use super::*;
1208 use counter_server::CounterEvent;
1214 type InputSlot = melin_transport_core::pipeline::InputSlot<CounterEvent>;
1215 use melin_transport_core::replication::protocol::{
1216 MAX_CONTROL_FRAME, MAX_DATA_FRAME, MSG_AUTH_OK, MSG_CHALLENGE_RESPONSE, MSG_SNAPSHOT_BEGIN,
1217 MSG_SNAPSHOT_CHUNK, MSG_SNAPSHOT_END, decode_auth_result, decode_challenge,
1218 decode_challenge_response, decode_primary_message, decode_replica_message, encode_ack,
1219 encode_auth_failed, encode_auth_ok, encode_chain_check, encode_challenge,
1220 encode_challenge_response, encode_handshake, encode_hash_mismatch, encode_heartbeat,
1221 encode_input_batch, encode_need_snapshot, encode_rotate, encode_segment_seed_begin,
1222 encode_snapshot_begin, encode_snapshot_chunk, encode_snapshot_end, encode_stream_start,
1223 read_frame, try_decode_input_batch,
1224 };
1225
1226 fn encode_input_batch_with_seq(end_sequence: u64, buf: &mut Vec<u8>) {
1230 let slot = InputSlot {
1231 connection_id: 0,
1232 key_hash: 0,
1233 sequence: end_sequence,
1234 timestamp_ns: 0,
1235 event: melin_journal::JournalEvent::Tick { now_ns: 0 },
1236 publish_ts: Default::default(),
1237 recv_ts: Default::default(),
1238 };
1239 encode_input_batch(&[slot], buf);
1240 }
1241
1242 #[test]
1243 fn handshake_encode_decode_round_trip() {
1244 let handshake = Handshake {
1245 last_sequence: 42,
1246 chain_hash: [0xAB; 32],
1247 epoch: 9,
1249 };
1250 let mut buf = Vec::new();
1251 encode_handshake(&handshake, &mut buf);
1252
1253 let payload = &buf[4..];
1255 let msg = decode_replica_message(payload).unwrap();
1256 match msg {
1257 ReplicaMessage::Handshake(h) => {
1258 assert_eq!(h.last_sequence, 42);
1259 assert_eq!(h.chain_hash, [0xAB; 32]);
1260 assert_eq!(h.epoch, 9);
1261 }
1262 _ => panic!("expected Handshake"),
1263 }
1264 }
1265
1266 #[test]
1267 fn ack_encode_decode_round_trip() {
1268 let ack = Ack {
1269 acked_sequence: 1000,
1270 in_memory_sequence: 1024,
1271 };
1272 let mut buf = Vec::new();
1273 encode_ack(&ack, &mut buf);
1274
1275 let payload = &buf[4..];
1276 let msg = decode_replica_message(payload).unwrap();
1277 match msg {
1278 ReplicaMessage::Ack(a) => {
1279 assert_eq!(a.acked_sequence, 1000);
1280 assert_eq!(a.in_memory_sequence, 1024);
1281 }
1282 _ => panic!("expected Ack"),
1283 }
1284 }
1285
1286 #[test]
1294 fn ack_wire_byte_pattern() {
1295 let ack = Ack {
1296 acked_sequence: 0xDEAD_BEEF_CAFE_F00D,
1297 in_memory_sequence: 0x1122_3344_5566_7788,
1298 };
1299 let mut buf = Vec::new();
1300 encode_ack(&ack, &mut buf);
1301 let expected: &[u8] = &[
1304 0x11, 0x00, 0x00, 0x00, 0x02, 0x0D, 0xF0, 0xFE, 0xCA, 0xEF, 0xBE, 0xAD, 0xDE, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, ];
1309 assert_eq!(buf.as_slice(), expected, "Ack wire layout drifted");
1310 }
1311
1312 #[test]
1313 fn stream_start_encode_decode_round_trip() {
1314 let mut buf = Vec::new();
1315 encode_stream_start(99, 42, [0xAA; 32], 5, 2, &mut buf);
1317
1318 let payload = &buf[4..];
1319 let msg = decode_primary_message(payload).unwrap();
1320 match msg {
1321 PrimaryMessage::StreamStart {
1322 start_sequence,
1323 segment_start_sequence,
1324 anchor_hash,
1325 epoch,
1326 ack_policy,
1327 } => {
1328 assert_eq!(start_sequence, 99);
1329 assert_eq!(segment_start_sequence, 42);
1330 assert_eq!(anchor_hash, [0xAA; 32]);
1331 assert_eq!(ack_policy, 2);
1332 assert_eq!(epoch, 5);
1333 }
1334 _ => panic!("expected StreamStart"),
1335 }
1336 }
1337
1338 #[test]
1339 fn heartbeat_encode_decode_round_trip() {
1340 let mut buf = Vec::new();
1341 encode_heartbeat(123, 2, &mut buf);
1342
1343 let payload = &buf[4..];
1344 let msg = decode_primary_message(payload).unwrap();
1345 match msg {
1346 PrimaryMessage::Heartbeat {
1347 sequence,
1348 ack_policy,
1349 } => {
1350 assert_eq!(sequence, 123);
1351 assert_eq!(ack_policy, 2);
1352 }
1353 _ => panic!("expected Heartbeat"),
1354 }
1355 }
1356
1357 #[test]
1358 fn need_snapshot_encode_decode_round_trip() {
1359 let mut buf = Vec::new();
1360 encode_need_snapshot(&mut buf);
1361
1362 let payload = &buf[4..];
1363 let msg = decode_primary_message(payload).unwrap();
1364 assert!(matches!(msg, PrimaryMessage::NeedSnapshot));
1365 }
1366
1367 #[test]
1368 fn hash_mismatch_encode_decode_round_trip() {
1369 let mut buf = Vec::new();
1370 encode_hash_mismatch(&mut buf);
1371
1372 let payload = &buf[4..];
1373 let msg = decode_primary_message(payload).unwrap();
1374 assert!(matches!(msg, PrimaryMessage::HashMismatch));
1375 }
1376
1377 #[test]
1378 fn rotate_encode_decode_round_trip() {
1379 let mut buf = Vec::new();
1380 encode_rotate(7_000_000, &[0xBB; 32], &mut buf);
1381
1382 let payload = &buf[4..];
1383 let msg = decode_primary_message(payload).unwrap();
1384 match msg {
1385 PrimaryMessage::Rotate {
1386 boundary_seq,
1387 tail_hash,
1388 } => {
1389 assert_eq!(boundary_seq, 7_000_000);
1390 assert_eq!(tail_hash, [0xBB; 32]);
1391 }
1392 _ => panic!("expected Rotate"),
1393 }
1394 }
1395
1396 #[test]
1397 fn chain_check_encode_decode_round_trip() {
1398 let mut buf = Vec::new();
1399 encode_chain_check(555, &[0xCC; 32], &mut buf);
1400
1401 let payload = &buf[4..];
1402 let msg = decode_primary_message(payload).unwrap();
1403 match msg {
1404 PrimaryMessage::ChainCheck {
1405 sequence,
1406 chain_hash,
1407 } => {
1408 assert_eq!(sequence, 555);
1409 assert_eq!(chain_hash, [0xCC; 32]);
1410 }
1411 _ => panic!("expected ChainCheck"),
1412 }
1413 }
1414
1415 #[test]
1419 fn rotate_wire_byte_pattern() {
1420 let mut hash = [0u8; 32];
1421 for (i, b) in hash.iter_mut().enumerate() {
1422 *b = i as u8;
1423 }
1424 let mut buf = Vec::new();
1425 encode_rotate(0xDEAD_BEEF_CAFE_F00D, &hash, &mut buf);
1426 let mut expected = vec![
1429 0x29, 0x00, 0x00, 0x00, 0x16, 0x0D, 0xF0, 0xFE, 0xCA, 0xEF, 0xBE, 0xAD, 0xDE, ];
1433 expected.extend_from_slice(&hash);
1434 assert_eq!(
1435 buf.as_slice(),
1436 expected.as_slice(),
1437 "Rotate wire layout drifted"
1438 );
1439 }
1440
1441 #[test]
1442 fn segment_seed_begin_encode_decode_round_trip() {
1443 let mut buf = Vec::new();
1444 encode_segment_seed_begin(123_456, &mut buf);
1445
1446 let payload = &buf[4..];
1447 let msg = decode_primary_message(payload).unwrap();
1448 match msg {
1449 PrimaryMessage::SegmentSeedBegin { seed_len } => {
1450 assert_eq!(seed_len, 123_456);
1451 }
1452 _ => panic!("expected SegmentSeedBegin"),
1453 }
1454 }
1455
1456 #[test]
1457 fn unknown_replica_message_type_is_error() {
1458 let payload = [0xFF, 0, 0, 0, 0, 0, 0, 0, 0];
1459 let result = decode_replica_message(&payload);
1460 assert!(result.is_err());
1461 }
1462
1463 #[test]
1464 fn unknown_primary_message_type_is_error() {
1465 let payload = [0xFF, 0, 0, 0, 0, 0, 0, 0, 0];
1466 let result = decode_primary_message(&payload);
1467 assert!(result.is_err());
1468 }
1469
1470 #[test]
1471 fn read_frame_enforces_max_size() {
1472 let mut buf = Vec::new();
1474 buf.extend_from_slice(&1000u32.to_le_bytes());
1475 buf.extend_from_slice(&[0u8; 100]); let mut cursor = std::io::Cursor::new(buf);
1478 let result = read_frame(&mut cursor, 64);
1479 assert!(result.is_err());
1480 }
1481
1482 #[test]
1483 fn challenge_encode_decode_round_trip() {
1484 let nonce = [0x42; 32];
1485 let mut buf = Vec::new();
1486 encode_challenge(&nonce, &mut buf);
1487
1488 let payload = &buf[4..];
1489 let decoded = decode_challenge(payload).unwrap();
1490 assert_eq!(decoded, nonce);
1491 }
1492
1493 #[test]
1494 fn challenge_response_encode_decode_round_trip() {
1495 let sig = [0xAA; 64];
1496 let pubkey = [0xBB; 32];
1497 let mut buf = Vec::new();
1498 encode_challenge_response(&sig, &pubkey, &mut buf);
1499
1500 let payload = &buf[4..];
1501 let (decoded_sig, decoded_pubkey) = decode_challenge_response(payload).unwrap();
1502 assert_eq!(decoded_sig, sig);
1503 assert_eq!(decoded_pubkey, pubkey);
1504 }
1505
1506 #[test]
1507 fn auth_ok_encode_decode_round_trip() {
1508 let mut buf = Vec::new();
1509 encode_auth_ok(&mut buf);
1510
1511 let payload = &buf[4..];
1512 assert!(decode_auth_result(payload).unwrap());
1513 }
1514
1515 #[test]
1516 fn auth_failed_encode_decode_round_trip() {
1517 let mut buf = Vec::new();
1518 encode_auth_failed(&mut buf);
1519
1520 let payload = &buf[4..];
1521 assert!(!decode_auth_result(payload).unwrap());
1522 }
1523
1524 #[test]
1525 fn decode_challenge_rejects_wrong_tag() {
1526 let mut payload = [0u8; 33];
1527 payload[0] = MSG_AUTH_OK;
1528 assert!(decode_challenge(&payload).is_err());
1529 }
1530
1531 #[test]
1532 fn decode_challenge_response_rejects_short_payload() {
1533 let payload = [MSG_CHALLENGE_RESPONSE; 10]; assert!(decode_challenge_response(&payload).is_err());
1535 }
1536
1537 #[test]
1538 fn auth_round_trip_valid_key() {
1539 use ed25519_dalek::SigningKey;
1540 use std::os::unix::net::UnixStream;
1541
1542 let repl_key = SigningKey::from_bytes(&[0xFC; 32]);
1543 let pub_b64 = base64::Engine::encode(
1544 &base64::engine::general_purpose::STANDARD,
1545 repl_key.verifying_key().to_bytes(),
1546 );
1547 let keys_content = format!("replication {pub_b64} test-replica\n");
1548 let authorized_keys = melin_app::auth::AuthorizedKeys::parse(&keys_content).unwrap();
1549
1550 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
1551 primary_stream
1552 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
1553 .unwrap();
1554 replica_stream
1555 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
1556 .unwrap();
1557
1558 let repl_key_clone = SigningKey::from_bytes(&[0xFC; 32]);
1559 let replica_handle = std::thread::spawn(move || {
1560 let mut conn = replica_stream;
1561 authenticate_with_primary(&mut conn, &repl_key_clone)
1562 });
1563
1564 let mut conn = primary_stream;
1565 authenticate_replica(&mut conn, &authorized_keys).unwrap();
1566
1567 replica_handle.join().unwrap().unwrap();
1568 }
1569
1570 #[test]
1571 fn auth_rejects_unknown_key() {
1572 use ed25519_dalek::SigningKey;
1573 use std::os::unix::net::UnixStream;
1574
1575 let authorized_key = SigningKey::from_bytes(&[0xAA; 32]);
1577 let rogue_key = SigningKey::from_bytes(&[0xBB; 32]);
1578 let pub_b64 = base64::Engine::encode(
1579 &base64::engine::general_purpose::STANDARD,
1580 authorized_key.verifying_key().to_bytes(),
1581 );
1582 let keys_content = format!("replication {pub_b64} authorized-replica\n");
1583 let authorized_keys = melin_app::auth::AuthorizedKeys::parse(&keys_content).unwrap();
1584
1585 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
1586 primary_stream
1587 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
1588 .unwrap();
1589 replica_stream
1590 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
1591 .unwrap();
1592
1593 let replica_handle = std::thread::spawn(move || {
1594 let mut conn = replica_stream;
1595 authenticate_with_primary(&mut conn, &rogue_key)
1596 });
1597
1598 let mut conn = primary_stream;
1599 let result = authenticate_replica(&mut conn, &authorized_keys);
1600 assert!(result.is_err());
1601 assert!(result.unwrap_err().to_string().contains("unknown"));
1602
1603 let replica_result = replica_handle.join().unwrap();
1605 assert!(replica_result.is_err());
1606 }
1607
1608 #[test]
1609 fn auth_rejects_wrong_permission() {
1610 use ed25519_dalek::SigningKey;
1611 use std::os::unix::net::UnixStream;
1612
1613 let key = SigningKey::from_bytes(&[0xCC; 32]);
1615 let pub_b64 = base64::Engine::encode(
1616 &base64::engine::general_purpose::STANDARD,
1617 key.verifying_key().to_bytes(),
1618 );
1619 let keys_content = format!("trader {pub_b64} wrong-role\n");
1620 let authorized_keys = melin_app::auth::AuthorizedKeys::parse(&keys_content).unwrap();
1621
1622 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
1623 primary_stream
1624 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
1625 .unwrap();
1626 replica_stream
1627 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
1628 .unwrap();
1629
1630 let replica_handle = std::thread::spawn(move || {
1631 let mut conn = replica_stream;
1632 authenticate_with_primary(&mut conn, &key)
1633 });
1634
1635 let mut conn = primary_stream;
1636 let result = authenticate_replica(&mut conn, &authorized_keys);
1637 assert!(result.is_err());
1638 assert!(result.unwrap_err().to_string().contains("Replication"));
1639
1640 let replica_result = replica_handle.join().unwrap();
1641 assert!(replica_result.is_err());
1642 }
1643
1644 #[test]
1647 fn auth_rejects_invalid_signature() {
1648 use ed25519_dalek::SigningKey;
1649 use std::os::unix::net::UnixStream;
1650
1651 let correct_key = SigningKey::from_bytes(&[0xDD; 32]);
1653 let pub_b64 = base64::Engine::encode(
1654 &base64::engine::general_purpose::STANDARD,
1655 correct_key.verifying_key().to_bytes(),
1656 );
1657 let keys_content = format!("replication {pub_b64} test-replica\n");
1658 let authorized_keys = melin_app::auth::AuthorizedKeys::parse(&keys_content).unwrap();
1659
1660 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
1661 primary_stream
1662 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
1663 .unwrap();
1664 replica_stream
1665 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
1666 .unwrap();
1667
1668 let replica_handle = std::thread::spawn(move || {
1671 use melin_transport_core::replication::protocol::*;
1672
1673 let mut reader = replica_stream.try_clone().unwrap();
1674 let mut writer = replica_stream;
1675
1676 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
1678 let nonce = decode_challenge(&frame).unwrap();
1679
1680 let wrong_key = SigningKey::from_bytes(&[0xEE; 32]);
1682 let bad_signature = ed25519_dalek::Signer::sign(&wrong_key, &nonce);
1683 let correct_pubkey = correct_key.verifying_key();
1684
1685 let mut buf = Vec::with_capacity(128);
1686 encode_challenge_response(
1687 &bad_signature.to_bytes(),
1688 correct_pubkey.as_bytes(),
1689 &mut buf,
1690 );
1691 writer.write_all(&buf).unwrap();
1692 writer.flush().unwrap();
1693
1694 let result_frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
1696 let ok = decode_auth_result(&result_frame).unwrap();
1697 assert!(!ok, "should receive auth failure");
1698 });
1699
1700 let mut conn = primary_stream;
1701 let result = authenticate_replica(&mut conn, &authorized_keys);
1702 assert!(result.is_err());
1703 assert!(
1704 result
1705 .unwrap_err()
1706 .to_string()
1707 .contains("signature verification failed"),
1708 "should fail on signature verification"
1709 );
1710
1711 replica_handle.join().unwrap();
1712 }
1713
1714 #[test]
1715 fn sender_receiver_end_to_end() {
1716 use std::os::unix::net::UnixStream;
1717
1718 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
1720
1721 let replica_handle = std::thread::spawn(move || {
1723 let mut reader = replica_stream.try_clone().unwrap();
1724 let mut writer = replica_stream;
1725
1726 let mut buf = Vec::new();
1728 let handshake = Handshake {
1729 last_sequence: 0,
1730 chain_hash: [0u8; 32],
1731 epoch: 0,
1732 };
1733 encode_handshake(&handshake, &mut buf);
1734 writer.write_all(&buf).unwrap();
1735 writer.flush().unwrap();
1736 buf.clear();
1737
1738 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
1740 let msg = decode_primary_message(&frame).unwrap();
1741 assert!(matches!(msg, PrimaryMessage::StreamStart { .. }));
1742
1743 let frame = read_frame(&mut reader, MAX_DATA_FRAME).unwrap();
1745 let slots: Vec<InputSlot> = try_decode_input_batch(&frame).expect("decode InputBatch");
1746 let end_seq = slots
1747 .last()
1748 .map(|s| s.sequence)
1749 .expect("InputBatch carried at least one slot");
1750
1751 let ack = Ack {
1753 acked_sequence: end_seq,
1754 in_memory_sequence: end_seq,
1755 };
1756 encode_ack(&ack, &mut buf);
1757 writer.write_all(&buf).unwrap();
1758 writer.flush().unwrap();
1759
1760 end_seq
1761 });
1762
1763 let mut p_reader = primary_stream.try_clone().unwrap();
1765 let mut p_writer = primary_stream;
1766
1767 let frame = read_frame(&mut p_reader, MAX_CONTROL_FRAME).unwrap();
1769 let handshake = match decode_replica_message(&frame).unwrap() {
1770 ReplicaMessage::Handshake(h) => h,
1771 _ => panic!("expected Handshake"),
1772 };
1773 assert_eq!(handshake.last_sequence, 0);
1774
1775 let mut buf = Vec::new();
1777 encode_stream_start(0, 1, [0u8; 32], 0, 1, &mut buf); p_writer.write_all(&buf).unwrap();
1779 p_writer.flush().unwrap();
1780 buf.clear();
1781
1782 encode_input_batch_with_seq(42, &mut buf);
1784 p_writer.write_all(&buf).unwrap();
1785 p_writer.flush().unwrap();
1786 buf.clear();
1787
1788 let frame = read_frame(&mut p_reader, MAX_CONTROL_FRAME).unwrap();
1790 let ack = match decode_replica_message(&frame).unwrap() {
1791 ReplicaMessage::Ack(a) => a,
1792 _ => panic!("expected Ack"),
1793 };
1794 assert_eq!(ack.acked_sequence, 42);
1795
1796 let end_seq = replica_handle.join().unwrap();
1798 assert_eq!(end_seq, 42);
1799 }
1800
1801 #[test]
1802 fn multiple_data_batches_acked_in_order() {
1803 use std::os::unix::net::UnixStream;
1806
1807 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
1808
1809 let replica_handle = std::thread::spawn(move || {
1810 let mut reader = replica_stream.try_clone().unwrap();
1811 let mut writer = replica_stream;
1812 let mut buf = Vec::new();
1813
1814 encode_handshake(
1816 &Handshake {
1817 last_sequence: 0,
1818 chain_hash: [0u8; 32],
1819 epoch: 0,
1820 },
1821 &mut buf,
1822 );
1823 writer.write_all(&buf).unwrap();
1824 writer.flush().unwrap();
1825 buf.clear();
1826
1827 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
1829 assert!(matches!(
1830 decode_primary_message(&frame).unwrap(),
1831 PrimaryMessage::StreamStart { .. }
1832 ));
1833
1834 let mut acked_seqs = Vec::new();
1836 for _ in 0..3 {
1837 let frame = read_frame(&mut reader, MAX_DATA_FRAME).unwrap();
1838 let slots: Vec<InputSlot> =
1839 try_decode_input_batch(&frame).expect("decode InputBatch");
1840 let end_seq = slots
1841 .last()
1842 .map(|s| s.sequence)
1843 .expect("InputBatch carried at least one slot");
1844 acked_seqs.push(end_seq);
1845
1846 encode_ack(
1847 &Ack {
1848 acked_sequence: end_seq,
1849 in_memory_sequence: end_seq,
1850 },
1851 &mut buf,
1852 );
1853 writer.write_all(&buf).unwrap();
1854 writer.flush().unwrap();
1855 buf.clear();
1856 }
1857
1858 acked_seqs
1859 });
1860
1861 let mut p_reader = primary_stream.try_clone().unwrap();
1863 let mut p_writer = primary_stream;
1864 let mut buf = Vec::new();
1865
1866 let frame = read_frame(&mut p_reader, MAX_CONTROL_FRAME).unwrap();
1868 assert!(matches!(
1869 decode_replica_message(&frame).unwrap(),
1870 ReplicaMessage::Handshake(_)
1871 ));
1872
1873 encode_stream_start(0, 1, [0u8; 32], 0, 1, &mut buf);
1875 p_writer.write_all(&buf).unwrap();
1876 p_writer.flush().unwrap();
1877 buf.clear();
1878
1879 for seq in [10u64, 20, 30] {
1881 encode_input_batch_with_seq(seq, &mut buf);
1882 p_writer.write_all(&buf).unwrap();
1883 p_writer.flush().unwrap();
1884 buf.clear();
1885 }
1886
1887 for expected_seq in [10u64, 20, 30] {
1889 let frame = read_frame(&mut p_reader, MAX_CONTROL_FRAME).unwrap();
1890 let ack = match decode_replica_message(&frame).unwrap() {
1891 ReplicaMessage::Ack(a) => a,
1892 other => panic!("expected Ack, got {other:?}"),
1893 };
1894 assert_eq!(ack.acked_sequence, expected_seq);
1895 }
1896
1897 let acked = replica_handle.join().unwrap();
1898 assert_eq!(acked, vec![10, 20, 30]);
1899 }
1900
1901 #[test]
1902 fn heartbeat_encode_contains_sequence() {
1903 let mut buf = Vec::new();
1906 encode_heartbeat(999, 1, &mut buf);
1907
1908 let payload = &buf[4..];
1909 match decode_primary_message(payload).unwrap() {
1910 PrimaryMessage::Heartbeat { sequence, .. } => {
1911 assert_eq!(sequence, 999);
1912 }
1913 other => panic!("expected Heartbeat, got {other:?}"),
1914 }
1915 }
1916
1917 #[test]
1918 fn replica_mid_stream_handshake_with_nonzero_sequence() {
1919 use std::os::unix::net::UnixStream;
1924
1925 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
1926
1927 let replica_handle = std::thread::spawn(move || {
1928 let mut reader = replica_stream.try_clone().unwrap();
1929 let mut writer = replica_stream;
1930 let mut buf = Vec::new();
1931
1932 encode_handshake(
1934 &Handshake {
1935 last_sequence: 100,
1936 chain_hash: [0xBB; 32],
1937 epoch: 0,
1938 },
1939 &mut buf,
1940 );
1941 writer.write_all(&buf).unwrap();
1942 writer.flush().unwrap();
1943 buf.clear();
1944
1945 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
1947 match decode_primary_message(&frame).unwrap() {
1948 PrimaryMessage::StreamStart { start_sequence, .. } => {
1949 assert_eq!(
1950 start_sequence, 100,
1951 "StreamStart should echo replica's last_sequence"
1952 );
1953 }
1954 other => panic!("expected StreamStart, got {other:?}"),
1955 }
1956
1957 let frame = read_frame(&mut reader, MAX_DATA_FRAME).unwrap();
1959 let slots: Vec<InputSlot> = try_decode_input_batch(&frame).expect("decode InputBatch");
1960 let end_sequence = slots
1961 .last()
1962 .map(|s| s.sequence)
1963 .expect("InputBatch carried at least one slot");
1964 assert!(
1965 end_sequence > 100,
1966 "InputBatch should be after replica's last_sequence"
1967 );
1968 });
1969
1970 let mut p_reader = primary_stream.try_clone().unwrap();
1972 let mut p_writer = primary_stream;
1973 let mut buf = Vec::new();
1974
1975 let frame = read_frame(&mut p_reader, MAX_CONTROL_FRAME).unwrap();
1977 let handshake = match decode_replica_message(&frame).unwrap() {
1978 ReplicaMessage::Handshake(h) => h,
1979 _ => panic!("expected Handshake"),
1980 };
1981 assert_eq!(handshake.last_sequence, 100);
1982 assert_eq!(handshake.chain_hash, [0xBB; 32]);
1983
1984 encode_stream_start(handshake.last_sequence, 1, [0u8; 32], 0, 1, &mut buf);
1986 p_writer.write_all(&buf).unwrap();
1987 p_writer.flush().unwrap();
1988 buf.clear();
1989
1990 encode_input_batch_with_seq(150, &mut buf);
1992 p_writer.write_all(&buf).unwrap();
1993 p_writer.flush().unwrap();
1994
1995 replica_handle.join().unwrap();
1996 }
1997
1998 #[test]
2013 fn receiver_refuses_stream_start_from_stale_primary() {
2014 use std::os::unix::net::UnixStream;
2015
2016 use melin_transport_core::fence::FenceState;
2017
2018 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
2019
2020 const STALE_EPOCH: u64 = 3;
2024 let primary_handle = std::thread::spawn(move || {
2025 let mut reader = primary_stream.try_clone().unwrap();
2026 let mut writer = primary_stream;
2027
2028 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
2029 let handshake = match decode_replica_message(&frame).unwrap() {
2030 ReplicaMessage::Handshake(h) => h,
2031 _ => panic!("expected Handshake"),
2032 };
2033 assert_eq!(handshake.epoch, 5, "replica advertises its real epoch");
2036
2037 let mut buf = Vec::new();
2038 encode_stream_start(
2039 handshake.last_sequence,
2040 1,
2041 [0u8; 32],
2042 STALE_EPOCH,
2043 1,
2044 &mut buf,
2045 );
2046 writer.write_all(&buf).unwrap();
2047 writer.flush().unwrap();
2048 });
2049
2050 let fence_state = Arc::new(FenceState::new(5));
2053 let mut r_reader = replica_stream.try_clone().unwrap();
2054 let mut r_writer = replica_stream;
2055
2056 let mut buf = Vec::new();
2057 encode_handshake(
2058 &Handshake {
2059 last_sequence: 0,
2060 chain_hash: [0u8; 32],
2061 epoch: fence_state.epoch(),
2062 },
2063 &mut buf,
2064 );
2065 r_writer.write_all(&buf).unwrap();
2066 r_writer.flush().unwrap();
2067
2068 let frame = read_frame(&mut r_reader, MAX_CONTROL_FRAME).unwrap();
2069 let stream_epoch = match decode_primary_message(&frame).unwrap() {
2070 PrimaryMessage::StreamStart { epoch, .. } => epoch,
2071 other => panic!("expected StreamStart, got {other:?}"),
2072 };
2073 assert_eq!(stream_epoch, STALE_EPOCH, "epoch must survive the wire");
2074
2075 assert!(
2078 fence_state.refuses_primary(stream_epoch),
2079 "replica at epoch 5 must refuse a StreamStart from epoch {STALE_EPOCH}"
2080 );
2081 assert_eq!(fence_state.epoch(), 5, "refusal must not lower our epoch");
2082
2083 assert!(!fence_state.refuses_primary(5), "same tenure is followed");
2086 assert!(!fence_state.refuses_primary(6), "newer primary is followed");
2087
2088 primary_handle.join().unwrap();
2089 }
2090
2091 #[test]
2092 fn snapshot_begin_encode_decode_round_trip() {
2093 let mut buf = Vec::new();
2094 encode_snapshot_begin(1_000_000, 42, &[0xAB; 32], &mut buf);
2095
2096 let payload = &buf[4..];
2097 let msg = decode_primary_message(payload).unwrap();
2098 match msg {
2099 PrimaryMessage::SnapshotBegin {
2100 snapshot_len,
2101 snap_sequence,
2102 snap_chain_hash,
2103 } => {
2104 assert_eq!(snapshot_len, 1_000_000);
2105 assert_eq!(snap_sequence, 42);
2106 assert_eq!(snap_chain_hash, [0xAB; 32]);
2107 }
2108 _ => panic!("expected SnapshotBegin"),
2109 }
2110 }
2111
2112 #[test]
2113 fn snapshot_chunk_encode_decode_round_trip() {
2114 let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
2115 let mut buf = Vec::new();
2116 encode_snapshot_chunk(&data, &mut buf);
2117
2118 let payload = &buf[4..];
2119 let msg = decode_primary_message(payload).unwrap();
2120 match msg {
2121 PrimaryMessage::SnapshotChunk(chunk) => {
2122 assert_eq!(chunk, data);
2123 }
2124 _ => panic!("expected SnapshotChunk"),
2125 }
2126 }
2127
2128 #[test]
2129 fn snapshot_end_encode_decode_round_trip() {
2130 let mut buf = Vec::new();
2131 encode_snapshot_end(0xDEADBEEF, &mut buf);
2132
2133 let payload = &buf[4..];
2134 let msg = decode_primary_message(payload).unwrap();
2135 match msg {
2136 PrimaryMessage::SnapshotEnd { crc32c } => {
2137 assert_eq!(crc32c, 0xDEADBEEF);
2138 }
2139 _ => panic!("expected SnapshotEnd"),
2140 }
2141 }
2142
2143 #[test]
2147 fn snapshot_receiver_detects_length_mismatch() {
2148 use std::os::unix::net::UnixStream;
2149
2150 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
2151
2152 let receiver = std::thread::spawn(move || -> String {
2154 let mut reader = replica_stream.try_clone().unwrap();
2155
2156 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
2158 assert!(matches!(
2159 decode_primary_message(&frame).unwrap(),
2160 PrimaryMessage::NeedSnapshot,
2161 ));
2162
2163 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
2165 let (snap_len, _snap_sequence, _snap_chain_hash) =
2166 match decode_primary_message(&frame).unwrap() {
2167 PrimaryMessage::SnapshotBegin {
2168 snapshot_len,
2169 snap_sequence,
2170 snap_chain_hash,
2171 } => (snapshot_len, snap_sequence, snap_chain_hash),
2172 other => panic!("expected SnapshotBegin, got {other:?}"),
2173 };
2174
2175 let mut received: u64 = 0;
2177 loop {
2178 let frame = read_frame(&mut reader, MAX_DATA_FRAME).unwrap();
2179 match decode_primary_message(&frame).unwrap() {
2180 PrimaryMessage::SnapshotChunk(data) => {
2181 received += data.len() as u64;
2182 }
2183 PrimaryMessage::SnapshotEnd { .. } => {
2184 if received != snap_len {
2185 return format!(
2186 "snapshot length mismatch: expected {snap_len} bytes, got {received}"
2187 );
2188 }
2189 return String::new(); }
2191 other => panic!("unexpected message: {other:?}"),
2192 }
2193 }
2194 });
2195
2196 let mut writer = primary_stream;
2198 let mut buf = Vec::new();
2199
2200 let actual_data = vec![0xAA; 100];
2201 let wrong_len = 999u64; encode_need_snapshot(&mut buf);
2204 std::io::Write::write_all(&mut writer, &buf).unwrap();
2205 buf.clear();
2206
2207 encode_snapshot_begin(wrong_len, 42, &[0xBB; 32], &mut buf);
2208 std::io::Write::write_all(&mut writer, &buf).unwrap();
2209 buf.clear();
2210
2211 encode_snapshot_chunk(&actual_data, &mut buf);
2212 std::io::Write::write_all(&mut writer, &buf).unwrap();
2213 buf.clear();
2214
2215 let crc = crc32c::crc32c(&actual_data);
2216 encode_snapshot_end(crc, &mut buf);
2217 std::io::Write::write_all(&mut writer, &buf).unwrap();
2218 std::io::Write::flush(&mut writer).unwrap();
2219
2220 let error_msg = receiver.join().unwrap();
2221 assert!(
2222 error_msg.contains("length mismatch"),
2223 "expected length mismatch error, got: {error_msg:?}"
2224 );
2225 }
2226
2227 #[test]
2231 fn snapshot_receiver_detects_crc_mismatch() {
2232 use std::os::unix::net::UnixStream;
2233
2234 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
2235
2236 let receiver = std::thread::spawn(move || -> String {
2237 let mut reader = replica_stream.try_clone().unwrap();
2238
2239 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
2241 assert!(matches!(
2242 decode_primary_message(&frame).unwrap(),
2243 PrimaryMessage::NeedSnapshot,
2244 ));
2245
2246 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
2248 let snap_len = match decode_primary_message(&frame).unwrap() {
2249 PrimaryMessage::SnapshotBegin { snapshot_len, .. } => snapshot_len,
2250 other => panic!("expected SnapshotBegin, got {other:?}"),
2251 };
2252
2253 let mut received_data = Vec::new();
2255 let mut received: u64 = 0;
2256 loop {
2257 let frame = read_frame(&mut reader, MAX_DATA_FRAME).unwrap();
2258 match decode_primary_message(&frame).unwrap() {
2259 PrimaryMessage::SnapshotChunk(data) => {
2260 received += data.len() as u64;
2261 received_data.extend_from_slice(&data);
2262 }
2263 PrimaryMessage::SnapshotEnd {
2264 crc32c: expected_crc,
2265 } => {
2266 if received != snap_len {
2267 return format!("length mismatch: {snap_len} vs {received}");
2268 }
2269 let actual_crc = crc32c::crc32c(&received_data);
2270 if actual_crc != expected_crc {
2271 return format!(
2272 "CRC mismatch: expected {expected_crc:#x}, got {actual_crc:#x}"
2273 );
2274 }
2275 return String::new();
2276 }
2277 other => panic!("unexpected message: {other:?}"),
2278 }
2279 }
2280 });
2281
2282 let mut writer = primary_stream;
2284 let mut buf = Vec::new();
2285
2286 let data = vec![0xAA; 100];
2287
2288 encode_need_snapshot(&mut buf);
2289 std::io::Write::write_all(&mut writer, &buf).unwrap();
2290 buf.clear();
2291
2292 encode_snapshot_begin(data.len() as u64, 42, &[0xBB; 32], &mut buf);
2293 std::io::Write::write_all(&mut writer, &buf).unwrap();
2294 buf.clear();
2295
2296 encode_snapshot_chunk(&data, &mut buf);
2297 std::io::Write::write_all(&mut writer, &buf).unwrap();
2298 buf.clear();
2299
2300 let wrong_crc = !crc32c::crc32c(&data);
2302 encode_snapshot_end(wrong_crc, &mut buf);
2303 std::io::Write::write_all(&mut writer, &buf).unwrap();
2304 std::io::Write::flush(&mut writer).unwrap();
2305
2306 let error_msg = receiver.join().unwrap();
2307 assert!(
2308 error_msg.contains("CRC mismatch"),
2309 "expected CRC mismatch error, got: {error_msg:?}"
2310 );
2311 }
2312
2313 #[test]
2316 fn snapshot_receiver_detects_chain_hash_mismatch() {
2317 use std::os::unix::net::UnixStream;
2318
2319 let (primary_stream, replica_stream) = UnixStream::pair().unwrap();
2320
2321 let receiver = std::thread::spawn(move || -> String {
2322 let mut reader = replica_stream.try_clone().unwrap();
2323
2324 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
2325 assert!(matches!(
2326 decode_primary_message(&frame).unwrap(),
2327 PrimaryMessage::NeedSnapshot,
2328 ));
2329
2330 let frame = read_frame(&mut reader, MAX_CONTROL_FRAME).unwrap();
2331 let (snap_len, _snap_sequence, snap_chain_hash) =
2332 match decode_primary_message(&frame).unwrap() {
2333 PrimaryMessage::SnapshotBegin {
2334 snapshot_len,
2335 snap_sequence,
2336 snap_chain_hash,
2337 } => (snapshot_len, snap_sequence, snap_chain_hash),
2338 other => panic!("expected SnapshotBegin, got {other:?}"),
2339 };
2340
2341 let mut received_data = Vec::new();
2343 let mut received: u64 = 0;
2344 loop {
2345 let frame = read_frame(&mut reader, MAX_DATA_FRAME).unwrap();
2346 match decode_primary_message(&frame).unwrap() {
2347 PrimaryMessage::SnapshotChunk(data) => {
2348 received += data.len() as u64;
2349 received_data.extend_from_slice(&data);
2350 }
2351 PrimaryMessage::SnapshotEnd {
2352 crc32c: expected_crc,
2353 } => {
2354 assert_eq!(received, snap_len, "length should match");
2355 let actual_crc = crc32c::crc32c(&received_data);
2356 assert_eq!(actual_crc, expected_crc, "CRC should match");
2357 break;
2358 }
2359 other => panic!("unexpected message: {other:?}"),
2360 }
2361 }
2362
2363 let loaded_hash = [0xFF; 32]; if loaded_hash != snap_chain_hash {
2367 return format!(
2368 "snapshot chain hash mismatch: primary sent {snap_chain_hash:02x?}, \
2369 loaded snapshot has {loaded_hash:02x?}"
2370 );
2371 }
2372 String::new()
2373 });
2374
2375 let mut writer = primary_stream;
2378 let mut buf = Vec::new();
2379
2380 let data = vec![0xAA; 64];
2381 let advertised_hash = [0xBB; 32];
2383
2384 encode_need_snapshot(&mut buf);
2385 std::io::Write::write_all(&mut writer, &buf).unwrap();
2386 buf.clear();
2387
2388 encode_snapshot_begin(data.len() as u64, 10, &advertised_hash, &mut buf);
2389 std::io::Write::write_all(&mut writer, &buf).unwrap();
2390 buf.clear();
2391
2392 encode_snapshot_chunk(&data, &mut buf);
2393 std::io::Write::write_all(&mut writer, &buf).unwrap();
2394 buf.clear();
2395
2396 let crc = crc32c::crc32c(&data);
2397 encode_snapshot_end(crc, &mut buf);
2398 std::io::Write::write_all(&mut writer, &buf).unwrap();
2399 std::io::Write::flush(&mut writer).unwrap();
2400
2401 let error_msg = receiver.join().unwrap();
2402 assert!(
2403 error_msg.contains("chain hash mismatch"),
2404 "expected chain hash mismatch error, got: {error_msg:?}"
2405 );
2406 }
2407
2408 #[test]
2411 fn primary_rejects_snapshot_with_invalid_magic() {
2412 let tmp = tempfile::tempdir().unwrap();
2413 let snap_path = tmp.path().join("test.snapshot");
2414
2415 let mut bad_snap = vec![0u8; 64];
2417 bad_snap[0..4].copy_from_slice(&0xDEAD_BEEFu32.to_le_bytes()); std::fs::write(&snap_path, &bad_snap).unwrap();
2420
2421 let snap_data = std::fs::read(&snap_path).unwrap();
2423 assert!(
2424 snap_data.len() >= 48,
2425 "file should be big enough for header"
2426 );
2427
2428 let magic = u32::from_le_bytes(snap_data[0..4].try_into().unwrap());
2429 assert_ne!(magic, 0x534E_4150);
2430 assert_eq!(magic, 0xDEAD_BEEF);
2431 }
2432
2433 #[test]
2436 fn primary_rejects_snapshot_too_small_for_header() {
2437 let tmp = tempfile::tempdir().unwrap();
2438 let snap_path = tmp.path().join("test.snapshot");
2439
2440 std::fs::write(&snap_path, [0u8; 20]).unwrap();
2442
2443 let snap_data = std::fs::read(&snap_path).unwrap();
2444 assert!(
2445 snap_data.len() < 48,
2446 "file must be too small for header validation"
2447 );
2448 }
2449
2450 #[test]
2451 fn decode_snapshot_begin_too_short() {
2452 let payload = [MSG_SNAPSHOT_BEGIN, 0x01, 0x02, 0x03];
2455 let err = decode_primary_message(&payload).unwrap_err();
2456 assert!(
2457 err.to_string().contains("SnapshotBegin too short"),
2458 "expected 'SnapshotBegin too short', got: {err}"
2459 );
2460 }
2461
2462 #[test]
2463 fn decode_snapshot_end_too_short() {
2464 let payload = [MSG_SNAPSHOT_END];
2466 let err = decode_primary_message(&payload).unwrap_err();
2467 assert!(
2468 err.to_string().contains("SnapshotEnd too short"),
2469 "expected 'SnapshotEnd too short', got: {err}"
2470 );
2471 }
2472
2473 #[test]
2474 fn decode_snapshot_chunk_empty_data() {
2475 let payload = [MSG_SNAPSHOT_CHUNK];
2477 let msg = decode_primary_message(&payload).unwrap();
2478 match msg {
2479 PrimaryMessage::SnapshotChunk(data) => {
2480 assert!(data.is_empty());
2481 }
2482 _ => panic!("expected SnapshotChunk"),
2483 }
2484 }
2485
2486 fn make_journal_cursor(val: u64) -> melin_pipeline::padding::Sequence {
2489 melin_pipeline::padding::Sequence::new(AtomicU64::new(val))
2490 }
2491
2492 #[test]
2493 fn pending_ack_queue_push_and_pop_ready() {
2494 let mut q = PendingAckQueue::new(8);
2495 assert!(q.is_empty());
2496 assert!(!q.is_full());
2497
2498 q.push(10, 100);
2499 q.push(20, 200);
2500 assert!(!q.is_empty());
2501
2502 let cursor = make_journal_cursor(5);
2504 assert!(q.pop_ready(&cursor).is_none());
2505
2506 cursor.get().store(15, Ordering::Relaxed);
2508 assert_eq!(q.pop_ready(&cursor), Some(100));
2509 assert!(!q.is_empty());
2511
2512 cursor.get().store(25, Ordering::Relaxed);
2514 assert_eq!(q.pop_ready(&cursor), Some(200));
2515 assert!(q.is_empty());
2516 }
2517
2518 #[test]
2519 fn pending_ack_queue_pop_ready_returns_highest_sequence() {
2520 let mut q = PendingAckQueue::new(8);
2524 q.push(10, 100);
2525 q.push(20, 200);
2526 q.push(30, 300);
2527
2528 let cursor = make_journal_cursor(30);
2529 assert_eq!(q.pop_ready(&cursor), Some(300));
2530 assert!(q.is_empty());
2531 }
2532
2533 #[test]
2534 fn pending_ack_queue_capacity_and_full() {
2535 let mut q = PendingAckQueue::new(8);
2536 for i in 0..8 {
2537 assert!(!q.is_full());
2538 q.push(i as u64 + 1, (i + 1) as u64 * 100);
2539 }
2540 assert!(q.is_full());
2541 }
2542
2543 #[test]
2548 fn pending_ack_queue_merges_into_the_newest_entry_when_full() {
2549 let mut q = PendingAckQueue::new(4);
2550 for i in 1..=4u64 {
2551 q.push(i * 10, i * 100);
2552 }
2553 assert!(q.is_full());
2554 assert_eq!(q.merged(), 0);
2555
2556 q.push(50, 500);
2558 assert_eq!(q.merged(), 1);
2559 assert_eq!(q.len(), 4, "merge must not grow the queue");
2560
2561 let cursor = make_journal_cursor(40);
2564 assert_eq!(q.pop_ready(&cursor), Some(300));
2565 assert!(!q.is_empty(), "merged entry is not durable yet");
2566
2567 cursor.get().store(50, Ordering::Relaxed);
2570 assert_eq!(q.pop_ready(&cursor), Some(500));
2571 assert!(q.is_empty());
2572 }
2573
2574 #[test]
2577 fn pending_ack_queue_merges_repeatedly_without_growing() {
2578 let mut q = PendingAckQueue::new(2);
2579 for i in 1..=100u64 {
2580 q.push(i, i * 10);
2581 }
2582 assert_eq!(q.len(), 2);
2583 assert_eq!(q.merged(), 98);
2584
2585 let cursor = make_journal_cursor(99);
2587 assert_eq!(q.pop_ready(&cursor), Some(10), "only the first entry");
2588 cursor.get().store(100, Ordering::Relaxed);
2590 assert_eq!(q.pop_ready(&cursor), Some(1000));
2591 }
2592
2593 #[test]
2594 fn pending_ack_queue_pop_oldest_blocking() {
2595 let mut q = PendingAckQueue::new(8);
2596 q.push(10, 100);
2597 q.push(20, 200);
2598
2599 let cursor = make_journal_cursor(25);
2602 let seq = q.pop_oldest_blocking(
2603 &cursor,
2604 melin_pipeline::wait::WaitStrategy::BusySpin,
2605 &AtomicBool::new(false),
2606 );
2607 assert_eq!(seq, Some(200));
2609 assert!(q.is_empty());
2610 }
2611
2612 #[test]
2615 fn pending_ack_queue_blocking_wait_aborts_on_journal_failure() {
2616 let mut q = PendingAckQueue::new(8);
2617 q.push(10, 100);
2618
2619 let cursor = make_journal_cursor(5);
2621 let abort = AtomicBool::new(true);
2622 assert_eq!(
2623 q.pop_oldest_blocking(
2624 &cursor,
2625 melin_pipeline::wait::WaitStrategy::BusySpin,
2626 &abort
2627 ),
2628 None
2629 );
2630 assert!(!q.is_empty(), "aborted wait must not pop the entry");
2631 assert_eq!(
2632 q.pop_all_blocking(
2633 &cursor,
2634 melin_pipeline::wait::WaitStrategy::BusySpin,
2635 &abort
2636 ),
2637 None
2638 );
2639 }
2640
2641 #[test]
2650 fn shutdown_pipeline_surfaces_journal_error_kind() {
2651 let flag = AtomicBool::new(false);
2652 let matching_joined = Arc::new(AtomicBool::new(false));
2653 let mj = Arc::clone(&matching_joined);
2654
2655 let journal = std::thread::spawn(|| -> Result<u32, melin_journal::JournalError> {
2656 Err(melin_journal::JournalError::ReplicaChainDivergence {
2657 sequence: 42,
2658 expected: [1u8; 32],
2659 actual: [2u8; 32],
2660 })
2661 });
2662 let matching = std::thread::spawn(move || {
2663 mj.store(true, Ordering::Release);
2664 7u64
2665 });
2666 let drain = std::thread::spawn(|| {});
2667
2668 let outcome = shutdown_pipeline::<u64, u32>(&flag, journal, matching, drain, None);
2669 assert!(flag.load(Ordering::Acquire), "shutdown flag must be set");
2670 assert!(
2671 matching_joined.load(Ordering::Acquire),
2672 "matching thread must be joined even when the journal failed"
2673 );
2674 match outcome {
2675 TeardownOutcome::JournalFailed(
2676 melin_journal::JournalError::ReplicaChainDivergence { sequence, .. },
2677 ) => assert_eq!(sequence, 42),
2678 _ => panic!("expected JournalFailed(ReplicaChainDivergence)"),
2679 }
2680 }
2681
2682 #[test]
2683 fn shutdown_pipeline_clean_returns_both_states() {
2684 let flag = AtomicBool::new(false);
2685 let journal =
2686 std::thread::spawn(|| -> Result<u32, melin_journal::JournalError> { Ok(11u32) });
2687 let matching = std::thread::spawn(|| 7u64);
2688 let drain = std::thread::spawn(|| {});
2689
2690 match shutdown_pipeline::<u64, u32>(&flag, journal, matching, drain, None) {
2691 TeardownOutcome::Clean(app, writer) => {
2692 assert_eq!(app, 7);
2693 assert_eq!(writer, 11);
2694 }
2695 _ => panic!("expected Clean"),
2696 }
2697 }
2698
2699 #[test]
2700 fn shutdown_pipeline_panicked_stage_reports_panicked() {
2701 let flag = AtomicBool::new(false);
2702 let journal =
2703 std::thread::spawn(|| -> Result<u32, melin_journal::JournalError> { Ok(11u32) });
2704 let matching = std::thread::spawn(|| -> u64 { panic!("matching stage died") });
2705 let drain = std::thread::spawn(|| {});
2706
2707 assert!(matches!(
2708 shutdown_pipeline::<u64, u32>(&flag, journal, matching, drain, None),
2709 TeardownOutcome::Panicked
2710 ));
2711 }
2712
2713 fn teardown_fixture(
2718 capacity: usize,
2719 ) -> (
2720 ReplicaPipelineHandles<counter_server::Counter, u32>,
2721 melin_pipeline::ring::Consumer<InputSlot>,
2722 ) {
2723 let (input_producer, mut consumers) =
2724 melin_pipeline::ring::DisruptorBuilder::<InputSlot>::new(capacity)
2725 .add_consumer()
2726 .build(melin_pipeline::wait::WaitStrategy::SpinThenYield);
2727 let consumer = consumers.pop().expect("one consumer");
2728 let handles = ReplicaPipelineHandles {
2729 input_producer,
2730 journal_cursor: Arc::new(make_journal_cursor(0)),
2731 last_seq: melin_transport_core::DurableWireSeqCursor::detached(
2732 melin_transport_core::WireSeq::new(0),
2733 ),
2734 chain_hash_lock: None,
2735 stream_marks: Arc::new(std::sync::Mutex::new(std::collections::VecDeque::new())),
2736 journal_failed: Arc::new(AtomicBool::new(false)),
2737 pipeline_shutdown: Arc::new(AtomicBool::new(false)),
2738 journal_handle: std::thread::spawn(|| -> Result<u32, melin_journal::JournalError> {
2739 Ok(11)
2740 }),
2741 matching_handle: std::thread::spawn(counter_server::Counter::default),
2742 drain_handle: std::thread::spawn(|| {}),
2743 shadow_handle: None,
2744 };
2745 (handles, consumer)
2746 }
2747
2748 #[test]
2754 fn teardown_publishes_shutdown_sentinel() {
2755 let (handles, mut consumer) = teardown_fixture(8);
2756 assert!(matches!(
2757 teardown_replica_pipeline::<counter_server::Counter, u32>(handles),
2758 TeardownOutcome::Clean(..)
2759 ));
2760 let (_, slot) = consumer.try_consume().expect("sentinel on the ring");
2761 assert!(
2762 slot.event.is_shutdown(),
2763 "published slot must be the sentinel"
2764 );
2765 assert!(consumer.try_consume().is_none(), "exactly one sentinel");
2766 }
2767
2768 fn backoff_after_disconnect(heard_from_primary: bool) -> std::time::Duration {
2775 let dir = tempfile::tempdir().expect("tempdir");
2776 type Writer = melin_journal::BufferedWriter<CounterEvent>;
2777 let mut pipeline: Option<ReplicaPipelineHandles<counter_server::Counter, Writer>> = None;
2778 let mut divergence_resyncs = 0u32;
2779 let mut backoff = MAX_BACKOFF;
2780 let shutdown = AtomicBool::new(true);
2781 let promote = crate::promotion::PromotionRequest::new();
2782 let after = handle_session_exit::<counter_server::Counter, Writer>(
2783 StreamingResult {
2784 exit: SessionExit::Disconnected,
2785 heard_from_primary,
2786 },
2787 &mut pipeline,
2788 &mut divergence_resyncs,
2789 &mut backoff,
2790 0,
2791 &dir.path().join("r.journal"),
2792 &dir.path().join("r.snapshot"),
2793 &melin_transport_core::fence::FenceState::new(0),
2794 &shutdown,
2795 &promote,
2796 || {},
2797 &(),
2798 );
2799 assert!(matches!(after, AfterSession::Reconnect));
2800 backoff
2801 }
2802
2803 #[test]
2808 fn disconnect_resets_backoff_when_primary_spoke() {
2809 assert_eq!(
2812 backoff_after_disconnect(true),
2813 std::time::Duration::from_secs(2)
2814 );
2815 }
2816
2817 #[test]
2822 fn disconnect_keeps_escalated_backoff_when_primary_silent() {
2823 assert_eq!(backoff_after_disconnect(false), MAX_BACKOFF);
2824 }
2825
2826 #[test]
2835 fn stream_gap_reconnects_and_keeps_pipeline() {
2836 let dir = tempfile::tempdir().expect("tempdir");
2837 type Writer = melin_journal::BufferedWriter<CounterEvent>;
2838 let (input_producer, mut consumers) =
2842 melin_pipeline::ring::DisruptorBuilder::<InputSlot>::new(4)
2843 .add_consumer()
2844 .build(melin_pipeline::wait::WaitStrategy::SpinThenYield);
2845 let _consumer = consumers.pop().expect("one consumer");
2846 let writer_path = dir.path().join("w.journal");
2847 let handles = ReplicaPipelineHandles {
2848 input_producer,
2849 journal_cursor: Arc::new(make_journal_cursor(0)),
2850 last_seq: melin_transport_core::DurableWireSeqCursor::detached(
2851 melin_transport_core::WireSeq::new(0),
2852 ),
2853 chain_hash_lock: None,
2854 stream_marks: Arc::new(std::sync::Mutex::new(std::collections::VecDeque::new())),
2855 journal_failed: Arc::new(AtomicBool::new(false)),
2856 pipeline_shutdown: Arc::new(AtomicBool::new(false)),
2857 journal_handle: std::thread::spawn(move || Writer::create(&writer_path)),
2858 matching_handle: std::thread::spawn(counter_server::Counter::default),
2859 drain_handle: std::thread::spawn(|| {}),
2860 shadow_handle: None,
2861 };
2862 let mut pipeline: Option<ReplicaPipelineHandles<counter_server::Counter, Writer>> =
2863 Some(handles);
2864 let mut divergence_resyncs = 0u32;
2865 let mut backoff = MAX_BACKOFF;
2866 let shutdown = AtomicBool::new(true);
2867 let promote = crate::promotion::PromotionRequest::new();
2868 let mut closed = false;
2869 let after = handle_session_exit::<counter_server::Counter, Writer>(
2870 StreamingResult {
2871 exit: SessionExit::StreamGap("sequence gap: expected 3, got 5".into()),
2872 heard_from_primary: true,
2873 },
2874 &mut pipeline,
2875 &mut divergence_resyncs,
2876 &mut backoff,
2877 2,
2878 &dir.path().join("r.journal"),
2879 &dir.path().join("r.snapshot"),
2880 &melin_transport_core::fence::FenceState::new(0),
2881 &shutdown,
2882 &promote,
2883 || closed = true,
2884 &(),
2885 );
2886 assert!(
2887 matches!(after, AfterSession::Reconnect),
2888 "a stream gap must reconnect, not return an error"
2889 );
2890 assert!(
2891 pipeline.is_some(),
2892 "the pipeline must survive for the reconnect"
2893 );
2894 assert!(closed, "the transport must be closed before redialing");
2895 assert_eq!(
2896 backoff,
2897 std::time::Duration::from_secs(2),
2898 "backoff reset to 1s then doubled by the shared helper"
2899 );
2900 assert_eq!(divergence_resyncs, 0, "not a resync");
2901 if let Some(p) = pipeline.take() {
2902 let _ = teardown_replica_pipeline::<counter_server::Counter, Writer>(p);
2903 }
2904 }
2905
2906 #[test]
2911 fn teardown_skips_sentinel_when_journal_failed_and_ring_full() {
2912 let (mut handles, mut consumer) = teardown_fixture(4);
2913 for seq in 0..4 {
2914 assert!(
2915 handles
2916 .input_producer
2917 .try_publish(InputSlot {
2918 sequence: seq,
2919 ..InputSlot::default()
2920 })
2921 .is_ok(),
2922 "ring must have space while filling"
2923 );
2924 }
2925 assert!(
2926 handles
2927 .input_producer
2928 .try_publish(InputSlot::default())
2929 .is_err(),
2930 "ring must be full"
2931 );
2932 handles.journal_failed.store(true, Ordering::Release);
2933 assert!(matches!(
2935 teardown_replica_pipeline::<counter_server::Counter, u32>(handles),
2936 TeardownOutcome::Clean(..)
2937 ));
2938 while let Some((_, slot)) = consumer.try_consume() {
2939 assert!(!slot.event.is_shutdown(), "no sentinel may be published");
2940 }
2941 }
2942
2943 #[test]
2944 fn pending_ack_queue_wraps_around() {
2945 let mut q = PendingAckQueue::new(8);
2946 let cursor = make_journal_cursor(100);
2947
2948 for round in 0..3 {
2950 for i in 0..8 {
2951 let target = (round * 8 + i) as u64 + 1;
2952 q.push(target, target * 10);
2953 }
2954 assert!(q.is_full());
2955 let seq = q.pop_ready(&cursor).expect("should be ready");
2956 assert_eq!(seq, (round * 8 + 8) as u64 * 10);
2957 assert!(q.is_empty());
2958 }
2959 }
2960
2961 #[test]
2962 fn pending_ack_queue_pop_all_blocking_empty() {
2963 let mut q = PendingAckQueue::new(8);
2964 let cursor = make_journal_cursor(0);
2965 assert!(
2966 q.pop_all_blocking(
2967 &cursor,
2968 melin_pipeline::wait::WaitStrategy::BusySpin,
2969 &AtomicBool::new(false)
2970 )
2971 .is_none()
2972 );
2973 }
2974
2975 #[test]
2978 fn dual_track_returns_none_when_both_tracks_idle() {
2979 let mut q = PendingAckQueue::new(8);
2980 let cursor = make_journal_cursor(0);
2981 assert!(
2982 try_flush_dual_track(&mut q, &cursor, 0, 0, 0).is_none(),
2983 "no advance on either track → no ack"
2984 );
2985 }
2986
2987 #[test]
2988 fn dual_track_fires_on_persisted_advance_only() {
2989 let mut q = PendingAckQueue::new(8);
2994 q.push(10, 100);
2995 let cursor = make_journal_cursor(20);
2996 let ack = try_flush_dual_track(&mut q, &cursor, 50, 0, 50).expect("persisted advanced");
2997 assert_eq!(ack.acked_sequence, 100);
2998 assert_eq!(ack.in_memory_sequence, 50);
2999 }
3000
3001 #[test]
3002 fn dual_track_fires_on_in_memory_advance_only() {
3003 let mut q = PendingAckQueue::new(8);
3006 let cursor = make_journal_cursor(0);
3007 let ack = try_flush_dual_track(&mut q, &cursor, 200, 100, 100).expect("in-memory advanced");
3008 assert_eq!(ack.acked_sequence, 100);
3009 assert_eq!(ack.in_memory_sequence, 200);
3010 }
3011
3012 #[test]
3013 fn dual_track_coalesces_until_caller_updates_trackers() {
3014 let mut q = PendingAckQueue::new(8);
3020 q.push(10, 100);
3021 let cursor = make_journal_cursor(20);
3022 let ack1 = try_flush_dual_track(&mut q, &cursor, 50, 0, 50).expect("call 1 fires");
3023 assert_eq!(ack1.acked_sequence, 100);
3024 let ack2 = try_flush_dual_track(&mut q, &cursor, 80, 0, 50)
3026 .expect("call 2 fires on in-memory advance");
3027 assert_eq!(
3028 ack2.acked_sequence, 0,
3029 "no new persisted pop → unwrap_or(last_sent)"
3030 );
3031 assert_eq!(ack2.in_memory_sequence, 80);
3032 }
3033
3034 #[test]
3035 fn dual_track_no_duplicate_ack_after_backpressure_drain() {
3036 let mut q = PendingAckQueue::new(4);
3054 for i in 1..=4u64 {
3057 q.push(i * 10, i * 100);
3058 }
3059 assert!(q.is_full());
3060
3061 let cursor = make_journal_cursor(40);
3064 let drained = q.pop_ready(&cursor).expect("all entries durable");
3065 assert_eq!(drained, 400);
3066 assert!(q.is_empty());
3067
3068 let mut last_sent_acked = drained;
3071 let mut last_sent_in_mem = 450u64;
3072
3073 assert!(
3078 try_flush_dual_track(
3079 &mut q,
3080 &cursor,
3081 last_sent_in_mem,
3082 last_sent_acked,
3083 last_sent_in_mem,
3084 )
3085 .is_none(),
3086 "no advance on either track after backpressure drain → no duplicate ack",
3087 );
3088
3089 q.push(50, 500);
3092 let cursor2 = make_journal_cursor(50);
3093 let ack = try_flush_dual_track(&mut q, &cursor2, 500, last_sent_acked, last_sent_in_mem)
3094 .expect("fresh batch after drain fires a new ack");
3095 assert!(
3096 ack.acked_sequence >= last_sent_acked,
3097 "regression: drain sent {last_sent_acked} but next ack carries {}",
3098 ack.acked_sequence,
3099 );
3100 assert_eq!(ack.acked_sequence, 500);
3101 assert_eq!(ack.in_memory_sequence, 500);
3102
3103 last_sent_acked = ack.acked_sequence;
3104 last_sent_in_mem = ack.in_memory_sequence;
3105
3106 assert!(
3110 try_flush_dual_track(
3111 &mut q,
3112 &cursor2,
3113 last_sent_in_mem,
3114 last_sent_acked,
3115 last_sent_in_mem,
3116 )
3117 .is_none(),
3118 "post-resume idle → no further ack",
3119 );
3120 }
3121}