You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by hg...@apache.org on 2026/08/18 09:35:10 UTC

(iggy) branch master updated: refactor(consensus): build replies in Owned and clear stale todos (#3908)

This is an automated email from the ASF dual-hosted git repository.

hubcio pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iggy.git


The following commit(s) were added to refs/heads/master by this push:
     new 6043d1940 refactor(consensus): build replies in Owned and clear stale todos (#3908)
6043d1940 is described below

commit 6043d194000cff5f5498a91dc2259e34762f7d1c
Author: Grzegorz Koszyk <11...@users.noreply.github.com>
AuthorDate: Tue Aug 18 11:35:06 2026 +0200

    refactor(consensus): build replies in Owned and clear stale todos (#3908)
---
 core/consensus/src/impls.rs         | 20 +++++++++----------
 core/consensus/src/lib.rs           |  7 ++++---
 core/consensus/src/plane_helpers.rs | 40 +++++++++++++++++--------------------
 core/consensus/src/vsr_timeout.rs   | 12 +++++++++--
 core/journal/src/lib.rs             | 16 ++-------------
 core/metadata/src/impls/metadata.rs |  8 +++++---
 core/server_common/src/iobuf.rs     | 10 ++++------
 core/server_common/src/lib.rs       | 15 ++------------
 core/server_common/src/storage.rs   | 32 +++++++++++++++++++++++++++++
 core/shard/src/router.rs            |  7 ++++---
 10 files changed, 91 insertions(+), 76 deletions(-)

diff --git a/core/consensus/src/impls.rs b/core/consensus/src/impls.rs
index a481e3465..50bb8523d 100644
--- a/core/consensus/src/impls.rs
+++ b/core/consensus/src/impls.rs
@@ -86,7 +86,6 @@ pub trait Sequencer {
     fn current_sequence(&self) -> Self::Sequence;
 
     /// Allocate the next sequence number.
-    /// TODO Should this return a Future<Output = u64>? for async case?
     fn next_sequence(&self) -> Self::Sequence;
 
     /// Update the current sequence number.
@@ -1167,9 +1166,9 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
             "VsrConsensus group must be METADATA_GROUP or a packable \
              IggyNamespace; got {group:#x}"
         );
-        // TODO: Verify that XOR-based seeding provides sufficient jitter diversity
-        // across groups. Consider using a proper hash (e.g., Murmur3) of
-        // (replica_id, group) for production.
+        // Jitter only has to desynchronize replicas of one group, whose ids
+        // differ, so the XOR cannot collide where it matters; `seed_from_u64`
+        // (SplitMix64) decorrelates the streams of nearby seeds.
         let timeout_seed = u128::from(replica) ^ u128::from(group);
         let prepare_queue_max = pipeline.prepare_queue_max();
         Self {
@@ -2059,7 +2058,7 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
         pipeline.clear_request_queue();
     }
 
-    /// Process one tick. Call this periodically (e.g., every 10ms).
+    /// Process one tick. Call this every [`crate::TICK_INTERVAL`].
     ///
     /// Returns a list of actions to take based on fired timeouts.
     /// Empty vec means no actions needed.
@@ -3227,9 +3226,8 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
             return CommitOutcome::Accepted;
         }
 
-        // TODO: Once connection-level peer verification is added promote
-        // this to an assert, the network layer would guarantee the sender
-        // matches header.replica.
+        // Tolerant skip, not an assert: the replica handshake proves cluster
+        // membership only, so nothing binds `header.replica` to the sender.
         if header.replica != self.primary_index(header.view) {
             return CommitOutcome::Accepted;
         }
@@ -3843,8 +3841,10 @@ where
     P: Pipeline<Entry = PipelineEntry>,
 {
     type MessageBus = B;
-    #[rustfmt::skip] // Scuffed formatter. TODO: Make the naming less ambiguous for `Message`.
-    type Message<H> = Message<H> where H: ConsensusHeader;
+    type Message<H>
+        = server_common::Message<H>
+    where
+        H: ConsensusHeader;
     type RoutedRequestHeader = RoutedRequestHeader;
     type ReplicateHeader = PrepareHeader;
     type AckHeader = PrepareOkHeader;
diff --git a/core/consensus/src/lib.rs b/core/consensus/src/lib.rs
index 91f685fa5..b88b21a4d 100644
--- a/core/consensus/src/lib.rs
+++ b/core/consensus/src/lib.rs
@@ -109,8 +109,9 @@ pub type AckMessage<C> = <C as Consensus>::Message<<C as Consensus>::AckHeader>;
 
 pub trait Consensus: Sized {
     type MessageBus: MessageBus;
-    #[rustfmt::skip] // Scuffed formatter.
-    type Message<H>: ConsensusMessage<H> where H: ConsensusHeader;
+    type Message<H>: ConsensusMessage<H>
+    where
+        H: ConsensusHeader;
 
     type RoutedRequestHeader: ConsensusHeader;
     type ReplicateHeader: ConsensusHeader;
@@ -199,4 +200,4 @@ pub use dvc_merge::*;
 mod vsr_state;
 pub use vsr_state::{VsrState, VsrStateError};
 mod vsr_timeout;
-pub use vsr_timeout::TimeoutManager;
+pub use vsr_timeout::{TICK_INTERVAL, TimeoutManager};
diff --git a/core/consensus/src/plane_helpers.rs b/core/consensus/src/plane_helpers.rs
index 1c576d09c..57c6d296a 100644
--- a/core/consensus/src/plane_helpers.rs
+++ b/core/consensus/src/plane_helpers.rs
@@ -534,7 +534,7 @@ where
 {
     let header_size = std::mem::size_of::<ReplyHeader>();
     let total_size = header_size + body_len;
-    let mut buffer = bytes::BytesMut::zeroed(total_size);
+    let mut buffer = Owned::<4096>::zeroed(total_size);
 
     let header = ReplyHeader {
         checksum: 0,
@@ -560,15 +560,12 @@ where
         operation: prepare_header.operation,
         ..Default::default()
     };
-    // `BytesMut` makes no alignment guarantee, so never cast into it.
-    buffer[..header_size].copy_from_slice(bytemuck::bytes_of(&header));
+    let bytes = buffer.as_mut_slice();
+    bytes[..header_size].copy_from_slice(bytemuck::bytes_of(&header));
 
-    fill(&mut buffer[header_size..]);
+    fill(&mut bytes[header_size..]);
 
-    // TODO: drop this copy once replies stop round-tripping through `Bytes`
-    // and the binary protocol uses `Owned` end-to-end.
-    Message::try_from(Owned::<4096>::copy_from_slice(buffer.as_ref()))
-        .expect("reply buffer must contain a valid reply message")
+    Message::try_from(buffer).expect("reply buffer must contain a valid reply message")
 }
 
 /// Builds a `Reply` carrying only a single-entry result section, no payload:
@@ -601,7 +598,7 @@ pub fn build_result_rejection_reply(
     const RESULT_BODY_LEN: usize = 12;
     let header_size = std::mem::size_of::<ReplyHeader>();
     let total_size = header_size + RESULT_BODY_LEN;
-    let mut buffer = bytes::BytesMut::zeroed(total_size);
+    let mut buffer = Owned::<4096>::zeroed(total_size);
 
     let header = ReplyHeader {
         cluster: request_header.cluster,
@@ -622,15 +619,15 @@ pub fn build_result_rejection_reply(
         operation: request_header.operation,
         ..Default::default()
     };
-    buffer[..header_size].copy_from_slice(bytemuck::bytes_of(&header));
+    let bytes = buffer.as_mut_slice();
+    bytes[..header_size].copy_from_slice(bytemuck::bytes_of(&header));
 
-    let body = &mut buffer[header_size..];
+    let body = &mut bytes[header_size..];
     body[0..4].copy_from_slice(&1u32.to_le_bytes());
     body[4..8].copy_from_slice(&0u32.to_le_bytes());
     body[8..12].copy_from_slice(&code.to_le_bytes());
 
-    Message::try_from(Owned::<4096>::copy_from_slice(buffer.as_ref()))
-        .expect("transient reply buffer must contain a valid reply message")
+    Message::try_from(buffer).expect("transient reply buffer must contain a valid reply message")
 }
 
 /// Reply for fast paths that skip the VSR pipeline (e.g. `AckLevel::NoAck`).
@@ -652,7 +649,7 @@ where
 {
     let header_size = std::mem::size_of::<ReplyHeader>();
     let total_size = header_size + body.len();
-    let mut buffer = bytes::BytesMut::zeroed(total_size);
+    let mut buffer = Owned::<4096>::zeroed(total_size);
 
     let commit = consensus.commit_max();
     let header = ReplyHeader {
@@ -675,14 +672,14 @@ where
         operation: request_header.operation,
         ..Default::default()
     };
-    buffer[..header_size].copy_from_slice(bytemuck::bytes_of(&header));
+    let bytes = buffer.as_mut_slice();
+    bytes[..header_size].copy_from_slice(bytemuck::bytes_of(&header));
 
     if !body.is_empty() {
-        buffer[header_size..].copy_from_slice(&body);
+        bytes[header_size..].copy_from_slice(&body);
     }
 
-    Message::try_from(Owned::<4096>::copy_from_slice(buffer.as_ref()))
-        .expect("reply buffer must contain a valid reply message")
+    Message::try_from(buffer).expect("reply buffer must contain a valid reply message")
 }
 
 /// Reply that denies a request on the primary before it enters the VSR
@@ -734,7 +731,7 @@ pub fn build_deny_reply_from_request_header(
     status: u32,
 ) -> Message<ReplyHeader> {
     let header_size = std::mem::size_of::<ReplyHeader>();
-    let mut buffer = bytes::BytesMut::zeroed(header_size);
+    let mut buffer = Owned::<4096>::zeroed(header_size);
 
     let header = ReplyHeader {
         cluster: request_header.cluster,
@@ -751,10 +748,9 @@ pub fn build_deny_reply_from_request_header(
         operation: request_header.operation,
         ..Default::default()
     };
-    buffer[..header_size].copy_from_slice(bytemuck::bytes_of(&header));
+    buffer.as_mut_slice()[..header_size].copy_from_slice(bytemuck::bytes_of(&header));
 
-    Message::try_from(Owned::<4096>::copy_from_slice(buffer.as_ref()))
-        .expect("deny reply buffer must contain a valid reply message")
+    Message::try_from(buffer).expect("deny reply buffer must contain a valid reply message")
 }
 
 /// Verify hash chain would not break if we add this header.
diff --git a/core/consensus/src/vsr_timeout.rs b/core/consensus/src/vsr_timeout.rs
index ddbe03702..9781520e8 100644
--- a/core/consensus/src/vsr_timeout.rs
+++ b/core/consensus/src/vsr_timeout.rs
@@ -31,10 +31,19 @@
 ///
 /// Timeouts count down from an initial duration (`after`) and fire when
 /// reaching zero. They support exponential backoff with jitter for retries.
+use std::time::Duration;
+
 use rand::RngExt;
 use rand_xoshiro::Xoshiro256Plus;
 use rand_xoshiro::rand_core::SeedableRng;
 
+/// Wall-clock length of one consensus tick.
+///
+/// Every tick count in this module is a multiple of this unit: a timeout of N
+/// ticks fires after N * `TICK_INTERVAL`, provided the owner drives
+/// [`TimeoutManager::tick`] at this cadence.
+pub const TICK_INTERVAL: Duration = Duration::from_millis(10);
+
 #[derive(Debug, Clone)]
 #[allow(unused)]
 pub struct Timeout {
@@ -137,8 +146,7 @@ pub struct TimeoutManager {
 
 #[allow(unused)]
 impl TimeoutManager {
-    // Timeout durations in ticks (10ms per tick).
-    // TODO define 10ms per tick in a separate constant.
+    // Timeout durations in ticks of [`TICK_INTERVAL`].
     /// Public so the runtime can pin its `[cluster] prepare_retransmit_interval`
     /// config default against this built-in.
     pub const PREPARE_TICKS: u64 = 25;
diff --git a/core/journal/src/lib.rs b/core/journal/src/lib.rs
index 1d223d7e6..f97dc35f4 100644
--- a/core/journal/src/lib.rs
+++ b/core/journal/src/lib.rs
@@ -19,6 +19,8 @@ use std::io;
 use std::ops::{Deref, RangeInclusive};
 use std::rc::Rc;
 
+pub use server_common::Storage;
+
 pub mod file_storage;
 pub mod local_gate;
 pub mod prepare_journal;
@@ -98,20 +100,6 @@ where
     fn set_snapshot_op(&self, op: u64);
 }
 
-// TODO: Move to other crate.
-pub trait Storage {
-    type Buffer;
-
-    fn write_at(&self, offset: usize, buf: Self::Buffer)
-    -> impl Future<Output = io::Result<usize>>;
-
-    fn read_at(
-        &self,
-        offset: usize,
-        buffer: Self::Buffer,
-    ) -> impl Future<Output = io::Result<Self::Buffer>>;
-}
-
 pub trait JournalHandle {
     type Storage: Storage;
     type Target: Journal<Self::Storage>;
diff --git a/core/metadata/src/impls/metadata.rs b/core/metadata/src/impls/metadata.rs
index acd357457..db84be4af 100644
--- a/core/metadata/src/impls/metadata.rs
+++ b/core/metadata/src/impls/metadata.rs
@@ -2663,9 +2663,11 @@ where
         // else re-peeks and moves on to the next committable op.
         let mut wire_replies: Vec<(CommitLogEvent, Message<ReplyHeader>)> = Vec::new();
         while let Some(prepare_header) = peek_committable_head(consensus) {
-            // TODO(hubcio): should we replace this with graceful fallback (warn + return)?
-            // When journal compaction is implemented compaction could race
-            // with this lookup if it removes entries below the commit number.
+            // A committed prepare missing from the journal is divergence; a
+            // warn-and-return here would strand `commit_min` behind
+            // `commit_max` forever (nothing re-applies a skipped op), so
+            // panicking is the answer. Journal compaction, if ever added,
+            // must not remove entries at or above the commit floor.
             let prepare = journal
                 .handle()
                 .entry(&prepare_header)
diff --git a/core/server_common/src/iobuf.rs b/core/server_common/src/iobuf.rs
index 7175ef1f6..3c793ec98 100644
--- a/core/server_common/src/iobuf.rs
+++ b/core/server_common/src/iobuf.rs
@@ -465,13 +465,11 @@ impl<const ALIGN: usize> Clone for Extent<ALIGN> {
     }
 }
 
-pub(crate) fn freeze_extent<const ALIGN: usize>(extent: Extent<ALIGN>) -> Frozen<ALIGN> {
+fn freeze_extent<const ALIGN: usize>(extent: Extent<ALIGN>) -> Frozen<ALIGN> {
     Frozen { inner: extent }
 }
 
-pub(crate) fn extent_from_aligned_vec<const ALIGN: usize>(
-    vec: AVec<u8, ConstAlign<ALIGN>>,
-) -> Extent<ALIGN> {
+fn extent_from_aligned_vec<const ALIGN: usize>(vec: AVec<u8, ConstAlign<ALIGN>>) -> Extent<ALIGN> {
     let (ptr, _, len, capacity) = vec.into_raw_parts();
     let guard = AVecRawGuard::<ALIGN>::new(ptr, len, capacity);
     let data = unsafe { NonNull::new_unchecked(ptr) };
@@ -485,7 +483,7 @@ pub(crate) fn extent_from_aligned_vec<const ALIGN: usize>(
     }
 }
 
-pub(crate) fn extent_offset_from_base<const ALIGN: usize>(extent: &Extent<ALIGN>) -> usize {
+fn extent_offset_from_base<const ALIGN: usize>(extent: &Extent<ALIGN>) -> usize {
     // SAFETY: the extent points into the control block allocation while it is alive.
     let offset = unsafe {
         extent
@@ -598,7 +596,7 @@ unsafe fn try_merge_extents<const ALIGN: usize>(
     }
 }
 
-pub(crate) fn try_coalesce_prefix_with_tail<const ALIGN: usize>(
+fn try_coalesce_prefix_with_tail<const ALIGN: usize>(
     prefix: Extent<ALIGN>,
     tail: Frozen<ALIGN>,
 ) -> Result<Frozen<ALIGN>, (Extent<ALIGN>, Frozen<ALIGN>)> {
diff --git a/core/server_common/src/lib.rs b/core/server_common/src/lib.rs
index 2aca6f258..c8fa01d42 100644
--- a/core/server_common/src/lib.rs
+++ b/core/server_common/src/lib.rs
@@ -23,25 +23,13 @@ pub mod crypto;
 pub mod diagnostics;
 pub mod executor;
 pub mod fs_utils;
-// TODO(hubcio): iobuf was relocated verbatim from `core/binary_protocol/src/consensus/iobuf.rs`
-// during the sans-io split. Its implementation is intentionally untouched; the
-// lints below predate the move and are tracked as tech debt for a 0.9.x cleanup pass.
-#[allow(
-    private_interfaces,
-    clippy::missing_errors_doc,
-    clippy::missing_panics_doc,
-    clippy::must_use_candidate,
-    clippy::return_self_not_must_use,
-    clippy::missing_const_for_fn,
-    clippy::non_send_fields_in_send_ty,
-    clippy::use_self
-)]
 pub mod iobuf;
 pub mod log;
 mod memory_pool;
 mod segment_storage;
 pub mod send_messages;
 pub mod sharding;
+mod storage;
 
 pub use bootstrap::create_directories;
 pub use buffer::PooledBuffer;
@@ -55,3 +43,4 @@ pub use memory_pool::{MEMORY_POOL, MemoryPool, MemoryPoolConfigOther, memory_poo
 pub use segment_storage::{
     IndexReader, IndexWriter, MessagesReader, MessagesWriter, SegmentStorage,
 };
+pub use storage::Storage;
diff --git a/core/server_common/src/storage.rs b/core/server_common/src/storage.rs
new file mode 100644
index 000000000..9c6950bf7
--- /dev/null
+++ b/core/server_common/src/storage.rs
@@ -0,0 +1,32 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::io;
+
+/// Positional byte io over a durable backing store.
+pub trait Storage {
+    type Buffer;
+
+    fn write_at(&self, offset: usize, buf: Self::Buffer)
+    -> impl Future<Output = io::Result<usize>>;
+
+    fn read_at(
+        &self,
+        offset: usize,
+        buffer: Self::Buffer,
+    ) -> impl Future<Output = io::Result<Self::Buffer>>;
+}
diff --git a/core/shard/src/router.rs b/core/shard/src/router.rs
index 7bdee26ff..0acb78a13 100644
--- a/core/shard/src/router.rs
+++ b/core/shard/src/router.rs
@@ -33,9 +33,10 @@ use server_common::{Message, MessageBag};
 /// How often the shard pump drives `VsrConsensus::tick`.
 ///
 /// Heartbeats, prepare retransmit, and view-change timeouts only advance
-/// when the tick runs ("call this periodically, e.g. every 10ms"). Public
-/// so the simulator can advance its virtual clock in whole tick intervals.
-pub const CONSENSUS_TICK_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
+/// when the tick runs. Re-exported from `consensus` so the drive cadence and
+/// the tick counts it feeds share one unit; public so the simulator can
+/// advance its virtual clock in whole tick intervals.
+pub use consensus::TICK_INTERVAL as CONSENSUS_TICK_INTERVAL;
 
 /// Inter-shard dispatch logic.
 ///