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/10/15 07:57:49 UTC
(iggy) 02/02: feat(cluster)!: spread and rebalance partition primaries
This is an automated email from the ASF dual-hosted git repository.
hubcio pushed a commit to branch feat/spread-placement
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit 6342eb14ceecf69e2ccee89b7d76ebc22cb9cc63
Author: Hubert Gruszecki <h....@gmail.com>
AuthorDate: Wed Oct 14 20:52:08 2026 +0200
feat(cluster)!: spread and rebalance partition primaries
Initial placement and fixed failover rotation concentrate primary work
on a subset of replicas. Persist per-assignment creation views and count
committed ownership plus canonical pending creates when placing groups.
Coordinate one primary transfer at a time after stable peer readiness.
Confirm the source frontier and target history, drain accepted work under
a revocable grant, and persist the ordinary consensus view change before
participation. Use the simulator clock for deterministic expiry.
Preserve the pipeline rebuild floor, isolate unclaimed QUIC evictions,
and distinguish first initialization from lost simulator history. Keep
regressions for identity recovery, durable drains and primary placement.
This checkpoint passes failure-time redistribution but retains a failing
five-node return regression: metadata recovery stalls after same-storage
restart while the peer has no persisted snapshot. PR6 acceptance and
the remaining PR4 review deferrals are still open in the design vault.
BREAKING CHANGE: require fresh IGGY-OWNERSHIP-HISTORY-7 storage for
per-assignment creation views and matching server releases for internal
rebalance command 33. Refuse incompatible existing storage unchanged.
---
core/binary_protocol/src/consensus/command.rs | 9 +-
core/binary_protocol/src/consensus/mod.rs | 2 +
.../src/consensus/primary_rebalance.rs | 304 +++++++++
core/binary_protocol/src/lib.rs | 14 +-
.../src/primitives/partition_assignment.rs | 24 +-
.../create_partitions_with_assignments.rs | 114 ++--
.../topics/create_topic_with_assignments.rs | 95 ++-
core/consensus/src/impls.rs | 293 ++++++++-
core/consensus/src/observability.rs | 2 +
core/consensus/src/plane_helpers.rs | 96 +++
.../tests/cluster/partition_primary_routing.rs | 422 ++++++++++++-
.../tests/cluster/staggered_bootstrap.rs | 13 +-
core/message_bus/src/lib.rs | 12 +-
core/message_bus/src/transports/quic.rs | 229 ++++++-
core/metadata/src/impls/metadata.rs | 682 ++++++++++++++++++++-
core/metadata/src/impls/mod.rs | 1 +
core/metadata/src/impls/placement.rs | 562 +++++++++++++++++
core/metadata/src/stm/authz.rs | 2 +-
core/metadata/src/stm/consumer_group.rs | 4 +-
core/metadata/src/stm/lifecycle.rs | 2 +-
core/metadata/src/stm/stream.rs | 177 ++++--
core/partitions/src/iggy_partition.rs | 379 +++++++++++-
core/partitions/src/io.rs | 26 +-
core/partitions/src/lib.rs | 3 +-
core/partitions/src/state_transfer.rs | 2 +
core/server/README.md | 16 +-
core/server/src/boot/mod.rs | 3 +-
core/server/src/consumer_group.rs | 2 +-
core/server/src/consumer_group/liveness.rs | 4 +-
core/server/src/dispatch/host.rs | 128 +++-
core/server/src/dispatch/partition.rs | 10 +-
core/server/src/dispatch/test_support.rs | 2 +-
core/server/src/http/reads.rs | 2 +-
core/server/src/partition_helpers.rs | 28 +-
core/server/src/partition_reconciler.rs | 6 +-
core/server_common/src/consensus_message.rs | 138 ++++-
core/shard/src/lib.rs | 590 +++++++++++++++++-
core/shard/src/metrics.rs | 2 +
core/shard/src/partition_io.rs | 4 +
core/shard/src/primary_rebalance.rs | 620 +++++++++++++++++++
core/shard/src/primary_rebalance/tests.rs | 550 +++++++++++++++++
core/shard/src/router.rs | 13 +
core/simulator/src/bus.rs | 47 +-
core/simulator/src/executor/time.rs | 17 +-
core/simulator/src/lib.rs | 357 ++++++++---
core/simulator/src/packet.rs | 32 +-
foreign/node/README.md | 2 +-
47 files changed, 5680 insertions(+), 362 deletions(-)
diff --git a/core/binary_protocol/src/consensus/command.rs b/core/binary_protocol/src/consensus/command.rs
index 49ee96ff0..3da38b94b 100644
--- a/core/binary_protocol/src/consensus/command.rs
+++ b/core/binary_protocol/src/consensus/command.rs
@@ -92,6 +92,9 @@ pub enum Command {
// may hold no replica of that partition. No reply: the commit replicates
// back.
ForwardCompletion = 32,
+
+ // Fresh metadata and partition readiness for primary rebalancing.
+ PrimaryRebalance = 33,
}
// SAFETY: Command is #[repr(u8)] with no padding bytes.
@@ -102,7 +105,7 @@ unsafe impl CheckedBitPattern for Command {
type Bits = u8;
fn is_valid_bit_pattern(bits: &u8) -> bool {
- *bits <= Self::ForwardCompletion as u8
+ *bits <= Self::PrimaryRebalance as u8
}
}
@@ -123,7 +126,7 @@ mod tests {
#[test]
fn replica_auth_commands_are_valid_bit_patterns() {
- for command in 14u8..=32 {
+ for command in 14u8..=33 {
let mut buf: AVec<u8, ConstAlign<16>> = AVec::new(16);
buf.resize(256, 0);
buf[60] = command;
@@ -131,7 +134,7 @@ mod tests {
}
let mut buf: AVec<u8, ConstAlign<16>> = AVec::new(16);
buf.resize(256, 0);
- buf[60] = 33;
+ buf[60] = 34;
assert!(bytemuck::checked::try_from_bytes::<GenericHeader>(&buf).is_err());
}
}
diff --git a/core/binary_protocol/src/consensus/mod.rs b/core/binary_protocol/src/consensus/mod.rs
index 8e7f398b0..07745df4e 100644
--- a/core/binary_protocol/src/consensus/mod.rs
+++ b/core/binary_protocol/src/consensus/mod.rs
@@ -41,6 +41,7 @@ mod consumer_session;
mod error;
mod header;
mod operation;
+mod primary_rebalance;
mod reply_result;
mod request;
@@ -62,6 +63,7 @@ pub use header::{
prepare_identity_checksum_bytes, read_size_field,
};
pub use operation::Operation;
+pub use primary_rebalance::{PrimaryRebalanceHeader, PrimaryRebalanceKind};
pub use reply_result::{
REJECTION_SECTION_LEN, RESULT_COUNT_LEN, RESULT_ENTRY_LEN, result_code, result_section_len,
write_rejection_section,
diff --git a/core/binary_protocol/src/consensus/primary_rebalance.rs b/core/binary_protocol/src/consensus/primary_rebalance.rs
new file mode 100644
index 000000000..c91bf4f50
--- /dev/null
+++ b/core/binary_protocol/src/consensus/primary_rebalance.rs
@@ -0,0 +1,304 @@
+// 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 super::{Command, ConsensusError, ConsensusHeader, HEADER_SIZE, Operation};
+use bytemuck::{CheckedBitPattern, NoUninit};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, CheckedBitPattern, NoUninit)]
+#[repr(u8)]
+pub enum PrimaryRebalanceKind {
+ MetadataProbe = 0,
+ MetadataReply = 1,
+ PartitionProbe = 2,
+ PartitionReply = 3,
+ SourceProbe = 4,
+ SourceReply = 5,
+}
+
+/// Same-release readiness exchange, always routed through the metadata owner.
+///
+/// `view` identifies the metadata coordinator's view, while `partition_view`
+/// belongs to the probed partition. A ready reply supplies evidence to the
+/// coordinator; it does not transfer ownership. Ingress must authenticate
+/// `replica`, and the coordinator must correlate the nonce and history fields.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, CheckedBitPattern, NoUninit)]
+#[repr(C)]
+pub struct PrimaryRebalanceHeader {
+ pub checksum: u128,
+ pub checksum_body: u128,
+ pub cluster: u128,
+ pub size: u32,
+ pub view: u32,
+ pub release: u32,
+ pub command: Command,
+ pub replica: u8,
+ pub reserved_frame: [u8; 66],
+ pub nonce: u128,
+ pub namespace: u64,
+ pub created_revision: u64,
+ pub commit: u64,
+ pub partition_view: u32,
+ pub kind: PrimaryRebalanceKind,
+ pub ready: u8,
+ pub reserved: [u8; 82],
+}
+
+const _: () = assert!(size_of::<PrimaryRebalanceHeader>() == HEADER_SIZE);
+
+impl ConsensusHeader for PrimaryRebalanceHeader {
+ const FRAME_SEALED: bool = true;
+ const COMMAND: Command = Command::PrimaryRebalance;
+
+ fn checksum(&self) -> u128 {
+ self.checksum
+ }
+
+ fn set_checksum(&mut self, checksum: u128) {
+ self.checksum = checksum;
+ }
+
+ fn operation(&self) -> Operation {
+ Operation::Reserved
+ }
+
+ fn command(&self) -> Command {
+ self.command
+ }
+
+ fn size(&self) -> u32 {
+ self.size
+ }
+
+ #[expect(
+ clippy::cast_possible_truncation,
+ reason = "HEADER_SIZE is fixed at 256 bytes"
+ )]
+ fn validate(&self) -> Result<(), ConsensusError> {
+ if self.command != Self::COMMAND {
+ return Err(ConsensusError::InvalidCommand {
+ expected: Self::COMMAND,
+ found: self.command,
+ });
+ }
+ if self.size as usize != HEADER_SIZE {
+ return Err(ConsensusError::InvalidSize {
+ expected: HEADER_SIZE as u32,
+ found: self.size,
+ });
+ }
+ if self.checksum_body != 0 || self.release != 0 {
+ return Err(ConsensusError::InvalidField(
+ "primary rebalance body checksum and release must be zero".into(),
+ ));
+ }
+ if self.reserved_frame != [0; 66] || self.reserved != [0; 82] {
+ return Err(ConsensusError::InvalidField(
+ "primary rebalance reserved bytes must be zero".into(),
+ ));
+ }
+ if self.nonce == 0 {
+ return Err(ConsensusError::InvalidField(
+ "primary rebalance nonce must be nonzero".into(),
+ ));
+ }
+ if self.ready > 1
+ || (self.ready != 0
+ && matches!(
+ self.kind,
+ PrimaryRebalanceKind::MetadataProbe
+ | PrimaryRebalanceKind::PartitionProbe
+ | PrimaryRebalanceKind::SourceProbe
+ ))
+ {
+ return Err(ConsensusError::InvalidField(
+ "primary rebalance probes cannot be ready; replies require 0 or 1".into(),
+ ));
+ }
+ match self.kind {
+ PrimaryRebalanceKind::MetadataProbe | PrimaryRebalanceKind::MetadataReply => {
+ if self.namespace != 0
+ || self.created_revision != 0
+ || self.commit != 0
+ || self.partition_view != 0
+ {
+ return Err(ConsensusError::InvalidField(
+ "primary rebalance metadata exchange cannot carry partition fields".into(),
+ ));
+ }
+ }
+ PrimaryRebalanceKind::PartitionProbe
+ | PrimaryRebalanceKind::PartitionReply
+ | PrimaryRebalanceKind::SourceProbe
+ | PrimaryRebalanceKind::SourceReply => {
+ if self.created_revision == 0 {
+ return Err(ConsensusError::InvalidField(
+ "primary rebalance partition revision must be nonzero".into(),
+ ));
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use aligned_vec::{AVec, ConstAlign};
+ use std::mem::offset_of;
+
+ fn header(kind: PrimaryRebalanceKind) -> PrimaryRebalanceHeader {
+ let partition = matches!(
+ kind,
+ PrimaryRebalanceKind::PartitionProbe
+ | PrimaryRebalanceKind::PartitionReply
+ | PrimaryRebalanceKind::SourceProbe
+ | PrimaryRebalanceKind::SourceReply
+ );
+ PrimaryRebalanceHeader {
+ checksum: 0,
+ checksum_body: 0,
+ cluster: 7,
+ size: u32::try_from(HEADER_SIZE).unwrap(),
+ view: 11,
+ release: 0,
+ command: Command::PrimaryRebalance,
+ replica: 2,
+ reserved_frame: [0; 66],
+ nonce: u128::MAX,
+ namespace: if partition { 17 } else { 0 },
+ created_revision: u64::from(partition),
+ commit: if partition { 23 } else { 0 },
+ partition_view: if partition { 5 } else { 0 },
+ kind,
+ ready: 0,
+ reserved: [0; 82],
+ }
+ }
+
+ #[test]
+ fn given_rebalance_phases_when_encoded_should_preserve_the_fixed_layout_and_seal() {
+ assert_eq!(offset_of!(PrimaryRebalanceHeader, nonce), 128);
+ assert_eq!(offset_of!(PrimaryRebalanceHeader, namespace), 144);
+ assert_eq!(offset_of!(PrimaryRebalanceHeader, created_revision), 152);
+ assert_eq!(offset_of!(PrimaryRebalanceHeader, commit), 160);
+ assert_eq!(offset_of!(PrimaryRebalanceHeader, partition_view), 168);
+ assert_eq!(offset_of!(PrimaryRebalanceHeader, kind), 172);
+ assert_eq!(offset_of!(PrimaryRebalanceHeader, ready), 173);
+ assert_eq!(offset_of!(PrimaryRebalanceHeader, reserved), 174);
+ for kind in [
+ PrimaryRebalanceKind::MetadataProbe,
+ PrimaryRebalanceKind::MetadataReply,
+ PrimaryRebalanceKind::PartitionProbe,
+ PrimaryRebalanceKind::PartitionReply,
+ PrimaryRebalanceKind::SourceProbe,
+ PrimaryRebalanceKind::SourceReply,
+ ] {
+ for ready in 0..=1 {
+ let mut original = header(kind);
+ original.ready = ready;
+ original.seal();
+ let decoded = bytemuck::checked::try_from_bytes::<PrimaryRebalanceHeader>(
+ bytemuck::bytes_of(&original),
+ )
+ .unwrap();
+ assert_eq!(*decoded, original);
+ decoded.verify_frame().unwrap();
+ let is_reply = matches!(
+ kind,
+ PrimaryRebalanceKind::MetadataReply
+ | PrimaryRebalanceKind::PartitionReply
+ | PrimaryRebalanceKind::SourceReply
+ );
+ assert_eq!(decoded.validate().is_ok(), ready == 0 || is_reply);
+ }
+ }
+ }
+
+ #[test]
+ fn given_a_rebalance_frame_when_fields_are_corrupt_should_reject_before_use() {
+ let mut valid = header(PrimaryRebalanceKind::PartitionReply);
+ valid.ready = 1;
+ valid.seal();
+ let mut bytes: AVec<u8, ConstAlign<16>> = AVec::new(16);
+ bytes.extend_from_slice(bytemuck::bytes_of(&valid));
+ for offset in [32, 52, 61, 128, 144, 152, 160, 168, 172, 173] {
+ bytes[offset] ^= 1;
+ let corrupted =
+ bytemuck::checked::try_from_bytes::<PrimaryRebalanceHeader>(&bytes).unwrap();
+ assert!(corrupted.verify_frame().is_err(), "offset {offset}");
+ bytes[offset] ^= 1;
+ }
+ for kind in 6..=u8::MAX {
+ bytes[offset_of!(PrimaryRebalanceHeader, kind)] = kind;
+ assert!(bytemuck::checked::try_from_bytes::<PrimaryRebalanceHeader>(&bytes).is_err());
+ }
+ }
+
+ #[test]
+ fn given_a_rebalance_frame_when_envelope_or_phase_fields_are_invalid_should_reject() {
+ let valid = header(PrimaryRebalanceKind::PartitionReply);
+ for change in [
+ |value: &mut PrimaryRebalanceHeader| value.command = Command::Commit,
+ |value: &mut PrimaryRebalanceHeader| {
+ value.size = u32::try_from(HEADER_SIZE - 1).unwrap();
+ },
+ |value: &mut PrimaryRebalanceHeader| {
+ value.size = u32::try_from(HEADER_SIZE + 1).unwrap();
+ },
+ |value: &mut PrimaryRebalanceHeader| value.size = u32::MAX,
+ |value: &mut PrimaryRebalanceHeader| value.checksum_body = 1,
+ |value: &mut PrimaryRebalanceHeader| value.release = 1,
+ |value: &mut PrimaryRebalanceHeader| value.reserved_frame[65] = 1,
+ |value: &mut PrimaryRebalanceHeader| value.reserved[81] = 1,
+ |value: &mut PrimaryRebalanceHeader| value.nonce = 0,
+ |value: &mut PrimaryRebalanceHeader| value.ready = 2,
+ |value: &mut PrimaryRebalanceHeader| value.created_revision = 0,
+ ] {
+ let mut invalid = valid;
+ change(&mut invalid);
+ invalid.seal();
+ invalid.verify_frame().unwrap();
+ assert!(invalid.validate().is_err(), "{invalid:?}");
+ }
+ for kind in [
+ PrimaryRebalanceKind::MetadataProbe,
+ PrimaryRebalanceKind::MetadataReply,
+ ] {
+ for change in [
+ |value: &mut PrimaryRebalanceHeader| value.namespace = 1,
+ |value: &mut PrimaryRebalanceHeader| value.created_revision = 1,
+ |value: &mut PrimaryRebalanceHeader| value.commit = 1,
+ |value: &mut PrimaryRebalanceHeader| value.partition_view = 1,
+ ] {
+ let mut invalid = header(kind);
+ change(&mut invalid);
+ assert!(invalid.validate().is_err(), "{invalid:?}");
+ }
+ }
+ for kind in [
+ PrimaryRebalanceKind::PartitionProbe,
+ PrimaryRebalanceKind::PartitionReply,
+ PrimaryRebalanceKind::SourceProbe,
+ PrimaryRebalanceKind::SourceReply,
+ ] {
+ let mut invalid = header(kind);
+ invalid.created_revision = 0;
+ assert!(invalid.validate().is_err(), "{kind:?}");
+ }
+ }
+}
diff --git a/core/binary_protocol/src/lib.rs b/core/binary_protocol/src/lib.rs
index 4626a6268..457d6670c 100644
--- a/core/binary_protocol/src/lib.rs
+++ b/core/binary_protocol/src/lib.rs
@@ -76,13 +76,13 @@ pub use consensus::{
ForwardLogoutResultHeader, ForwardRegisterHeader, ForwardRegisterOutcome,
ForwardRegisterResultHeader, GenericHeader, HEADER_SIZE, LIFECYCLE_BATCH_HEADER_SIZE,
LIFECYCLE_COMPLETION_SIZE, LIFECYCLE_COMPLETIONS_MAX, MAX_CONSUMER_SESSIONS_PER_HEARTBEAT,
- Operation, PrepareHeader, PrepareOkHeader, REJECTION_SECTION_LEN, RESERVED_COMMAND_LEN,
- RepairPrepareHeader, RepairRangeReplyHeader, ReplyHeader, RequestHeader, RequestPreparesHeader,
- RequestStartViewHeader, RequestStateChunkHeader, RequestStateTransferHeader,
- RoutedRequestHeader, SIZE_FIELD_OFFSET, StartViewChangeHeader, StartViewHeader,
- StateChunkHeader, StateTransferTargetHeader, frame_body, frame_checksum_bytes,
- prepare_identity_checksum_bytes, read_size_field, result_code, result_section_len,
- write_rejection_section,
+ Operation, PrepareHeader, PrepareOkHeader, PrimaryRebalanceHeader, PrimaryRebalanceKind,
+ REJECTION_SECTION_LEN, RESERVED_COMMAND_LEN, RepairPrepareHeader, RepairRangeReplyHeader,
+ ReplyHeader, RequestHeader, RequestPreparesHeader, RequestStartViewHeader,
+ RequestStateChunkHeader, RequestStateTransferHeader, RoutedRequestHeader, SIZE_FIELD_OFFSET,
+ StartViewChangeHeader, StartViewHeader, StateChunkHeader, StateTransferTargetHeader,
+ frame_body, frame_checksum_bytes, prepare_identity_checksum_bytes, read_size_field,
+ result_code, result_section_len, write_rejection_section,
};
pub use dispatch::{COMMAND_TABLE, CommandMeta, lookup_by_operation, lookup_command};
pub use error::WireError;
diff --git a/core/binary_protocol/src/primitives/partition_assignment.rs b/core/binary_protocol/src/primitives/partition_assignment.rs
index 27e8f9e72..646c425c7 100644
--- a/core/binary_protocol/src/primitives/partition_assignment.rs
+++ b/core/binary_protocol/src/primitives/partition_assignment.rs
@@ -23,11 +23,14 @@ use bytes::{BufMut, BytesMut};
pub struct CreatedPartitionAssignment {
pub partition_id: u32,
pub consensus_group_id: u64,
+ /// Committed placement seed, sealed by the request body checksum and never
+ /// restamped when a later metadata view retransmits the create.
+ pub initial_view: u32,
}
impl CreatedPartitionAssignment {
- /// Fixed wire size: a `u32` partition id and a `u64` consensus group id.
- pub const ENCODED_SIZE: usize = 12;
+ /// Fixed wire size: partition id, consensus group id and initial view.
+ pub const ENCODED_SIZE: usize = 16;
}
impl WireEncode for CreatedPartitionAssignment {
@@ -38,6 +41,7 @@ impl WireEncode for CreatedPartitionAssignment {
fn encode(&self, buf: &mut BytesMut) {
buf.put_u32_le(self.partition_id);
buf.put_u64_le(self.consensus_group_id);
+ buf.put_u32_le(self.initial_view);
}
}
@@ -55,8 +59,9 @@ impl WireDecode for CreatedPartitionAssignment {
Self {
partition_id: read_u32_le(buf, 0)?,
consensus_group_id: read_u64_le(buf, 4)?,
+ initial_view: read_u32_le(buf, 12)?,
},
- 12,
+ Self::ENCODED_SIZE,
))
}
}
@@ -69,12 +74,21 @@ mod tests {
#[test]
fn roundtrip() {
let request = CreatedPartitionAssignment {
- partition_id: 7,
- consensus_group_id: 42,
+ partition_id: 0x0102_0304,
+ consensus_group_id: 0x0506_0708_090A_0B0C,
+ initial_view: 0x0D0E_0F10,
};
let bytes = request.to_bytes();
let (decoded, consumed) = CreatedPartitionAssignment::decode(&bytes).unwrap();
assert_eq!(consumed, bytes.len());
assert_eq!(decoded, request);
+ assert_eq!(bytes.len(), CreatedPartitionAssignment::ENCODED_SIZE);
+ assert_eq!(
+ bytes.as_ref(),
+ &[4, 3, 2, 1, 12, 11, 10, 9, 8, 7, 6, 5, 16, 15, 14, 13]
+ );
+ for truncated in 0..bytes.len() {
+ assert!(CreatedPartitionAssignment::decode(&bytes[..truncated]).is_err());
+ }
}
}
diff --git a/core/binary_protocol/src/requests/partitions/create_partitions_with_assignments.rs b/core/binary_protocol/src/requests/partitions/create_partitions_with_assignments.rs
index 904ed6e5f..d035906b0 100644
--- a/core/binary_protocol/src/requests/partitions/create_partitions_with_assignments.rs
+++ b/core/binary_protocol/src/requests/partitions/create_partitions_with_assignments.rs
@@ -29,10 +29,6 @@ fn usize_to_u32(value: usize, context: &str) -> u32 {
pub struct CreatePartitionsWithAssignmentsRequest {
pub request: CreatePartitionsRequest,
pub partitions: Vec<CreatedPartitionAssignment>,
- /// View the admitting primary minted this create in. Rides the body, which
- /// `checksum_body` seals, so unlike the header's `view` it is never restamped
- /// by a post-view-change retransmit: every replica decodes the same value.
- pub created_view: u32,
}
impl WireEncode for CreatePartitionsWithAssignmentsRequest {
@@ -44,7 +40,6 @@ impl WireEncode for CreatePartitionsWithAssignmentsRequest {
.iter()
.map(WireEncode::encoded_size)
.sum::<usize>()
- + 4
}
fn encode(&self, buf: &mut BytesMut) {
@@ -60,15 +55,31 @@ impl WireEncode for CreatePartitionsWithAssignmentsRequest {
for partition in &self.partitions {
partition.encode(buf);
}
- buf.put_u32_le(self.created_view);
}
}
impl WireDecode for CreatePartitionsWithAssignmentsRequest {
+ fn decode_from(buf: &[u8]) -> Result<Self, WireError> {
+ let (request, consumed) = Self::decode(buf)?;
+ if consumed != buf.len() {
+ return Err(WireError::Validation(
+ "trailing create partitions assignment bytes".into(),
+ ));
+ }
+ Ok(request)
+ }
+
fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> {
let request_size = read_u32_le(buf, 0)? as usize;
- let request_start = 4;
- let request_end = request_start + request_size;
+ let request_start: usize = 4;
+ let request_end =
+ request_start
+ .checked_add(request_size)
+ .ok_or_else(|| WireError::UnexpectedEof {
+ offset: request_start,
+ need: request_size,
+ have: buf.len().saturating_sub(request_start),
+ })?;
if buf.len() < request_end {
return Err(WireError::UnexpectedEof {
offset: request_start,
@@ -77,32 +88,35 @@ impl WireDecode for CreatePartitionsWithAssignmentsRequest {
});
}
- let request = CreatePartitionsRequest::decode_from(&buf[request_start..request_end])?;
+ let (request, consumed) =
+ CreatePartitionsRequest::decode(&buf[request_start..request_end])?;
+ if consumed != request_size {
+ return Err(WireError::Validation(
+ "trailing create partitions request bytes".into(),
+ ));
+ }
let partitions_count = read_u32_le(buf, request_end)? as usize;
+ if partitions_count != request.partitions_count as usize {
+ return Err(WireError::Validation(
+ "partition assignment count mismatch".into(),
+ ));
+ }
let mut offset = request_end + 4;
- let mut partitions = Vec::with_capacity(partitions_count);
+ let mut partitions = Vec::with_capacity(crate::codec::bounded_capacity(
+ partitions_count,
+ buf.len().saturating_sub(offset),
+ CreatedPartitionAssignment::ENCODED_SIZE,
+ ));
for _ in 0..partitions_count {
let (partition, consumed) = CreatedPartitionAssignment::decode(&buf[offset..])?;
offset += consumed;
partitions.push(partition);
}
- // Trailing field: entries journaled before it existed end here and read
- // 0, the view every plane starts in. 1-3 leftover bytes are corruption,
- // not an old shape, so they still error.
- let created_view = if offset < buf.len() {
- let view = read_u32_le(buf, offset)?;
- offset += 4;
- view
- } else {
- 0
- };
-
Ok((
Self {
request,
partitions,
- created_view,
},
offset,
))
@@ -112,10 +126,10 @@ impl WireDecode for CreatePartitionsWithAssignmentsRequest {
#[cfg(test)]
mod tests {
use super::CreatePartitionsWithAssignmentsRequest;
- use crate::WireIdentifier;
use crate::codec::{WireDecode, WireEncode};
use crate::primitives::partition_assignment::CreatedPartitionAssignment;
use crate::requests::partitions::CreatePartitionsRequest;
+ use crate::{WireError, WireIdentifier};
#[test]
fn roundtrip() {
@@ -127,44 +141,74 @@ mod tests {
},
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 9,
partition_id: 3,
consensus_group_id: 11,
},
CreatedPartitionAssignment {
+ initial_view: 10,
partition_id: 4,
consensus_group_id: 12,
},
],
- created_view: 9,
};
let bytes = request.to_bytes();
let (decoded, consumed) = CreatePartitionsWithAssignmentsRequest::decode(&bytes).unwrap();
assert_eq!(consumed, bytes.len());
assert_eq!(decoded, request);
+ assert_eq!(bytes.len(), request.encoded_size());
}
#[test]
- fn decode_without_trailing_view_reads_zero() {
- let request = CreatePartitionsWithAssignmentsRequest {
+ fn given_malformed_assignments_when_decoding_should_reject() {
+ let mut request = CreatePartitionsWithAssignmentsRequest {
request: CreatePartitionsRequest {
stream_id: WireIdentifier::numeric(1),
topic_id: WireIdentifier::numeric(2),
partitions_count: 1,
},
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 9,
partition_id: 3,
consensus_group_id: 11,
}],
- created_view: 9,
};
- // Bytes journaled before the field existed: same shape, no trailing u32.
let bytes = request.to_bytes();
- let old_bytes = &bytes[..bytes.len() - 4];
- let (decoded, consumed) =
- CreatePartitionsWithAssignmentsRequest::decode(old_bytes).unwrap();
- assert_eq!(consumed, old_bytes.len());
- assert_eq!(decoded.created_view, 0);
- assert_eq!(decoded.partitions, request.partitions);
- assert_eq!(decoded.request, request.request);
+ for truncated in 0..bytes.len() {
+ assert!(
+ CreatePartitionsWithAssignmentsRequest::decode_from(&bytes[..truncated]).is_err()
+ );
+ }
+ let mut trailing = bytes.to_vec();
+ trailing.push(0);
+ assert!(CreatePartitionsWithAssignmentsRequest::decode_from(&trailing).is_err());
+
+ let request_end = size_of::<u32>() + request.request.encoded_size();
+ let mut embedded_trailing = bytes.to_vec();
+ embedded_trailing.insert(request_end, 0);
+ embedded_trailing[..4].copy_from_slice(
+ &u32::try_from(request.request.encoded_size() + 1)
+ .unwrap()
+ .to_le_bytes(),
+ );
+ assert!(CreatePartitionsWithAssignmentsRequest::decode_from(&embedded_trailing).is_err());
+ assert!(matches!(
+ CreatePartitionsWithAssignmentsRequest::decode_from(&u32::MAX.to_le_bytes()),
+ Err(WireError::UnexpectedEof { .. })
+ ));
+
+ for count in [0, 2, u32::MAX] {
+ request.request.partitions_count = count;
+ assert!(matches!(
+ CreatePartitionsWithAssignmentsRequest::decode_from(&request.to_bytes()),
+ Err(WireError::Validation(_))
+ ));
+ }
+ let mut huge_count = request.to_bytes().to_vec();
+ huge_count[request_end..request_end + 4].copy_from_slice(&u32::MAX.to_le_bytes());
+ assert!(matches!(
+ CreatePartitionsWithAssignmentsRequest::decode_from(&huge_count),
+ Err(WireError::UnexpectedEof { .. })
+ ));
}
}
diff --git a/core/binary_protocol/src/requests/topics/create_topic_with_assignments.rs b/core/binary_protocol/src/requests/topics/create_topic_with_assignments.rs
index 632286530..a43e06a43 100644
--- a/core/binary_protocol/src/requests/topics/create_topic_with_assignments.rs
+++ b/core/binary_protocol/src/requests/topics/create_topic_with_assignments.rs
@@ -38,10 +38,6 @@ pub struct CreateTopicWithAssignmentsRequest {
pub request: CreateTopicRequest,
pub derived_options: WireOptions,
pub partitions: Vec<CreatedPartitionAssignment>,
- /// View the admitting primary minted this create in. Rides the body, which
- /// `checksum_body` seals, so unlike the header's `view` it is never restamped
- /// by a post-view-change retransmit: every replica decodes the same value.
- pub created_view: u32,
}
impl WireEncode for CreateTopicWithAssignmentsRequest {
@@ -55,7 +51,6 @@ impl WireEncode for CreateTopicWithAssignmentsRequest {
.iter()
.map(WireEncode::encoded_size)
.sum::<usize>()
- + 4
}
fn encode(&self, buf: &mut BytesMut) {
@@ -76,11 +71,20 @@ impl WireEncode for CreateTopicWithAssignmentsRequest {
for partition in &self.partitions {
partition.encode(buf);
}
- buf.put_u32_le(self.created_view);
}
}
impl WireDecode for CreateTopicWithAssignmentsRequest {
+ fn decode_from(buf: &[u8]) -> Result<Self, WireError> {
+ let (request, consumed) = Self::decode(buf)?;
+ if consumed != buf.len() {
+ return Err(WireError::Validation(
+ "trailing create topic assignment bytes".into(),
+ ));
+ }
+ Ok(request)
+ }
+
fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> {
let request_size = read_u32_le(buf, 0)? as usize;
let request_start: usize = 4;
@@ -104,12 +108,22 @@ impl WireDecode for CreateTopicWithAssignmentsRequest {
});
}
- let request = CreateTopicRequest::decode_from(&buf[request_start..request_end])?;
+ let (request, consumed) = CreateTopicRequest::decode(&buf[request_start..request_end])?;
+ if consumed != request_size {
+ return Err(WireError::Validation(
+ "trailing create topic request bytes".into(),
+ ));
+ }
let (derived_options, derived_consumed) = decode_options_prefixed(buf, request_end)?;
let derived_end = request_end + derived_consumed;
let partitions_count = read_u32_le(buf, derived_end)? as usize;
+ if partitions_count != request.partitions_count as usize {
+ return Err(WireError::Validation(
+ "partition assignment count mismatch".into(),
+ ));
+ }
let mut offset = derived_end + 4;
let mut partitions = Vec::with_capacity(crate::codec::bounded_capacity(
partitions_count,
@@ -122,23 +136,11 @@ impl WireDecode for CreateTopicWithAssignmentsRequest {
partitions.push(partition);
}
- // Trailing field: entries journaled before it existed end here and read
- // 0, the view every plane starts in. 1-3 leftover bytes are corruption,
- // not an old shape, so they still error.
- let created_view = if offset < buf.len() {
- let view = read_u32_le(buf, offset)?;
- offset += 4;
- view
- } else {
- 0
- };
-
Ok((
Self {
request,
derived_options,
partitions,
- created_view,
},
offset,
))
@@ -148,13 +150,13 @@ impl WireDecode for CreateTopicWithAssignmentsRequest {
#[cfg(test)]
mod tests {
use super::CreateTopicWithAssignmentsRequest;
- use crate::WireIdentifier;
use crate::codec::{WireDecode, WireEncode};
use crate::primitives::identifier::WireName;
use crate::primitives::options::WireOptions;
use crate::primitives::partition_assignment::CreatedPartitionAssignment;
use crate::primitives::user_headers::encode_user_headers;
use crate::requests::topics::CreateTopicRequest;
+ use crate::{WireError, WireIdentifier};
use bytes::BytesMut;
fn options_block(entries: &[(u8, &[u8], u8, &[u8])]) -> WireOptions {
@@ -175,25 +177,27 @@ mod tests {
derived_options: options_block(&[(2, b"max_topic_size", 12, &1024u64.to_le_bytes())]),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 7,
partition_id: 0,
consensus_group_id: 1,
},
CreatedPartitionAssignment {
+ initial_view: 8,
partition_id: 1,
consensus_group_id: 2,
},
],
- created_view: 7,
};
let bytes = request.to_bytes();
let (decoded, consumed) = CreateTopicWithAssignmentsRequest::decode(&bytes).unwrap();
assert_eq!(consumed, bytes.len());
assert_eq!(decoded, request);
+ assert_eq!(bytes.len(), request.encoded_size());
}
#[test]
- fn decode_without_trailing_view_reads_zero() {
- let request = CreateTopicWithAssignmentsRequest {
+ fn given_malformed_assignments_when_decoding_should_reject() {
+ let mut request = CreateTopicWithAssignmentsRequest {
request: CreateTopicRequest {
stream_id: WireIdentifier::numeric(1),
partitions_count: 1,
@@ -202,19 +206,47 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 7,
partition_id: 0,
consensus_group_id: 1,
}],
- created_view: 7,
};
- // Bytes journaled before the field existed: same shape, no trailing u32.
let bytes = request.to_bytes();
- let old_bytes = &bytes[..bytes.len() - 4];
- let (decoded, consumed) = CreateTopicWithAssignmentsRequest::decode(old_bytes).unwrap();
- assert_eq!(consumed, old_bytes.len());
- assert_eq!(decoded.created_view, 0);
- assert_eq!(decoded.partitions, request.partitions);
- assert_eq!(decoded.request, request.request);
+ for truncated in 0..bytes.len() {
+ assert!(CreateTopicWithAssignmentsRequest::decode_from(&bytes[..truncated]).is_err());
+ }
+ let mut trailing = bytes.to_vec();
+ trailing.push(0);
+ assert!(CreateTopicWithAssignmentsRequest::decode_from(&trailing).is_err());
+
+ let request_end = size_of::<u32>() + request.request.encoded_size();
+ let mut embedded_trailing = bytes.to_vec();
+ embedded_trailing.insert(request_end, 0);
+ embedded_trailing[..4].copy_from_slice(
+ &u32::try_from(request.request.encoded_size() + 1)
+ .unwrap()
+ .to_le_bytes(),
+ );
+ assert!(CreateTopicWithAssignmentsRequest::decode_from(&embedded_trailing).is_err());
+ assert!(matches!(
+ CreateTopicWithAssignmentsRequest::decode_from(&u32::MAX.to_le_bytes()),
+ Err(WireError::UnexpectedEof { .. })
+ ));
+
+ for count in [0, 2, u32::MAX] {
+ request.request.partitions_count = count;
+ assert!(matches!(
+ CreateTopicWithAssignmentsRequest::decode_from(&request.to_bytes()),
+ Err(WireError::Validation(_))
+ ));
+ }
+ let mut huge_count = request.to_bytes().to_vec();
+ let count_offset = huge_count.len() - CreatedPartitionAssignment::ENCODED_SIZE - 4;
+ huge_count[count_offset..count_offset + 4].copy_from_slice(&u32::MAX.to_le_bytes());
+ assert!(matches!(
+ CreateTopicWithAssignmentsRequest::decode_from(&huge_count),
+ Err(WireError::UnexpectedEof { .. })
+ ));
}
#[test]
@@ -228,7 +260,6 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![],
- created_view: 0,
};
let bytes = request.to_bytes();
let (decoded, consumed) = CreateTopicWithAssignmentsRequest::decode(&bytes).unwrap();
diff --git a/core/consensus/src/impls.rs b/core/consensus/src/impls.rs
index fd96e580a..00c636f74 100644
--- a/core/consensus/src/impls.rs
+++ b/core/consensus/src/impls.rs
@@ -1811,6 +1811,12 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
self.ceded_primaryship.get()
}
+ /// Normal status can persist while a newer view is being confirmed.
+ #[must_use]
+ pub const fn has_observed_newer_view(&self) -> bool {
+ self.observed_newer_view.get() > self.view.get()
+ }
+
/// Set the per-boot incarnation nonce, at boot before `init`. Production
/// supplies a random `u128`; the deterministic simulator supplies a
/// seed-derived value bumped per restart. See the `incarnation` field.
@@ -1838,6 +1844,42 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
self.primary_index(self.view.get()) == self.replica
}
+ /// Ask the partition quorum to elect `target` in the next view assigned to it.
+ /// A ready backup may initiate this too. Refusal leaves consensus unchanged.
+ /// The caller fences the incarnation, drains history work, refreshes the DVC
+ /// suffix and persists the new view before dispatching the returned actions.
+ pub fn request_primary_transfer(&self, expected_view: u32, target: u8) -> Vec<VsrAction> {
+ let view = self.view();
+ if self.group == METADATA_GROUP
+ || target >= self.replica_count
+ || view != expected_view
+ || !self.is_normal()
+ || self.has_ceded_primaryship()
+ || self.is_transferring()
+ || self.view_log_unproven()
+ || self.observed_newer_view.get() > view
+ || self.commit_min() != self.commit_max()
+ || self.commit_max() < self.recovery_barrier()
+ || !self.applied_view_start()
+ {
+ return Vec::new();
+ }
+ let primary = self.primary_index(view);
+ if target == primary {
+ return Vec::new();
+ }
+ let replicas = u32::from(self.replica_count);
+ let distance = (u32::from(target) + replicas - u32::from(primary)) % replicas;
+ let Some(next_view) = view.checked_add(distance) else {
+ return Vec::new();
+ };
+ self.enter_view_change(
+ PlaneKind::Partitions,
+ next_view,
+ ViewChangeReason::PrimaryTransfer,
+ )
+ }
+
/// Advance `commit_max` - the highest op known to be committed by the cluster.
///
/// Called when the replica learns about new commits from the primary
@@ -4140,6 +4182,8 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
};
let new_op = merged.op_head;
let max_commit = merged.commit_max;
+ // Repair can apply beyond the commit point frozen in the DVC merge.
+ let rebuild_after = self.commit_min().max(max_commit);
// The one view-change exit that skips `reset_view_change_state`, so the DVCs
// (a suffix `Vec` per sender, per group led) would be held for the whole
@@ -4189,7 +4233,7 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
timeouts.start(TimeoutKind::CommitMessage);
// If there are uncommitted ops in the rebuilt pipeline, start the
// Prepare timeout so that lost PrepareOks trigger retransmission.
- if max_commit < new_op {
+ if rebuild_after < new_op {
timeouts.start(TimeoutKind::Prepare);
}
}
@@ -4226,20 +4270,20 @@ impl<B: MessageBus, P: Pipeline<Entry = PipelineEntry>> VsrConsensus<B, P> {
actions.push(VsrAction::CommitJournal);
// The new primary must rebuild its pipeline from the journal so that
// incoming PrepareOk messages can be matched and commits can proceed.
- if max_commit < new_op {
+ if rebuild_after < new_op {
// `complete_view_change_as_primary` already refused a non-fitting
// range. Asserted so the sites cannot drift; this one cannot decline.
debug_assert!(
- (new_op - max_commit) <= self.prepare_queue_max as u64,
+ (new_op - rebuild_after) <= self.prepare_queue_max as u64,
"view change: uncommitted range {}..={} ({} ops) exceeds pipeline capacity ({}); \
the merged log claims more in-flight ops than the pipeline can hold",
- max_commit + 1,
+ rebuild_after + 1,
new_op,
- new_op - max_commit,
+ new_op - rebuild_after,
self.prepare_queue_max,
);
actions.push(VsrAction::RebuildPipeline {
- from_op: max_commit + 1,
+ from_op: rebuild_after + 1,
to_op: new_op,
});
}
@@ -4632,9 +4676,8 @@ mod fresh_group_start_tests {
const CREATED_VIEW: u32 = 4;
- /// The case the seed exists for: a group created after the metadata plane
- /// elected must not start at view 0, or it names a replica the roster does
- /// not advertise and no client can be routed to it.
+ /// Fresh replicas must agree on the committed assignment's initial view,
+ /// including a chosen view above zero, before the group starts serving.
#[test]
fn given_a_fresh_group_when_created_after_an_election_should_seed_the_creation_view() {
let start = fresh_group_start(false, None, CREATED_VIEW);
@@ -5629,6 +5672,7 @@ mod timestamp_clamp_tests {
#[cfg(test)]
mod vsr_consensus_tests {
use super::*;
+ use futures::FutureExt;
use message_bus::BusMessage;
#[test]
@@ -5705,6 +5749,237 @@ mod vsr_consensus_tests {
assert!(!consensus.is_transferring());
}
+ #[test]
+ fn given_ready_replica_when_requesting_primary_transfer_should_select_next_target_view() {
+ const REPLICAS: u8 = 5;
+ const INCARNATION: u64 = 17;
+ for (replica, view, target, next_view) in [
+ (1, 0, 3, 3),
+ (3, 6, 3, 8),
+ (1, 6, 4, 9),
+ (2, 9, 1, 11),
+ (2, 4, 0, 5),
+ (2, u32::MAX - 1, 0, u32::MAX),
+ ] {
+ let mut consensus =
+ VsrConsensus::new(1, replica, REPLICAS, 0, StageNoopBus, LocalPipeline::new());
+ consensus.set_view(view);
+ consensus.set_log_view(view);
+ consensus.set_partition_incarnation(INCARNATION);
+ consensus.mark_superblock_durable(view, view);
+ consensus.init();
+
+ let actions = consensus.request_primary_transfer(view, target);
+
+ assert!(matches!(
+ actions.as_slice(),
+ [VsrAction::SendStartViewChange { view, group: 0 }] if *view == next_view
+ ));
+ assert_eq!(consensus.view(), next_view);
+ assert_eq!(consensus.primary_index(next_view), target);
+ assert_eq!(consensus.status(), Status::ViewChange);
+ assert_eq!(consensus.log_view(), view);
+ assert_eq!(consensus.partition_incarnation(), INCARNATION);
+ assert!(consensus.needs_superblock_persist());
+ assert_eq!(consensus.svc_count_excluding_self(), 0);
+ assert!(consensus.sent_own_start_view_change.get());
+ }
+ }
+
+ #[test]
+ fn given_backup_transfer_when_primary_receives_svc_should_join_the_target_election() {
+ const TARGET: u8 = 2;
+ let backup = VsrConsensus::new(1, 1, 3, 0, StageNoopBus, LocalPipeline::new());
+ let primary = VsrConsensus::new(1, 0, 3, 0, StageNoopBus, LocalPipeline::new());
+ backup.init();
+ primary.init();
+ assert!(!backup.request_primary_transfer(0, TARGET).is_empty());
+ assert_eq!(primary.status(), Status::Normal);
+
+ let message = Message::<StartViewChangeHeader>::new(size_of::<StartViewChangeHeader>())
+ .transmute_header(|_, header: &mut StartViewChangeHeader| {
+ header.command = Command::StartViewChange;
+ header.cluster = 1;
+ header.replica = backup.replica();
+ header.view = backup.view();
+ header.group = backup.group();
+ header.size = u32::try_from(size_of::<StartViewChangeHeader>()).unwrap();
+ header.seal();
+ });
+ let actions = primary.handle_start_view_change(PlaneKind::Partitions, message.header());
+
+ assert_eq!(primary.view(), u32::from(TARGET));
+ assert_eq!(primary.status(), Status::ViewChange);
+ assert_eq!(primary.log_view(), 0);
+ assert!(
+ actions.iter().any(|action| matches!(
+ action,
+ VsrAction::SendStartViewChange { view: 2, group: 0 }
+ ))
+ );
+ assert!(actions.iter().any(|action| matches!(
+ action,
+ VsrAction::SendDoViewChange {
+ target: TARGET,
+ view: 2,
+ ..
+ }
+ )));
+ assert!(primary.pending_view_log().is_none());
+ }
+
+ #[test]
+ fn given_pending_mutation_when_requesting_primary_transfer_should_preserve_identity_and_wake_waiter()
+ {
+ const COMMITTED: u64 = 7;
+ const INCARNATION: u64 = 17;
+ let consensus = VsrConsensus::new(1, 0, 3, 0, StageNoopBus, LocalPipeline::new());
+ consensus.init();
+ consensus.set_partition_incarnation(INCARNATION);
+ consensus.sequencer().set_sequence(COMMITTED);
+ consensus.restore_commit_state(COMMITTED, COMMITTED);
+ let message = projected_prepare(COMMITTED + 1, 0xfeed).transmute_header(
+ |previous, header: &mut PrepareHeader| {
+ *header = previous;
+ header.operation = Operation::SendMessages;
+ header.client = 31;
+ header.session = 37;
+ header.request = 41;
+ header.partition_incarnation = INCARNATION;
+ },
+ );
+ let receiver = consensus.pipeline_message_with_subscriber(PlaneKind::Partitions, &message);
+ let pending = *message.header();
+ let checksum = consensus.last_prepare_checksum();
+
+ assert!(!consensus.request_primary_transfer(0, 2).is_empty());
+
+ assert_eq!(consensus.commit_min(), COMMITTED);
+ assert_eq!(consensus.commit_max(), COMMITTED);
+ assert_eq!(consensus.sequencer().current_sequence(), pending.op);
+ assert_eq!(consensus.last_prepare_checksum(), checksum);
+ consensus.with_pipeline(|pipeline| {
+ let entry = pipeline.entry_by_op(pending.op).unwrap();
+ assert_eq!(
+ bytemuck::bytes_of(&entry.header),
+ bytemuck::bytes_of(&pending)
+ );
+ assert!(!entry.has_reply_sender());
+ });
+ assert!(matches!(
+ receiver.now_or_never(),
+ Some(Err(crate::oneshot::Canceled))
+ ));
+ assert_eq!(consensus.log_view(), 0);
+ }
+
+ #[test]
+ fn given_unready_or_stale_transfer_when_requested_should_leave_consensus_unchanged() {
+ const VIEW: u32 = 6;
+ for reason in [
+ "stale view",
+ "existing primary",
+ "unknown target",
+ "recovering",
+ "view change",
+ "ceded",
+ "state transfer",
+ "unproved history",
+ "newer view observed",
+ "unapplied commit",
+ "recovery barrier",
+ "view start head",
+ ] {
+ let mut consensus = VsrConsensus::new(1, 2, 5, 0, StageNoopBus, LocalPipeline::new());
+ consensus.set_view(VIEW);
+ consensus.set_log_view(VIEW);
+ consensus.mark_superblock_durable(VIEW, VIEW);
+ consensus.init();
+ let mut expected_view = VIEW;
+ let mut target = 3;
+ match reason {
+ "stale view" => expected_view -= 1,
+ "existing primary" => target = consensus.primary_index(VIEW),
+ "unknown target" => target = consensus.replica_count(),
+ "recovering" => consensus.begin_view_probe(),
+ "view change" => {
+ let _ = consensus.enter_view_change(
+ PlaneKind::Partitions,
+ VIEW,
+ ViewChangeReason::ReceivedStartViewChange,
+ );
+ }
+ "ceded" => consensus.init_as_backup(),
+ "state transfer" => consensus.begin_state_transfer_await(),
+ "unproved history" => consensus.fence_view_log(1, 1),
+ "newer view observed" => consensus.observe_newer_view(VIEW + 1),
+ "unapplied commit" => consensus.advance_commit_max(1),
+ "recovery barrier" => consensus.set_recovery_barrier(1),
+ "view start head" => consensus.view_start_head.set(1),
+ _ => unreachable!(),
+ }
+ let before = (
+ consensus.view(),
+ consensus.log_view(),
+ consensus.status(),
+ consensus.commit_min(),
+ consensus.commit_max(),
+ consensus.sequencer().current_sequence(),
+ consensus.svc_count_excluding_self(),
+ consensus.sent_own_start_view_change.get(),
+ consensus.needs_superblock_persist(),
+ );
+ let timers = format!("{:?}", consensus.timeouts.borrow());
+
+ assert!(
+ consensus
+ .request_primary_transfer(expected_view, target)
+ .is_empty(),
+ "accepted {reason}"
+ );
+
+ assert_eq!(
+ before,
+ (
+ consensus.view(),
+ consensus.log_view(),
+ consensus.status(),
+ consensus.commit_min(),
+ consensus.commit_max(),
+ consensus.sequencer().current_sequence(),
+ consensus.svc_count_excluding_self(),
+ consensus.sent_own_start_view_change.get(),
+ consensus.needs_superblock_persist(),
+ ),
+ "mutated {reason}"
+ );
+ assert_eq!(
+ timers,
+ format!("{:?}", consensus.timeouts.borrow()),
+ "rearmed {reason}"
+ );
+ }
+ }
+
+ #[test]
+ fn given_metadata_or_exhausted_view_when_requesting_primary_transfer_should_refuse() {
+ for (group, view) in [(METADATA_GROUP, 0), (0, u32::MAX)] {
+ let mut consensus =
+ VsrConsensus::new(1, 0, 5, group, StageNoopBus, LocalPipeline::new());
+ consensus.set_view(view);
+ consensus.set_log_view(view);
+ consensus.mark_superblock_durable(view, view);
+ consensus.init();
+
+ assert!(consensus.request_primary_transfer(view, 1).is_empty());
+ assert_eq!(consensus.view(), view);
+ assert_eq!(consensus.log_view(), view);
+ assert_eq!(consensus.status(), Status::Normal);
+ assert!(!consensus.needs_superblock_persist());
+ assert!(!consensus.sent_own_start_view_change.get());
+ }
+ }
+
// A backup left behind on VIEW (partition healed across an election, or a
// fresh node that never saw it) keeps getting newer-view heartbeats it
// cannot process -- they never reset its heartbeat timer, so the timer
diff --git a/core/consensus/src/observability.rs b/core/consensus/src/observability.rs
index d85a4da4e..8696e2d44 100644
--- a/core/consensus/src/observability.rs
+++ b/core/consensus/src/observability.rs
@@ -56,6 +56,7 @@ impl ReplicaRole {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViewChangeReason {
NormalHeartbeatTimeout,
+ PrimaryTransfer,
/// The current view's primary sent a `RequestStartView` probe: it
/// cannot lead (restarted, or abandoned the view mid-view-change), so
/// peers elect without waiting for its heartbeats to stop arriving
@@ -75,6 +76,7 @@ impl ViewChangeReason {
pub const fn as_str(self) -> &'static str {
match self {
Self::NormalHeartbeatTimeout => "normal_heartbeat_timeout",
+ Self::PrimaryTransfer => "primary_transfer",
Self::PrimaryProbedView => "primary_probed_view",
Self::ViewProbeUnanswered => "view_probe_unanswered",
Self::ViewChangeStatusTimeout => "view_change_status_timeout",
diff --git a/core/consensus/src/plane_helpers.rs b/core/consensus/src/plane_helpers.rs
index 7b743f22f..ea5e33cf9 100644
--- a/core/consensus/src/plane_helpers.rs
+++ b/core/consensus/src/plane_helpers.rs
@@ -2017,6 +2017,102 @@ mod tests {
assert!(consensus.applied_view_start());
}
+ #[test]
+ fn given_parked_view_repair_when_starting_should_rebuild_only_unapplied_ops() {
+ const MERGED_COMMIT: u64 = 2;
+ const HEAD: u64 = 5;
+ const VIEW: u32 = 3;
+
+ for (applied_before, repaired_to, expected_start) in [
+ (2, 3, Some(4)),
+ (2, 5, None),
+ (2, 2, Some(3)),
+ (0, 0, Some(3)),
+ ] {
+ let consensus = VsrConsensus::new(1, 0, 3, 0, NoopBus, LocalPipeline::new());
+ consensus.init();
+ consensus.restore_commit_state(applied_before, MERGED_COMMIT);
+ consensus.sequencer().set_sequence(HEAD);
+ install_local_suffix(&consensus, HEAD, MERGED_COMMIT, 0);
+ let _ = consensus.handle_start_view_change(PlaneKind::Metadata, &svc_header(1, VIEW));
+ let (dvc, body) = dvc_with_full_suffix(2, VIEW, 0, HEAD, MERGED_COMMIT);
+ let _ = consensus.handle_do_view_change(PlaneKind::Metadata, &dvc, &body);
+ let merged = consensus.pending_view_log().expect("the view is parked");
+ assert_eq!(merged.commit_max, MERGED_COMMIT);
+
+ // Repair may apply a verified prefix after the DVC quorum is frozen.
+ for op in applied_before + 1..=repaired_to {
+ consensus.advance_commit_max(op);
+ consensus.advance_commit_min(op);
+ }
+ assert_eq!(consensus.log_view(), 0);
+ consensus.settle_view_log_proof();
+ let actions = consensus.start_pending_view(PlaneKind::Metadata);
+ let mut rebuilt_from = None;
+ for action in actions {
+ match action {
+ VsrAction::CommitJournal => {
+ for op in consensus.commit_min() + 1..=consensus.commit_max() {
+ consensus.advance_commit_min(op);
+ }
+ }
+ VsrAction::RebuildPipeline { from_op, to_op } => {
+ rebuilt_from = Some(from_op);
+ assert_eq!(to_op, HEAD);
+ consensus.with_pipeline_mut(|pipeline| {
+ for op in from_op..=to_op {
+ let header = *merged
+ .headers
+ .iter()
+ .find(|header| header.op == op)
+ .expect("the decided history is available");
+ let mut entry = PipelineEntry::new(header);
+ entry.add_ack(consensus.replica());
+ pipeline.push(entry);
+ }
+ });
+ }
+ _ => {}
+ }
+ }
+ assert_eq!(
+ rebuilt_from, expected_start,
+ "repair applied through {repaired_to}"
+ );
+
+ for header in merged
+ .headers
+ .iter()
+ .rev()
+ .filter(|header| header.op > repaired_to.max(MERGED_COMMIT))
+ {
+ let ack = PrepareOkHeader {
+ command: Command::PrepareOk,
+ view: VIEW,
+ replica: 1,
+ op: header.op,
+ prepare_checksum: header.checksum,
+ ..Default::default()
+ };
+ assert!(ack_quorum_reached(&consensus, PlaneKind::Metadata, &ack));
+ let ready = peek_committable_head(&consensus)
+ .expect("the next op must commit in this view");
+ assert_eq!(ready.checksum, header.checksum);
+ assert_eq!(consensus.pop_committed_prepare().unwrap().header, ready);
+ consensus.advance_commit_min(ready.op);
+ }
+ assert_eq!(consensus.view(), VIEW);
+ assert_eq!(consensus.status(), Status::Normal);
+ assert_eq!(consensus.commit_min(), HEAD);
+ assert!(consensus.pipeline_is_empty());
+ assert!(consensus.applied_view_start());
+ assert_eq!(
+ consensus.last_prepare_checksum(),
+ merged.headers[0].checksum
+ );
+ }
+ }
+
#[test]
fn loopback_cleared_on_complete_view_change_as_primary() {
// 3 replicas, replica 0 is primary for view 0 (and view 3: 3 % 3 = 0).
diff --git a/core/integration/tests/cluster/partition_primary_routing.rs b/core/integration/tests/cluster/partition_primary_routing.rs
index 5bdb574b0..0d8f5376d 100644
--- a/core/integration/tests/cluster/partition_primary_routing.rs
+++ b/core/integration/tests/cluster/partition_primary_routing.rs
@@ -16,7 +16,7 @@
// under the License.
//! Metadata and partition consensus groups choose primaries independently.
-//! New partitions must inherit the metadata view, while existing partitions
+//! New partitions use their committed placement views, while existing partitions
//! can retain a different primary after a metadata-only election. SDK clients
//! settle on the metadata leader, so both writes to new partitions and group
//! polls of existing partitions must reach an owner that can commit progress.
@@ -102,6 +102,7 @@ const SEND_BUDGET: Duration = Duration::from_secs(20);
/// the state this test needs before it can observe anything.
const PRECONDITION_BUDGET: Duration = Duration::from_secs(20);
const PRECONDITION_POLL: Duration = Duration::from_millis(500);
+const REBALANCE_BUDGET: Duration = Duration::from_secs(120);
fn message(payload: &str) -> IggyMessage {
IggyMessage::from_str(payload).expect("build message")
@@ -119,8 +120,406 @@ fn send_body(payload: &str) -> SendMessages {
}
}
+async fn partition_route(
+ client: &TcpClient,
+ stream: &Identifier,
+ topic: &Identifier,
+ partition_id: u32,
+) -> PartitionRouteResponse {
+ let request = GetPartitionRouteRequest {
+ stream_id: identifier_to_wire(stream).unwrap(),
+ topic_id: identifier_to_wire(topic).unwrap(),
+ partition_id,
+ }
+ .to_bytes();
+ timeout(PRECONDITION_BUDGET, async {
+ loop {
+ match client
+ .send_raw_with_response(GET_PARTITION_ROUTE_CODE, request.clone())
+ .await
+ {
+ Ok(reply) => break PartitionRouteResponse::decode_from(&reply).unwrap(),
+ Err(IggyError::TransientNotAccepted) => sleep(PRECONDITION_POLL).await,
+ Err(error) => panic!("route {stream}/{topic}/{partition_id}: {error}"),
+ }
+ }
+ })
+ .await
+ .unwrap_or_else(|_| panic!("partition {stream}/{topic}/{partition_id} never became routable"))
+}
+
+#[iggy_harness(cluster_nodes = 3, server(sharding.cpu_allocation = "2"))]
+async fn given_concurrent_creates_when_growing_partitions_should_spread_and_serve_every_partition(
+ harness: &mut TestHarness,
+) {
+ const FIRST_TOPIC: &str = "spread-first";
+ const SECOND_TOPIC: &str = "spread-second";
+ const THIRD_TOPIC: &str = "spread-third";
+ const INITIAL_PARTITIONS: u32 = 3;
+ const ADDED_PARTITIONS: u32 = 3;
+ const SECOND_PARTITIONS: u32 = 2;
+ const THIRD_PARTITIONS: u32 = 4;
+
+ let first = connect_without_login(harness.node(0).tcp_addr().unwrap()).await;
+ first
+ .login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
+ .await
+ .unwrap();
+ let second = connect_without_login(harness.node(0).tcp_addr().unwrap()).await;
+ second
+ .login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
+ .await
+ .unwrap();
+ first.create_stream(STREAM_NAME).await.unwrap();
+ let stream = Identifier::named(STREAM_NAME).unwrap();
+ let options = TopicCreateOptions {
+ partitions_count: Some(INITIAL_PARTITIONS),
+ durability: Durability::Persisted,
+ message_expiry: Some(IggyExpiry::NeverExpire),
+ ..TopicCreateOptions::default()
+ };
+ first
+ .create_topic(&stream, FIRST_TOPIC, &options)
+ .await
+ .unwrap();
+ let first_topic = Identifier::named(FIRST_TOPIC).unwrap();
+ for partition_id in 0..INITIAL_PARTITIONS {
+ let route = partition_route(&first, &stream, &first_topic, partition_id).await;
+ assert_eq!(u32::from(route.primary_replica), partition_id);
+ assert_eq!(route.view, partition_id);
+ }
+
+ let second_options = TopicCreateOptions {
+ partitions_count: Some(SECOND_PARTITIONS),
+ ..options.clone()
+ };
+ let third_options = TopicCreateOptions {
+ partitions_count: Some(THIRD_PARTITIONS),
+ ..options
+ };
+ let (second_result, third_result) = futures::join!(
+ first.create_topic(&stream, SECOND_TOPIC, &second_options),
+ second.create_topic(&stream, THIRD_TOPIC, &third_options),
+ );
+ second_result.unwrap();
+ third_result.unwrap();
+ let mut topics = [
+ (FIRST_TOPIC, INITIAL_PARTITIONS),
+ (SECOND_TOPIC, SECOND_PARTITIONS),
+ (THIRD_TOPIC, THIRD_PARTITIONS),
+ ];
+ assert_initial_spread(&first, &stream, &topics, harness.cluster_size()).await;
+ first
+ .create_partitions(&stream, &first_topic, ADDED_PARTITIONS)
+ .await
+ .unwrap();
+ topics[0].1 += ADDED_PARTITIONS;
+ assert_initial_spread(&first, &stream, &topics, harness.cluster_size()).await;
+
+ let mut original_routes = Vec::new();
+ for (name, count) in topics {
+ let topic = Identifier::named(name).unwrap();
+ for partition_id in 0..count {
+ let route = partition_route(&first, &stream, &topic, partition_id).await;
+ original_routes.push((name, partition_id, route));
+ let payload = format!("{name}-{partition_id}");
+ let mut messages = vec![message(&payload)];
+ first
+ .send_messages(
+ &stream,
+ &topic,
+ &Partitioning::partition_id(partition_id),
+ &mut messages,
+ )
+ .await
+ .unwrap();
+ assert_partition_payload(&second, &stream, &topic, partition_id, &payload).await;
+ }
+ }
+ drop(first);
+ drop(second);
+ for node in 0..harness.cluster_size() {
+ harness.stop_node(node).unwrap();
+ }
+ for node in 0..harness.cluster_size() {
+ harness.restart_node(node).unwrap();
+ }
+ let recovered = connect_without_login(harness.node(0).tcp_addr().unwrap()).await;
+ recovered
+ .login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
+ .await
+ .unwrap();
+ for (name, partition_id, original) in original_routes {
+ let topic = Identifier::named(name).unwrap();
+ let route = partition_route(&recovered, &stream, &topic, partition_id).await;
+ assert_eq!(route.incarnation, original.incarnation);
+ assert_eq!(route.partitions_count, original.partitions_count);
+ assert!(route.view >= original.view, "{name}/{partition_id}");
+ let payload = format!("{name}-{partition_id}");
+ assert_partition_payload(&recovered, &stream, &topic, partition_id, &payload).await;
+ }
+}
+
+async fn assert_initial_spread(
+ client: &TcpClient,
+ stream: &Identifier,
+ topics: &[(&str, u32)],
+ replicas: usize,
+) {
+ let mut primary_counts = vec![0_u32; replicas];
+ for &(name, count) in topics {
+ let topic = Identifier::named(name).unwrap();
+ for partition_id in 0..count {
+ let route = partition_route(client, stream, &topic, partition_id).await;
+ assert_eq!(route.view, u32::from(route.primary_replica));
+ primary_counts[usize::from(route.primary_replica)] += 1;
+ }
+ }
+ let total: u32 = topics.iter().map(|(_, count)| count).sum();
+ assert_eq!(
+ primary_counts,
+ vec![total / u32::try_from(replicas).unwrap(); replicas],
+ "create batches and growth must count already admitted assignments"
+ );
+}
+
+async fn assert_partition_payload(
+ client: &TcpClient,
+ stream: &Identifier,
+ topic: &Identifier,
+ partition_id: u32,
+ expected: &str,
+) {
+ let polled = client
+ .poll_messages(
+ stream,
+ topic,
+ Some(partition_id),
+ &Consumer::default(),
+ &PollingStrategy::offset(0),
+ 1,
+ false,
+ )
+ .await
+ .unwrap();
+ assert_eq!(polled.messages.len(), 1, "{topic}/{partition_id}");
+ assert_eq!(polled.messages[0].payload.as_ref(), expected.as_bytes());
+}
+
+#[iggy_harness(cluster_nodes = 5, server(sharding.cpu_allocation = "2"))]
+async fn given_balanced_primaries_when_a_replica_fails_and_returns_should_rebalance_without_data_loss(
+ harness: &mut TestHarness,
+) {
+ const TOPIC_COUNT: usize = 100;
+ const PHASES: [&str; 3] = ["before-failure", "while-absent", "after-return"];
+
+ let client = connect_without_login(harness.node(1).tcp_addr().unwrap()).await;
+ client
+ .login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
+ .await
+ .unwrap();
+ let identity = client.session_identity().await.unwrap();
+ client.create_stream(STREAM_NAME).await.unwrap();
+ let stream = Identifier::named(STREAM_NAME).unwrap();
+ let options = TopicCreateOptions {
+ partitions_count: Some(1),
+ durability: Durability::Persisted,
+ message_expiry: Some(IggyExpiry::NeverExpire),
+ ..TopicCreateOptions::default()
+ };
+ let mut topics = Vec::with_capacity(TOPIC_COUNT);
+ for index in 0..TOPIC_COUNT {
+ let name = format!("rebalance-{index}");
+ client.create_topic(&stream, &name, &options).await.unwrap();
+ topics.push(Identifier::named(&name).unwrap());
+ }
+ let mut request = RequestHeader {
+ client: identity.client_id,
+ session: identity.session,
+ request: RAW_REQUEST_START,
+ ..Default::default()
+ };
+ let initial =
+ wait_for_balanced_routes(harness, &client, &stream, &topics, &[20; 5], &mut request).await;
+ append_and_assert_partition_sentinels(&client, &stream, &topics, &PHASES[..1]).await;
+
+ harness.kill_node(0).unwrap();
+ let surviving = wait_for_balanced_routes(
+ harness,
+ &client,
+ &stream,
+ &topics,
+ &[0, 25, 25, 25, 25],
+ &mut request,
+ )
+ .await;
+ append_and_assert_partition_sentinels(&client, &stream, &topics, &PHASES[..2]).await;
+
+ harness.restart_node(0).unwrap();
+ let returned =
+ wait_for_balanced_routes(harness, &client, &stream, &topics, &[20; 5], &mut request).await;
+ for (index, original) in initial.iter().enumerate() {
+ assert_ne!(original.incarnation, 0);
+ for current in [&surviving[index], &returned[index]] {
+ assert_eq!(
+ current.incarnation, original.incarnation,
+ "{}",
+ topics[index]
+ );
+ assert_eq!(current.partitions_count, 1, "{}", topics[index]);
+ assert!(current.view >= original.view, "{}", topics[index]);
+ }
+ assert!(
+ returned[index].view >= surviving[index].view,
+ "{}",
+ topics[index]
+ );
+ }
+ append_and_assert_partition_sentinels(&client, &stream, &topics, &PHASES).await;
+ let current_identity = client.session_identity().await.unwrap();
+ assert_eq!(current_identity.client_id, identity.client_id);
+ assert_eq!(current_identity.session, identity.session);
+}
+
+async fn wait_for_balanced_routes(
+ harness: &TestHarness,
+ client: &TcpClient,
+ stream: &Identifier,
+ topics: &[Identifier],
+ expected_counts: &[usize],
+ request: &mut RequestHeader,
+) -> Vec<PartitionRouteResponse> {
+ let mut last_counts = vec![vec![0; expected_counts.len()]; expected_counts.len()];
+ timeout(REBALANCE_BUDGET, async {
+ let binding = BindSessionRequest {
+ version_info: ClientVersionInfo {
+ protocol_version: IGGY_PROTOCOL_VERSION,
+ sdk_name: WireName::new("routing-test").unwrap(),
+ sdk_version: WireName::new("1.0.0").unwrap(),
+ },
+ identity: client.session_identity().await.unwrap(),
+ bind_secret: client.session_bind_secret().await.unwrap(),
+ }
+ .to_bytes();
+ let route_requests: Vec<_> = topics
+ .iter()
+ .map(|topic| {
+ GetPartitionRouteRequest {
+ stream_id: identifier_to_wire(stream).unwrap(),
+ topic_id: identifier_to_wire(topic).unwrap(),
+ partition_id: PARTITION_ID,
+ }
+ .to_bytes()
+ })
+ .collect();
+ let mut observers = Vec::with_capacity(expected_counts.len());
+ for (node, count) in expected_counts.iter().enumerate() {
+ if *count == 0 {
+ continue;
+ }
+ let address = harness.node(node).tcp_addr().unwrap();
+ let mut socket = raw_tcp::connect_to(address).await;
+ loop {
+ match data_request(&mut socket, request, BIND_SESSION_CODE, &binding, None).await {
+ Ok(_) => break,
+ Err(IggyError::TransientNotAccepted) => sleep(PRECONDITION_POLL).await,
+ Err(error) => panic!("node {node} refused the existing session: {error:?}"),
+ }
+ }
+ assert_eq!(socket.peer_addr().unwrap(), address);
+ observers.push((node, socket));
+ }
+ loop {
+ let mut snapshots = Vec::with_capacity(observers.len());
+ for (node, socket) in &mut observers {
+ let mut routes = Vec::with_capacity(topics.len());
+ for body in &route_requests {
+ match data_request(socket, request, GET_PARTITION_ROUTE_CODE, body, None).await {
+ Ok(body) => routes.push(PartitionRouteResponse::decode_from(&body).unwrap()),
+ Err(IggyError::TransientNotAccepted) => break,
+ Err(error) => panic!("node {node} refused a partition route: {error:?}"),
+ }
+ }
+ if routes.len() != topics.len() {
+ break;
+ }
+ let mut counts = vec![0; expected_counts.len()];
+ for route in &routes {
+ counts[usize::from(route.primary_replica)] += 1;
+ }
+ last_counts[*node].clone_from(&counts);
+ if counts != expected_counts {
+ break;
+ }
+ snapshots.push(routes);
+ }
+ if snapshots.len() == observers.len()
+ && snapshots.windows(2).all(|pair| {
+ pair[0].iter().zip(&pair[1]).all(|(left, right)| {
+ (left.incarnation, left.partitions_count, left.view, left.primary_replica)
+ == (right.incarnation, right.partitions_count, right.view, right.primary_replica)
+ })
+ })
+ {
+ return snapshots.remove(0);
+ }
+ sleep(PRECONDITION_POLL).await;
+ }
+ })
+ .await
+ .unwrap_or_else(|_| {
+ panic!(
+ "partition primaries did not converge to {expected_counts:?} within {REBALANCE_BUDGET:?}; \
+ physical-node observations: {last_counts:?}"
+ )
+ })
+}
+
+async fn append_and_assert_partition_sentinels(
+ client: &TcpClient,
+ stream: &Identifier,
+ topics: &[Identifier],
+ phases: &[&str],
+) {
+ timeout(REBALANCE_BUDGET, async {
+ for topic in topics {
+ let payload = format!("{topic}:{}", phases.last().unwrap());
+ client
+ .send_messages(
+ stream,
+ topic,
+ &Partitioning::partition_id(PARTITION_ID),
+ &mut [message(&payload)],
+ )
+ .await
+ .unwrap();
+ let polled = client
+ .poll_messages(
+ stream,
+ topic,
+ Some(PARTITION_ID),
+ &Consumer::default(),
+ &PollingStrategy::offset(0),
+ u32::try_from(phases.len() + 1).unwrap(),
+ false,
+ )
+ .await
+ .unwrap();
+ assert_eq!(polled.messages.len(), phases.len(), "{topic}");
+ for (message, phase) in polled.messages.iter().zip(phases) {
+ assert_eq!(
+ message.payload.as_ref(),
+ format!("{topic}:{phase}").as_bytes()
+ );
+ }
+ }
+ })
+ .await
+ .expect("every partition must preserve and serve its history across rebalancing");
+}
+
#[iggy_harness(cluster_nodes = 3)]
-async fn given_metadata_view_moved_when_producing_to_a_fresh_topic_should_reach_the_advertised_leader(
+async fn given_metadata_view_moved_when_creating_topic_should_route_to_its_assigned_primary(
harness: &mut TestHarness,
) {
// Kill node 0: it is the view-0 primary of BOTH planes, so the metadata
@@ -159,9 +558,8 @@ async fn given_metadata_view_moved_when_producing_to_a_fresh_topic_should_reach_
}
};
- // A brand-new topic. Its partition group is seeded from the metadata view,
- // so its primary is the advertised leader; left at view 0 it would be
- // replica 0, the node that was just killed and restarted.
+ // With no existing partitions, the placement tie goes to replica 0,
+ // independently of the metadata primary elected above.
let setup = harness
.root_client_for_node(leader)
.await
@@ -186,6 +584,14 @@ async fn given_metadata_view_moved_when_producing_to_a_fresh_topic_should_reach_
.expect("create topic");
let topic_id = Identifier::named(TOPIC_NAME).expect("topic identifier");
let partitioning = Partitioning::partition_id(PARTITION_ID);
+ let route_client = connect_without_login(harness.node(leader).tcp_addr().unwrap()).await;
+ route_client
+ .login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
+ .await
+ .unwrap();
+ let route = partition_route(&route_client, &stream_id, &topic_id, PARTITION_ID).await;
+ assert_eq!(route.primary_replica, 0);
+ assert_eq!(route.view, INITIAL_VIEW);
// Where a client asking for node 0 actually ends up.
let leader_address = harness
@@ -211,10 +617,8 @@ async fn given_metadata_view_moved_when_producing_to_a_fresh_topic_should_reach_
is testing a different node than this test claims"
);
- // The contract: the node the roster advertises accepts a partition write.
- // Seeded from the metadata view the group's primary IS that node; left at
- // view 0 it would be replica 0, and every client would be steered away
- // from the only node that could accept.
+ // The session connection follows metadata leadership, while the write
+ // must reach the independently assigned partition primary.
let accepted_by_leader = send_once(&on_node_zero, &stream_id, &topic_id, &partitioning).await;
assert!(
accepted_by_leader.is_ok(),
diff --git a/core/integration/tests/cluster/staggered_bootstrap.rs b/core/integration/tests/cluster/staggered_bootstrap.rs
index 2103a3722..b3598df63 100644
--- a/core/integration/tests/cluster/staggered_bootstrap.rs
+++ b/core/integration/tests/cluster/staggered_bootstrap.rs
@@ -33,10 +33,9 @@
//!
//! Two independent things are asserted, because they can fail separately:
//!
-//! - A topic created while replica 0 is absent is writable at the advertised
-//! leader. This is the routing contract, and it holds only because a fresh
-//! partition group seeds its view from the metadata plane rather than
-//! starting at view 0 (which would name replica 0, the node that was late).
+//! - After replica 0 joins, a new topic is writable through a client connected
+//! to the metadata leader. Partition placement chooses its primary separately,
+//! so the client must route the write to the assigned owner.
//! - The late replica converges. It missed the ops committed before it
//! arrived, and the harness's usual all-nodes mesh gate is what normally
//! guarantees no node is ever in that position.
@@ -122,10 +121,8 @@ async fn given_replica_zero_arrives_late_when_producing_to_a_fresh_topic_should_
let topic_id = Identifier::named(TOPIC_NAME).expect("topic identifier");
let partitioning = Partitioning::partition_id(PARTITION_ID);
- // The routing contract. The partition group is brand new, so its view is
- // whatever it was seeded with: the metadata view, which is not 0 here.
- // Seeded at 0 instead it would name replica 0, the node that arrived late,
- // and no client could be told to go there.
+ // The session follows metadata leadership; partition writes must reach
+ // the independently assigned owner.
let mut messages = vec![message("probe")];
let accepted = tokio::time::timeout(
SEND_BUDGET,
diff --git a/core/message_bus/src/lib.rs b/core/message_bus/src/lib.rs
index 0662eeff6..9a4900420 100644
--- a/core/message_bus/src/lib.rs
+++ b/core/message_bus/src/lib.rs
@@ -684,6 +684,12 @@ pub trait MessageBus {
iggy_common::IggyTimestamp::now().as_micros()
}
+ /// Monotonic time for local deadlines, independent of message-pump progress.
+ /// Simulator overrides must share one timeline across replicas and restarts.
+ fn monotonic_now(&self) -> Instant {
+ Instant::now()
+ }
+
/// Drain this bus's plaintext replica socket-read counters.
///
/// The provided default returns zeros so the simulator bus and the
@@ -1359,7 +1365,7 @@ impl<T: MessageBus + ?Sized> MessageBus for std::rc::Rc<T> {
}
// Forward the defaulted methods too. Without this, a `Rc`-wrapped bus that
- // overrides `sleep`/`spawn`/`realtime_micros` (the simulator's virtual timer,
+ // overrides `sleep`/`spawn`/clock reads (the simulator's virtual timer,
// spawn queue, and virtual clock) would be silently reverted to the defaults
// through the wrapper. No-op for production, whose `IggyMessageBus` uses those
// defaults anyway.
@@ -1375,6 +1381,10 @@ impl<T: MessageBus + ?Sized> MessageBus for std::rc::Rc<T> {
(**self).realtime_micros()
}
+ fn monotonic_now(&self) -> Instant {
+ (**self).monotonic_now()
+ }
+
fn take_replica_read_stats(&self) -> ReplicaReadMetrics {
(**self).take_replica_read_stats()
}
diff --git a/core/message_bus/src/transports/quic.rs b/core/message_bus/src/transports/quic.rs
index 77548aa15..04fdbea5e 100644
--- a/core/message_bus/src/transports/quic.rs
+++ b/core/message_bus/src/transports/quic.rs
@@ -340,7 +340,7 @@ fn read_u64(bytes: &[u8], offset: usize) -> Option<u64> {
struct ReplyRouter {
/// Waiting streams by request id, oldest first.
waiters: HashMap<u64, VecDeque<oneshot::Sender<BusMessage>>>,
- /// Frames that came while no stream waited for them, oldest first.
+ /// Keyed replies that came while no stream waited for them, oldest first.
unclaimed: VecDeque<BusMessage>,
/// When `unclaimed` holds this many frames, it drops its oldest one.
unclaimed_max: usize,
@@ -357,15 +357,15 @@ impl ReplyRouter {
/// Register a stream that waits for the reply to `request_id`.
///
- /// The stream first takes the oldest unclaimed frame that has no request
- /// id or has its own. The SDK replays an explicit transient with the same
+ /// The stream first takes the oldest unclaimed reply with its request
+ /// id. The SDK replays an explicit transient with the same
/// request id on a new stream, so a late reply of the first attempt
/// answers the replay. The replies for other ids ahead of that frame are
/// dropped, because their streams already ended.
fn register(&mut self, request_id: u64) -> oneshot::Receiver<BusMessage> {
let (waiter, reply) = oneshot::channel();
while let Some(frame) = self.unclaimed.pop_front() {
- if !matches!(reply_route(&frame), ReplyRoute::Keyed(id) if id != request_id) {
+ if matches!(reply_route(&frame), ReplyRoute::Keyed(id) if id == request_id) {
// `reply` is alive, so the send cannot fail.
let _ = waiter.send(frame);
return reply;
@@ -380,11 +380,15 @@ impl ReplyRouter {
/// Hand a reply to the oldest waiter of its request id, and a frame
/// without one to every waiter, because an eviction ends every request
- /// of the connection. A frame no stream takes stays unclaimed.
+ /// of the connection. Only keyed replies can wait for a future stream;
+ /// an old eviction must not answer a newly registered request.
fn route(&mut self, frame: BusMessage) {
let unclaimed = match reply_route(&frame) {
ReplyRoute::Keyed(request_id) => self.deliver(request_id, frame),
- ReplyRoute::Unkeyed => self.broadcast(frame),
+ ReplyRoute::Unkeyed => {
+ self.broadcast(&frame);
+ None
+ }
};
if let Some(frame) = unclaimed {
if self.unclaimed.len() == self.unclaimed_max {
@@ -424,13 +428,10 @@ impl ReplyRouter {
unclaimed
}
- /// Returns the frame if no waiter took it.
- fn broadcast(&mut self, frame: BusMessage) -> Option<BusMessage> {
- let mut delivered = false;
+ fn broadcast(&mut self, frame: &BusMessage) {
for waiter in self.waiters.drain().flat_map(|(_, waiters)| waiters) {
- delivered |= waiter.send(frame.clone()).is_ok();
+ let _ = waiter.send(frame.clone());
}
- (!delivered).then_some(frame)
}
}
@@ -686,11 +687,16 @@ mod tests {
use crate::lifecycle::{FusedShutdown, Shutdown};
use async_channel::bounded;
use compio::io::AsyncWrite;
+ use compio::net::UdpSocket;
use compio_quic::ClientBuilder;
use iggy_binary_protocol::{Command, GenericHeader, HEADER_SIZE, Operation, SIZE_FIELD_OFFSET};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use server_common::iobuf::Frozen;
use server_common::{MESSAGE_ALIGN, Message};
+ use std::cell::Cell;
+ use std::future::Future;
+ use std::rc::Rc;
+ use std::task::Poll;
use std::time::Duration;
const TEST_CLIENT: u128 = 1;
@@ -1142,6 +1148,84 @@ mod tests {
assert_eq!(routed_commit(&mut second), Some(SECOND_COMMIT));
}
+ #[test]
+ fn given_no_live_waiters_when_an_eviction_arrives_should_not_reach_a_later_stream() {
+ for canceled_waiter in [false, true] {
+ let mut router = ReplyRouter::new(UNCLAIMED_MAX);
+ if canceled_waiter {
+ drop(router.register(FIRST_REQUEST));
+ }
+ router.route(header_only(Command::Eviction).into());
+ let mut later = router.register(SECOND_REQUEST);
+ assert!(
+ later.try_recv().unwrap().is_none(),
+ "an eviction with no live waiter must not answer a later request"
+ );
+ router.route(reply(SECOND_REQUEST, SECOND_COMMIT));
+ assert_eq!(routed_commit(&mut later), Some(SECOND_COMMIT));
+ assert!(router.unclaimed.is_empty());
+ }
+ }
+
+ #[compio::test]
+ async fn given_an_unclaimed_eviction_when_a_new_quic_stream_opens_should_receive_its_reply() {
+ let (conn, client, _endpoints) = connect(ONE_STREAM).await;
+ let (outbound, inbound, shutdown, server) = drive(conn);
+ outbound
+ .send(header_only(Command::Eviction).into())
+ .await
+ .unwrap();
+ // Routing finishes in the same poll as dequeue, before another task can run.
+ compio::time::timeout(
+ TEST_WAIT,
+ futures::future::poll_fn(|cx| {
+ if outbound.is_empty() {
+ Poll::Ready(())
+ } else {
+ cx.waker().wake_by_ref();
+ Poll::Pending
+ }
+ }),
+ )
+ .await
+ .expect("the transport routed the eviction before the next stream opens");
+
+ let mut response = send_request(&client, SECOND_REQUEST).await;
+ assert_eq!(forwarded(&inbound).await, SECOND_REQUEST);
+ outbound
+ .send(reply(SECOND_REQUEST, SECOND_COMMIT))
+ .await
+ .unwrap();
+ let answer = read_answer(&mut response).await;
+ assert_eq!(answer.header().command, Command::Reply);
+ assert_eq!(reply_header(answer.as_slice()).request, SECOND_REQUEST);
+ assert_eq!(reply_header(answer.as_slice()).commit, SECOND_COMMIT);
+
+ shutdown.trigger();
+ compio::time::timeout(TEST_WAIT, server)
+ .await
+ .unwrap()
+ .unwrap();
+ }
+
+ #[test]
+ fn given_live_waiters_when_evicted_should_broadcast_only_to_existing_streams() {
+ let mut router = ReplyRouter::new(UNCLAIMED_MAX);
+ let mut first = router.register(FIRST_REQUEST);
+ let mut second = router.register(SECOND_REQUEST);
+ router.route(header_only(Command::Eviction).into());
+ for receiver in [&mut first, &mut second] {
+ assert_eq!(
+ receiver.try_recv().unwrap().unwrap().first().as_slice()[COMMAND_OFFSET],
+ Command::Eviction as u8
+ );
+ }
+ let mut later = router.register(FIRST_REQUEST);
+ assert!(later.try_recv().unwrap().is_none());
+ router.route(reply(FIRST_REQUEST, SECOND_COMMIT));
+ assert_eq!(routed_commit(&mut later), Some(SECOND_COMMIT));
+ }
+
/// A late reply waits for the stream that replays its request id. The
/// replies for other ids ahead of it are dropped, so a later stream with
/// such an id gets only its own reply.
@@ -1233,6 +1317,129 @@ mod tests {
.expect("the server exits normally");
}
+ #[compio::test]
+ #[allow(clippy::too_many_lines)]
+ async fn given_reply_fin_before_shutdown_when_ack_arrives_late_should_drain_before_closing() {
+ const MAX_UDP_DATAGRAM_SIZE: usize = u16::MAX as usize;
+ install_crypto_provider();
+ let (cert, key) = self_signed();
+ let server = server_endpoint(cert.clone(), key, &tuning(ONE_STREAM)).await;
+ let server_addr = server.local_addr().unwrap();
+ let listener = QuicTransportListener::new(server);
+ let client_endpoint = client_endpoint(cert).await;
+ let relay = Rc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
+ let hold_upstream = Rc::new(Cell::new(false));
+ let held_packet = Rc::new(RefCell::new(None));
+ let (held_tx, held_rx) = bounded(1);
+ let relay_socket = Rc::clone(&relay);
+ let relay_hold = Rc::clone(&hold_upstream);
+ let relay_packet = Rc::clone(&held_packet);
+ let relay_task = compio::runtime::spawn(async move {
+ let mut client_addr = None;
+ loop {
+ let BufResult(result, mut packet) =
+ relay_socket.recv_from(vec![0; MAX_UDP_DATAGRAM_SIZE]).await;
+ let (length, source) = result.unwrap();
+ packet.truncate(length);
+ let destination = if source == server_addr {
+ client_addr.expect("client starts the handshake")
+ } else {
+ client_addr = Some(source);
+ if relay_hold.get() {
+ *relay_packet.borrow_mut() = Some(packet);
+ let _ = held_tx.try_send(());
+ continue;
+ }
+ server_addr
+ };
+ let BufResult(sent, _) = relay_socket.send_to(packet, destination).await;
+ assert_eq!(sent.unwrap(), length);
+ }
+ });
+ let connecting = client_endpoint
+ .connect(relay.local_addr().unwrap(), "localhost", None)
+ .unwrap();
+ let (accepted, client) = futures::join!(listener.accept(), connecting);
+ let (conn, _) = accepted.unwrap();
+ let server_connection = conn.connection.clone();
+ let client = client.unwrap();
+ let (outbound, out_rx) = bounded(1);
+ let (in_tx, inbound) = bounded(1);
+ let (shutdown, token) = Shutdown::new();
+ let shutdown_observer = shutdown.clone();
+ let (polled_tx, polled_rx) = bounded(1);
+ let ctx = ActorContext {
+ in_tx,
+ rx: out_rx,
+ shutdown: FusedShutdown::single(token),
+ conn_shutdown: shutdown.clone(),
+ max_batch: 1,
+ max_message_size: framing::MAX_MESSAGE_SIZE,
+ label: "late-ack-test",
+ peer: "relay".to_string(),
+ };
+ let mut run = Box::pin(conn.with_close_grace(TEST_WAIT).run(ctx));
+ let server_task = compio::runtime::spawn(futures::future::poll_fn(move |cx| {
+ let result = run.as_mut().poll(cx);
+ if shutdown_observer.is_triggered() {
+ let _ = polled_tx.try_send(result.is_pending());
+ }
+ result
+ }));
+
+ let mut response = send_request(&client, FIRST_REQUEST).await;
+ assert_eq!(forwarded(&inbound).await, FIRST_REQUEST);
+ let acks_before_reply = client.stats().frame_tx.acks;
+ hold_upstream.set(true);
+ outbound
+ .send(reply(FIRST_REQUEST, FIRST_COMMIT))
+ .await
+ .unwrap();
+ let BufResult(received, bytes) =
+ compio::time::timeout(TEST_WAIT, response.read_to_end(Vec::new()))
+ .await
+ .expect("reply and FIN arrive while upstream ACKs are held");
+ assert_eq!(received.unwrap(), HEADER_SIZE);
+ assert_eq!(reply_header(&bytes).commit, FIRST_COMMIT);
+ compio::time::timeout(TEST_WAIT, async {
+ while client.stats().frame_tx.acks == acks_before_reply
+ || held_packet.borrow().is_none()
+ {
+ held_rx.recv().await.unwrap();
+ }
+ })
+ .await
+ .expect("client generated an ACK and relay retained upstream traffic");
+
+ shutdown.trigger();
+ assert!(
+ compio::time::timeout(TEST_WAIT, polled_rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ "the real transport must remain pending after shutdown while its FIN is unacknowledged"
+ );
+ let acks_before_release = server_connection.stats().frame_rx.acks;
+ hold_upstream.set(false);
+ let packet = held_packet
+ .borrow_mut()
+ .take()
+ .expect("held upstream packet");
+ let BufResult(sent, _) = relay.send_to(packet, server_addr).await;
+ sent.unwrap();
+ compio::time::timeout(TEST_WAIT, server_task)
+ .await
+ .expect("late ACK releases the drain within close_grace")
+ .unwrap();
+ assert!(
+ server_connection.stats().frame_rx.acks > acks_before_release,
+ "the drain completes after a late ACK reaches the server"
+ );
+ compio::time::timeout(TEST_WAIT, relay_task.cancel())
+ .await
+ .expect("relay task releases its socket within the test bound");
+ }
+
#[compio::test]
#[allow(clippy::future_not_send)]
async fn given_missing_reply_when_shutdown_grace_expires_should_close_within_the_bound() {
diff --git a/core/metadata/src/impls/metadata.rs b/core/metadata/src/impls/metadata.rs
index 2f7e19cb8..20a0374c1 100644
--- a/core/metadata/src/impls/metadata.rs
+++ b/core/metadata/src/impls/metadata.rs
@@ -17,6 +17,7 @@
use crate::MuxStateMachine;
use crate::applied_frontier::AppliedFrontier;
+use crate::impls::placement::PlacementState;
use crate::stm::authz::{PartitionsCreate, admits_partitions_create, gated_apply};
use crate::stm::consumer_group::CompleteConsumerGroupRevocationRequest;
use crate::stm::snapshot::{
@@ -68,6 +69,7 @@ use message_bus::MessageBus;
use server_common::Message;
use server_common::fatal::NoteDescriptorExhaustion;
use server_common::iobuf::{Frozen, Owned};
+use server_common::sharding::IggyNamespace;
use std::cell::{Cell, RefCell};
use std::io;
#[cfg(feature = "simulator")]
@@ -87,6 +89,25 @@ fn freeze_client_reply(
message.into_frozen()
}
+/// Last locally observed normal view of one committed partition incarnation.
+/// Absence of a newer report preserves this view; it is not a health signal.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PartitionPlacementView {
+ pub namespace: IggyNamespace,
+ pub created_revision: u64,
+ pub view: u32,
+}
+
+/// One suggested transfer, fenced by the observed view and committed incarnation.
+/// Execution must separately confirm source and target partition readiness.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PartitionPrimaryTransfer {
+ pub namespace: IggyNamespace,
+ pub created_revision: u64,
+ pub view: u32,
+ pub target: u8,
+}
+
pub trait StreamsFrontend {
#[must_use]
fn users(&self) -> &Users;
@@ -993,6 +1014,7 @@ pub struct IggyMetadata<C, J, S, M, SB = PingPongSuperblock> {
/// `LeftRight::read` panic. See `server/src/boot::shard_main`.
pub mux_stm: Rc<M>,
pub allocator: ConsensusGroupAllocator,
+ placement: RefCell<PlacementState>,
/// Snapshot coordinator - present when persistent checkpointing is configured.
pub coordinator: Option<SnapshotCoordinator<M>>,
/// Serializes `on_replicate`'s journal-mutation section (forced
@@ -1101,6 +1123,7 @@ where
superblock_retry_after_micros: Cell::new(0),
mux_stm,
allocator,
+ placement: RefCell::default(),
coordinator,
journal_gate: LocalGate::new(),
client_table: RefCell::new(ClientTable::new(CLIENTS_TABLE_MAX)),
@@ -1354,6 +1377,7 @@ where
Error = iggy_common::IggyError,
>,
{
+ #[allow(clippy::too_many_lines)]
async fn on_request(
&self,
message: <VsrConsensus<B> as Consensus>::Message<RoutedRequestHeader>,
@@ -1439,8 +1463,24 @@ where
return;
}
+ let request_header = *message.header();
let prepare = match self.prepare_request(message) {
Ok(prepare) => prepare,
+ Err(IggyError::TransientNotAccepted) => {
+ let reply = build_result_rejection_reply(
+ &request_header,
+ consensus.commit_max(),
+ IggyError::TransientNotAccepted.as_code(),
+ );
+ if let Err(error) = consensus
+ .message_bus()
+ .send_to_client(client_id, freeze_client_reply(reply.into_generic()))
+ .await
+ {
+ debug!(%error, client_id, "placement admission refusal could not reach client");
+ }
+ return;
+ }
Err(error) => {
// Structurally-invalid request (not client-allowed, undecodable
// body, or partition-id overflow). Evict instead of dropping: a
@@ -3190,13 +3230,22 @@ where
// The acting-user RBAC stamp lives in the shared `prepare_request`
// (op-guarded, fail-closed on an unknown session). `request_preflight`
// above proved this client's session is live, so it resolves there.
- let Ok(prepare) = self.prepare_request(message) else {
- // Structurally-invalid request. Return an eviction frame (relayed to
- // the socket by the home shard) rather than `Canceled`, which leaves
- // the shard silent and the SDK retrying forever.
- let reason = eviction_reason_for_invalid(request_header.operation);
- let ctx = EvictionContext::from_consensus(consensus);
- return Ok(build_eviction_message(ctx, client_id, reason).into_generic());
+ let prepare = match self.prepare_request(message) {
+ Ok(prepare) => prepare,
+ Err(IggyError::TransientNotAccepted) => {
+ return Ok(build_result_rejection_reply(
+ &request_header,
+ consensus.commit_max(),
+ IggyError::TransientNotAccepted.as_code(),
+ )
+ .into_generic());
+ }
+ Err(_) => {
+ // Malformed requests retain the existing session eviction policy.
+ let reason = eviction_reason_for_invalid(request_header.operation);
+ let ctx = EvictionContext::from_consensus(consensus);
+ return Ok(build_eviction_message(ctx, client_id, reason).into_generic());
+ }
};
// A view change canceled the pending prepare before commit. The op may
@@ -3579,7 +3628,7 @@ where
/// client's watermark between push and drain (`Duplicate` /
/// `AlreadyApplied` / `AlreadyRegistered`). Skipping produces a duplicate
/// prepare and panics.
- #[allow(clippy::future_not_send)]
+ #[allow(clippy::future_not_send, clippy::too_many_lines)]
async fn drain_request_queue_into_prepares(&self) {
let consensus = self.consensus.as_ref().unwrap();
// Promote while prepare slots exist. Requests are queued for two
@@ -3642,8 +3691,26 @@ where
continue;
}
+ let request_header = *req.message.header();
let prepare = match self.prepare_request(req.message) {
Ok(prepare) => prepare,
+ Err(IggyError::TransientNotAccepted) => {
+ let reply = build_result_rejection_reply(
+ &request_header,
+ consensus.commit_max(),
+ IggyError::TransientNotAccepted.as_code(),
+ );
+ if let Some(sender) = reply_sender {
+ let _ = sender.send(reply);
+ } else if let Err(error) = consensus
+ .message_bus()
+ .send_to_client(client_id, freeze_client_reply(reply.into_generic()))
+ .await
+ {
+ debug!(%error, client_id, "queued placement admission refusal could not reach client");
+ }
+ continue;
+ }
Err(error) => {
// Same invariant as `on_request`: a structurally-invalid
// request evicts, never a silent drop, or the SDK retries
@@ -3959,6 +4026,129 @@ where
);
}
+ /// Merge locally published normal views without treating missing reports as
+ /// failures. Incarnation checks keep deleted namespaces from transferring load.
+ pub fn observe_partition_views(&self, reports: &[PartitionPlacementView]) {
+ self.placement
+ .borrow_mut()
+ .observe(self.mux_stm.streams(), reports);
+ }
+
+ /// Suggest one count-balancing move only after normal failover has settled.
+ /// `after` rotates candidates so a recovering target cannot starve other groups.
+ pub fn primary_rebalance_candidate(
+ &self,
+ eligible: &[bool],
+ after: Option<IggyNamespace>,
+ ) -> Option<PartitionPrimaryTransfer> {
+ self.placement.borrow().primary_rebalance_candidate(
+ self.mux_stm.streams(),
+ self.consensus.as_ref()?.replica_count(),
+ eligible,
+ after,
+ )
+ }
+
+ /// Return an observed normal view only for the current, unblocked incarnation.
+ pub fn partition_placement_view(
+ &self,
+ namespace: IggyNamespace,
+ created_revision: u64,
+ ) -> Option<PartitionPlacementView> {
+ self.placement.borrow().partition_placement_view(
+ self.mux_stm.streams(),
+ namespace,
+ created_revision,
+ )
+ }
+
+ /// Reconstruct at most one missing reservation per metadata tick. Admission
+ /// stays synchronous and refuses creates until every canonical summary exists.
+ #[allow(clippy::future_not_send)]
+ pub async fn refresh_placement(&self) {
+ let (Some(consensus), Some(journal)) = (self.consensus.as_ref(), self.journal.as_ref())
+ else {
+ return;
+ };
+ let Ok(headers) = self.pending_placement_headers() else {
+ return;
+ };
+ let Some(header) = headers
+ .into_iter()
+ .find(|header| !self.placement.borrow().contains(header))
+ else {
+ return;
+ };
+ let view = consensus.view();
+ let Some(prepare) = journal.handle().entry(&header).await else {
+ return;
+ };
+ if prepare.header().op != header.op
+ || prepare.header().checksum != header.checksum
+ || verify_prepare_integrity(prepare.header(), prepare.as_slice()).is_err()
+ || consensus.view() != view
+ || !is_caught_up_primary(consensus)
+ || header.op <= consensus.commit_min()
+ || !consensus.pipeline_holds_entry(header.op, header.checksum)
+ {
+ return;
+ }
+ if let Ok(Some(highest_group_id)) = self
+ .placement
+ .borrow_mut()
+ .remember(&prepare, consensus.replica_count())
+ {
+ self.allocator.observe(highest_group_id);
+ }
+ }
+
+ fn placement_counts(&self) -> Result<Vec<u64>, IggyError> {
+ let headers = self.pending_placement_headers()?;
+ let consensus = self.consensus.as_ref().unwrap();
+ let mut placement = self.placement.borrow_mut();
+ let mut counts =
+ placement.committed_counts(self.mux_stm.streams(), consensus.replica_count());
+ for header in headers {
+ placement.add_reservation(&header, &mut counts)?;
+ }
+ Ok(counts)
+ }
+
+ fn pending_placement_headers(&self) -> Result<Vec<PrepareHeader>, IggyError> {
+ let consensus = self
+ .consensus
+ .as_ref()
+ .ok_or(IggyError::TransientNotAccepted)?;
+ if !is_caught_up_primary(consensus) {
+ return Err(IggyError::TransientNotAccepted);
+ }
+ self.placement.borrow_mut().prune(|op, checksum| {
+ op > consensus.commit_min() && consensus.pipeline_holds_entry(op, checksum)
+ });
+ consensus.with_pipeline(|pipeline| {
+ let committed = consensus.commit_min();
+ let sequence = consensus.sequencer().current_sequence();
+ if sequence < committed || sequence - committed > pipeline.prepare_queue_max() as u64 {
+ return Err(IggyError::TransientNotAccepted);
+ }
+ let mut headers = Vec::new();
+ for op in committed.saturating_add(1)..=sequence {
+ let header = pipeline
+ .entry_by_op(op)
+ .ok_or(IggyError::TransientNotAccepted)?
+ .header;
+ if matches!(
+ header.operation,
+ Operation::CreateTopicWithAssignments
+ | Operation::CreatePartitionsWithAssignments
+ ) {
+ headers.push(header);
+ }
+ }
+ Ok(headers)
+ })
+ }
+
#[allow(clippy::too_many_lines)]
fn prepare_request(
&self,
@@ -4097,6 +4287,7 @@ where
},
&supplied_options,
)?;
+ let mut counts = self.placement_counts()?;
let partitions = self
.allocator
.allocate_many(request.partitions_count as usize)
@@ -4107,6 +4298,7 @@ where
partition_id: u32::try_from(partition_id)
.map_err(|_| IggyError::InvalidCommand)?,
consensus_group_id,
+ initial_view: PlacementState::select(&mut counts)?,
})
})
.collect::<Result<Vec<_>, _>>()?;
@@ -4114,11 +4306,6 @@ where
request,
derived_options,
partitions,
- // Minted once here, on the admitting primary, and sealed by
- // `checksum_body`: the header's `view` is restamped on a
- // post-view-change retransmit, so a body-carried copy is the
- // only per-op view every replica commits identically.
- created_view: consensus.view(),
}
.to_bytes();
Ok(build_prepare_message(
@@ -4136,6 +4323,7 @@ where
// read here would decide against possibly-uncommitted state and
// drop without a reply (TOCTOU + wedge). See the metadata
// validation design doc.
+ let mut counts = self.placement_counts()?;
let partitions = self
.allocator
.allocate_many(request.partitions_count as usize)
@@ -4146,14 +4334,13 @@ where
partition_id: u32::try_from(offset)
.map_err(|_| IggyError::InvalidCommand)?,
consensus_group_id,
+ initial_view: PlacementState::select(&mut counts)?,
})
})
.collect::<Result<Vec<_>, _>>()?;
let body = PersistedCreatePartitionsRequest {
request,
partitions,
- // Same body-carried view as `PersistedCreateTopicRequest`.
- created_view: consensus.view(),
}
.to_bytes();
Ok(build_prepare_message(
@@ -4169,10 +4356,14 @@ where
// node default frozen at update time.
_ => Ok(message.project(consensus)),
}?;
- Ok(consensus::seal_prepare_capacity(
+ let prepare = consensus::seal_prepare_capacity(
prepare,
consensus.retry_capacity(&self.client_table.borrow()),
- ))
+ );
+ self.placement
+ .borrow_mut()
+ .remember(&prepare, consensus.replica_count())?;
+ Ok(prepare)
}
/// Replicate a prepare message to the next replica in the chain.
@@ -5436,10 +5627,20 @@ mod tests {
wire_user_id: u32,
stream_id: WireIdentifier,
name: &str,
+ ) -> Message<RoutedRequestHeader> {
+ create_topic_request_with_count(client, wire_user_id, stream_id, name, 1)
+ }
+
+ fn create_topic_request_with_count(
+ client: u128,
+ wire_user_id: u32,
+ stream_id: WireIdentifier,
+ name: &str,
+ partitions_count: u32,
) -> Message<RoutedRequestHeader> {
let body = CreateTopicRequest {
stream_id,
- partitions_count: 1,
+ partitions_count,
name: WireName::new(name).unwrap(),
options: WireOptions::empty(),
}
@@ -5467,6 +5668,441 @@ mod tests {
message
}
+ fn placement_metadata() -> IggyMetadata<VsrConsensus<NoopBus>, PrepareJournal, (), TestMux> {
+ placement_metadata_with_bus(NoopBus)
+ }
+
+ fn placement_metadata_with_bus<B: MessageBus>(
+ bus: B,
+ ) -> IggyMetadata<VsrConsensus<B>, PrepareJournal, (), TestMux> {
+ let consensus = VsrConsensus::new(
+ 1,
+ 0,
+ 3,
+ server_common::sharding::METADATA_GROUP,
+ bus,
+ LocalPipeline::new(),
+ );
+ consensus.init();
+ let metadata =
+ IggyMetadata::new(Some(consensus), None, None, None, TestMux::default(), None);
+ for client in 1..=3 {
+ metadata
+ .client_table
+ .borrow_mut()
+ .commit_register(client, 0, [0x5a; 32], register_reply(client, 1))
+ .unwrap();
+ }
+ metadata
+ }
+
+ fn placement_request(client: u128, name: &str, count: u32) -> Message<RoutedRequestHeader> {
+ create_topic_request_with_count(client, 0, WireIdentifier::numeric(0), name, count)
+ }
+
+ fn assigned_views(prepare: &Message<PrepareHeader>) -> Vec<u32> {
+ PersistedCreateTopicRequest::decode_from(prepare.body())
+ .unwrap()
+ .partitions
+ .into_iter()
+ .map(|partition| partition.initial_view)
+ .collect()
+ }
+
+ #[test]
+ fn given_pending_placement_when_admitting_another_batch_should_spread_before_wal_append() {
+ let metadata = placement_metadata();
+ let consensus = metadata.consensus.as_ref().unwrap();
+ let first = metadata
+ .prepare_request(placement_request(1, "first", 4))
+ .unwrap();
+ assert_eq!(assigned_views(&first), [0, 1, 2, 0]);
+ consensus.pipeline_message(PlaneKind::Metadata, &first);
+ let second = metadata
+ .prepare_request(placement_request(2, "second", 2))
+ .unwrap();
+ assert_eq!(
+ assigned_views(&second),
+ [1, 2],
+ "admitted assignments reserve load before append can yield"
+ );
+ assert!(metadata.journal.is_none());
+ }
+
+ #[test]
+ fn given_rolled_back_placement_when_admitting_another_batch_should_release_reservations() {
+ let metadata = placement_metadata();
+ let consensus = metadata.consensus.as_ref().unwrap();
+ let first = metadata
+ .prepare_request(placement_request(1, "first", 2))
+ .unwrap();
+ consensus.pipeline_message(PlaneKind::Metadata, &first);
+ assert_eq!(
+ consensus.rollback_pipelined_prepare(first.header()),
+ PrepareRollback::Unwound
+ );
+ let second = metadata
+ .prepare_request(placement_request(2, "second", 1))
+ .unwrap();
+ assert_eq!(assigned_views(&second), [0]);
+ }
+
+ #[test]
+ fn given_rejected_create_when_committed_should_release_its_placement_reservations() {
+ let metadata = placement_metadata();
+ let consensus = metadata.consensus.as_ref().unwrap();
+ let first = metadata
+ .prepare_request(placement_request(1, "missing-stream", 2))
+ .unwrap();
+ consensus.pipeline_message(PlaneKind::Metadata, &first);
+ consensus.with_pipeline_mut(|pipeline| {
+ pipeline.pop().unwrap();
+ });
+ let op = first.header().op;
+ let reply = metadata.apply_prepare(first);
+ assert_ne!(iggy_binary_protocol::result_code(reply.body()), Some(0));
+ consensus.advance_commit_max(op);
+ consensus.advance_commit_min(op);
+ let second = metadata
+ .prepare_request(placement_request(2, "next", 1))
+ .unwrap();
+ assert_eq!(
+ assigned_views(&second),
+ [0],
+ "a committed rejection leaves no partition load"
+ );
+ }
+
+ #[test]
+ fn given_committed_create_when_admitting_another_should_count_it_once() {
+ let mut metadata = placement_metadata();
+ metadata.mux_stm = Rc::new(TestMux::new((
+ users_with_topic_manager(),
+ (stream_with_one_partition().into(), ()),
+ )));
+ let consensus = metadata.consensus.as_ref().unwrap();
+ let first = metadata
+ .prepare_request(placement_request(1, "new-topic", 2))
+ .unwrap();
+ assert_eq!(assigned_views(&first), [1, 2]);
+ consensus.pipeline_message(PlaneKind::Metadata, &first);
+ consensus.with_pipeline_mut(|pipeline| {
+ pipeline.pop().unwrap();
+ });
+ let op = first.header().op;
+ let reply = metadata.apply_prepare(first);
+ assert_eq!(iggy_binary_protocol::result_code(reply.body()), Some(0));
+ consensus.advance_commit_max(op);
+ consensus.advance_commit_min(op);
+ let second = metadata
+ .prepare_request(placement_request(2, "next", 1))
+ .unwrap();
+ assert_eq!(assigned_views(&second), [0]);
+ }
+
+ #[test]
+ fn given_missing_pipeline_entry_when_creating_should_refuse_without_allocating() {
+ let metadata = placement_metadata();
+ let consensus = metadata.consensus.as_ref().unwrap();
+ consensus.sequencer().set_sequence(1);
+ assert!(matches!(
+ metadata.prepare_request(placement_request(1, "missing", 2)),
+ Err(IggyError::TransientNotAccepted)
+ ));
+ consensus.sequencer().set_sequence(0);
+ let first = metadata
+ .prepare_request(placement_request(1, "ready", 1))
+ .unwrap();
+ let assignments = PersistedCreateTopicRequest::decode_from(first.body())
+ .unwrap()
+ .partitions;
+ assert_eq!(
+ assignments[0].consensus_group_id, 1,
+ "refusal cannot consume group ids"
+ );
+ assert_eq!(assignments[0].initial_view, 0);
+ }
+
+ #[test]
+ fn given_unknown_session_when_creating_should_not_allocate_groups() {
+ let metadata = placement_metadata();
+ assert!(matches!(
+ metadata.prepare_request(placement_request(99, "unauthorized", 2)),
+ Err(IggyError::Unauthenticated)
+ ));
+ let first = metadata
+ .prepare_request(placement_request(1, "authorized", 1))
+ .unwrap();
+ assert_eq!(
+ PersistedCreateTopicRequest::decode_from(first.body())
+ .unwrap()
+ .partitions[0]
+ .consensus_group_id,
+ 1
+ );
+ }
+
+ #[test]
+ fn given_partition_observations_when_creating_should_keep_highest_matching_incarnation() {
+ let mut metadata = placement_metadata();
+ let mut streams = stream_with_one_partition();
+ let partition = &mut streams
+ .items
+ .get_mut(0)
+ .unwrap()
+ .topics
+ .get_mut(0)
+ .unwrap()
+ .partitions[0];
+ partition.created_revision = 7;
+ partition.created_view = 2;
+ metadata.mux_stm = Rc::new(TestMux::new((
+ users_with_topic_manager(),
+ (streams.into(), ()),
+ )));
+ let namespace = IggyNamespace::new(0, 0, 0);
+ metadata.observe_partition_views(&[
+ PartitionPlacementView {
+ namespace,
+ created_revision: 7,
+ view: 6,
+ },
+ PartitionPlacementView {
+ namespace,
+ created_revision: 7,
+ view: 4,
+ },
+ PartitionPlacementView {
+ namespace,
+ created_revision: 6,
+ view: 100,
+ },
+ PartitionPlacementView {
+ namespace,
+ created_revision: 8,
+ view: 101,
+ },
+ ]);
+ let first = metadata
+ .prepare_request(placement_request(1, "observed", 1))
+ .unwrap();
+ assert_eq!(
+ assigned_views(&first),
+ [1],
+ "view 6 keeps load on replica 0 despite older reports"
+ );
+ metadata.observe_partition_views(&[]);
+ let unchanged = metadata
+ .prepare_request(placement_request(2, "missing-report", 1))
+ .unwrap();
+ assert_eq!(assigned_views(&unchanged), [1]);
+
+ let mut recreated = stream_with_one_partition();
+ let partition = &mut recreated
+ .items
+ .get_mut(0)
+ .unwrap()
+ .topics
+ .get_mut(0)
+ .unwrap()
+ .partitions[0];
+ partition.created_revision = 8;
+ partition.created_view = 2;
+ metadata.mux_stm = Rc::new(TestMux::new((
+ users_with_topic_manager(),
+ (recreated.into(), ()),
+ )));
+ metadata.observe_partition_views(&[PartitionPlacementView {
+ namespace,
+ created_revision: 7,
+ view: 102,
+ }]);
+ let next = metadata
+ .prepare_request(placement_request(3, "recreated", 1))
+ .unwrap();
+ assert_eq!(
+ assigned_views(&next),
+ [0],
+ "recreation falls back to its own committed view 2"
+ );
+ metadata.mux_stm = Rc::new(TestMux::default());
+ let empty = metadata
+ .prepare_request(placement_request(3, "deleted", 1))
+ .unwrap();
+ assert_eq!(assigned_views(&empty), [0]);
+ }
+
+ #[compio::test]
+ async fn given_inherited_create_when_summary_missing_should_refuse_then_restore_from_wal() {
+ let directory = tempfile::tempdir().unwrap();
+ let journal = PrepareJournal::open(&directory.path().join("journal.wal"), 0)
+ .await
+ .unwrap();
+ let old_primary = placement_metadata();
+ let inherited = old_primary
+ .prepare_request(placement_request(1, "inherited", 2))
+ .unwrap();
+ journal.handle().append(inherited.clone()).await.unwrap();
+ let mut metadata = placement_metadata();
+ metadata.journal = Some(journal);
+ let consensus = metadata.consensus.as_ref().unwrap();
+ consensus.pipeline_message(PlaneKind::Metadata, &inherited);
+ assert!(matches!(
+ metadata.prepare_request(placement_request(2, "waiting", 1)),
+ Err(IggyError::TransientNotAccepted)
+ ));
+ let reply = metadata
+ .submit_request_in_process(placement_request(2, "waiting", 1))
+ .await
+ .unwrap()
+ .try_into_typed::<ReplyHeader>()
+ .unwrap();
+ assert_eq!(
+ iggy_binary_protocol::result_code(reply.body()),
+ Some(IggyError::TransientNotAccepted.as_code())
+ );
+ assert!(!reply.header().has_committed_result());
+ metadata.refresh_placement().await;
+ let next = metadata
+ .prepare_request(placement_request(2, "ready", 1))
+ .unwrap();
+ let assignments = PersistedCreateTopicRequest::decode_from(next.body())
+ .unwrap()
+ .partitions;
+ assert_eq!(assignments[0].initial_view, 2);
+ assert_eq!(
+ assignments[0].consensus_group_id, 3,
+ "inherited ids must seed the allocator before admission"
+ );
+ }
+
+ #[compio::test]
+ async fn given_missing_placement_summary_when_wire_or_queue_submits_should_reply_58_without_eviction()
+ {
+ let old_primary = placement_metadata();
+ let inherited = old_primary
+ .prepare_request(placement_request(1, "inherited", 2))
+ .unwrap();
+ let metadata = placement_metadata_with_bus(ClientSendSpyBus::default());
+ let consensus = metadata.consensus.as_ref().unwrap();
+ consensus.pipeline_message(PlaneKind::Metadata, &inherited);
+ metadata.on_request(placement_request(2, "wire", 1)).await;
+ {
+ let replies = consensus.message_bus().client_replies.borrow();
+ assert_eq!(replies.len(), 1);
+ let frame = replies[0].first();
+ let header =
+ bytemuck::checked::from_bytes::<ReplyHeader>(&frame[..size_of::<ReplyHeader>()]);
+ assert_eq!(header.command, Command::Reply);
+ assert!(!header.has_committed_result());
+ assert_eq!(
+ iggy_binary_protocol::result_code(&frame[size_of::<ReplyHeader>()..]),
+ Some(IggyError::TransientNotAccepted.as_code())
+ );
+ }
+ let (queued, receiver) =
+ consensus::RequestEntry::with_subscriber(placement_request(3, "queued", 1));
+ assert!(consensus.push_queued_request(queued).is_ok());
+ metadata.drain_request_queue_into_prepares().await;
+ let reply = receiver.await.unwrap();
+ assert_eq!(
+ iggy_binary_protocol::result_code(reply.body()),
+ Some(IggyError::TransientNotAccepted.as_code())
+ );
+ assert!(!reply.header().has_committed_result());
+ assert_eq!(metadata.allocator.highest(), 0);
+ assert_eq!(
+ resolve_acting_user_id(Operation::CreateTopic, 2, &metadata.client_table).unwrap(),
+ Some(0)
+ );
+ assert_eq!(
+ resolve_acting_user_id(Operation::CreateTopic, 3, &metadata.client_table).unwrap(),
+ Some(0)
+ );
+ }
+
+ #[compio::test]
+ async fn given_wrong_canonical_wal_body_when_refreshing_placement_should_keep_admission_closed()
+ {
+ let directory = tempfile::tempdir().unwrap();
+ let journal = PrepareJournal::open(&directory.path().join("journal.wal"), 0)
+ .await
+ .unwrap();
+ let source = placement_metadata();
+ let expected = source
+ .prepare_request(placement_request(1, "expected", 2))
+ .unwrap();
+ let different = source
+ .prepare_request(placement_request(2, "different", 1))
+ .unwrap();
+ assert_eq!(expected.header().op, different.header().op);
+ assert_ne!(expected.header().checksum, different.header().checksum);
+ journal.handle().append(different).await.unwrap();
+ let mut metadata = placement_metadata();
+ metadata.journal = Some(journal);
+ metadata
+ .consensus
+ .as_ref()
+ .unwrap()
+ .pipeline_message(PlaneKind::Metadata, &expected);
+ metadata.refresh_placement().await;
+ assert!(matches!(
+ metadata.prepare_request(placement_request(3, "blocked", 1)),
+ Err(IggyError::TransientNotAccepted)
+ ));
+ assert_eq!(
+ metadata.allocator.highest(),
+ 0,
+ "an op-only WAL match must not supply assignment ids"
+ );
+ }
+
+ #[compio::test]
+ async fn given_replaced_pipeline_create_when_refreshing_should_discard_old_summary() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut metadata = placement_metadata();
+ metadata.journal = Some(
+ PrepareJournal::open(&directory.path().join("journal.wal"), 0)
+ .await
+ .unwrap(),
+ );
+ let consensus = metadata.consensus.as_ref().unwrap();
+ let old = metadata
+ .prepare_request(placement_request(1, "old", 2))
+ .unwrap();
+ consensus.pipeline_message(PlaneKind::Metadata, &old);
+ assert_eq!(
+ consensus.rollback_pipelined_prepare(old.header()),
+ PrepareRollback::Unwound
+ );
+ let source = placement_metadata();
+ let replacement = source
+ .prepare_request(placement_request(2, "replacement", 1))
+ .unwrap();
+ consensus.pipeline_message(PlaneKind::Metadata, &replacement);
+ metadata
+ .journal
+ .as_ref()
+ .unwrap()
+ .handle()
+ .append(replacement)
+ .await
+ .unwrap();
+ assert!(matches!(
+ metadata.prepare_request(placement_request(3, "blocked", 1)),
+ Err(IggyError::TransientNotAccepted)
+ ));
+ metadata.refresh_placement().await;
+ let next = metadata
+ .prepare_request(placement_request(3, "ready", 1))
+ .unwrap();
+ assert_eq!(
+ assigned_views(&next),
+ [1],
+ "only the replacement's one assignment remains reserved"
+ );
+ }
+
#[test]
fn prepare_request_stamps_create_topic_from_client_table_not_wire() {
// `CreateTopic` is the projection that reaches `build_prepare_message`
@@ -5594,6 +6230,7 @@ mod tests {
#[derive(Debug, Default)]
struct ClientSendSpyBus {
client_sends: RefCell<Vec<u128>>,
+ client_replies: RefCell<Vec<BusMessage>>,
}
#[allow(clippy::future_not_send)]
@@ -5602,9 +6239,10 @@ mod tests {
async fn send_to_client(
&self,
client_id: u128,
- _data: impl Into<BusMessage>,
+ data: impl Into<BusMessage>,
) -> Result<(), SendError> {
self.client_sends.borrow_mut().push(client_id);
+ self.client_replies.borrow_mut().push(data.into());
Ok(())
}
async fn send_to_replica(
@@ -6083,11 +6721,11 @@ mod tests {
name: WireName::new("existing").unwrap(),
options: WireOptions::empty(),
},
- created_view: 0,
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
partition_id: 0,
consensus_group_id: 1,
+ initial_view: 0,
}],
},
&mut inner,
@@ -7268,7 +7906,6 @@ mod tests {
&RoutedRequestHeader::default(),
Operation::CreatePartitionsWithAssignments,
&PersistedCreatePartitionsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
@@ -7277,6 +7914,7 @@ mod tests {
partitions: vec![CreatedPartitionAssignment {
partition_id: 1,
consensus_group_id: 2,
+ initial_view: 0,
}],
}
.to_bytes(),
@@ -7789,11 +8427,11 @@ mod tests {
name: WireName::new("topic").unwrap(),
options: WireOptions::empty(),
},
- created_view: 0,
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
partition_id: 0,
consensus_group_id: 1,
+ initial_view: 0,
}],
},
&mut inner,
diff --git a/core/metadata/src/impls/mod.rs b/core/metadata/src/impls/mod.rs
index 55dbf855f..9e391c1a2 100644
--- a/core/metadata/src/impls/mod.rs
+++ b/core/metadata/src/impls/mod.rs
@@ -16,6 +16,7 @@
// under the License.
pub mod metadata;
+mod placement;
pub mod recovery;
/// Subdirectory under the data root where metadata state is stored.
diff --git a/core/metadata/src/impls/placement.rs b/core/metadata/src/impls/placement.rs
new file mode 100644
index 000000000..34972e358
--- /dev/null
+++ b/core/metadata/src/impls/placement.rs
@@ -0,0 +1,562 @@
+// 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 crate::impls::metadata::{PartitionPlacementView, PartitionPrimaryTransfer};
+use crate::stm::stream::{Partition, Streams, find_partition};
+use ahash::AHashMap;
+use iggy_binary_protocol::primitives::partition_assignment::CreatedPartitionAssignment;
+use iggy_binary_protocol::requests::partitions::CreatePartitionsWithAssignmentsRequest;
+use iggy_binary_protocol::requests::topics::CreateTopicWithAssignmentsRequest;
+use iggy_binary_protocol::{Operation, PrepareHeader, WireDecode};
+use iggy_common::IggyError;
+use server_common::Message;
+use server_common::sharding::IggyNamespace;
+
+/// Summaries are only a cache. The live canonical pipeline decides which
+/// reservations count, so commit, rejection and log replacement need no undo.
+#[derive(Default)]
+pub(super) struct PlacementState {
+ observations: AHashMap<IggyNamespace, ObservedView>,
+ reservations: AHashMap<(u64, u128), Vec<u64>>,
+}
+
+struct ObservedView {
+ report: PartitionPlacementView,
+ present: bool,
+}
+
+impl PlacementState {
+ pub(super) fn observe(&mut self, streams: &Streams, reports: &[PartitionPlacementView]) {
+ let () = streams.read(|inner| {
+ for report in reports {
+ let namespace = report.namespace;
+ let Some(partition) = inner
+ .items
+ .get(namespace.stream_id())
+ .and_then(|stream| stream.topics.get(namespace.topic_id()))
+ .and_then(|topic| find_partition(&topic.partitions, namespace.partition_id()))
+ else {
+ continue;
+ };
+ if partition.created_revision != report.created_revision {
+ continue;
+ }
+ if report.view < partition.created_view {
+ continue;
+ }
+ self.observations
+ .entry(namespace)
+ .and_modify(|previous| {
+ if previous.report.created_revision == report.created_revision {
+ previous.report.view = previous.report.view.max(report.view);
+ } else {
+ previous.report = *report;
+ }
+ })
+ .or_insert(ObservedView {
+ report: *report,
+ present: true,
+ });
+ }
+ });
+ }
+
+ pub(super) fn committed_counts(&mut self, streams: &Streams, replicas: u8) -> Vec<u64> {
+ let counts = streams.read(|inner| {
+ let mut counts = vec![0; usize::from(replicas)];
+ for observation in self.observations.values_mut() {
+ observation.present = false;
+ }
+ for (stream_id, stream) in &inner.items {
+ for (topic_id, topic) in &stream.topics {
+ for partition in &topic.partitions {
+ let namespace = IggyNamespace::new(stream_id, topic_id, partition.id);
+ let view = self
+ .observations
+ .get_mut(&namespace)
+ .filter(|observation| {
+ observation.report.created_revision == partition.created_revision
+ })
+ .map_or(partition.created_view, |observation| {
+ observation.present = true;
+ observation.report.view.max(partition.created_view)
+ });
+ counts[(view % u32::from(replicas)) as usize] += 1;
+ }
+ }
+ }
+ counts
+ });
+ self.observations
+ .retain(|_, observation| observation.present);
+ counts
+ }
+
+ pub(super) fn primary_rebalance_candidate(
+ &self,
+ streams: &Streams,
+ replicas: u8,
+ eligible: &[bool],
+ after: Option<IggyNamespace>,
+ ) -> Option<PartitionPrimaryTransfer> {
+ let replicas = usize::from(replicas);
+ let available = eligible.iter().filter(|&&available| available).count();
+ if eligible.len() != replicas || available < 2 || available <= replicas / 2 {
+ return None;
+ }
+ streams.read(|inner| {
+ let mut counts = vec![0_u64; replicas];
+ let mut first: Vec<Option<PartitionPlacementView>> = vec![None; replicas];
+ let mut next: Vec<Option<PartitionPlacementView>> = vec![None; replicas];
+ for (stream_id, stream) in &inner.items {
+ for (topic_id, topic) in &stream.topics {
+ if inner.lifecycle_blocks(stream_id, Some(topic_id)) {
+ continue;
+ }
+ for partition in &topic.partitions {
+ let namespace = IggyNamespace::new(stream_id, topic_id, partition.id);
+ let report = self.matching_view(namespace, partition)?;
+ let primary = report.view as usize % replicas;
+ if !eligible[primary] {
+ return None;
+ }
+ counts[primary] += 1;
+ if first[primary].is_none_or(|first| namespace < first.namespace) {
+ first[primary] = Some(report);
+ }
+ if after.is_none_or(|cursor| namespace > cursor)
+ && next[primary].is_none_or(|next| namespace < next.namespace)
+ {
+ next[primary] = Some(report);
+ }
+ }
+ }
+ }
+ let mut available = eligible
+ .iter()
+ .enumerate()
+ .filter_map(|(replica, &eligible)| eligible.then_some(replica));
+ let mut source = available.next()?;
+ let mut target = source;
+ for replica in available {
+ if counts[replica] > counts[source] {
+ source = replica;
+ }
+ if counts[replica] < counts[target] {
+ target = replica;
+ }
+ }
+ if counts[source].saturating_sub(counts[target]) <= 1 {
+ return None;
+ }
+ let report = next[source].or(first[source])?;
+ Some(PartitionPrimaryTransfer {
+ namespace: report.namespace,
+ created_revision: report.created_revision,
+ view: report.view,
+ target: u8::try_from(target).ok()?,
+ })
+ })
+ }
+
+ pub(super) fn partition_placement_view(
+ &self,
+ streams: &Streams,
+ namespace: IggyNamespace,
+ created_revision: u64,
+ ) -> Option<PartitionPlacementView> {
+ streams.read(|inner| {
+ if inner.lifecycle_blocks(namespace.stream_id(), Some(namespace.topic_id())) {
+ return None;
+ }
+ let topic = inner
+ .items
+ .get(namespace.stream_id())?
+ .topics
+ .get(namespace.topic_id())?;
+ let partition = find_partition(&topic.partitions, namespace.partition_id())?;
+ if partition.created_revision != created_revision {
+ return None;
+ }
+ self.matching_view(namespace, partition)
+ })
+ }
+
+ pub(super) fn select(counts: &mut [u64]) -> Result<u32, IggyError> {
+ let (replica, count) = counts
+ .iter_mut()
+ .enumerate()
+ .min_by_key(|(replica, count)| (**count, *replica))
+ .ok_or(IggyError::TransientNotAccepted)?;
+ *count += 1;
+ u32::try_from(replica).map_err(|_| IggyError::TransientNotAccepted)
+ }
+
+ pub(super) fn prune(&mut self, retained: impl Fn(u64, u128) -> bool) {
+ self.reservations
+ .retain(|&(op, checksum), _| retained(op, checksum));
+ }
+
+ pub(super) fn contains(&self, header: &PrepareHeader) -> bool {
+ self.reservations
+ .contains_key(&(header.op, header.checksum))
+ }
+
+ pub(super) fn add_reservation(
+ &self,
+ header: &PrepareHeader,
+ counts: &mut [u64],
+ ) -> Result<(), IggyError> {
+ let reserved = self
+ .reservations
+ .get(&(header.op, header.checksum))
+ .ok_or(IggyError::TransientNotAccepted)?;
+ for (count, reserved) in counts.iter_mut().zip(reserved) {
+ *count += reserved;
+ }
+ Ok(())
+ }
+
+ pub(super) fn remember(
+ &mut self,
+ prepare: &Message<PrepareHeader>,
+ replicas: u8,
+ ) -> Result<Option<u64>, IggyError> {
+ let partitions = match prepare.header().operation {
+ Operation::CreateTopicWithAssignments => {
+ CreateTopicWithAssignmentsRequest::decode_from(prepare.body())
+ .map_err(|_| IggyError::InvalidCommand)?
+ .partitions
+ }
+ Operation::CreatePartitionsWithAssignments => {
+ CreatePartitionsWithAssignmentsRequest::decode_from(prepare.body())
+ .map_err(|_| IggyError::InvalidCommand)?
+ .partitions
+ }
+ _ => return Ok(None),
+ };
+ let mut counts = vec![0; usize::from(replicas)];
+ let mut highest_group_id = 0;
+ for CreatedPartitionAssignment {
+ consensus_group_id,
+ initial_view,
+ ..
+ } in partitions
+ {
+ counts[(initial_view % u32::from(replicas)) as usize] += 1;
+ highest_group_id = highest_group_id.max(consensus_group_id);
+ }
+ self.reservations
+ .insert((prepare.header().op, prepare.header().checksum), counts);
+ Ok(Some(highest_group_id))
+ }
+
+ fn matching_view(
+ &self,
+ namespace: IggyNamespace,
+ partition: &Partition,
+ ) -> Option<PartitionPlacementView> {
+ self.observations
+ .get(&namespace)
+ .map(|observation| observation.report)
+ .filter(|report| report.created_revision == partition.created_revision)
+ .filter(|report| report.view >= partition.created_view)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::stm::StateHandler;
+ use crate::stm::lifecycle::apply_with_lifecycle_completion;
+ use iggy_binary_protocol::WireIdentifier;
+ use iggy_binary_protocol::requests::streams::DeleteStreamRequest;
+ use iggy_binary_protocol::requests::topics::DeleteTopicRequest;
+ use iggy_common::IggyTimestamp;
+
+ fn observed_topics(views: &[u32]) -> (Streams, PlacementState) {
+ let streams = Streams::default();
+ let mut placement = PlacementState::default();
+ for (topic, &view) in views.iter().enumerate() {
+ let namespace = IggyNamespace::new(0, topic, 0);
+ streams.seed_namespace(namespace, u64::try_from(topic).unwrap() + 1, view);
+ placement.observe(
+ &streams,
+ &[PartitionPlacementView {
+ namespace,
+ created_revision: streams.created_revision_for_namespace(namespace).unwrap(),
+ view,
+ }],
+ );
+ }
+ (streams, placement)
+ }
+
+ #[test]
+ fn given_failed_and_returned_replica_when_rebalancing_should_restore_even_ownership() {
+ let views = (0..100).map(|topic| topic % 5).collect::<Vec<_>>();
+ let (streams, mut placement) = observed_topics(&views);
+ for topic in (0..100).step_by(5) {
+ let namespace = IggyNamespace::new(0, topic, 0);
+ placement.observe(
+ &streams,
+ &[PartitionPlacementView {
+ namespace,
+ created_revision: streams.created_revision_for_namespace(namespace).unwrap(),
+ view: 1,
+ }],
+ );
+ }
+ assert_eq!(placement.committed_counts(&streams, 5), [0, 40, 20, 20, 20]);
+ for (eligible, expected_counts, expected_moves) in [
+ ([false, true, true, true, true], [0, 25, 25, 25, 25], 15),
+ ([true; 5], [20; 5], 20),
+ ] {
+ let mut moves = 0;
+ let mut after = None;
+ while let Some(transfer) =
+ placement.primary_rebalance_candidate(&streams, 5, &eligible, after)
+ {
+ assert!(moves < 100, "each completed transfer must reduce imbalance");
+ assert!(eligible[usize::from(transfer.target)]);
+ let next_view =
+ transfer.view + (u32::from(transfer.target) + 5 - transfer.view % 5) % 5;
+ assert!(next_view > transfer.view);
+ placement.observe(
+ &streams,
+ &[PartitionPlacementView {
+ namespace: transfer.namespace,
+ created_revision: transfer.created_revision,
+ view: next_view,
+ }],
+ );
+ after = Some(transfer.namespace);
+ moves += 1;
+ }
+ assert_eq!(moves, expected_moves);
+ assert_eq!(placement.committed_counts(&streams, 5), expected_counts);
+ }
+ assert_eq!(
+ PlacementState::default().committed_counts(&streams, 5),
+ [20; 5],
+ "transfers must not rewrite committed initial views"
+ );
+ }
+
+ #[test]
+ fn given_balanced_or_almost_balanced_primaries_when_selecting_should_not_transfer() {
+ for views in [&[][..], &[0, 1, 2], &[0, 1, 2, 0]] {
+ let (streams, placement) = observed_topics(views);
+ assert!(
+ placement
+ .primary_rebalance_candidate(&streams, 3, &[true; 3], None)
+ .is_none()
+ );
+ }
+ }
+
+ #[test]
+ fn given_unsettled_failover_or_no_quorum_when_selecting_should_wait() {
+ let (streams, placement) = observed_topics(&[0, 0, 0, 1, 2]);
+ for eligible in [
+ &[false, true, true, true, true][..],
+ &[true, true, false, false, false],
+ &[true, false, false, false, false],
+ &[true; 4],
+ ] {
+ assert!(
+ placement
+ .primary_rebalance_candidate(&streams, 5, eligible, None)
+ .is_none()
+ );
+ }
+ assert!(
+ placement
+ .primary_rebalance_candidate(&streams, 0, &[], None)
+ .is_none()
+ );
+ assert!(
+ placement
+ .primary_rebalance_candidate(&streams, 1, &[true], None)
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn given_tied_load_and_recovering_target_when_selecting_should_rotate_candidates() {
+ let (streams, placement) = observed_topics(&[0, 0, 0, 1, 1, 1]);
+ for (after, expected_topic) in [(None, 0), (Some(0), 1), (Some(1), 2), (Some(2), 0)] {
+ let transfer = placement
+ .primary_rebalance_candidate(
+ &streams,
+ 5,
+ &[true; 5],
+ after.map(|topic| IggyNamespace::new(0, topic, 0)),
+ )
+ .unwrap();
+ assert_eq!(transfer.namespace, IggyNamespace::new(0, expected_topic, 0));
+ assert_eq!(transfer.view, 0, "lowest replica id wins the source tie");
+ assert_eq!(transfer.target, 2, "lowest replica id wins the target tie");
+ }
+ }
+
+ #[test]
+ fn given_missing_observation_when_selecting_should_require_a_matching_normal_view() {
+ let (streams, mut placement) = observed_topics(&[2, 2, 2]);
+ let namespace = IggyNamespace::new(0, 0, 0);
+ let report = placement.observations.remove(&namespace).unwrap().report;
+ for stale in [
+ PartitionPlacementView { view: 1, ..report },
+ PartitionPlacementView {
+ created_revision: report.created_revision + 1,
+ ..report
+ },
+ ] {
+ placement.observe(&streams, &[stale]);
+ assert!(
+ placement
+ .primary_rebalance_candidate(&streams, 3, &[true; 3], None)
+ .is_none()
+ );
+ assert!(
+ placement
+ .partition_placement_view(&streams, namespace, report.created_revision)
+ .is_none()
+ );
+ }
+ placement.observe(&streams, &[report]);
+ assert!(
+ placement
+ .primary_rebalance_candidate(&streams, 3, &[true; 3], None)
+ .is_some()
+ );
+ }
+
+ #[test]
+ fn given_pending_parent_deletion_when_selecting_should_exclude_its_partitions() {
+ let (streams, placement) = observed_topics(&[0, 0, 0]);
+ let namespace = IggyNamespace::new(0, 0, 0);
+ let revision = streams.created_revision_for_namespace(namespace).unwrap();
+ let mut inner = streams.read(Clone::clone);
+ inner.apply_context.metadata_op = 100;
+ assert_eq!(
+ DeleteTopicRequest {
+ stream_id: WireIdentifier::numeric(0),
+ topic_id: WireIdentifier::numeric(0),
+ }
+ .apply(&mut inner, IggyTimestamp::from(1))
+ .code,
+ 0
+ );
+ let deleting_topic = Streams::from(inner);
+ let transfer = placement
+ .primary_rebalance_candidate(&deleting_topic, 3, &[true; 3], None)
+ .unwrap();
+ assert_eq!(transfer.namespace, IggyNamespace::new(0, 1, 0));
+ assert!(
+ placement
+ .partition_placement_view(&deleting_topic, namespace, revision)
+ .is_none()
+ );
+
+ let mut inner = streams.read(Clone::clone);
+ inner.apply_context.metadata_op = 101;
+ assert_eq!(
+ DeleteStreamRequest {
+ stream_id: WireIdentifier::numeric(0),
+ }
+ .apply(&mut inner, IggyTimestamp::from(1))
+ .code,
+ 0
+ );
+ let deleting_stream = Streams::from(inner);
+ assert!(
+ placement
+ .primary_rebalance_candidate(&deleting_stream, 3, &[true; 3], None)
+ .is_none()
+ );
+ assert!(
+ placement
+ .partition_placement_view(&deleting_stream, namespace, revision)
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn given_recreated_namespace_when_selecting_should_wait_for_its_own_observation() {
+ let (streams, mut placement) = observed_topics(&[0, 0, 0]);
+ let namespace = IggyNamespace::new(0, 0, 0);
+ let old_report = placement.observations[&namespace].report;
+ let mut inner = streams.read(Clone::clone);
+ assert_eq!(
+ apply_with_lifecycle_completion(
+ &DeleteTopicRequest {
+ stream_id: WireIdentifier::numeric(0),
+ topic_id: WireIdentifier::numeric(0),
+ },
+ &mut inner,
+ IggyTimestamp::from(1),
+ )
+ .code,
+ 0
+ );
+ let recreated = Streams::from(inner);
+ assert!(
+ placement
+ .partition_placement_view(&recreated, namespace, old_report.created_revision)
+ .is_none()
+ );
+ recreated.seed_namespace(namespace, 100, 0);
+ let new_revision = recreated.created_revision_for_namespace(namespace).unwrap();
+ assert_ne!(new_revision, old_report.created_revision);
+ placement.observe(
+ &recreated,
+ &[PartitionPlacementView {
+ view: 100,
+ ..old_report
+ }],
+ );
+ assert!(
+ placement
+ .primary_rebalance_candidate(&recreated, 3, &[true; 3], None)
+ .is_none()
+ );
+ assert!(
+ placement
+ .partition_placement_view(&recreated, namespace, new_revision)
+ .is_none()
+ );
+ placement.observe(
+ &recreated,
+ &[PartitionPlacementView {
+ namespace,
+ created_revision: new_revision,
+ view: 0,
+ }],
+ );
+ let transfer = placement
+ .primary_rebalance_candidate(&recreated, 3, &[true; 3], None)
+ .unwrap();
+ assert_eq!(transfer.namespace, namespace);
+ assert_eq!(transfer.created_revision, new_revision);
+ assert!(
+ placement
+ .partition_placement_view(&recreated, namespace, old_report.created_revision)
+ .is_none()
+ );
+ }
+}
diff --git a/core/metadata/src/stm/authz.rs b/core/metadata/src/stm/authz.rs
index 69c60bc00..3bcb48db7 100644
--- a/core/metadata/src/stm/authz.rs
+++ b/core/metadata/src/stm/authz.rs
@@ -527,7 +527,6 @@ mod tests {
fn create_topic_body(stream_id: u32, name: &str) -> bytes::Bytes {
CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: CreateTopicRequest {
stream_id: WireIdentifier::numeric(stream_id),
partitions_count: 1,
@@ -536,6 +535,7 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
diff --git a/core/metadata/src/stm/consumer_group.rs b/core/metadata/src/stm/consumer_group.rs
index 33022cd14..1cb39bcb1 100644
--- a/core/metadata/src/stm/consumer_group.rs
+++ b/core/metadata/src/stm/consumer_group.rs
@@ -1817,7 +1817,6 @@ mod tests {
IggyTimestamp::now(),
);
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: CreateTopicRequest {
stream_id: WireIdentifier::numeric(0),
partitions_count: 1,
@@ -1826,6 +1825,7 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -1891,7 +1891,6 @@ mod tests {
state.apply_context.metadata_op += 1;
StateHandler::apply(
&CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: CreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
@@ -1899,6 +1898,7 @@ mod tests {
},
partitions: (0..count)
.map(|partition_id| CreatedPartitionAssignment {
+ initial_view: 0,
partition_id,
consensus_group_id: u64::from(partition_id) + 2,
})
diff --git a/core/metadata/src/stm/lifecycle.rs b/core/metadata/src/stm/lifecycle.rs
index 5f33161ba..85261ec41 100644
--- a/core/metadata/src/stm/lifecycle.rs
+++ b/core/metadata/src/stm/lifecycle.rs
@@ -1491,7 +1491,6 @@ mod tests {
#[test]
fn given_pending_intent_when_topic_is_created_should_admit_and_apply_alike() {
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: CreateTopicRequest {
stream_id: WireIdentifier::numeric(0),
partitions_count: 1,
@@ -1500,6 +1499,7 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
diff --git a/core/metadata/src/stm/stream.rs b/core/metadata/src/stm/stream.rs
index c3e0a4e8d..2712b0847 100644
--- a/core/metadata/src/stm/stream.rs
+++ b/core/metadata/src/stm/stream.rs
@@ -109,14 +109,10 @@ pub struct Partition {
/// reused the slab key, so the local partition is stale and must be torn
/// down before rebuild.
pub created_revision: u64,
- /// View the admitting primary minted the create in, read off the request
- /// body (never the prepare header, whose `view` a post-view-change
- /// retransmit restamps per delivery). Every replica seeds the partition's
- /// consensus group from it, so they all name the same primary: the metadata
- /// primary at creation, which is what the roster advertises. Never above
- /// the group's current view, since the group starts here and views only
- /// climb, so a replica materialising late joins at or below its peers, the
- /// floor a view-0 start used to be.
+ /// Committed initial view selected for this partition. Every replica uses
+ /// this body-carried value to seed the same primary, including late
+ /// materialisation and replay after a metadata view change. Partition
+ /// elections may advance beyond this floor without changing the assignment.
pub created_view: u32,
/// Replicated delete watermark: the reconciler on every replica removes
/// sealed segments with `end_offset` below this. Advanced monotonically by
@@ -1873,7 +1869,6 @@ impl Streams {
stream_slab: usize,
topic_slab: usize,
target_partitions: &[CreatedPartitionAssignment],
- created_view: u32,
) {
let stream_wire =
WireIdentifier::numeric(u32::try_from(stream_slab).expect("sim stream slab fits u32"));
@@ -1911,7 +1906,6 @@ impl Streams {
},
derived_options: WireOptions::empty(),
partitions,
- created_view,
},
IggyTimestamp::from(1),
ApplyContext::default(),
@@ -1932,8 +1926,8 @@ impl Streams {
/// the missing partition. Mirrors [`Users::ensure_root_user`](crate::stm::user::Users::ensure_root_user): a seed
/// helper that bypasses consensus, never a production runtime path.
///
- /// `created_view` stands in for the view a real create's admitting primary
- /// mints into the request body; see [`Partition::created_view`].
+ /// `created_view` supplies each seeded assignment's initial view;
+ /// see [`Partition::created_view`].
///
/// # Panics
/// Panics if the apply is attempted on a reader handle rather than the
@@ -1973,12 +1967,13 @@ impl Streams {
// leave no gap for a later sibling to fall into.
let target_partitions: Vec<_> = (0..=partition_id)
.map(|id| CreatedPartitionAssignment {
+ initial_view: created_view,
partition_id: id,
consensus_group_id: sibling_group_id(id),
})
.collect();
self.seed_stream_slabs(stream_slab);
- self.seed_topic_slabs(stream_slab, topic_slab, &target_partitions, created_view);
+ self.seed_topic_slabs(stream_slab, topic_slab, &target_partitions);
if self.created_revision_for_namespace(namespace).is_some() {
return;
@@ -1997,6 +1992,7 @@ impl Streams {
let base = u32::try_from(base).expect("sim partition base fits u32");
let partitions = (base..=partition_id)
.map(|id| CreatedPartitionAssignment {
+ initial_view: created_view,
partition_id: id - base,
consensus_group_id: sibling_group_id(id),
})
@@ -2011,7 +2007,6 @@ impl Streams {
.expect("sim partition count fits u32"),
},
partitions,
- created_view,
},
IggyTimestamp::from(1),
ApplyContext::default(),
@@ -2052,7 +2047,7 @@ const fn admits_slab_key(vacant_key: usize, ceiling: usize) -> bool {
/// A primary mints dense 0-based ids, so the vector index IS the id and the
/// direct hit answers every ordinary topic. The scan exists only for a vector
/// left sparse by a partition delete, where an index no longer names its id.
-fn find_partition(partitions: &[Partition], partition_id: usize) -> Option<&Partition> {
+pub(crate) fn find_partition(partitions: &[Partition], partition_id: usize) -> Option<&Partition> {
if let Some(partition) = partitions.get(partition_id)
&& partition.id == partition_id
{
@@ -2328,7 +2323,7 @@ impl StateHandler for CreateTopicWithAssignmentsRequest {
consensus_group_id: partition.consensus_group_id,
created_at: timestamp,
created_revision: new_revision,
- created_view: self.created_view,
+ created_view: partition.initial_view,
deleted_up_to_offset: 0,
};
topic.partitions.push(partition);
@@ -2617,7 +2612,7 @@ impl StateHandler for CreatePartitionsWithAssignmentsRequest {
consensus_group_id: partition.consensus_group_id,
created_at: timestamp,
created_revision: new_revision,
- created_view: self.created_view,
+ created_view: partition.initial_view,
deleted_up_to_offset: 0,
});
}
@@ -3042,7 +3037,6 @@ mod tests {
..TopicCreateOptions::default()
};
let request = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: WireCreateTopicRequest {
stream_id: WireIdentifier::numeric(0),
partitions_count: 1,
@@ -3053,6 +3047,7 @@ mod tests {
},
derived_options: derived.to_wire().unwrap(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -3092,49 +3087,86 @@ mod tests {
);
}
- /// The seed every replica materialises a group from is the body-carried
- /// `created_view`, minted once by the admitting primary. A header-derived
- /// view would differ per replica after a post-view-change retransmit.
#[test]
- fn create_ops_record_the_body_carried_view_on_the_partition() {
+ fn given_committed_assignments_when_replaying_should_preserve_each_initial_view() {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "s");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 7,
request: WireCreateTopicRequest {
stream_id: WireIdentifier::numeric(0),
- partitions_count: 1,
+ partitions_count: 2,
name: WireName::new("t").unwrap(),
options: WireOptions::empty(),
},
derived_options: WireOptions::empty(),
- partitions: vec![CreatedPartitionAssignment {
- partition_id: 0,
- consensus_group_id: 1,
- }],
+ partitions: vec![
+ CreatedPartitionAssignment {
+ partition_id: 0,
+ consensus_group_id: 1,
+ initial_view: 7,
+ },
+ CreatedPartitionAssignment {
+ partition_id: 1,
+ consensus_group_id: 2,
+ initial_view: 8,
+ },
+ ],
};
+ let create_topic =
+ CreateTopicWithAssignmentsRequest::decode_from(&create_topic.to_bytes()).unwrap();
let reply = StateHandler::apply(&create_topic, &mut inner, IggyTimestamp::from(1));
assert_eq!(reply.code, 0, "create topic must succeed");
let create_partitions = CreatePartitionsWithAssignmentsRequest {
- created_view: 9,
request: CreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
- partitions_count: 1,
+ partitions_count: 2,
},
- partitions: vec![CreatedPartitionAssignment {
- partition_id: 0,
- consensus_group_id: 2,
- }],
+ partitions: vec![
+ CreatedPartitionAssignment {
+ partition_id: 0,
+ consensus_group_id: 3,
+ initial_view: 9,
+ },
+ CreatedPartitionAssignment {
+ partition_id: 1,
+ consensus_group_id: 4,
+ initial_view: 10,
+ },
+ ],
};
- let reply = StateHandler::apply(&create_partitions, &mut inner, IggyTimestamp::from(2));
+ let committed_body = create_partitions.to_bytes();
+ let streams: Streams = inner.into();
+ let mut snapshot = MetadataSnapshot::new(1);
+ snapshot.streams = Some(streams.to_snapshot());
+ let decoded = MetadataSnapshot::decode(&snapshot.encode().unwrap()).unwrap();
+ let mut restored =
+ StreamsInner::inner_from_snapshot(decoded.streams.unwrap(), Arc::default());
+
+ let replayed =
+ CreatePartitionsWithAssignmentsRequest::decode_from(&committed_body).unwrap();
+ let reply = StateHandler::apply(&replayed, &mut restored, IggyTimestamp::from(2));
assert_eq!(reply.code, 0, "create partitions must succeed");
- let topic = inner.items.get(0).unwrap().topics.get(0).unwrap();
- assert_eq!(topic.partitions[0].created_view, 7);
- assert_eq!(topic.partitions[1].created_view, 9);
+ let restored: Streams = restored.into();
+ let restored = Streams::from_snapshot(restored.to_snapshot()).unwrap();
+ let assignments = restored.read(|inner| {
+ let topic = inner.items.get(0).unwrap().topics.get(0).unwrap();
+ topic
+ .partitions
+ .iter()
+ .map(|partition| {
+ (
+ partition.id,
+ partition.consensus_group_id,
+ partition.created_view,
+ )
+ })
+ .collect::<Vec<_>>()
+ });
+ assert_eq!(assignments, [(0, 1, 7), (1, 2, 8), (2, 3, 9), (3, 4, 10)]);
}
/// A client may send the literal 0 that means "resolve the default". The
@@ -3172,7 +3204,6 @@ mod tests {
&mut sentinel,
);
let request = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: WireCreateTopicRequest {
stream_id: WireIdentifier::numeric(0),
partitions_count: 1,
@@ -3181,6 +3212,7 @@ mod tests {
},
derived_options: derived.to_wire().unwrap(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -3209,7 +3241,6 @@ mod tests {
let message_expiry = IggyExpiry::from(5_000_000u64);
let max_topic_size = MaxTopicSize::from(10_000_000_000u64);
let create = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: WireCreateTopicRequest {
stream_id: WireIdentifier::numeric(0),
partitions_count: 1,
@@ -3228,6 +3259,7 @@ mod tests {
.to_wire()
.unwrap(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -3349,15 +3381,16 @@ mod tests {
.to_wire()
.unwrap();
let created = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request,
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 2,
},
@@ -3386,13 +3419,13 @@ mod tests {
StreamsInner::inner_from_snapshot(decoded.streams.unwrap(), Arc::default());
let revision = restored.revision;
let create = CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
partitions_count: 1,
},
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 3,
}],
@@ -3499,15 +3532,16 @@ mod tests {
for stream_id in 0..2u32 {
for topic_name in ["logs", "events"] {
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(stream_id, 2, topic_name),
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 2,
},
@@ -3568,15 +3602,16 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "stream");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 2, "topic"),
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 2,
},
@@ -3597,15 +3632,16 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "stream");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 2, "topic"),
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 10,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 11,
},
@@ -3614,7 +3650,6 @@ mod tests {
let _ = StateHandler::apply(&create_topic, &mut inner, IggyTimestamp::now());
let create_partitions = CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
@@ -3622,10 +3657,12 @@ mod tests {
},
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 12,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 13,
},
@@ -3654,15 +3691,16 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "stream");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 2, "topic"),
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 100,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 101,
},
@@ -3689,15 +3727,16 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "stream");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 2, "topic"),
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 50,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 51,
},
@@ -3706,7 +3745,6 @@ mod tests {
let _ = StateHandler::apply(&create_topic, &mut inner, IggyTimestamp::now());
let create_partitions = CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
@@ -3716,10 +3754,12 @@ mod tests {
// two topic-creation partitions), so resolved ids are 2 and 3.
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 60,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 61,
},
@@ -3744,13 +3784,13 @@ mod tests {
create_stream(&mut inner, "stream");
// Topic missing => validation failure path
let create_partitions = CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(99),
partitions_count: 1,
},
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -3787,11 +3827,11 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "stream");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, partitions_count, "topic"),
derived_options: WireOptions::empty(),
partitions: (0..partitions_count)
.map(|partition_id| CreatedPartitionAssignment {
+ initial_view: 0,
partition_id,
consensus_group_id: 1,
})
@@ -3836,10 +3876,10 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "stream");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 1, "topic"),
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -4116,15 +4156,16 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "alpha");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 2, "logs"),
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 3,
consensus_group_id: 1,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 4,
consensus_group_id: 2,
},
@@ -4191,11 +4232,11 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "alpha");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 4, "logs"),
derived_options: WireOptions::empty(),
partitions: (0..4)
.map(|partition_id| CreatedPartitionAssignment {
+ initial_view: 0,
partition_id,
consensus_group_id: u64::from(partition_id) + 1,
})
@@ -4275,10 +4316,10 @@ mod tests {
// inherit what the probe above counted.
create_stream(&mut inner, "beta");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 1, "logs"),
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -4361,10 +4402,10 @@ mod tests {
let mut inner = StreamsInner::new();
create_stream(&mut inner, "alpha");
let create_topic = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 1, "logs"),
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -4586,7 +4627,6 @@ mod tests {
for index in 0..MAX_TOPICS {
let request = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 0, &format!("t{index}")),
derived_options: WireOptions::empty(),
partitions: Vec::new(),
@@ -4596,7 +4636,6 @@ mod tests {
}
let overflow = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 0, "one-too-many"),
derived_options: WireOptions::empty(),
partitions: Vec::new(),
@@ -4626,10 +4665,10 @@ mod tests {
create_stream(&mut inner, "s");
let seed = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 1, "t"),
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: u32::try_from(MAX_PARTITIONS - 2).unwrap(),
consensus_group_id: 1,
}],
@@ -4641,13 +4680,13 @@ mod tests {
// Resolves to MAX_PARTITIONS - 1: the last legal id.
let last = CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
partitions_count: 1,
},
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 2,
}],
@@ -4659,13 +4698,13 @@ mod tests {
);
let overflow = CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
partitions_count: 1,
},
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 3,
}],
@@ -4691,10 +4730,10 @@ mod tests {
create_stream(&mut inner, "s");
let request = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 1, "t"),
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: u32::try_from(MAX_PARTITIONS).unwrap(),
consensus_group_id: 1,
}],
@@ -4763,7 +4802,6 @@ mod tests {
create_stream(&mut inner, "s");
for name in ["a", "b", "c"] {
let request = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 0, name),
derived_options: WireOptions::empty(),
partitions: Vec::new(),
@@ -4822,15 +4860,16 @@ mod tests {
create_stream(&mut inner, "s");
let request = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 2, "t"),
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 7,
consensus_group_id: 1,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 7,
consensus_group_id: 2,
},
@@ -4857,10 +4896,10 @@ mod tests {
create_stream(&mut inner, "s");
let seed = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 1, "t"),
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -4871,7 +4910,6 @@ mod tests {
);
let duplicate = CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
@@ -4879,10 +4917,12 @@ mod tests {
},
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 2,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 3,
},
@@ -4910,10 +4950,10 @@ mod tests {
create_stream(&mut inner, "s");
let seed = CreateTopicWithAssignmentsRequest {
- created_view: 0,
request: make_topic_request(0, 1, "t"),
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
@@ -4924,7 +4964,6 @@ mod tests {
);
let distinct = CreatePartitionsWithAssignmentsRequest {
- created_view: 0,
request: WireCreatePartitionsRequest {
stream_id: WireIdentifier::numeric(0),
topic_id: WireIdentifier::numeric(0),
@@ -4932,10 +4971,12 @@ mod tests {
},
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 2,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 3,
},
diff --git a/core/partitions/src/iggy_partition.rs b/core/partitions/src/iggy_partition.rs
index 421595b38..aa06ebeaa 100644
--- a/core/partitions/src/iggy_partition.rs
+++ b/core/partitions/src/iggy_partition.rs
@@ -527,6 +527,10 @@ pub enum PendingPartitionTransition {
View {
drain: Option<crate::PersistenceDrain>,
},
+ PrimaryTransfer {
+ request: crate::PreparedPrimaryTransfer,
+ drain: Option<crate::PersistenceDrain>,
+ },
Truncate {
ops: std::ops::RangeInclusive<u64>,
drain: Option<crate::PersistenceDrain>,
@@ -1431,6 +1435,7 @@ where
}
pub fn begin_quarantine(&mut self, frontier: u64) {
+ self.cancel_primary_transfer();
if self
.superblock_intent
.get()
@@ -5577,6 +5582,57 @@ where
|| self.transition.is_some()
}
+ /// Fence new admission while accepted history work drains for this grant.
+ /// Refusal leaves the current history owner unchanged.
+ pub fn defer_primary_transfer(&mut self, request: crate::PreparedPrimaryTransfer) -> bool {
+ if self.transition.is_some()
+ || !self.deferred_views.is_empty()
+ || !self.primary_transfer_is_current(&request)
+ {
+ return false;
+ }
+ self.transition = Some(PendingPartitionTransition::PrimaryTransfer {
+ request,
+ drain: None,
+ });
+ self.notify_io();
+ true
+ }
+
+ fn primary_transfer_is_current(&self, request: &crate::PreparedPrimaryTransfer) -> bool {
+ request.is_active_at(self.consensus.message_bus().monotonic_now())
+ && request.created_revision == self.created_revision()
+ && request.expected_view == self.consensus.view()
+ && request.target < self.consensus.replica_count()
+ && request.target != self.consensus.primary_index(self.consensus.view())
+ && self.consensus.is_normal()
+ && !self.consensus.has_ceded_primaryship()
+ && !self.consensus.is_transferring()
+ && !self.consensus.view_log_unproven()
+ && self.fatal.is_none()
+ && !self.materialization_missing
+ && !self.io_active.is_retiring()
+ && !self.is_shutting_down()
+ }
+
+ pub(crate) fn cancel_primary_transfer(&mut self) {
+ if !matches!(
+ self.transition,
+ Some(PendingPartitionTransition::PrimaryTransfer { .. })
+ ) {
+ return;
+ }
+ if let Some(PendingPartitionTransition::PrimaryTransfer { request, drain }) =
+ self.transition.take()
+ {
+ request.active.store(false, Ordering::Release);
+ if let (Some(persistence), Some(drain)) = (&self.persistence, drain) {
+ persistence.finish_drain(&drain);
+ }
+ }
+ self.notify_io();
+ }
+
/// Keep the newest frame per phase and sender until history writes drain.
pub fn defer_view_transition(&mut self, message: server_common::MessageBag) {
let Some((view, phase, sender)) = deferred_view_order(&message) else {
@@ -5585,6 +5641,7 @@ where
if sender >= self.consensus.replica_count() {
return;
}
+ self.cancel_primary_transfer();
if let Some(pending) = self.deferred_views.iter_mut().find(|pending| {
deferred_view_order(pending).is_some_and(|(_, pending_phase, pending_sender)| {
pending_phase == phase && pending_sender == sender
@@ -5614,6 +5671,7 @@ where
actions: Vec<consensus::VsrAction>,
peer: Option<u8>,
) {
+ self.cancel_primary_transfer();
self.transition = Some(PendingPartitionTransition::Truncate {
ops,
drain: None,
@@ -5647,6 +5705,7 @@ where
match self.resume_io_inner(config).await {
Ok(step) => step,
Err(error) => {
+ self.cancel_primary_transfer();
self.fail_io_work(&error, false);
if self.maintenance.shutdown.is_some() {
self.maintenance.shutdown = Some(PartitionShutdownPhase::Complete);
@@ -5661,6 +5720,11 @@ where
&mut self,
config: &PartitionsConfig,
) -> Result<crate::PartitionIoStep, IggyError> {
+ if let Some(PendingPartitionTransition::PrimaryTransfer { request, .. }) = &self.transition
+ && !self.primary_transfer_is_current(request)
+ {
+ self.cancel_primary_transfer();
+ }
if self.transition.is_none() && !self.deferred_views.is_empty() {
self.transition = Some(PendingPartitionTransition::View { drain: None });
}
@@ -5799,7 +5863,33 @@ where
return Ok(crate::PartitionIoStep::Progress);
}
}
- if let Some(PendingPartitionTransition::View { drain, .. }) = &mut self.transition {
+ if matches!(
+ self.transition,
+ Some(PendingPartitionTransition::PrimaryTransfer { .. })
+ ) && self.consensus.commit_min() < self.consensus.commit_max()
+ {
+ // Commit selection refuses history transitions. This synchronous
+ // window keeps admission fenced between pump events while draining
+ // the already committed prefix before handing leadership away.
+ let transition = self.transition.take();
+ let mut headers = self.select_persistable_commits(config);
+ let reply = !headers.is_empty() && self.consensus.is_primary();
+ if headers.is_empty() {
+ headers = self.collect_committable_from_journal(COMMIT_WALK_OPS_MAX, config);
+ }
+ let selected = self.select_commit(headers, config, reply);
+ self.transition = transition;
+ return Ok(if selected {
+ crate::PartitionIoStep::Progress
+ } else {
+ crate::PartitionIoStep::Pending
+ });
+ }
+ if let Some(
+ PendingPartitionTransition::View { drain }
+ | PendingPartitionTransition::PrimaryTransfer { drain, .. },
+ ) = &mut self.transition
+ {
if let Some(persistence) = &self.persistence {
let drain = drain.get_or_insert_with(|| persistence.begin_drain());
if !persistence
@@ -5810,7 +5900,11 @@ where
}
persistence.finish_drain(drain);
}
- self.transition = None;
+ if let Some(PendingPartitionTransition::PrimaryTransfer { request, .. }) =
+ self.transition.take()
+ {
+ return Ok(crate::PartitionIoStep::PrimaryTransfer(request));
+ }
let next = self
.deferred_views
.iter()
@@ -14012,6 +14106,287 @@ mod tests {
Rc::clone(persistence).run()
}
+ fn primary_transfer_grant<B: MessageBus, SB: SuperblockStore>(
+ partition: &IggyPartition<B, SB>,
+ ) -> crate::PreparedPrimaryTransfer {
+ const TEST_GRANT_TTL: std::time::Duration = std::time::Duration::from_secs(30);
+ crate::PreparedPrimaryTransfer {
+ created_revision: partition.created_revision(),
+ expected_view: partition.consensus.view(),
+ target: 1,
+ active: Arc::new(AtomicBool::new(true)),
+ expires_at: std::time::Instant::now() + TEST_GRANT_TTL,
+ }
+ }
+
+ #[compio::test]
+ async fn given_busy_wal_when_primary_transfer_drains_should_fence_admission_and_release_pause()
+ {
+ for (cancel, expire) in [(false, false), (true, false), (false, true)] {
+ let directory = tempfile::tempdir().unwrap();
+ let (mut partition, replies) = recording_partition_at(0, 3);
+ partition.set_created_revision(7);
+ partition.set_partition_dir(directory.path().to_string_lossy().into_owned());
+ partition.open_persistence().await.unwrap();
+ let persistence = Rc::clone(partition.persistence.as_ref().unwrap());
+ let writer = hold_wal_writer(&persistence);
+ let request = primary_transfer_grant(&partition);
+ for (created_revision, expected_view, active) in [
+ (request.created_revision + 1, request.expected_view, true),
+ (request.created_revision, request.expected_view + 1, true),
+ (request.created_revision, request.expected_view, false),
+ ] {
+ assert!(
+ !partition.defer_primary_transfer(crate::PreparedPrimaryTransfer {
+ created_revision,
+ expected_view,
+ target: request.target,
+ active: Arc::new(AtomicBool::new(active)),
+ expires_at: request.expires_at,
+ })
+ );
+ assert!(partition.transition.is_none());
+ assert!(persistence.has_capacity(size_of::<PrepareHeader>()));
+ }
+ let active = Arc::clone(&request.active);
+ assert!(partition.defer_primary_transfer(request));
+ let config = repair_config();
+ assert!(matches!(
+ partition.resume_io(&config).await,
+ crate::PartitionIoStep::Pending
+ ));
+ assert!(!persistence.has_capacity(size_of::<PrepareHeader>()));
+ partition
+ .on_request(
+ store_offset_request(42, 1, ConsumerKind::Consumer, 7, 0, AckLevel::NoAck),
+ None,
+ )
+ .await;
+ let status = bytemuck::checked::from_bytes::<ReplyHeader>(
+ &replies.borrow()[0].1.as_slice()[..size_of::<ReplyHeader>()],
+ )
+ .status;
+ assert_eq!(status, IggyError::TransientNotAccepted.as_code());
+ assert_eq!(partition.consensus.sequencer().current_sequence(), 0);
+ assert!(!partition.defer_primary_transfer(primary_transfer_grant(&partition)));
+
+ if cancel || expire {
+ if expire {
+ let Some(PendingPartitionTransition::PrimaryTransfer { request, .. }) =
+ &mut partition.transition
+ else {
+ panic!("the held writer must keep its grant");
+ };
+ request.expires_at = std::time::Instant::now();
+ assert!(active.load(Ordering::Acquire));
+ } else {
+ active.store(false, Ordering::Release);
+ }
+ assert!(matches!(
+ partition.resume_io(&config).await,
+ crate::PartitionIoStep::Pending
+ ));
+ assert!(partition.transition.is_none());
+ assert!(persistence.has_capacity(size_of::<PrepareHeader>()));
+ }
+ writer.await;
+ let step = partition.resume_io(&config).await;
+ if cancel || expire {
+ assert!(matches!(step, crate::PartitionIoStep::Pending));
+ } else {
+ let crate::PartitionIoStep::PrimaryTransfer(request) = step else {
+ panic!("settled WAL must release the transfer continuation");
+ };
+ assert_eq!(request.created_revision, 7);
+ assert_eq!(request.expected_view, 0);
+ assert_eq!(request.target, 1);
+ assert!(Arc::ptr_eq(&request.active, &active));
+ }
+ assert!(persistence.has_capacity(size_of::<PrepareHeader>()));
+ assert_eq!(partition.consensus.view(), 0);
+ assert!(partition.transition.is_none());
+ assert!(partition.fatal().is_none());
+ }
+ }
+
+ #[compio::test]
+ async fn given_accepted_no_ack_write_when_primary_transfer_drains_should_finish_its_reply() {
+ const CLIENT: u128 = 42;
+ const CONSUMER: u32 = 7;
+ const STEPS_MAX: usize = 32;
+ let directory = tempfile::tempdir().unwrap();
+ let (mut partition, replies) = recording_partition_at(0, 3);
+ set_offset_dirs_under(&mut partition, directory.path());
+ partition.stats.increment_messages_count(1);
+ partition.set_io_notifier(
+ Rc::new(|_, _| {}),
+ crate::largest_legal_job_charge().unwrap(),
+ );
+ let store = store_offset_request(
+ CLIENT,
+ 1,
+ ConsumerKind::Consumer,
+ CONSUMER,
+ 0,
+ AckLevel::NoAck,
+ );
+ partition
+ .apply_consumer_offset_no_ack(
+ Box::new(*store.header()),
+ ConsumerKind::Consumer,
+ CONSUMER,
+ Some(0),
+ None,
+ )
+ .await;
+ let config = repair_config();
+ let captured = loop {
+ match partition.resume_io(&config).await {
+ crate::PartitionIoStep::Progress => {}
+ crate::PartitionIoStep::Ready(plan) => {
+ break partition.capture_io(plan, &config).unwrap().unwrap();
+ }
+ _ => panic!("accepted store must reach its file write"),
+ }
+ };
+ assert_eq!(
+ captured.identity.continuation,
+ crate::PartitionIoContinuation::NoAck
+ );
+ assert!(partition.defer_primary_transfer(primary_transfer_grant(&partition)));
+ assert!(matches!(
+ partition.resume_io(&config).await,
+ crate::PartitionIoStep::Pending
+ ));
+ assert!(replies.borrow().is_empty());
+ let result = captured.job.execute().await;
+ assert!(matches!(
+ partition.resume_io(&config).await,
+ crate::PartitionIoStep::Pending
+ ));
+ partition.accept_io(captured.identity, result).unwrap();
+ if let Some(gate) = captured.gate {
+ gate.release();
+ }
+ let mut finished = false;
+ for _ in 0..STEPS_MAX {
+ match partition.resume_io(&config).await {
+ crate::PartitionIoStep::Progress => {}
+ crate::PartitionIoStep::Ready(plan) => {
+ execute_partition_io_plan(&mut partition, &config, plan).await;
+ }
+ crate::PartitionIoStep::PrimaryTransfer(_) => {
+ finished = true;
+ break;
+ }
+ _ => panic!("accepted store must settle before transfer"),
+ }
+ }
+ assert!(finished);
+ assert_eq!(
+ partition.get_consumer_offset(PollingConsumer::Consumer(
+ usize::try_from(CONSUMER).unwrap(),
+ 0,
+ )),
+ Some(0)
+ );
+ assert_eq!(replies.borrow().len(), 1);
+ assert_eq!(
+ bytemuck::checked::from_bytes::<ReplyHeader>(
+ &replies.borrow()[0].1.as_slice()[..size_of::<ReplyHeader>()],
+ )
+ .status,
+ 0
+ );
+ assert!(partition.no_ack.is_empty());
+ assert_eq!(partition.consensus.view(), 0);
+ }
+
+ #[compio::test]
+ async fn given_unapplied_commit_when_primary_transfer_drains_should_apply_before_handoff() {
+ const STEPS_MAX: usize = 64;
+ let directory = tempfile::tempdir().unwrap();
+ let (mut partition, _replies, config, parent) =
+ partition_with_committed_send(directory.path(), iggy_common::Durability::Replicated, 3)
+ .await;
+ partition.set_io_notifier(
+ Rc::new(|_, _| {}),
+ crate::largest_legal_job_charge().unwrap(),
+ );
+ let prepare = checksummed_segment_prepare(2, parent, 1, b"committed-before-transfer");
+ let header = *prepare.header();
+ let persistence = Rc::clone(partition.persistence.as_ref().unwrap());
+ persistence
+ .append(prepare.clone().into_frozen(), false)
+ .unwrap();
+ assert!(persistence.start());
+ Rc::clone(&persistence).run().await;
+ partition
+ .consensus
+ .with_pipeline_mut(|pipeline| pipeline.push(PipelineEntry::new(header)));
+ partition
+ .append_repaired_send_messages(prepare)
+ .await
+ .unwrap();
+ partition.consensus.sequencer().set_sequence(header.op);
+ partition
+ .consensus
+ .set_last_prepare_checksum(header.checksum);
+ partition.consensus.advance_commit_max(header.op);
+ assert_eq!(partition.consensus.commit_min(), 1);
+ assert!(partition.defer_primary_transfer(primary_transfer_grant(&partition)));
+ let mut finished = false;
+ for _ in 0..STEPS_MAX {
+ match partition.resume_io(&config).await {
+ crate::PartitionIoStep::Progress => {}
+ crate::PartitionIoStep::Ready(plan) => {
+ execute_partition_io_plan(&mut partition, &config, plan).await;
+ }
+ crate::PartitionIoStep::PrimaryTransfer(request) => {
+ assert_eq!(partition.consensus.commit_min(), header.op);
+ assert!(
+ !partition
+ .consensus
+ .request_primary_transfer(request.expected_view, request.target)
+ .is_empty()
+ );
+ finished = true;
+ break;
+ }
+ _ => panic!("committed prefix must drain under the admission fence"),
+ }
+ }
+ assert!(finished);
+ assert_eq!(partition.stats.messages_count_inconsistent(), 2);
+ assert!(partition.fatal().is_none());
+ }
+
+ #[compio::test]
+ async fn given_planned_primary_transfer_when_a_view_frame_arrives_should_preserve_real_transition()
+ {
+ let (mut partition, _) = recording_partition_at(0, 3);
+ let request = primary_transfer_grant(&partition);
+ let active = Arc::clone(&request.active);
+ assert!(partition.defer_primary_transfer(request));
+ let message = Message::<StartViewHeader>::new(size_of::<StartViewHeader>())
+ .transmute_header(|_, header: &mut StartViewHeader| {
+ header.command = Command::StartView;
+ header.size = u32::try_from(size_of::<StartViewHeader>()).unwrap();
+ header.view = 1;
+ header.replica = 1;
+ });
+ partition.defer_view_transition(server_common::MessageBag::StartView(message));
+ assert!(!active.load(Ordering::Acquire));
+ partition.cancel_primary_transfer();
+ assert!(matches!(
+ partition.transition,
+ Some(PendingPartitionTransition::View { .. })
+ ));
+ assert!(matches!(partition.resume_io(&repair_config()).await,
+ crate::PartitionIoStep::Transition(server_common::MessageBag::StartView(message))
+ if message.header().view == 1));
+ }
+
/// The primary's Commit heartbeat, handled as the shard's `on_commit` does.
async fn commit_on_heartbeat(
partition: &mut IggyPartition<RecordingBus>,
diff --git a/core/partitions/src/io.rs b/core/partitions/src/io.rs
index 1e516c7e1..842113351 100644
--- a/core/partitions/src/io.rs
+++ b/core/partitions/src/io.rs
@@ -20,8 +20,10 @@ use std::collections::HashSet;
use std::io::IoSlice;
use std::path::{Path, PathBuf};
use std::rc::Rc;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Poll, Waker};
-use std::time::Duration;
+use std::time::{Duration, Instant};
use compio::fs::File;
use consensus::VsrState;
@@ -298,12 +300,34 @@ pub struct PartitionIoPlan {
pub allocation_charge: usize,
}
+/// A coordinator grant issued only after fresh target readiness.
+///
+/// The shared flag revokes this one move on timeout or metadata leadership loss; the shard
+/// rechecks it and the captured history/view after draining, before election.
+/// The deadline also expires the grant while the coordinator is stalled.
+#[derive(Debug)]
+pub struct PreparedPrimaryTransfer {
+ pub created_revision: u64,
+ pub expected_view: u32,
+ pub target: u8,
+ pub active: Arc<AtomicBool>,
+ pub expires_at: Instant,
+}
+
+impl PreparedPrimaryTransfer {
+ #[must_use]
+ pub fn is_active_at(&self, now: Instant) -> bool {
+ self.active.load(Ordering::Acquire) && now < self.expires_at
+ }
+}
+
pub enum PartitionIoStep {
WireActions(Vec<consensus::VsrAction>),
Progress,
Pending,
Ready(PartitionIoPlan),
Transition(server_common::MessageBag),
+ PrimaryTransfer(PreparedPrimaryTransfer),
ViewApplied {
actions: Vec<consensus::VsrAction>,
peer: Option<u8>,
diff --git a/core/partitions/src/lib.rs b/core/partitions/src/lib.rs
index 92711d2ce..d71727bfd 100644
--- a/core/partitions/src/lib.rs
+++ b/core/partitions/src/lib.rs
@@ -57,7 +57,8 @@ pub use io::{
CapturedPartitionIo, MaterializationIoJob, MaterializationIoResult, PARTITION_IO_DRAIN_TIMEOUT,
PartitionIncarnation, PartitionIoContinuation, PartitionIoIdentity, PartitionIoJob,
PartitionIoNotifier, PartitionIoPlan, PartitionIoQuiescence, PartitionIoResources,
- PartitionIoResult, PartitionIoStep, PartitionTeardown, largest_legal_job_charge,
+ PartitionIoResult, PartitionIoStep, PartitionTeardown, PreparedPrimaryTransfer,
+ largest_legal_job_charge,
};
pub use journal::{EVICTED_RING_BYTES_MAX, EVICTED_RING_CAPACITY};
diff --git a/core/partitions/src/state_transfer.rs b/core/partitions/src/state_transfer.rs
index cd5748515..41e37a099 100644
--- a/core/partitions/src/state_transfer.rs
+++ b/core/partitions/src/state_transfer.rs
@@ -3346,6 +3346,7 @@ where
}
let pending =
self.prepare_state_transfer_install(commit_op, staged, offsets_bytes, peer)?;
+ self.cancel_primary_transfer();
self.transition = Some(crate::iggy_partition::PendingPartitionTransition::Install(
Box::new(pending),
));
@@ -4468,6 +4469,7 @@ where
let peer = self.consensus().primary_index(self.consensus().view());
let pending =
self.prepare_state_transfer_install(commit_op, staged, offsets_bytes, peer)?;
+ self.cancel_primary_transfer();
self.transition = Some(crate::iggy_partition::PendingPartitionTransition::Install(
Box::new(pending),
));
diff --git a/core/server/README.md b/core/server/README.md
index 348a8f857..e4693a6ad 100644
--- a/core/server/README.md
+++ b/core/server/README.md
@@ -44,9 +44,11 @@ Command-line arguments include `--replica-id`, `--fresh` (`-f`), `--with-default
Deploy matching server and SDK releases together. Rolling upgrades and mixed
server versions are unsupported. Partition control frames from older servers
carry incarnation zero and are rejected, so a mixed-version cluster cannot
-complete partition view changes. The `IGGY-OWNERSHIP-HISTORY-6` storage gate
+complete partition view changes. The `IGGY-OWNERSHIP-HISTORY-7` storage gate
requires fresh storage and rejects older data directories without modifying them.
Cached replies now preserve a committed-result marker, which older receipts lack.
+Partition creation records carry an initial view for each assignment, replacing
+the single request-wide view in older metadata WAL entries.
No in-place upgrade or implicit migration is supported. A separately validated
offline migration or restore procedure would be required to reuse existing data.
@@ -72,6 +74,16 @@ IGGY_TCP_ADDRESS=127.0.0.1:8090 IGGY_HTTP_ENABLED=false cargo run --bin iggy-ser
Cluster membership, quorum and replica addressing live under `[cluster]`.
+New partition primaries are spread across the configured replicas using each
+partition's last observed primary, or its committed initial view before an
+observation arrives. Concurrent creates count pending assignments too. Every
+configured replica remains eligible, including an offline replica; ordinary
+partition failover handles that initial target. After the responsive replica set
+has been stable for five seconds, the metadata primary balances existing primary
+counts one partition at a time. It confirms the source's committed frontier and
+the target's applied history before requesting a persisted consensus view change.
+Recovering partitions delay transfers. Every replica still stores every partition.
+
Protocol 0.11.1 uses client-owned registration proofs and `BindSession` (15) to
share a logical session across connections. Command 14 is retired. Primary
polling uses commands 103 and 104; offset routing uses 123. Disconnecting a
@@ -200,7 +212,7 @@ Before a partition can serve, initialization publishes its incarnation in
`partition-initialization/<namespace>/created.revision` under the system data
directory. This atomic record remains outside the partition directory, including
after that directory is lost. Preserve it with metadata and partition backups.
-Storage format `IGGY-OWNERSHIP-HISTORY-6` requires this initialization contract;
+Storage format `IGGY-OWNERSHIP-HISTORY-7` requires this initialization contract;
older data directories are refused before mutation.
Retirement also writes `retirement.fence` in that external namespace directory
diff --git a/core/server/src/boot/mod.rs b/core/server/src/boot/mod.rs
index 47be3b093..ff4ed3f4d 100644
--- a/core/server/src/boot/mod.rs
+++ b/core/server/src/boot/mod.rs
@@ -90,7 +90,7 @@ use tracing::{error, info, warn};
const STORAGE_FORMAT_FILE: &str = "storage-format";
const STORAGE_FORMAT_TEMP_FILE: &str = "storage-format.tmp";
-const STORAGE_FORMAT: &[u8] = b"IGGY-OWNERSHIP-HISTORY-6\n";
+const STORAGE_FORMAT: &[u8] = b"IGGY-OWNERSHIP-HISTORY-7\n";
/// Load the server configuration from the active config provider.
///
@@ -1235,6 +1235,7 @@ mod tests {
b"IGGY-OWNERSHIP-HISTORY-3\n",
b"IGGY-OWNERSHIP-HISTORY-4\n",
b"IGGY-OWNERSHIP-HISTORY-5\n",
+ b"IGGY-OWNERSHIP-HISTORY-6\n",
b"IGGY-DURABLE-SESSIONS-3\n",
&STORAGE_FORMAT[..STORAGE_FORMAT.len() - 1],
] {
diff --git a/core/server/src/consumer_group.rs b/core/server/src/consumer_group.rs
index 3f9d9d63a..bb832b505 100644
--- a/core/server/src/consumer_group.rs
+++ b/core/server/src/consumer_group.rs
@@ -302,11 +302,11 @@ mod tests {
derived_options: WireOptions::empty(),
partitions: (0..PARTITION_COUNT)
.map(|partition_id| CreatedPartitionAssignment {
+ initial_view: 0,
partition_id,
consensus_group_id: u64::from(partition_id) + 1,
})
.collect(),
- created_view: 0,
}
.to_bytes(),
))
diff --git a/core/server/src/consumer_group/liveness.rs b/core/server/src/consumer_group/liveness.rs
index 744f859aa..575858b5b 100644
--- a/core/server/src/consumer_group/liveness.rs
+++ b/core/server/src/consumer_group/liveness.rs
@@ -917,9 +917,9 @@ mod tests {
name: WireName::new("legacy").unwrap(),
options: WireOptions::empty(),
},
- created_view: 0,
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 2,
}],
@@ -1184,9 +1184,9 @@ mod tests {
name: WireName::new("topic").unwrap(),
options: WireOptions::empty(),
},
- created_view: 0,
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
diff --git a/core/server/src/dispatch/host.rs b/core/server/src/dispatch/host.rs
index 64f3cec3c..80d22867f 100644
--- a/core/server/src/dispatch/host.rs
+++ b/core/server/src/dispatch/host.rs
@@ -43,7 +43,7 @@ use crate::session_manager::SessionManager;
use crate::shell::{ShellBus, ShellShardHandle};
use ahash::AHashMap;
use configs::server::ServerConfig;
-use iggy_binary_protocol::{GenericHeader, PrepareHeader};
+use iggy_binary_protocol::{Command, GenericHeader, PrepareHeader};
use journal::superblock::{PingPongSuperblock, SuperblockStore};
use journal::{Journal, JournalHandle};
use message_bus::MessageBus;
@@ -155,13 +155,21 @@ where
S: 'static,
SB: SuperblockStore + 'static,
{
- fn on_replica_message(&self, _replica_id: u8, message: Message<GenericHeader>) {
+ fn on_replica_message(&self, replica_id: u8, message: Message<GenericHeader>) {
+ if message.header().command == Command::PrimaryRebalance
+ && message.header().replica != replica_id
+ {
+ return;
+ }
if let Some(shard) = upgrade_shard_handle(&self.shard_handle) {
shard.dispatch(message);
}
}
fn on_client_request(&self, client_id: u128, message: Message<GenericHeader>) {
+ if message.header().command == Command::PrimaryRebalance {
+ return;
+ }
enqueue_client_request(
&self.bus,
&self.shard_handle,
@@ -217,3 +225,119 @@ where
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::dispatch::test_support::{FIRST_BOOT, SpyBus, test_shard};
+ use iggy_binary_protocol::{
+ CommitHeader, ConsensusHeader, HEADER_SIZE, PrimaryRebalanceHeader, PrimaryRebalanceKind,
+ };
+ use journal::prepare_journal::PrepareJournal;
+ use metadata::impls::metadata::IggySnapshot;
+ use server_common::MessageBag;
+ use server_common::sharding::METADATA_GROUP;
+ use shard::{ShardFrame, shard_channel};
+
+ const REBALANCE_KINDS: [PrimaryRebalanceKind; 6] = [
+ PrimaryRebalanceKind::MetadataProbe,
+ PrimaryRebalanceKind::MetadataReply,
+ PrimaryRebalanceKind::PartitionProbe,
+ PrimaryRebalanceKind::PartitionReply,
+ PrimaryRebalanceKind::SourceProbe,
+ PrimaryRebalanceKind::SourceReply,
+ ];
+
+ fn rebalance_frame(kind: PrimaryRebalanceKind) -> Message<GenericHeader> {
+ Message::<PrimaryRebalanceHeader>::new(HEADER_SIZE)
+ .transmute_header(|_, header: &mut PrimaryRebalanceHeader| {
+ header.command = Command::PrimaryRebalance;
+ header.size = u32::try_from(HEADER_SIZE).unwrap();
+ header.cluster = 1;
+ header.replica = 2;
+ header.nonce = 1;
+ header.kind = kind;
+ if matches!(
+ kind,
+ PrimaryRebalanceKind::PartitionProbe
+ | PrimaryRebalanceKind::PartitionReply
+ | PrimaryRebalanceKind::SourceProbe
+ | PrimaryRebalanceKind::SourceReply
+ ) {
+ header.created_revision = 1;
+ }
+ header.ready = u8::from(matches!(
+ kind,
+ PrimaryRebalanceKind::MetadataReply
+ | PrimaryRebalanceKind::PartitionReply
+ | PrimaryRebalanceKind::SourceReply
+ ));
+ header.seal();
+ })
+ .into_generic()
+ }
+
+ #[test]
+ fn given_rebalance_ingress_when_sender_is_spoofed_should_drop_before_routing() {
+ let bus = SpyBus::default();
+ let mut shard = test_shard(&bus, 0, 3, FIRST_BOOT);
+ let (sender, inbox, _reply_inbox) = shard_channel(0, 1, 1);
+ shard.attach_senders(vec![sender]);
+ let shard = Rc::new(shard);
+ let handle = Rc::new(RefCell::new(Some(Rc::downgrade(&shard))));
+ let host = ServerHost::new(&bus, &handle, Arc::new(ServerConfig::default()), 1);
+ for kind in REBALANCE_KINDS {
+ host.on_replica_message(1, rebalance_frame(kind));
+ assert!(
+ inbox.try_recv().is_err(),
+ "spoofed {kind:?} reached the owner"
+ );
+ host.on_replica_message(2, rebalance_frame(kind));
+ let Ok(ShardFrame::Consensus {
+ target_shard: 0,
+ message: MessageBag::PrimaryRebalance(message),
+ }) = inbox.try_recv()
+ else {
+ panic!("authenticated {kind:?} must reach the metadata owner");
+ };
+ assert_eq!(message.header().kind, kind);
+ assert_eq!(message.header().replica, 2);
+ }
+
+ let commit = Message::<CommitHeader>::new(HEADER_SIZE).transmute_header(
+ |_, header: &mut CommitHeader| {
+ header.command = Command::Commit;
+ header.size = u32::try_from(HEADER_SIZE).unwrap();
+ header.replica = 0;
+ header.group = METADATA_GROUP;
+ header.seal();
+ },
+ );
+ host.on_replica_message(1, commit.into_generic());
+ assert!(matches!(
+ inbox.try_recv(),
+ Ok(ShardFrame::Consensus {
+ message: MessageBag::Commit(_),
+ ..
+ })
+ ));
+ }
+
+ #[compio::test]
+ async fn given_rebalance_frame_on_client_connection_when_received_should_not_admit_it() {
+ let bus = SpyBus::default();
+ let handle: ShellShardHandle<SpyBus, PrepareJournal, IggySnapshot> = Rc::default();
+ let host = ServerHost::new(&bus, &handle, Arc::new(ServerConfig::default()), 1);
+ for kind in REBALANCE_KINDS {
+ host.on_client_request(7, rebalance_frame(kind));
+ assert!(
+ host.queues.borrow().is_empty(),
+ "client {kind:?} was queued"
+ );
+ assert!(
+ host.active.borrow().is_empty(),
+ "client {kind:?} was admitted"
+ );
+ }
+ }
+}
diff --git a/core/server/src/dispatch/partition.rs b/core/server/src/dispatch/partition.rs
index b650b4832..63c6434dd 100644
--- a/core/server/src/dispatch/partition.rs
+++ b/core/server/src/dispatch/partition.rs
@@ -1832,15 +1832,16 @@ mod tests {
derived_options: WireOptions::empty(),
partitions: vec![
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
},
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 1,
consensus_group_id: 2,
},
],
- created_view: 0,
}
.to_bytes(),
))
@@ -2054,10 +2055,10 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
- created_view: 0,
};
md.mux_stm
.update(prepare_message(
@@ -2077,7 +2078,6 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: Vec::new(),
- created_view: 0,
};
md.mux_stm
.update(prepare_message(
@@ -3341,10 +3341,10 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
- created_view: 0,
};
md.mux_stm
.update(prepare_message(
@@ -3750,10 +3750,10 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
- created_view: 0,
}
.to_bytes(),
)
diff --git a/core/server/src/dispatch/test_support.rs b/core/server/src/dispatch/test_support.rs
index 49bad2958..611bf1d21 100644
--- a/core/server/src/dispatch/test_support.rs
+++ b/core/server/src/dispatch/test_support.rs
@@ -385,10 +385,10 @@ pub fn create_one_partition(shard: &TestShard) -> IggyNamespace {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id: 1,
}],
- created_view: 0,
}
.to_bytes(),
))
diff --git a/core/server/src/http/reads.rs b/core/server/src/http/reads.rs
index c83adfdec..a224c084b 100644
--- a/core/server/src/http/reads.rs
+++ b/core/server/src/http/reads.rs
@@ -614,10 +614,10 @@ mod tests {
},
derived_options: WireOptions::empty(),
partitions: vec![CreatedPartitionAssignment {
+ initial_view: 0,
partition_id: 0,
consensus_group_id,
}],
- created_view: 0,
},
);
GetTopicResponse::decode_from(&reply).unwrap().topic.id as usize
diff --git a/core/server/src/partition_helpers.rs b/core/server/src/partition_helpers.rs
index 4cc492f38..d49f6a53e 100644
--- a/core/server/src/partition_helpers.rs
+++ b/core/server/src/partition_helpers.rs
@@ -902,11 +902,9 @@ async fn recover_partition_segments(
/// The namespace arrives packed, so its components are in range by
/// construction. Metadata admission is what bounds them.
///
-/// `created_view` is the view a group with no durable record of its own starts
-/// in: the metadata plane's view when it committed the create, recorded on
-/// the committed partition so every replica seeds the same value. See the
-/// `seed_view` comment below for why a group left at view 0 is unreachable. A
-/// restart keeps it as a view floor while probing for the live view, without
+/// `created_view` is the committed assignment's initial view, independent of
+/// metadata leadership. Every replica seeds a fresh group from that value.
+/// A restart keeps it as a view floor while probing for the live view, without
/// assigning it to the recovered log.
///
/// The returned partition's `offset` / `dirty_offset` are `0` and its
@@ -1030,22 +1028,10 @@ pub async fn build_partition_fresh(
timers: &timers,
durable_view,
view_fallback,
- // Both planes pick their primary as `view % replica_count` from
- // their OWN view counter. A group left at view 0 while the
- // metadata plane sits elsewhere therefore names a different node
- // than the roster advertises as leader, and nothing routes a
- // partition write across that gap: the client is sent to the
- // metadata leader and refused there for the whole budget. Seeding
- // from the view the create was admitted in keeps the two congruent
- // for a group born after a metadata election.
- //
- // The seed comes off the committed partition, not this replica's
- // live metadata view: the two differ once the metadata plane
- // elects again, and a seed above the group's real view is an
- // empty log that outranks committed history in the next DVC
- // merge. The value rides the create's request body (a header view
- // is restamped per delivery), so every replica commits the same
- // one and a late materialiser lands at or below its peers.
+ // Placement chooses this group's initial view independently of
+ // metadata leadership. Use its committed assignment: a late
+ // materializer must not invent a higher empty history that could
+ // outrank acknowledged entries in the next view change.
seed_view,
incarnation: None,
join,
diff --git a/core/server/src/partition_reconciler.rs b/core/server/src/partition_reconciler.rs
index 29793c658..1a4ad30d9 100644
--- a/core/server/src/partition_reconciler.rs
+++ b/core/server/src/partition_reconciler.rs
@@ -2043,6 +2043,7 @@ mod tests {
fn assignment(partition_id: u32, consensus_group_id: u64) -> CreatedPartitionAssignment {
CreatedPartitionAssignment {
+ initial_view: 0,
partition_id,
consensus_group_id,
}
@@ -2070,13 +2071,12 @@ mod tests {
let req = CreateTopicWithAssignmentsRequest {
request: CreateTopicRequest {
stream_id: WireIdentifier::numeric(stream_id),
- partitions_count: 1,
+ partitions_count: u32::try_from(assignments.len()).unwrap(),
name: WireName::new(name).expect("test topic name fits WireName"),
options: WireOptions::empty(),
},
derived_options: WireOptions::empty(),
partitions: assignments,
- created_view: 0,
};
mux.update(build_prepare(
op,
@@ -3075,7 +3075,6 @@ mod tests {
partitions_count: 2,
},
partitions: vec![assignment(0, 3), assignment(1, 4)],
- created_view: 0,
},
))
.expect("CreatePartitions apply succeeds");
@@ -5134,7 +5133,6 @@ mod tests {
partitions_count: 1,
},
partitions: vec![assignment(0, 3)],
- created_view: 0,
},
))
.expect("CreatePartitions apply succeeds");
diff --git a/core/server_common/src/consensus_message.rs b/core/server_common/src/consensus_message.rs
index 6e5cc8ccf..03c5ebdfc 100644
--- a/core/server_common/src/consensus_message.rs
+++ b/core/server_common/src/consensus_message.rs
@@ -22,11 +22,11 @@ use iggy_binary_protocol::{
Command, CommitHeader, ConsensusError, ConsensusHeader, ConsumerSessionHeartbeatHeader,
DoViewChangeHeader, ForwardCompletionHeader, ForwardLogoutHeader, ForwardLogoutResultHeader,
ForwardRegisterHeader, ForwardRegisterResultHeader, GenericHeader, HEADER_SIZE, Operation,
- PrepareHeader, PrepareOkHeader, RepairPrepareHeader, RepairRangeReplyHeader, RequestHeader,
- RequestPreparesHeader, RequestStartViewHeader, RequestStateChunkHeader,
- RequestStateTransferHeader, RoutedRequestHeader, StartViewChangeHeader, StartViewHeader,
- StateChunkHeader, StateTransferTargetHeader, frame_checksum_bytes,
- prepare_identity_checksum_bytes,
+ PrepareHeader, PrepareOkHeader, PrimaryRebalanceHeader, RepairPrepareHeader,
+ RepairRangeReplyHeader, RequestHeader, RequestPreparesHeader, RequestStartViewHeader,
+ RequestStateChunkHeader, RequestStateTransferHeader, RoutedRequestHeader,
+ StartViewChangeHeader, StartViewHeader, StateChunkHeader, StateTransferTargetHeader,
+ frame_checksum_bytes, prepare_identity_checksum_bytes,
};
use smallvec::SmallVec;
use std::{
@@ -647,6 +647,8 @@ pub enum MessageBag {
ForwardLogoutResult(Message<ForwardLogoutResultHeader>),
/// A backup reports session liveness to the metadata primary without a reply.
ConsumerSessionHeartbeat(Message<ConsumerSessionHeartbeatHeader>),
+ /// Readiness exchanges pass through shard 0 before reaching a partition owner.
+ PrimaryRebalance(Message<PrimaryRebalanceHeader>),
/// A backup relays a partition completion to the metadata primary without a reply.
ForwardCompletion(Message<ForwardCompletionHeader>),
}
@@ -735,6 +737,7 @@ impl MessageBag {
}
Self::ForwardLogoutResult(message) => (message.header().operation(), METADATA_GROUP),
Self::ForwardCompletion(message) => (message.header().operation(), METADATA_GROUP),
+ Self::PrimaryRebalance(message) => (message.header().operation(), METADATA_GROUP),
}
}
@@ -768,6 +771,7 @@ impl MessageBag {
Self::ConsumerSessionHeartbeat(message) => message.into_generic(),
Self::ForwardLogoutResult(message) => message.into_generic(),
Self::ForwardCompletion(message) => message.into_generic(),
+ Self::PrimaryRebalance(message) => message.into_generic(),
}
}
@@ -795,6 +799,7 @@ impl MessageBag {
Self::ConsumerSessionHeartbeat(message) => message.header().command,
Self::ForwardLogoutResult(message) => message.header().command,
Self::ForwardCompletion(message) => message.header().command,
+ Self::PrimaryRebalance(message) => message.header().command,
}
}
@@ -822,6 +827,7 @@ impl MessageBag {
Self::ConsumerSessionHeartbeat(message) => message.header().size(),
Self::ForwardLogoutResult(message) => message.header().size(),
Self::ForwardCompletion(message) => message.header().size(),
+ Self::PrimaryRebalance(message) => message.header().size(),
}
}
@@ -849,6 +855,7 @@ impl MessageBag {
Self::ConsumerSessionHeartbeat(message) => message.header().operation(),
Self::ForwardLogoutResult(message) => message.header().operation(),
Self::ForwardCompletion(message) => message.header().operation(),
+ Self::PrimaryRebalance(message) => message.header().operation(),
}
}
}
@@ -990,6 +997,9 @@ where
Command::ForwardCompletion => Ok(Self::ForwardCompletion(
value.try_into_typed::<ForwardCompletionHeader>()?,
)),
+ Command::PrimaryRebalance => Ok(Self::PrimaryRebalance(
+ value.try_into_typed::<PrimaryRebalanceHeader>()?,
+ )),
// Reply / Eviction are server-to-client frames; they do not
// appear on the inbound dispatch path.
Command::Reply | Command::Eviction => Err(ConsensusError::ClientBoundCommand(command)),
@@ -1006,9 +1016,10 @@ mod tests {
use super::*;
use iggy_binary_protocol::{
ForwardLogoutHeader, ForwardLogoutOutcome, ForwardLogoutResultHeader, HEADER_SIZE,
- Operation, ReplyHeader, RequestHeader, frame_checksum_bytes,
+ Operation, PrimaryRebalanceKind, ReplyHeader, RequestHeader, frame_checksum_bytes,
};
use smallvec::smallvec;
+ use std::mem::offset_of;
// Field offsets via `offset_of!`: a field reorder fails to compile here
// rather than silently corrupting test bytes.
@@ -1319,6 +1330,121 @@ mod tests {
assert_eq!(result.size(), HEADER_SIZE as u32);
}
+ fn primary_rebalance_frame(kind: PrimaryRebalanceKind) -> Message<PrimaryRebalanceHeader> {
+ Message::<PrimaryRebalanceHeader>::new(HEADER_SIZE).transmute_header(
+ |_, header: &mut PrimaryRebalanceHeader| {
+ header.command = Command::PrimaryRebalance;
+ header.size = HEADER_SIZE as u32;
+ header.cluster = 7;
+ header.view = 11;
+ header.replica = 2;
+ header.nonce = 13;
+ header.kind = kind;
+ if matches!(
+ kind,
+ PrimaryRebalanceKind::PartitionProbe
+ | PrimaryRebalanceKind::PartitionReply
+ | PrimaryRebalanceKind::SourceProbe
+ | PrimaryRebalanceKind::SourceReply
+ ) {
+ header.namespace = 17;
+ header.created_revision = 19;
+ header.commit = 23;
+ header.partition_view = 5;
+ }
+ header.ready = u8::from(matches!(
+ kind,
+ PrimaryRebalanceKind::MetadataReply
+ | PrimaryRebalanceKind::PartitionReply
+ | PrimaryRebalanceKind::SourceReply
+ ));
+ header.seal();
+ },
+ )
+ }
+
+ #[test]
+ fn given_rebalance_phases_when_dispatched_should_route_through_metadata_with_identity_intact() {
+ for kind in [
+ PrimaryRebalanceKind::MetadataProbe,
+ PrimaryRebalanceKind::MetadataReply,
+ PrimaryRebalanceKind::PartitionProbe,
+ PrimaryRebalanceKind::PartitionReply,
+ PrimaryRebalanceKind::SourceProbe,
+ PrimaryRebalanceKind::SourceReply,
+ ] {
+ let frame = primary_rebalance_frame(kind);
+ let expected = *frame.header();
+ let bag = MessageBag::try_from(frame.into_generic()).unwrap();
+ assert!(matches!(bag, MessageBag::PrimaryRebalance(_)));
+ assert_eq!(bag.routing(), (Operation::Reserved, METADATA_GROUP));
+ assert_eq!(bag.command(), Command::PrimaryRebalance);
+ assert_eq!(bag.operation(), Operation::Reserved);
+ assert_eq!(bag.size(), HEADER_SIZE as u32);
+ let decoded = bag
+ .into_generic()
+ .try_into_typed::<PrimaryRebalanceHeader>()
+ .unwrap();
+ assert_eq!(*decoded.header(), expected);
+ assert!(decoded.body().is_empty());
+ }
+ }
+
+ #[test]
+ fn given_invalid_rebalance_fields_when_dispatched_should_reject_before_routing() {
+ for (offset, value, bit_pattern) in [
+ (offset_of!(PrimaryRebalanceHeader, kind), u8::MAX, true),
+ (offset_of!(PrimaryRebalanceHeader, reserved_frame), 1, false),
+ (offset_of!(PrimaryRebalanceHeader, reserved), 1, false),
+ (offset_of!(PrimaryRebalanceHeader, checksum_body), 1, false),
+ (offset_of!(PrimaryRebalanceHeader, release), 1, false),
+ (offset_of!(PrimaryRebalanceHeader, nonce), 0, false),
+ (offset_of!(PrimaryRebalanceHeader, ready), 1, false),
+ (offset_of!(PrimaryRebalanceHeader, namespace), 1, false),
+ ] {
+ let mut owned =
+ primary_rebalance_frame(PrimaryRebalanceKind::MetadataProbe).into_owned();
+ owned.as_mut_slice()[offset] = value;
+ seal_header_bytes(owned.as_mut_slice());
+ let generic = Message::<GenericHeader>::try_from(owned).unwrap();
+ let error = MessageBag::try_from(generic).unwrap_err();
+ if bit_pattern {
+ assert!(matches!(error, ConsensusError::InvalidBitPattern));
+ } else {
+ assert!(
+ matches!(error, ConsensusError::InvalidField(_)),
+ "{offset}: {error}"
+ );
+ }
+ }
+
+ let mut owned = primary_rebalance_frame(PrimaryRebalanceKind::PartitionReply).into_owned();
+ owned.as_mut_slice()[offset_of!(PrimaryRebalanceHeader, nonce)] ^= 1;
+ let generic = Message::<GenericHeader>::try_from(owned).unwrap();
+ assert!(matches!(
+ MessageBag::try_from(generic),
+ Err(ConsensusError::FrameChecksumMismatch { .. })
+ ));
+ }
+
+ #[test]
+ fn given_a_rebalance_frame_when_it_advertises_a_body_should_reject_before_routing() {
+ let valid = primary_rebalance_frame(PrimaryRebalanceKind::PartitionProbe);
+ let mut owned = Owned::<MESSAGE_ALIGN>::zeroed(HEADER_SIZE + 1);
+ owned.as_mut_slice()[..HEADER_SIZE].copy_from_slice(valid.as_slice());
+ owned.as_mut_slice()[SIZE_OFF..SIZE_OFF + size_of::<u32>()]
+ .copy_from_slice(&((HEADER_SIZE + 1) as u32).to_le_bytes());
+ seal_header_bytes(owned.as_mut_slice());
+ let generic = Message::<GenericHeader>::try_from(owned).unwrap();
+ assert!(matches!(
+ MessageBag::try_from(generic),
+ Err(ConsensusError::InvalidSize {
+ expected: 256,
+ found: 257
+ })
+ ));
+ }
+
// Construction via Message::new (zeroed)
#[test]
diff --git a/core/shard/src/lib.rs b/core/shard/src/lib.rs
index 9ac537a7e..0970ef4c1 100644
--- a/core/shard/src/lib.rs
+++ b/core/shard/src/lib.rs
@@ -23,6 +23,7 @@ pub mod metrics;
mod partition_io;
pub use partition_io::{PartitionIoLimits, PartitionIoLimitsError};
mod poll;
+mod primary_rebalance;
mod router;
pub mod shards_table;
@@ -65,7 +66,7 @@ use message_bus::installer::conn_info::{ClientConnMeta, ClientTransportKind};
use message_bus::replica::listener::MessageHandler;
use message_bus::{BusMessage, ConnectionPermit, MessageBus, SharedTlsServerConfig};
use metadata::IggyMetadata;
-use metadata::impls::metadata::StreamsFrontend;
+use metadata::impls::metadata::{PartitionPlacementView, StreamsFrontend};
use metadata::stm::StateMachine;
use metadata::{BoundSession, MetadataSubmitError};
use partitions::state_transfer::TransferArtifact;
@@ -124,16 +125,18 @@ where
pub struct PartitionMaterialisation {
epoch: u64,
created_view: u32,
+ first_initialization: bool,
consumer_offsets_max: usize,
}
#[cfg(feature = "simulator")]
impl PartitionMaterialisation {
#[must_use]
- pub const fn new(epoch: u64, created_view: u32) -> Self {
+ pub const fn new(epoch: u64, created_view: u32, first_initialization: bool) -> Self {
Self {
epoch,
created_view,
+ first_initialization,
consumer_offsets_max: partitions::DEFAULT_CONSUMER_OFFSETS_MAX,
}
}
@@ -905,6 +908,9 @@ pub enum LifecycleFrame {
/// the per-shard reconciler. No payload: reconciler re-reads target
/// state. Drops covered by the periodic safety tick.
MetadataCommitTick,
+ /// Last-known serving views, retried by a bounded sweep on each owning shard.
+ PartitionPlacementViews(Vec<PartitionPlacementView>),
+ PrimaryRebalance(Box<primary_rebalance::LocalRebalance>),
PartitionPersistenceCompleted(partitions::PersistenceCompletion),
/// Wake marker for the reconciler-to-pump funnel. Pump drains the
/// shard's `reconcile_queue` on receipt; tail drain on every frame
@@ -1674,6 +1680,8 @@ where
/// cursor the leading groups would spend the whole budget on every pass and
/// the tail would never be reached. See [`rotate_sweep_to_cursor`].
partition_walk_cursor: Cell<Option<IggyNamespace>>,
+ partition_placement_cursor: Cell<Option<IggyNamespace>>,
+ primary_rebalance: RefCell<primary_rebalance::PrimaryRebalance>,
/// Consecutive metadata superblock write failures tolerated before the
/// process fail-stops. Defaults to 0 (disabled) so the simulator and tests
@@ -1912,6 +1920,8 @@ where
repair_gap_debounce_ticks: Cell::new(partitions::REPAIR_RETRY_TICKS),
partition_repairs_inflight: Cell::new(0),
partition_walk_cursor: Cell::new(None),
+ partition_placement_cursor: Cell::new(None),
+ primary_rebalance: RefCell::default(),
superblock_wedged_fatal_failures: Cell::new(0),
bus_max_message_size: Cell::new(DEFAULT_BUS_MAX_MESSAGE_SIZE),
metadata_transfer_attempts: Cell::new(0),
@@ -2486,6 +2496,8 @@ where
repair_gap_debounce_ticks: Cell::new(partitions::REPAIR_RETRY_TICKS),
partition_repairs_inflight: Cell::new(0),
partition_walk_cursor: Cell::new(None),
+ partition_placement_cursor: Cell::new(None),
+ primary_rebalance: RefCell::default(),
superblock_wedged_fatal_failures: Cell::new(0),
bus_max_message_size: Cell::new(DEFAULT_BUS_MAX_MESSAGE_SIZE),
metadata_transfer_attempts: Cell::new(0),
@@ -3300,7 +3312,11 @@ where
M: RestorableMetadataStm,
T: ShardsTable,
{
+ self.fence_rebalance_authority(&message);
match message {
+ MessageBag::PrimaryRebalance(message) => {
+ self.on_primary_rebalance(*message.header()).await;
+ }
MessageBag::Request(request) => {
// One header read for the pair; `header()` casts on every call.
let routing = {
@@ -4463,8 +4479,8 @@ where
/// reports `commit_offset` 0, which reads as a regression rather than a
/// harness that discarded the log.
///
- /// `materialisation` carries the committed `created_revision` and the view
- /// the metadata plane created the namespace in; see `fresh_group_start`.
+ /// `materialisation` carries the committed `created_revision` and this
+ /// partition's assigned initial view; see `fresh_group_start`.
///
/// Once inserted, this also runs the same parked-frame redispatch as
/// `ReconcileOp::InsertOwned`. The simulator bypasses the reconciler build,
@@ -4493,6 +4509,7 @@ where
let PartitionMaterialisation {
epoch,
created_view,
+ first_initialization,
consumer_offsets_max,
} = materialisation;
let partitions = self.plane.partitions();
@@ -4509,27 +4526,15 @@ where
LocalPipeline::new(),
self.partition_consensus.clock.clone(),
);
- // The SAME decision `build_partition_fresh` makes, not a copy of it.
- // This path cannot call that builder (it does real filesystem work and
- // this runs on in-memory storage), and while the two decided
- // separately the simulator exercised neither the creation-view seed
- // nor the plane split it closes. `retained` is populated only by the
- // restart path, which is this path's evidence of a prior life.
let durable_view = recovered_state
.as_ref()
.map(|state| (state.view, state.log_view));
- let recovered_metadata = self
- .plane
- .metadata()
- .applied_frontier()
- .recovered_revision();
- // Synthetic seed helpers create revision-zero groups in an explicitly
- // fresh simulator. A restart always supplies retained state.
- let allow_bootstrap = epoch > recovered_metadata
- || (epoch == 0 && recovered_metadata == 0 && retained.is_none());
- consensus.set_recovery_election_allowed(allow_bootstrap || retained.is_some());
- let restarted =
- (retained.is_some() || !allow_bootstrap) && self.partition_consensus.replica_count > 1;
+ // The harness's incarnation-qualified store is its initialization ledger.
+ // Recovered metadata can precede the group's first materialization;
+ // missing retained history alone cannot distinguish that from data loss.
+ consensus.set_recovery_election_allowed(first_initialization || retained.is_some());
+ let restarted = (retained.is_some() || !first_initialization)
+ && self.partition_consensus.replica_count > 1;
let consensus::FreshGroupStart {
join,
view_fallback,
@@ -5846,6 +5851,8 @@ where
if consensus.state_transfer_stage() == consensus::StateTransferStage::Idle {
*self.metadata_repair.borrow_mut() = None;
consensus.begin_state_transfer_await();
+ *self.primary_rebalance.borrow_mut() =
+ primary_rebalance::PrimaryRebalance::default();
tracing::info!(
shard = self.id,
peer = header.replica,
@@ -7866,6 +7873,7 @@ where
// the pump's owned scratch (as `process_loopback` does) so no
// partitions-plane borrow is held across the tick `.await`.
namespace_scratch.extend(partitions.namespaces().copied());
+ self.publish_partition_views(namespace_scratch);
// Resume where the last sweep ran out of walk budget, so the cap below
// spreads over every group instead of replaying the same prefix.
rotate_sweep_to_cursor(namespace_scratch, self.partition_walk_cursor.get());
@@ -8491,6 +8499,61 @@ where
fatal
}
+ /// Re-read a bounded range on retry so a full inbox retains no stale payload.
+ fn publish_partition_views(&self, namespaces: &[IggyNamespace]) {
+ if namespaces.is_empty() {
+ self.partition_placement_cursor.set(None);
+ return;
+ }
+ let Some(sender) = self.senders.first() else {
+ return;
+ };
+ let start = self.partition_placement_cursor.get().map_or(0, |cursor| {
+ namespaces.partition_point(|namespace| *namespace < cursor) % namespaces.len()
+ });
+ let visited = namespaces
+ .len()
+ .min(PARTITION_PLACEMENT_REPORTS_PER_TICK_MAX);
+ let partitions = self.plane.partitions();
+ let mut reports = Vec::with_capacity(visited);
+ for namespace in namespaces[start..]
+ .iter()
+ .chain(&namespaces[..start])
+ .take(visited)
+ {
+ let Some(partition) = partitions.get_by_ns(namespace) else {
+ continue;
+ };
+ let consensus = partition.consensus();
+ let view = consensus.view();
+ if partition.fatal().is_none()
+ && consensus.is_normal()
+ && !consensus.is_transferring()
+ && !(consensus.has_ceded_primaryship()
+ && consensus.primary_index(view) == consensus.replica())
+ {
+ reports.push(PartitionPlacementView {
+ namespace: *namespace,
+ created_revision: partition.created_revision(),
+ view,
+ });
+ }
+ }
+ if !reports.is_empty()
+ && let Err(error) = sender.try_send(ShardFrame::lifecycle(
+ LifecycleFrame::PartitionPlacementViews(reports),
+ ))
+ {
+ self.metrics.record_frame_drop(
+ metrics::frame_drop_variant::PARTITION_PLACEMENT_VIEWS,
+ coordinator::classify_try_send_err(&error),
+ );
+ return;
+ }
+ self.partition_placement_cursor
+ .set(Some(namespaces[(start + visited) % namespaces.len()]));
+ }
+
/// Whether this shard may build a partition offer for `namespace` without
/// pushing the served-payload working set past its byte budget.
///
@@ -10434,7 +10497,8 @@ where
#[allow(clippy::future_not_send, clippy::too_many_lines)]
pub async fn tick_metadata(&self)
where
- B: MessageBus,
+ B: MessageBus + 'static,
+ T: ShardsTable,
MJ: JournalHandle,
<MJ as JournalHandle>::Target:
Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>,
@@ -10457,6 +10521,9 @@ where
refresh_metadata_dvc_suffix(consensus, metadata.journal.as_ref());
}
let actions = consensus.tick(PlaneKind::Metadata);
+ if !consensus.is_primary() || !primary_rebalance::consensus_ready(consensus) {
+ *self.primary_rebalance.borrow_mut() = primary_rebalance::PrimaryRebalance::default();
+ }
let (local_actions, wire_actions) = split_local_actions(actions);
dispatch_vsr_actions(consensus, metadata.journal.as_ref(), &local_actions).await;
@@ -10492,6 +10559,8 @@ where
// would otherwise wait for unrelated traffic. Quiet no-op when
// nothing is stranded.
metadata.resume_stranded_commits().await;
+ metadata.refresh_placement().await;
+ self.tick_primary_rebalance().await;
self.advance_pending_metadata_view().await;
self.expire_idle_state_transfer_offers();
@@ -11112,6 +11181,9 @@ const PARTITION_REPAIRS_INFLIGHT_MAX: usize = 8;
/// `ceil(groups / cap)` ticks however many groups are owed at once.
const PARTITION_WALKS_PER_TICK_MAX: usize = 16;
+/// One lifecycle batch per tick; the cursor also bounds visits to ineligible groups.
+const PARTITION_PLACEMENT_REPORTS_PER_TICK_MAX: usize = 64;
+
/// Floor under the gap detector's debounce, in ticks.
///
/// The debounce reads `[cluster] repair_gap_debounce_interval`, and
@@ -13749,6 +13821,478 @@ mod metadata_repair_session_tests {
}
}
+#[cfg(test)]
+mod partition_placement_tests {
+ use super::*;
+ use consensus::{CLIENTS_TABLE_MAX, LocalPipeline, build_reply_message_with};
+ use iggy_binary_protocol::requests::topics::{
+ CreateTopicRequest, CreateTopicWithAssignmentsRequest,
+ };
+ use iggy_binary_protocol::{
+ ReplyHeader, WireDecode, WireEncode, WireIdentifier, WireName, WireOptions,
+ };
+ use iggy_common::{IggyByteSize, PartitionStats};
+ use journal::prepare_journal::PrepareJournal;
+ use message_bus::IggyMessageBus;
+ use metadata::MuxStateMachine;
+ use metadata::impls::metadata::IggySnapshot;
+ use metadata::impls::recovery::{ReplicaIdentity, recover};
+ use metadata::stm::stream::Streams;
+ use metadata::stm::user::Users;
+ use partitions::{PartitionPathLayout, PartitionsConfig};
+ use server_common::sharding::METADATA_GROUP;
+ use shards_table::PapayaShardsTable;
+ use std::collections::BTreeSet;
+ use std::mem::size_of;
+ use std::sync::Arc;
+
+ type PlacementShard = IggyShard<
+ Rc<IggyMessageBus>,
+ PrepareJournal,
+ IggySnapshot,
+ MuxStateMachine<variadic!(Users, Streams)>,
+ PapayaShardsTable,
+ >;
+
+ fn owner(shard_id: u16) -> (PlacementShard, Receiver<ShardFrame>) {
+ let bus = Rc::new(IggyMessageBus::new(shard_id));
+ let segment_size = IggyByteSize::from(1_048_576_u64);
+ let partitions = IggyPartitions::new(
+ ShardId::new(shard_id),
+ PartitionsConfig {
+ messages_required_to_save: 100,
+ size_of_messages_required_to_save: segment_size,
+ validate_checksum: true,
+ segment_size,
+ preallocate_segments: false,
+ encryptor: None,
+ path_layout: PartitionPathLayout::default(),
+ },
+ );
+ let metadata = IggyMetadata::new(
+ None,
+ None,
+ None,
+ None,
+ MuxStateMachine::<variadic!(Users, Streams)>::default(),
+ None,
+ );
+ let mut shard = PlacementShard::without_inbox(
+ ShardIdentity::new(shard_id, "partition-placement-test".to_string()),
+ bus.clone(),
+ metadata,
+ partitions,
+ PapayaShardsTable::new(),
+ PartitionConsensusConfig::new(1, ReplicaTopology::new(0, 3), bus),
+ );
+ let (senders, mut inboxes, _reply_inboxes) = shard_mesh_channels(shard_id + 1, 1, 1);
+ let target = inboxes[0].take().expect("shard zero inbox");
+ shard.attach_senders(senders);
+ (shard, target)
+ }
+
+ fn insert(shard: &PlacementShard, id: usize, revision: u64, view: u32) -> IggyNamespace {
+ let namespace = IggyNamespace::new(0, 0, id);
+ let mut consensus = VsrConsensus::new(
+ 1,
+ 0,
+ 3,
+ namespace.inner(),
+ shard.bus.clone(),
+ LocalPipeline::new(),
+ );
+ consensus.set_view(view);
+ consensus.init();
+ let mut partition = IggyPartition::with_in_memory_storage(
+ Arc::new(PartitionStats::default()),
+ consensus,
+ shard.plane.partitions().config().segment_size,
+ );
+ partition.set_created_revision(revision);
+ shard.plane.partitions().insert(namespace, partition);
+ namespace
+ }
+
+ fn publish(shard: &PlacementShard) {
+ let namespaces: Vec<_> = shard.plane.partitions().namespaces().copied().collect();
+ shard.publish_partition_views(&namespaces);
+ }
+
+ fn receive(inbox: &Receiver<ShardFrame>) -> Vec<PartitionPlacementView> {
+ let ShardFrame::Lifecycle(LifecycleFrame::PartitionPlacementViews(reports)) =
+ inbox.try_recv().expect("placement report queued")
+ else {
+ panic!("expected partition placement observations");
+ };
+ assert!(inbox.try_recv().is_err(), "at most one batch per sweep");
+ reports
+ }
+
+ #[compio::test]
+ async fn given_owned_groups_when_ticking_should_report_only_normal_serving_views_to_shard_zero()
+ {
+ for shard_id in [0, 1] {
+ let (shard, inbox) = owner(shard_id);
+ for id in 0..6 {
+ let view = u32::from(id == 1);
+ insert(&shard, id, 7, view);
+ }
+ let partitions = shard.plane.partitions();
+ partitions
+ .get_by_ns(&IggyNamespace::new(0, 0, 2))
+ .unwrap()
+ .consensus()
+ .begin_view_probe();
+ partitions
+ .get_by_ns(&IggyNamespace::new(0, 0, 3))
+ .unwrap()
+ .consensus()
+ .begin_state_transfer_await();
+ partitions
+ .get_by_ns(&IggyNamespace::new(0, 0, 4))
+ .unwrap()
+ .consensus()
+ .init_as_backup();
+ partitions.tombstone(IggyNamespace::new(0, 0, 5));
+
+ assert!(shard.tick_partitions(&mut Vec::new()).await.is_none());
+
+ let reports = receive(&inbox);
+ assert_eq!(reports.len(), 2);
+ assert_eq!(reports[0].namespace, IggyNamespace::new(0, 0, 0));
+ assert_eq!(reports[0].view, 0, "a normal primary contributes");
+ assert_eq!(reports[1].namespace, IggyNamespace::new(0, 0, 1));
+ assert_eq!(
+ reports[1].view, 1,
+ "a normal backup contributes its known view"
+ );
+ assert!(reports.iter().all(|report| report.created_revision == 7));
+ }
+ }
+
+ #[compio::test]
+ async fn given_more_groups_than_one_batch_when_publishing_should_bound_batches_and_cover_the_tail()
+ {
+ let (shard, inbox) = owner(1);
+ let count = PARTITION_PLACEMENT_REPORTS_PER_TICK_MAX * 2 + 3;
+ for id in 0..count {
+ insert(&shard, id, 7, 0);
+ }
+ let mut observed = BTreeSet::new();
+ for _ in 0..count.div_ceil(PARTITION_PLACEMENT_REPORTS_PER_TICK_MAX) {
+ publish(&shard);
+ let reports = receive(&inbox);
+ assert_eq!(reports.len(), PARTITION_PLACEMENT_REPORTS_PER_TICK_MAX);
+ observed.extend(
+ reports
+ .into_iter()
+ .map(|report| report.namespace.partition_id()),
+ );
+ }
+ assert_eq!(observed, (0..count).collect());
+
+ let removed = shard.partition_placement_cursor.get().unwrap();
+ shard.plane.partitions().remove(&removed);
+ publish(&shard);
+ let reports = receive(&inbox);
+ assert_eq!(
+ reports[0].namespace.partition_id(),
+ removed.partition_id() + 1
+ );
+ assert!(reports.iter().all(|report| report.namespace != removed));
+ }
+
+ #[compio::test]
+ async fn given_a_full_inbox_when_retried_should_publish_current_incarnation_without_skipping_groups()
+ {
+ let (shard, inbox) = owner(1);
+ let namespace = insert(&shard, 0, 7, 0);
+ insert(&shard, 1, 7, 0);
+ assert!(
+ shard.senders[0]
+ .try_send(ShardFrame::lifecycle(LifecycleFrame::MetadataCommitTick))
+ .is_ok()
+ );
+
+ publish(&shard);
+ assert_eq!(shard.partition_placement_cursor.get(), None);
+ assert_eq!(
+ inbox.len(),
+ 1,
+ "no deferred report queue grows behind the full inbox"
+ );
+ assert!(matches!(
+ inbox.try_recv(),
+ Ok(ShardFrame::Lifecycle(LifecycleFrame::MetadataCommitTick))
+ ));
+ shard.plane.partitions().remove(&namespace);
+ insert(&shard, 0, 11, 9);
+
+ publish(&shard);
+ let reports = receive(&inbox);
+ assert_eq!(reports.len(), 2);
+ assert_eq!(reports[0].namespace, namespace);
+ assert_eq!(reports[0].created_revision, 11);
+ assert_eq!(
+ reports[0].view, 9,
+ "retry rereads rather than retaining the old observation"
+ );
+ assert_eq!(reports[1].namespace, IggyNamespace::new(0, 0, 1));
+ }
+
+ #[compio::test]
+ async fn given_an_ineligible_prefix_when_publishing_should_bound_visits_and_reach_live_groups()
+ {
+ let (shard, inbox) = owner(1);
+ for id in 0..=PARTITION_PLACEMENT_REPORTS_PER_TICK_MAX {
+ let namespace = insert(&shard, id, 7, 0);
+ if id < PARTITION_PLACEMENT_REPORTS_PER_TICK_MAX {
+ shard
+ .plane
+ .partitions()
+ .get_by_ns(&namespace)
+ .unwrap()
+ .consensus()
+ .begin_view_probe();
+ }
+ }
+ publish(&shard);
+ assert!(
+ inbox.try_recv().is_err(),
+ "one sweep visits at most its bounded range"
+ );
+
+ publish(&shard);
+ let reports = receive(&inbox);
+ assert_eq!(reports.len(), 1);
+ assert_eq!(
+ reports[0].namespace.partition_id(),
+ PARTITION_PLACEMENT_REPORTS_PER_TICK_MAX
+ );
+ }
+
+ #[compio::test]
+ #[allow(clippy::too_many_lines)]
+ async fn given_reopened_pending_create_when_rebuilding_pipeline_should_restore_placement_reservations()
+ {
+ type PlacementMetadata = IggyMetadata<
+ VsrConsensus<Rc<IggyMessageBus>>,
+ PrepareJournal,
+ IggySnapshot,
+ MuxStateMachine<variadic!(Users, Streams)>,
+ >;
+ const JOURNAL_SLOTS: usize = 128;
+ const FIRST_CLIENT: u128 = 7;
+ const NEXT_CLIENT: u128 = 8;
+ const ADMISSION_BUDGET: Duration = Duration::from_secs(5);
+ let register = |metadata: &PlacementMetadata, client| {
+ let reply = build_reply_message_with(
+ &PrepareHeader {
+ client,
+ op: 1,
+ operation: Operation::Register,
+ ..Default::default()
+ },
+ 0,
+ |_| {},
+ );
+ metadata
+ .client_table
+ .borrow_mut()
+ .commit_register(client, 0, [0x5a; 32], reply)
+ .unwrap();
+ };
+ let request = |client, name: &str| {
+ let body = CreateTopicRequest {
+ stream_id: WireIdentifier::numeric(0),
+ partitions_count: 2,
+ name: WireName::new(name).unwrap(),
+ options: WireOptions::empty(),
+ }
+ .to_bytes();
+ let header_size = size_of::<RoutedRequestHeader>();
+ let mut message = Message::<RoutedRequestHeader>::new(header_size + body.len());
+ message.as_mut_slice()[header_size..].copy_from_slice(&body);
+ message.transmute_header(|_, header| {
+ *header = RoutedRequestHeader {
+ command: Command::Request,
+ operation: Operation::CreateTopic,
+ size: u32::try_from(header_size + body.len()).unwrap(),
+ client,
+ session: 1,
+ request: 1,
+ group: METADATA_GROUP,
+ ..Default::default()
+ };
+ })
+ };
+ let capture = async |metadata: &PlacementMetadata, request, op| {
+ let mut submit = Box::pin(metadata.submit_request_in_process(request));
+ compio::time::timeout(ADMISSION_BUDGET, async {
+ loop {
+ assert!(
+ submit.as_mut().now_or_never().is_none(),
+ "three replicas need another acknowledgment before commit"
+ );
+ let journal = metadata.journal.as_ref().unwrap();
+ let header = journal.handle().header(op).map(|header| *header);
+ if let Some(header) = header {
+ break journal.handle().entry(&header).await.unwrap();
+ }
+ compio::time::sleep(Duration::from_millis(1)).await;
+ }
+ })
+ .await
+ .expect("admission must append within its budget")
+ };
+
+ let directory = tempfile::tempdir().unwrap();
+ let metadata_directory = directory.path().join(metadata::impls::METADATA_DIR);
+ std::fs::create_dir(&metadata_directory).unwrap();
+ let inherited = {
+ let journal = PrepareJournal::open_with_slots(
+ &metadata_directory.join("journal.wal"),
+ 0,
+ JOURNAL_SLOTS,
+ )
+ .await
+ .unwrap();
+ let consensus = VsrConsensus::new(
+ 1,
+ 0,
+ 3,
+ METADATA_GROUP,
+ Rc::new(IggyMessageBus::new(0)),
+ LocalPipeline::new(),
+ );
+ consensus.init();
+ let metadata = PlacementMetadata::new(
+ Some(consensus),
+ Some(journal),
+ None,
+ None,
+ MuxStateMachine::default(),
+ None,
+ );
+ register(&metadata, FIRST_CLIENT);
+ let prepare = capture(&metadata, request(FIRST_CLIENT, "inherited"), 1).await;
+ assert_eq!(metadata.consensus.as_ref().unwrap().commit_min(), 0);
+ prepare
+ };
+ let original = CreateTopicWithAssignmentsRequest::decode_from(inherited.body())
+ .unwrap()
+ .partitions;
+ assert_eq!(
+ original
+ .iter()
+ .map(|partition| (partition.consensus_group_id, partition.initial_view))
+ .collect::<Vec<_>>(),
+ [(1, 0), (2, 1)]
+ );
+
+ let recovered = recover::<MuxStateMachine<variadic!(Users, Streams)>>(
+ directory.path(),
+ ReplicaIdentity {
+ cluster: 1,
+ replica_id: 0,
+ replica_count: 3,
+ },
+ JOURNAL_SLOTS,
+ CLIENTS_TABLE_MAX,
+ |_| {},
+ |_, _| {},
+ )
+ .await
+ .unwrap();
+ assert_eq!(recovered.last_applied_op, None);
+ assert_eq!(recovered.last_journaled_op, Some(inherited.header().op));
+ assert_eq!(recovered.chain_break_op, None);
+ let reopened = recovered
+ .journal
+ .handle()
+ .entry(inherited.header())
+ .await
+ .unwrap();
+ assert_eq!(reopened.as_slice(), inherited.as_slice());
+
+ // Enter the recovered-primary seam; the network election itself is covered separately.
+ let consensus = VsrConsensus::new(
+ 1,
+ 0,
+ 3,
+ METADATA_GROUP,
+ Rc::new(IggyMessageBus::new(0)),
+ LocalPipeline::new(),
+ );
+ consensus.init();
+ consensus
+ .sequencer()
+ .set_sequence(recovered.last_journaled_op.unwrap());
+ consensus.set_last_prepare_checksum(inherited.header().checksum);
+ let metadata = PlacementMetadata::new(
+ Some(consensus),
+ Some(recovered.journal),
+ recovered.snapshot,
+ Some(Rc::new(recovered.superblock)),
+ recovered.mux_stm,
+ None,
+ );
+ register(&metadata, NEXT_CLIENT);
+ let consensus = metadata.consensus.as_ref().unwrap();
+ assert!(consensus.pipeline_is_empty());
+ dispatch_vsr_actions(
+ consensus,
+ metadata.journal.as_ref(),
+ &[VsrAction::RebuildPipeline {
+ from_op: recovered.last_applied_op.unwrap_or(0) + 1,
+ to_op: recovered.last_journaled_op.unwrap(),
+ }],
+ )
+ .await;
+ assert!(consensus.pipeline_holds_entry(inherited.header().op, inherited.header().checksum));
+ let refused = metadata
+ .submit_request_in_process(request(NEXT_CLIENT, "next"))
+ .await
+ .unwrap()
+ .try_into_typed::<ReplyHeader>()
+ .unwrap();
+ assert_eq!(
+ iggy_binary_protocol::result_code(refused.body()),
+ Some(IggyError::TransientNotAccepted.as_code())
+ );
+ assert!(!refused.header().has_committed_result());
+ assert_eq!(metadata.allocator.highest(), 0);
+ metadata.refresh_placement().await;
+ assert_eq!(metadata.allocator.highest(), 2);
+ let next = capture(&metadata, request(NEXT_CLIENT, "next"), 2).await;
+ let assignments = CreateTopicWithAssignmentsRequest::decode_from(next.body())
+ .unwrap()
+ .partitions;
+ assert_eq!(
+ assignments
+ .iter()
+ .map(|partition| (partition.consensus_group_id, partition.initial_view))
+ .collect::<Vec<_>>(),
+ [(3, 2), (4, 0)]
+ );
+ assert_eq!(next.header().parent, inherited.header().checksum);
+ assert!(consensus.pipeline_holds_entry(inherited.header().op, inherited.header().checksum));
+ let retained = metadata
+ .journal
+ .as_ref()
+ .unwrap()
+ .handle()
+ .entry(inherited.header())
+ .await
+ .unwrap();
+ assert_eq!(
+ retained.as_slice(),
+ inherited.as_slice(),
+ "reconstruction must preserve the original assignment bytes"
+ );
+ }
+}
+
#[cfg(test)]
mod partition_ack_durability_tests {
use super::*;
diff --git a/core/shard/src/metrics.rs b/core/shard/src/metrics.rs
index d544b2154..898ecccef 100644
--- a/core/shard/src/metrics.rs
+++ b/core/shard/src/metrics.rs
@@ -104,6 +104,8 @@ pub mod frame_drop_variant {
pub const FORWARD_CLIENT_SEND: &str = "forward_client_send";
pub const FORWARD_REPLICA_SEND: &str = "forward_replica_send";
pub const METADATA_COMMIT_TICK: &str = "metadata_commit_tick";
+ pub const PARTITION_PLACEMENT_VIEWS: &str = "partition_placement_views";
+ pub const PRIMARY_REBALANCE: &str = "primary_rebalance";
/// A delegated replica handshake's outcome ack to shard 0 was
/// dropped; the shard-0 deadline expiry recovers the slot / pending
/// entry, so this stays informational.
diff --git a/core/shard/src/partition_io.rs b/core/shard/src/partition_io.rs
index 592091d6a..efc3d517a 100644
--- a/core/shard/src/partition_io.rs
+++ b/core/shard/src/partition_io.rs
@@ -724,6 +724,10 @@ where
self.on_message(message).await;
self.partition_io.continue_ready(namespace, incarnation);
}
+ partitions::PartitionIoStep::PrimaryTransfer(request) => {
+ self.apply_primary_transfer(namespace, request).await;
+ self.partition_io.continue_ready(namespace, incarnation);
+ }
partitions::PartitionIoStep::Progress => {
self.partition_io.continue_ready(namespace, incarnation);
}
diff --git a/core/shard/src/primary_rebalance.rs b/core/shard/src/primary_rebalance.rs
new file mode 100644
index 000000000..2d6c0287f
--- /dev/null
+++ b/core/shard/src/primary_rebalance.rs
@@ -0,0 +1,620 @@
+// 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.
+
+//! The metadata primary coordinates one partition view change at a time.
+//! Eligibility requires fresh challenges, and a transfer additionally requires
+//! the target's applied partition prefix. The local drain holds a revocable
+//! grant so queued work cannot outlive the coordinator's readiness evidence.
+
+use crate::shards_table::calculate_shard_assignment;
+use crate::{
+ IggyShard, LifecycleFrame, RestorableMetadataStm, ShardFrame, ShardsTable,
+ dispatch_partition_journal_actions, dispatch_partition_wire_actions,
+ refresh_partition_dvc_suffix, split_local_actions,
+};
+use consensus::{Consensus, MetadataHandle, PartitionsHandle, VsrConsensus};
+use iggy_binary_protocol::{
+ Command, ConsensusHeader, HEADER_SIZE, PrepareHeader, PrimaryRebalanceHeader,
+ PrimaryRebalanceKind,
+};
+use journal::superblock::SuperblockStore;
+use journal::{Journal, JournalHandle};
+use message_bus::MessageBus;
+use metadata::impls::metadata::PartitionPrimaryTransfer;
+use partitions::{IggyPartition, PreparedPrimaryTransfer};
+use server_common::Message;
+use server_common::MessageBag;
+use server_common::sharding::IggyNamespace;
+use server_common::sharding::METADATA_GROUP;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::{Duration, Instant};
+
+const PROBE_INTERVAL: Duration = Duration::from_secs(1);
+const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
+const STABLE_INTERVAL: Duration = Duration::from_secs(5);
+const GRANT_TIMEOUT: Duration = Duration::from_secs(1);
+const TRANSFER_TIMEOUT: Duration = Duration::from_secs(30);
+const PROBES_PER_TICK: usize = 8;
+
+#[cfg(test)]
+mod tests;
+
+pub struct PrimaryRebalance {
+ view: Option<u32>,
+ peers: Vec<Peer>,
+ eligible: Vec<bool>,
+ stable_since: Instant,
+ next_move: Instant,
+ cursor: Option<IggyNamespace>,
+ pending: Option<PendingMove>,
+}
+
+#[derive(Clone, Default)]
+struct Peer {
+ nonce: Option<u128>,
+ sent_at: Option<Instant>,
+ ready_at: Option<Instant>,
+}
+
+struct PendingMove {
+ plan: PartitionPrimaryTransfer,
+ probe: PrimaryRebalanceHeader,
+ phase: MovePhase,
+ since: Instant,
+ active: Arc<AtomicBool>,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum MovePhase {
+ Capture,
+ Probe,
+ Transfer,
+}
+
+impl Drop for PendingMove {
+ fn drop(&mut self) {
+ self.active.store(false, Ordering::Release);
+ }
+}
+
+/// Only the metadata owner accepts wire frames. Partition owners receive
+/// in-process probes and grants after that owner has checked their authority.
+pub enum LocalRebalance {
+ Wire(PrimaryRebalanceHeader),
+ Capture(PrimaryRebalanceHeader),
+ Probe(PrimaryRebalanceHeader),
+ Transfer {
+ namespace: IggyNamespace,
+ request: PreparedPrimaryTransfer,
+ },
+}
+
+impl PrimaryRebalance {
+ fn observe_peer(&mut self, header: &PrimaryRebalanceHeader, now: Instant) {
+ if self.view != Some(header.view) {
+ return;
+ }
+ let Some(peer) = self.peers.get_mut(usize::from(header.replica)) else {
+ return;
+ };
+ if peer.nonce != Some(header.nonce)
+ || peer
+ .sent_at
+ .is_none_or(|sent| now.duration_since(sent) > PROBE_TIMEOUT)
+ {
+ return;
+ }
+ peer.nonce = None;
+ peer.ready_at = (header.ready == 1).then_some(now);
+ }
+
+ fn matches_pending(
+ &self,
+ header: &PrimaryRebalanceHeader,
+ phase: MovePhase,
+ now: Instant,
+ ) -> bool {
+ self.view == Some(header.view)
+ && self.pending.as_ref().is_some_and(|pending| {
+ pending.phase == phase
+ && now.duration_since(pending.since) <= PROBE_TIMEOUT
+ && pending.probe.nonce == header.nonce
+ && pending.probe.namespace == header.namespace
+ && pending.probe.created_revision == header.created_revision
+ && pending.probe.partition_view == header.partition_view
+ && (phase == MovePhase::Capture || pending.probe.commit == header.commit)
+ })
+ }
+}
+
+impl Default for PrimaryRebalance {
+ fn default() -> Self {
+ Self {
+ view: None,
+ peers: Vec::new(),
+ eligible: Vec::new(),
+ stable_since: Instant::now(),
+ next_move: Instant::now(),
+ cursor: None,
+ pending: None,
+ }
+ }
+}
+
+impl<B, MJ, S, M, T, SB> IggyShard<B, MJ, S, M, T, SB>
+where
+ B: MessageBus + 'static,
+ SB: SuperblockStore,
+ MJ: JournalHandle,
+ MJ::Target: Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>,
+ M: RestorableMetadataStm,
+ T: ShardsTable,
+{
+ pub(crate) fn fence_rebalance_authority(&self, message: &MessageBag) {
+ if message.routing().1 != METADATA_GROUP {
+ return;
+ }
+ let Some(consensus) = self.plane.metadata().consensus.as_ref() else {
+ return;
+ };
+ let invalidates = match message {
+ MessageBag::StartViewChange(message) => message.header().view >= consensus.view(),
+ MessageBag::DoViewChange(message) => message.header().view >= consensus.view(),
+ MessageBag::StartView(message) => message.header().view >= consensus.view(),
+ MessageBag::RequestStartView(message) => message.header().view > consensus.view(),
+ MessageBag::Commit(message) => message.header().view > consensus.view(),
+ MessageBag::Prepare(message) => message.header().view > consensus.view(),
+ MessageBag::RepairPrepare(message) => message.header().0.view > consensus.view(),
+ _ => false,
+ };
+ // Revoke before a metadata handler can suspend on persistence while
+ // another shard still holds an unconsumed grant from this coordinator.
+ if invalidates {
+ *self.primary_rebalance.borrow_mut() = PrimaryRebalance::default();
+ }
+ }
+
+ #[allow(clippy::future_not_send, clippy::too_many_lines)]
+ pub(crate) async fn tick_primary_rebalance(&self) {
+ let metadata = self.plane.metadata();
+ let Some(consensus) = metadata.consensus.as_ref() else {
+ return;
+ };
+ if self.id != 0 || !consensus.is_primary() || !consensus_ready(consensus) {
+ *self.primary_rebalance.borrow_mut() = PrimaryRebalance::default();
+ return;
+ }
+ let mut outgoing = Vec::with_capacity(PROBES_PER_TICK);
+ let mut capture = None;
+ let now = self.bus.monotonic_now();
+ {
+ let mut state = self.primary_rebalance.borrow_mut();
+ let replicas = usize::from(consensus.replica_count());
+ if state.view != Some(consensus.view()) {
+ *state = PrimaryRebalance {
+ view: Some(consensus.view()),
+ peers: vec![Peer::default(); replicas],
+ eligible: vec![false; replicas],
+ stable_since: now,
+ next_move: now,
+ ..PrimaryRebalance::default()
+ };
+ }
+ let mut changed = false;
+ for replica in 0..consensus.replica_count() {
+ let index = usize::from(replica);
+ let ready = replica == consensus.replica()
+ || state.peers[index]
+ .ready_at
+ .is_some_and(|ready| now.duration_since(ready) <= PROBE_TIMEOUT);
+ if state.eligible[index] != ready {
+ state.eligible[index] = ready;
+ changed = true;
+ }
+ if replica == consensus.replica() || outgoing.len() == PROBES_PER_TICK {
+ continue;
+ }
+ let peer = &mut state.peers[index];
+ let elapsed = peer.sent_at.map_or(PROBE_TIMEOUT + PROBE_INTERVAL, |sent| {
+ now.duration_since(sent)
+ });
+ if (peer.nonce.is_some() && elapsed <= PROBE_TIMEOUT) || elapsed < PROBE_INTERVAL {
+ continue;
+ }
+ let nonce = self.next_forward_nonce(consensus.replica());
+ peer.nonce = Some(nonce);
+ peer.sent_at = Some(now);
+ outgoing.push((replica, probe_header(consensus, nonce)));
+ }
+ if changed {
+ state.stable_since = now;
+ state.pending = None;
+ }
+ if let Some(pending) = state.pending.as_ref() {
+ let elapsed = now.duration_since(pending.since);
+ let current = metadata.partition_placement_view(
+ pending.plan.namespace,
+ pending.plan.created_revision,
+ );
+ let invalid = current.is_none_or(|current| current.view != pending.plan.view);
+ let expired = match pending.phase {
+ MovePhase::Capture | MovePhase::Probe => elapsed > PROBE_TIMEOUT,
+ MovePhase::Transfer => {
+ elapsed > TRANSFER_TIMEOUT
+ || (elapsed > GRANT_TIMEOUT
+ && pending.active.swap(false, Ordering::AcqRel))
+ }
+ };
+ if invalid || expired {
+ state.pending = None;
+ }
+ }
+ if state.pending.is_none()
+ && now >= state.next_move
+ && now.duration_since(state.stable_since) >= STABLE_INTERVAL
+ {
+ state.next_move = now + PROBE_INTERVAL;
+ if let Some(plan) =
+ metadata.primary_rebalance_candidate(&state.eligible, state.cursor)
+ {
+ let mut probe =
+ probe_header(consensus, self.next_forward_nonce(consensus.replica()));
+ probe.kind = PrimaryRebalanceKind::SourceProbe;
+ probe.namespace = plan.namespace.inner();
+ probe.created_revision = plan.created_revision;
+ probe.partition_view = plan.view;
+ state.cursor = Some(plan.namespace);
+ state.pending = Some(PendingMove {
+ plan,
+ probe,
+ phase: MovePhase::Capture,
+ since: now,
+ active: Arc::new(AtomicBool::new(true)),
+ });
+ capture = Some(probe);
+ }
+ }
+ }
+ if let Some(probe) = capture {
+ self.send_rebalance(consensus.primary_index(probe.partition_view), probe)
+ .await;
+ }
+ for (replica, probe) in outgoing {
+ self.send_rebalance(replica, probe).await;
+ }
+ }
+
+ #[allow(clippy::future_not_send, clippy::too_many_lines)]
+ pub(crate) async fn on_primary_rebalance(&self, header: PrimaryRebalanceHeader) {
+ let Some(consensus) = self.plane.metadata().consensus.as_ref() else {
+ return;
+ };
+ if self.id != 0
+ || header.cluster != consensus.cluster()
+ || header.replica >= consensus.replica_count()
+ || header.view != consensus.view()
+ {
+ return;
+ }
+ let now = self.bus.monotonic_now();
+ match header.kind {
+ PrimaryRebalanceKind::MetadataProbe
+ | PrimaryRebalanceKind::PartitionProbe
+ | PrimaryRebalanceKind::SourceProbe => {
+ if header.replica != consensus.primary_index(header.view) {
+ return;
+ }
+ if header.kind != PrimaryRebalanceKind::MetadataProbe && consensus_ready(consensus)
+ {
+ self.send_local_rebalance(
+ self.rebalance_partition_shard(header.namespace),
+ if header.kind == PrimaryRebalanceKind::SourceProbe {
+ LocalRebalance::Capture(header)
+ } else {
+ LocalRebalance::Probe(header)
+ },
+ );
+ return;
+ }
+ let mut reply = header;
+ reply.replica = consensus.replica();
+ reply.kind = match header.kind {
+ PrimaryRebalanceKind::MetadataProbe => PrimaryRebalanceKind::MetadataReply,
+ PrimaryRebalanceKind::SourceProbe => PrimaryRebalanceKind::SourceReply,
+ _ => PrimaryRebalanceKind::PartitionReply,
+ };
+ reply.ready = u8::from(
+ header.kind == PrimaryRebalanceKind::MetadataProbe
+ && consensus_ready(consensus),
+ );
+ self.send_rebalance(header.replica, reply).await;
+ }
+ PrimaryRebalanceKind::MetadataReply => {
+ if consensus.is_primary() && consensus_ready(consensus) {
+ self.primary_rebalance
+ .borrow_mut()
+ .observe_peer(&header, now);
+ }
+ }
+ PrimaryRebalanceKind::SourceReply => {
+ if !consensus.is_primary() || !consensus_ready(consensus) {
+ return;
+ }
+ let outgoing = {
+ let mut state = self.primary_rebalance.borrow_mut();
+ if !state.matches_pending(&header, MovePhase::Capture, now)
+ || header.replica != consensus.primary_index(header.partition_view)
+ {
+ return;
+ }
+ if header.ready == 0 {
+ state.pending = None;
+ return;
+ }
+ let Some(pending) = state.pending.as_mut() else {
+ return;
+ };
+ pending.probe.commit = header.commit;
+ pending.probe.kind = PrimaryRebalanceKind::PartitionProbe;
+ pending.phase = MovePhase::Probe;
+ pending.since = now;
+ (pending.plan.target, pending.probe)
+ };
+ self.send_rebalance(outgoing.0, outgoing.1).await;
+ }
+ PrimaryRebalanceKind::PartitionReply => {
+ if !consensus.is_primary() || !consensus_ready(consensus) {
+ return;
+ }
+ let request = {
+ let mut state = self.primary_rebalance.borrow_mut();
+ if !state.matches_pending(&header, MovePhase::Probe, now)
+ || state
+ .pending
+ .as_ref()
+ .is_none_or(|pending| pending.plan.target != header.replica)
+ {
+ return;
+ }
+ if header.ready == 0 {
+ state.pending = None;
+ return;
+ }
+ let Some(pending) = state.pending.as_mut() else {
+ return;
+ };
+ pending.phase = MovePhase::Transfer;
+ pending.since = now;
+ PreparedPrimaryTransfer {
+ created_revision: pending.plan.created_revision,
+ expected_view: pending.plan.view,
+ target: pending.plan.target,
+ active: Arc::clone(&pending.active),
+ expires_at: pending.since + GRANT_TIMEOUT,
+ }
+ };
+ self.send_local_rebalance(
+ self.rebalance_partition_shard(header.namespace),
+ LocalRebalance::Transfer {
+ namespace: IggyNamespace::from_raw(header.namespace),
+ request,
+ },
+ );
+ }
+ }
+ }
+
+ #[allow(clippy::future_not_send)]
+ pub(crate) async fn on_local_rebalance(&self, frame: LocalRebalance) {
+ match frame {
+ LocalRebalance::Wire(header) => self.on_primary_rebalance(header).await,
+ LocalRebalance::Capture(mut header) | LocalRebalance::Probe(mut header) => {
+ let capture = matches!(frame, LocalRebalance::Capture(_));
+ let namespace = IggyNamespace::from_raw(header.namespace);
+ let partition = self.plane.partitions().get_by_ns(&namespace);
+ header.ready = u8::from(partition.is_some_and(|partition| {
+ self.rebalance_incarnation_current(namespace, header.created_revision)
+ && if capture {
+ partition_history_ready(partition, &header)
+ && partition.consensus().is_primary()
+ } else {
+ partition_ready(partition, &header)
+ }
+ }));
+ if let Some(partition) = partition {
+ let coordinator = header.replica;
+ header.replica = partition.consensus().replica();
+ header.kind = if capture {
+ header.commit = partition.consensus().commit_max();
+ PrimaryRebalanceKind::SourceReply
+ } else {
+ PrimaryRebalanceKind::PartitionReply
+ };
+ self.send_rebalance(coordinator, header).await;
+ }
+ }
+ LocalRebalance::Transfer { namespace, request } => {
+ if self.rebalance_incarnation_current(namespace, request.created_revision)
+ && let Some(partition) = self.plane.partitions().get_mut_by_ns(&namespace)
+ {
+ partition.defer_primary_transfer(request);
+ }
+ }
+ }
+ }
+
+ #[allow(clippy::future_not_send)]
+ pub(crate) async fn apply_primary_transfer(
+ &self,
+ namespace: IggyNamespace,
+ request: PreparedPrimaryTransfer,
+ ) {
+ if !self.rebalance_incarnation_current(namespace, request.created_revision) {
+ return;
+ }
+ let Some(partition) = self.plane.partitions().get_mut_by_ns(&namespace) else {
+ return;
+ };
+ if partition.created_revision() != request.created_revision
+ || partition.fatal().is_some()
+ || partition.requires_state_transfer()
+ || partition.history_is_busy()
+ || self.bus.monotonic_now() >= request.expires_at
+ || !request.active.swap(false, Ordering::AcqRel)
+ {
+ return;
+ }
+ refresh_partition_dvc_suffix(partition);
+ let consensus = partition.consensus();
+ let actions = consensus.request_primary_transfer(request.expected_view, request.target);
+ if actions.is_empty() {
+ return;
+ }
+ tracing::info!(
+ namespace_raw = namespace.inner(),
+ created_revision = request.created_revision,
+ previous_view = request.expected_view,
+ view = consensus.view(),
+ target = request.target,
+ "rebalancing partition primary after target readiness confirmation"
+ );
+ let (local, wire) = split_local_actions(actions);
+ dispatch_partition_journal_actions(consensus, partition, &local).await;
+ dispatch_partition_wire_actions::<B, _, MJ, _>(consensus, partition, wire).await;
+ }
+
+ fn rebalance_incarnation_current(&self, namespace: IggyNamespace, revision: u64) -> bool {
+ self.shards_table.epoch_for(namespace) == Some(revision)
+ && !self
+ .plane
+ .metadata()
+ .mux_stm
+ .streams()
+ .lifecycle_blocks(namespace.stream_id(), Some(namespace.topic_id()))
+ && self
+ .plane
+ .metadata()
+ .mux_stm
+ .streams()
+ .created_revision_for_namespace(namespace)
+ == Some(revision)
+ }
+
+ fn rebalance_partition_shard(&self, raw: u64) -> u16 {
+ let namespace = IggyNamespace::from_raw(raw);
+ self.shards_table
+ .shard_for(namespace)
+ .unwrap_or_else(|| calculate_shard_assignment(&namespace, self.shard_count))
+ }
+
+ fn send_local_rebalance(&self, shard: u16, frame: LocalRebalance) {
+ let Some(sender) = self.senders.get(usize::from(shard)) else {
+ self.metrics.record_frame_drop(
+ crate::metrics::frame_drop_variant::PRIMARY_REBALANCE,
+ crate::metrics::frame_drop_reason::UNROUTABLE,
+ );
+ return;
+ };
+ // Every phase is bounded by a coordinator deadline; a full inbox
+ // abandons this attempt without retaining another queue of work.
+ if let Err(error) = sender.try_send(ShardFrame::lifecycle(
+ LifecycleFrame::PrimaryRebalance(Box::new(frame)),
+ )) {
+ self.metrics.record_frame_drop(
+ crate::metrics::frame_drop_variant::PRIMARY_REBALANCE,
+ crate::coordinator::classify_try_send_err(&error),
+ );
+ }
+ }
+
+ #[allow(clippy::future_not_send)]
+ async fn send_rebalance(&self, target: u8, mut header: PrimaryRebalanceHeader) {
+ if target == header.replica {
+ self.send_local_rebalance(0, LocalRebalance::Wire(header));
+ return;
+ }
+ header.seal();
+ let message = Message::<PrimaryRebalanceHeader>::new(HEADER_SIZE)
+ .transmute_header(|_, output: &mut PrimaryRebalanceHeader| *output = header);
+ let _ = self
+ .bus
+ .send_to_replica(target, message.into_generic().into_frozen())
+ .await;
+ }
+}
+
+pub fn consensus_ready<B: MessageBus>(consensus: &VsrConsensus<B>) -> bool {
+ consensus.is_normal()
+ && !consensus.has_ceded_primaryship()
+ && !consensus.has_observed_newer_view()
+ && !consensus.is_transferring()
+ && !consensus.view_log_unproven()
+ && consensus.applied_view_start()
+ && consensus.commit_min() >= consensus.recovery_barrier()
+}
+
+fn partition_ready<B: MessageBus, SB: SuperblockStore>(
+ partition: &IggyPartition<B, SB>,
+ probe: &PrimaryRebalanceHeader,
+) -> bool {
+ partition_history_ready(partition, probe)
+ && partition.consensus().commit_min() >= probe.commit
+ && partition.consensus().commit_min() == partition.consensus().commit_max()
+ && !partition.history_is_busy()
+}
+
+fn partition_history_ready<B: MessageBus, SB: SuperblockStore>(
+ partition: &IggyPartition<B, SB>,
+ probe: &PrimaryRebalanceHeader,
+) -> bool {
+ partition.created_revision() == probe.created_revision
+ && partition.consensus().view() == probe.partition_view
+ && consensus_ready(partition.consensus())
+ && partition.fatal().is_none()
+ && !partition.requires_state_transfer()
+ && !partition.read_history_is_changing()
+}
+
+#[expect(
+ clippy::cast_possible_truncation,
+ reason = "HEADER_SIZE is fixed at 256 bytes"
+)]
+const fn probe_header<B: MessageBus>(
+ consensus: &VsrConsensus<B>,
+ nonce: u128,
+) -> PrimaryRebalanceHeader {
+ PrimaryRebalanceHeader {
+ checksum: 0,
+ checksum_body: 0,
+ cluster: consensus.cluster(),
+ size: HEADER_SIZE as u32,
+ view: consensus.view(),
+ release: 0,
+ command: Command::PrimaryRebalance,
+ replica: consensus.replica(),
+ reserved_frame: [0; 66],
+ nonce,
+ namespace: 0,
+ created_revision: 0,
+ commit: 0,
+ partition_view: 0,
+ kind: PrimaryRebalanceKind::MetadataProbe,
+ ready: 0,
+ reserved: [0; 82],
+ }
+}
diff --git a/core/shard/src/primary_rebalance/tests.rs b/core/shard/src/primary_rebalance/tests.rs
new file mode 100644
index 000000000..c4155fe22
--- /dev/null
+++ b/core/shard/src/primary_rebalance/tests.rs
@@ -0,0 +1,550 @@
+// 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 super::*;
+use crate::shards_table::PapayaShardsTable;
+use crate::{
+ PartitionConsensusConfig, Receiver, ReplicaTopology, ShardIdentity, shard_mesh_channels,
+};
+use consensus::{LocalPipeline, StateTransferStage};
+use iggy_binary_protocol::{CommitHeader, StartViewChangeHeader};
+use iggy_common::{IggyByteSize, PartitionStats, variadic};
+use journal::prepare_journal::PrepareJournal;
+use journal::superblock::{PingPongSuperblock, SuperblockContents};
+use message_bus::{BusMessage, SendError};
+use metadata::impls::metadata::IggySnapshot;
+use metadata::stm::stream::Streams;
+use metadata::stm::user::Users;
+use metadata::{IggyMetadata, MuxStateMachine};
+use partitions::{IggyPartitions, PartitionPathLayout, PartitionsConfig};
+use server_common::MESSAGE_ALIGN;
+use server_common::iobuf::Frozen;
+use server_common::sharding::{METADATA_GROUP, ShardId};
+use std::cell::{Cell, RefCell};
+use std::pin::pin;
+use std::rc::Rc;
+use std::task::Poll;
+
+const CLUSTER: u128 = 7;
+const REPLICAS: u8 = 3;
+const METADATA_VIEW: u32 = 3;
+const PARTITION_VIEW: u32 = 4;
+const CREATED_REVISION: u64 = 11;
+const COMMITTED: u64 = 13;
+const TARGET: u8 = 2;
+const NONCE: u128 = 17;
+
+#[derive(Debug, Default)]
+struct RecordingBus {
+ sent: RefCell<Vec<(u8, PrimaryRebalanceHeader)>>,
+}
+
+#[allow(clippy::future_not_send, clippy::unused_async_trait_impl)]
+impl MessageBus for RecordingBus {
+ fn track_background(&self, _handle: message_bus::JoinHandle<()>) {}
+
+ async fn send_to_client(
+ &self,
+ _client_id: u128,
+ _data: impl Into<BusMessage>,
+ ) -> Result<(), SendError> {
+ panic!("readiness exchange must not send client traffic");
+ }
+
+ async fn send_to_replica(
+ &self,
+ replica: u8,
+ frame: Frozen<MESSAGE_ALIGN>,
+ ) -> Result<(), SendError> {
+ assert_eq!(frame.len(), HEADER_SIZE);
+ let mut message = Message::<PrimaryRebalanceHeader>::new(HEADER_SIZE);
+ message.as_mut_slice().copy_from_slice(frame.as_slice());
+ message.header().validate().unwrap();
+ message.header().verify_frame().unwrap();
+ self.sent.borrow_mut().push((replica, *message.header()));
+ Ok(())
+ }
+
+ fn set_connection_lost_fn(&self, _callback: message_bus::ConnectionLostFn) {}
+ fn set_replica_forward_fn(&self, _callback: message_bus::ReplicaForwardFn) {}
+ fn set_client_forward_fn(&self, _callback: message_bus::ClientForwardFn) {}
+}
+
+type TestShard<SB = PingPongSuperblock> = IggyShard<
+ Rc<RecordingBus>,
+ PrepareJournal,
+ IggySnapshot,
+ MuxStateMachine<variadic!(Users, Streams)>,
+ PapayaShardsTable,
+ SB,
+>;
+
+fn owner() -> (TestShard, Receiver<ShardFrame>) {
+ owner_with_superblock(None)
+}
+
+fn owner_with_superblock<SB: SuperblockStore>(
+ superblock: Option<Rc<SB>>,
+) -> (TestShard<SB>, Receiver<ShardFrame>) {
+ let bus = Rc::new(RecordingBus::default());
+ let mut consensus = VsrConsensus::new(
+ CLUSTER,
+ 0,
+ REPLICAS,
+ METADATA_GROUP,
+ Rc::clone(&bus),
+ LocalPipeline::new(),
+ );
+ consensus.set_view(METADATA_VIEW);
+ consensus.init();
+ let segment_size = IggyByteSize::from(1_048_576_u64);
+ let partitions = IggyPartitions::new(
+ ShardId::new(0),
+ PartitionsConfig {
+ messages_required_to_save: 100,
+ size_of_messages_required_to_save: segment_size,
+ validate_checksum: true,
+ segment_size,
+ preallocate_segments: false,
+ encryptor: None,
+ path_layout: PartitionPathLayout::default(),
+ },
+ );
+ let metadata = IggyMetadata::new(
+ Some(consensus),
+ None,
+ None,
+ superblock,
+ MuxStateMachine::<variadic!(Users, Streams)>::default(),
+ None,
+ );
+ let mut shard = TestShard::<SB>::without_inbox(
+ ShardIdentity::new(0, "primary-rebalance-test".to_owned()),
+ Rc::clone(&bus),
+ metadata,
+ partitions,
+ PapayaShardsTable::new(),
+ PartitionConsensusConfig::new(CLUSTER, ReplicaTopology::new(0, REPLICAS), bus),
+ );
+ let (senders, mut inboxes, _reply_inboxes) = shard_mesh_channels(1, 1, 1);
+ shard.attach_senders(senders);
+ (shard, inboxes[0].take().unwrap())
+}
+
+fn arm<SB: SuperblockStore>(
+ shard: &TestShard<SB>,
+ phase: MovePhase,
+) -> (PrimaryRebalanceHeader, Arc<AtomicBool>) {
+ let namespace = IggyNamespace::new(1, 1, 0);
+ let consensus = shard.plane.metadata().consensus.as_ref().unwrap();
+ let mut probe = probe_header(consensus, NONCE);
+ probe.namespace = namespace.inner();
+ probe.created_revision = CREATED_REVISION;
+ probe.partition_view = PARTITION_VIEW;
+ probe.commit = COMMITTED;
+ probe.kind = if phase == MovePhase::Capture {
+ PrimaryRebalanceKind::SourceProbe
+ } else {
+ PrimaryRebalanceKind::PartitionProbe
+ };
+ let active = Arc::new(AtomicBool::new(true));
+ *shard.primary_rebalance.borrow_mut() = PrimaryRebalance {
+ view: Some(METADATA_VIEW),
+ peers: vec![Peer::default(); usize::from(REPLICAS)],
+ eligible: vec![true; usize::from(REPLICAS)],
+ pending: Some(PendingMove {
+ plan: PartitionPrimaryTransfer {
+ namespace,
+ created_revision: CREATED_REVISION,
+ view: PARTITION_VIEW,
+ target: TARGET,
+ },
+ probe,
+ phase,
+ since: Instant::now(),
+ active: Arc::clone(&active),
+ }),
+ ..PrimaryRebalance::default()
+ };
+ probe.kind = if phase == MovePhase::Capture {
+ PrimaryRebalanceKind::SourceReply
+ } else {
+ PrimaryRebalanceKind::PartitionReply
+ };
+ probe.replica = if phase == MovePhase::Capture {
+ consensus.primary_index(PARTITION_VIEW)
+ } else {
+ TARGET
+ };
+ probe.ready = 1;
+ (probe, active)
+}
+
+#[compio::test]
+async fn given_pending_target_probe_when_reply_is_stale_or_mismatched_should_not_grant() {
+ for changed in [
+ "cluster",
+ "nonce",
+ "metadata view",
+ "namespace",
+ "incarnation",
+ "partition view",
+ "commit",
+ "target",
+ "expired",
+ ] {
+ let (shard, inbox) = owner();
+ let (valid, active) = arm(&shard, MovePhase::Probe);
+ let mut reply = valid;
+ match changed {
+ "cluster" => reply.cluster += 1,
+ "nonce" => reply.nonce += 1,
+ "metadata view" => reply.view += 1,
+ "namespace" => reply.namespace += 1,
+ "incarnation" => reply.created_revision += 1,
+ "partition view" => reply.partition_view += 1,
+ "commit" => reply.commit += 1,
+ "target" => reply.replica = 0,
+ "expired" => {
+ shard
+ .primary_rebalance
+ .borrow_mut()
+ .pending
+ .as_mut()
+ .unwrap()
+ .since = Instant::now()
+ .checked_sub(PROBE_TIMEOUT + PROBE_INTERVAL)
+ .unwrap();
+ }
+ _ => unreachable!(),
+ }
+ shard.on_primary_rebalance(reply).await;
+ assert!(
+ inbox.try_recv().is_err(),
+ "{changed} reply granted a transfer"
+ );
+ assert!(shard.bus.sent.borrow().is_empty());
+ assert!(active.load(Ordering::Acquire));
+ assert!(
+ shard
+ .primary_rebalance
+ .borrow()
+ .pending
+ .as_ref()
+ .is_some_and(|pending| pending.phase == MovePhase::Probe)
+ );
+ }
+}
+
+#[compio::test]
+async fn given_primary_frontier_when_target_confirms_it_should_issue_one_revocable_grant() {
+ let (shard, inbox) = owner();
+ let (mut source, active) = arm(&shard, MovePhase::Capture);
+ source.commit = COMMITTED + 1;
+ let mut wrong_source = source;
+ wrong_source.replica = TARGET;
+ shard.on_primary_rebalance(wrong_source).await;
+ assert!(shard.bus.sent.borrow().is_empty());
+ assert!(inbox.try_recv().is_err());
+
+ shard.on_primary_rebalance(source).await;
+ let (target, probe) = shard.bus.sent.borrow()[0];
+ assert_eq!(target, TARGET);
+ assert_eq!(probe.kind, PrimaryRebalanceKind::PartitionProbe);
+ assert_eq!(probe.commit, source.commit);
+ assert_eq!(probe.nonce, source.nonce);
+ assert_eq!(probe.replica, 0);
+ assert!(inbox.try_recv().is_err());
+ shard.on_primary_rebalance(source).await;
+ assert_eq!(shard.bus.sent.borrow().len(), 1);
+
+ let mut reply = probe;
+ reply.kind = PrimaryRebalanceKind::PartitionReply;
+ reply.replica = TARGET;
+ reply.ready = 1;
+ shard.on_primary_rebalance(reply).await;
+ let ShardFrame::Lifecycle(LifecycleFrame::PrimaryRebalance(frame)) = inbox.try_recv().unwrap()
+ else {
+ panic!("ready target must dispatch the local grant");
+ };
+ let LocalRebalance::Transfer { namespace, request } = *frame else {
+ panic!("target confirmation must yield a transfer");
+ };
+ assert_eq!(namespace.inner(), probe.namespace);
+ assert_eq!(request.created_revision, CREATED_REVISION);
+ assert_eq!(request.expected_view, PARTITION_VIEW);
+ assert_eq!(request.target, TARGET);
+ assert!(Arc::ptr_eq(&active, &request.active));
+ assert!(request.is_active_at(shard.bus.monotonic_now()));
+ assert!(request.expires_at <= Instant::now() + GRANT_TIMEOUT);
+ shard.on_primary_rebalance(reply).await;
+ assert!(
+ inbox.try_recv().is_err(),
+ "a replay must not issue a second grant"
+ );
+
+ shard
+ .plane
+ .metadata()
+ .consensus
+ .as_ref()
+ .unwrap()
+ .begin_view_probe();
+ shard.tick_primary_rebalance().await;
+ assert!(
+ !request.is_active_at(shard.bus.monotonic_now()),
+ "coordinator authority loss must revoke queued work"
+ );
+ assert!(shard.primary_rebalance.borrow().pending.is_none());
+}
+
+#[compio::test]
+async fn given_target_rejection_when_reply_is_correlated_should_revoke_and_ignore_late_success() {
+ let (shard, inbox) = owner();
+ let (mut reply, active) = arm(&shard, MovePhase::Probe);
+ reply.ready = 0;
+ shard.on_primary_rebalance(reply).await;
+ assert!(!active.load(Ordering::Acquire));
+ assert!(shard.primary_rebalance.borrow().pending.is_none());
+ reply.ready = 1;
+ shard.on_primary_rebalance(reply).await;
+ assert!(inbox.try_recv().is_err());
+}
+
+fn suspect_primary(group: u64, view: u32) -> MessageBag {
+ MessageBag::StartViewChange(
+ Message::<StartViewChangeHeader>::new(HEADER_SIZE).transmute_header(
+ |_, header: &mut StartViewChangeHeader| {
+ header.cluster = CLUSTER;
+ header.group = group;
+ header.view = view;
+ header.replica = 1;
+ header.command = Command::StartViewChange;
+ header.size = u32::try_from(HEADER_SIZE).unwrap();
+ },
+ ),
+ )
+}
+
+#[compio::test]
+async fn given_queued_grant_when_metadata_authority_changes_should_revoke_before_handler_suspends()
+{
+ let superblock = Rc::new(HeldSuperblock::default());
+ let (shard, _inbox) = owner_with_superblock(Some(Rc::clone(&superblock)));
+ let (_probe, active) = arm(&shard, MovePhase::Transfer);
+ let mut dispatch =
+ pin!(shard.dispatch_message(suspect_primary(METADATA_GROUP, METADATA_VIEW + 1), None,));
+ assert_eq!(futures::poll!(&mut dispatch), Poll::Pending);
+ assert!(superblock.entered.get());
+ assert!(shard.bus.sent.borrow().is_empty());
+ assert!(!active.load(Ordering::Acquire));
+ assert!(shard.primary_rebalance.borrow().pending.is_none());
+}
+
+#[derive(Default)]
+struct HeldSuperblock {
+ entered: Cell<bool>,
+}
+
+#[allow(clippy::future_not_send)]
+impl SuperblockStore for HeldSuperblock {
+ async fn write(&self, _payload: &[u8]) -> std::io::Result<()> {
+ self.entered.set(true);
+ std::future::pending().await
+ }
+
+ fn read_latest(&self) -> impl Future<Output = std::io::Result<SuperblockContents>> {
+ std::future::ready(Ok(SuperblockContents::Empty))
+ }
+}
+
+#[test]
+fn given_queued_grant_when_unrelated_or_current_traffic_arrives_should_preserve_authority() {
+ let partition_group = IggyNamespace::new(1, 1, 0).inner();
+ for (group, view, changes_view, should_revoke) in [
+ (partition_group, METADATA_VIEW + 1, true, false),
+ (METADATA_GROUP, METADATA_VIEW - 1, true, false),
+ (METADATA_GROUP, METADATA_VIEW, true, true),
+ (METADATA_GROUP, METADATA_VIEW, false, false),
+ (METADATA_GROUP, METADATA_VIEW + 1, false, true),
+ ] {
+ let (shard, _inbox) = owner();
+ let (_probe, active) = arm(&shard, MovePhase::Transfer);
+ let message = if changes_view {
+ suspect_primary(group, view)
+ } else {
+ MessageBag::Commit(Message::<CommitHeader>::new(HEADER_SIZE).transmute_header(
+ |_, header: &mut CommitHeader| {
+ header.cluster = CLUSTER;
+ header.group = group;
+ header.view = view;
+ header.replica = 1;
+ header.command = Command::Commit;
+ header.size = u32::try_from(HEADER_SIZE).unwrap();
+ },
+ ))
+ };
+ shard.fence_rebalance_authority(&message);
+ assert_eq!(
+ active.load(Ordering::Acquire),
+ !should_revoke,
+ "group={group}, view={view}, changes_view={changes_view}"
+ );
+ assert_eq!(
+ shard.primary_rebalance.borrow().pending.is_none(),
+ should_revoke
+ );
+ }
+}
+
+#[test]
+fn given_health_challenge_when_reply_is_overdue_or_replayed_should_not_extend_readiness() {
+ let (shard, _inbox) = owner();
+ let consensus = shard.plane.metadata().consensus.as_ref().unwrap();
+ let mut reply = probe_header(consensus, NONCE);
+ reply.kind = PrimaryRebalanceKind::MetadataReply;
+ reply.replica = TARGET;
+ reply.ready = 1;
+ for changed in ["nonce", "view", "replica", "expired", "unsent"] {
+ let mut state = PrimaryRebalance {
+ view: Some(METADATA_VIEW),
+ peers: vec![Peer::default(); usize::from(REPLICAS)],
+ ..PrimaryRebalance::default()
+ };
+ let previous = Instant::now()
+ .checked_sub(PROBE_TIMEOUT + PROBE_INTERVAL)
+ .unwrap();
+ state.peers[usize::from(TARGET)] = Peer {
+ nonce: Some(NONCE),
+ sent_at: Some(Instant::now()),
+ ready_at: Some(previous),
+ };
+ let mut invalid = reply;
+ match changed {
+ "nonce" => invalid.nonce += 1,
+ "view" => invalid.view += 1,
+ "replica" => invalid.replica = REPLICAS,
+ "expired" => state.peers[usize::from(TARGET)].sent_at = Some(previous),
+ "unsent" => state.peers[usize::from(TARGET)].sent_at = None,
+ _ => unreachable!(),
+ }
+ state.observe_peer(&invalid, Instant::now());
+ assert_eq!(
+ state.peers[usize::from(TARGET)].ready_at,
+ Some(previous),
+ "{changed}"
+ );
+ assert_eq!(
+ state.peers[usize::from(TARGET)].nonce,
+ Some(NONCE),
+ "{changed}"
+ );
+ state.peers[usize::from(TARGET)].sent_at = Some(Instant::now());
+ state.observe_peer(&reply, Instant::now());
+ let accepted_at = state.peers[usize::from(TARGET)].ready_at;
+ assert!(accepted_at.is_some_and(|ready| ready > previous));
+ assert_eq!(state.peers[usize::from(TARGET)].nonce, None);
+ reply.ready = 0;
+ state.observe_peer(&reply, Instant::now());
+ assert_eq!(state.peers[usize::from(TARGET)].ready_at, accepted_at);
+ reply.ready = 1;
+ }
+}
+
+fn ready_partition() -> (IggyPartition<Rc<RecordingBus>>, PrimaryRebalanceHeader) {
+ let (shard, _inbox) = owner();
+ let (probe, _active) = arm(&shard, MovePhase::Probe);
+ let mut consensus = VsrConsensus::new(
+ CLUSTER,
+ TARGET,
+ REPLICAS,
+ probe.namespace,
+ Rc::clone(&shard.bus),
+ LocalPipeline::new(),
+ );
+ consensus.set_view(PARTITION_VIEW);
+ consensus.init();
+ consensus.restore_commit_state(COMMITTED, COMMITTED);
+ let mut partition = IggyPartition::with_in_memory_storage(
+ Arc::new(PartitionStats::default()),
+ consensus,
+ shard.plane.partitions().config().segment_size,
+ );
+ partition.set_created_revision(CREATED_REVISION);
+ (partition, probe)
+}
+
+#[test]
+fn given_partition_probe_when_local_history_is_not_ready_should_refuse() {
+ for changed in [
+ "incarnation",
+ "view",
+ "observed newer view",
+ "prefix",
+ "unapplied",
+ "recovering",
+ "unproved",
+ "transfer",
+ "ceded",
+ "recovery barrier",
+ "transition",
+ ] {
+ let (mut partition, mut probe) = ready_partition();
+ assert!(
+ partition_ready(&partition, &probe),
+ "ready fixture: {changed}"
+ );
+ match changed {
+ "incarnation" => probe.created_revision += 1,
+ "view" => probe.partition_view += 1,
+ "observed newer view" => partition.consensus().observe_newer_view(PARTITION_VIEW + 1),
+ "prefix" => probe.commit += 1,
+ "unapplied" => partition.consensus().advance_commit_max(COMMITTED + 1),
+ "recovering" => partition.consensus().begin_view_probe(),
+ "unproved" => partition.consensus().fence_view_log(COMMITTED, COMMITTED),
+ "transfer" => partition
+ .consensus()
+ .set_state_transfer_stage(StateTransferStage::AwaitingTarget),
+ "ceded" => partition.consensus().init_as_backup(),
+ "recovery barrier" => partition.consensus().set_recovery_barrier(COMMITTED + 1),
+ "transition" => {
+ partition.defer_view_truncation((COMMITTED + 1)..=u64::MAX, Vec::new(), None);
+ }
+ _ => unreachable!(),
+ }
+ assert!(!partition_ready(&partition, &probe), "{changed}");
+ }
+}
+
+#[test]
+fn given_busy_source_history_when_capturing_frontier_should_allow_drain_but_not_target_readiness() {
+ let (mut partition, probe) = ready_partition();
+ partition.consensus().advance_commit_max(COMMITTED + 1);
+ assert!(partition_history_ready(&partition, &probe));
+ assert!(!partition_ready(&partition, &probe));
+ let request = PreparedPrimaryTransfer {
+ created_revision: CREATED_REVISION,
+ expected_view: PARTITION_VIEW,
+ target: TARGET,
+ active: Arc::new(AtomicBool::new(true)),
+ expires_at: Instant::now() + GRANT_TIMEOUT,
+ };
+ assert!(partition.defer_primary_transfer(request));
+ assert!(partition.history_is_busy());
+ assert!(partition_history_ready(&partition, &probe));
+ assert!(!partition_ready(&partition, &probe));
+}
diff --git a/core/shard/src/router.rs b/core/shard/src/router.rs
index 9ed483177..cba1c0dd1 100644
--- a/core/shard/src/router.rs
+++ b/core/shard/src/router.rs
@@ -1016,6 +1016,19 @@ where
);
}
}
+ LifecycleFrame::PartitionPlacementViews(reports) => {
+ if self.id == 0 {
+ self.plane.metadata().observe_partition_views(&reports);
+ } else {
+ self.metrics.record_frame_drop(
+ frame_drop_variant::PARTITION_PLACEMENT_VIEWS,
+ frame_drop_reason::MISROUTED,
+ );
+ }
+ }
+ LifecycleFrame::PrimaryRebalance(frame) => {
+ self.on_local_rebalance(*frame).await;
+ }
LifecycleFrame::PartitionPersistenceCompleted(completion) => {
let namespace = IggyNamespace::from_raw(completion.group);
let partitions = self.plane.partitions();
diff --git a/core/simulator/src/bus.rs b/core/simulator/src/bus.rs
index e680cf777..c656496c6 100644
--- a/core/simulator/src/bus.rs
+++ b/core/simulator/src/bus.rs
@@ -38,7 +38,7 @@ use std::collections::{HashMap, HashSet, VecDeque};
use std::future::Future;
use std::ops::Deref;
use std::rc::Rc;
-use std::time::Duration;
+use std::time::{Duration, Instant};
/// Convert an inbound Frozen (bus trait payload) into a `Message` for the
/// simulator's packet layer. The sim keeps `Message<GenericHeader>` in its
@@ -265,6 +265,10 @@ impl MessageBus for SimOutbox {
// prepare-timestamp clock agree to the microsecond.
SimClock::new(self.timer.clone()).realtime().as_micros()
}
+
+ fn monotonic_now(&self) -> Instant {
+ self.timer.monotonic_now()
+ }
}
/// Newtype wrapper for shared [`SimOutbox`] that implements [`MessageBus`]
@@ -323,6 +327,10 @@ impl MessageBus for SharedSimOutbox {
fn realtime_micros(&self) -> u64 {
self.0.realtime_micros()
}
+
+ fn monotonic_now(&self) -> Instant {
+ self.0.monotonic_now()
+ }
}
/// The router's dispatch/pump impl block requires `ConnectionInstaller`
@@ -413,13 +421,50 @@ impl ConnectionInstaller for SharedSimOutbox {
mod tests {
use super::*;
use message_bus::installer::conn_info::ClientTransportKind;
+ use partitions::PreparedPrimaryTransfer;
use std::cell::Cell;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicBool, Ordering};
fn test_outbox() -> SimOutbox {
SimOutbox::new(0, TimerHandle::new(), Rc::new(PendingSpawns::default()))
}
+ #[test]
+ fn given_shared_virtual_clock_when_time_advances_should_expire_grants_without_pump_ticks() {
+ let timer = TimerHandle::new();
+ let spawns = Rc::new(PendingSpawns::default());
+ let bus = Rc::new(SharedSimOutbox(Rc::new(SimOutbox::new(
+ 0,
+ timer.clone(),
+ Rc::clone(&spawns),
+ ))));
+ let start = MessageBus::monotonic_now(&bus);
+ let timeout = Duration::from_secs(1);
+ let active = Arc::new(AtomicBool::new(true));
+ let grant = PreparedPrimaryTransfer {
+ created_revision: 1,
+ expected_view: 0,
+ target: 1,
+ active: Arc::clone(&active),
+ expires_at: start + timeout,
+ };
+ assert!(grant.is_active_at(MessageBus::monotonic_now(&bus)));
+ assert_eq!(MessageBus::monotonic_now(&bus), start);
+
+ assert_eq!(timer.advance(timeout / 2), [] as [u64; 0]);
+ let restarted = SharedSimOutbox(Rc::new(SimOutbox::new(0, timer.clone(), spawns)));
+ assert_eq!(restarted.monotonic_now(), start + timeout / 2);
+ assert_eq!(MessageBus::monotonic_now(&bus), restarted.monotonic_now());
+ assert!(grant.is_active_at(restarted.monotonic_now()));
+
+ assert_eq!(timer.advance(timeout / 2), [] as [u64; 0]);
+ assert_eq!(MessageBus::monotonic_now(&bus), start + timeout);
+ assert!(!grant.is_active_at(MessageBus::monotonic_now(&bus)));
+ assert!(active.load(Ordering::Acquire));
+ }
+
#[test]
fn client_meta_round_trips_and_lost_fn_fires() {
let bus = test_outbox();
diff --git a/core/simulator/src/executor/time.rs b/core/simulator/src/executor/time.rs
index 56e07de95..e3df91f09 100644
--- a/core/simulator/src/executor/time.rs
+++ b/core/simulator/src/executor/time.rs
@@ -30,7 +30,7 @@ use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll, Waker};
-use std::time::Duration;
+use std::time::{Duration, Instant};
/// A point on the simulated timeline, in nanoseconds since simulation start.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -57,6 +57,7 @@ impl TimerHandle {
pub(crate) fn new() -> Self {
Self(Rc::new(TimeShared {
now_nanos: Cell::new(0),
+ origin: Instant::now(),
queue: RefCell::new(TimerQueue {
heap: BinaryHeap::new(),
next_seq: 0,
@@ -70,6 +71,19 @@ impl TimerHandle {
SimInstant(self.0.now_nanos.get())
}
+ /// Local deadline time shares the virtual timeline across cloned handles.
+ /// The host origin never enters a wire frame or the deterministic trace.
+ ///
+ /// # Panics
+ /// Panics if virtual time exceeds the platform's `Instant` range.
+ #[must_use]
+ pub(crate) fn monotonic_now(&self) -> Instant {
+ self.0
+ .origin
+ .checked_add(Duration::from_nanos(self.0.now_nanos.get()))
+ .expect("virtual monotonic time exceeds Instant range")
+ }
+
/// A future that completes once virtual time has advanced past
/// `now + duration`. The deadline is fixed here, at creation.
///
@@ -180,6 +194,7 @@ impl Drop for SleepFuture {
#[derive(Debug)]
struct TimeShared {
now_nanos: Cell<u64>,
+ origin: Instant,
queue: RefCell<TimerQueue>,
}
diff --git a/core/simulator/src/lib.rs b/core/simulator/src/lib.rs
index eb0cab75a..9848ffa7b 100644
--- a/core/simulator/src/lib.rs
+++ b/core/simulator/src/lib.rs
@@ -226,11 +226,10 @@ pub struct Simulator {
/// Evicted clients and the refusing replicas, in delivery order. Recovery
/// must bind that transport before retrying its unresolved requests.
evicted: Vec<(u128, u8)>,
- /// The view each namespace was created in, what production records on the
- /// committed partition and every replica seeds its group from. Read from the
- /// metadata plane once, at the first seed, and reused for every later seed
- /// of that namespace, a restart's included, so no replica seeds a view its
- /// peers did not.
+ /// Creation views retained across materialization and restart. Manual
+ /// fixtures choose the metadata view at first seed; replicated creates use
+ /// their committed per-assignment views. Later seeds reuse the same choice
+ /// so replicas cannot initialize one group with different views.
partition_created_views: HashMap<IggyNamespace, u32>,
/// Replies a setup handshake pulled off the wire that were not its own.
///
@@ -658,9 +657,9 @@ impl Simulator {
}
}
- /// The view `namespace` was created in: the metadata plane's view at its
- /// first seed, as the prepare of a real create carries it, and the same value
- /// for every seed after. `None` with no live metadata consensus to read.
+ /// Manual fixtures choose the metadata view at first seed and retain it
+ /// for later seeds. Production create requests choose each assignment's
+ /// initial view separately. `None` with no live metadata consensus to read.
fn partition_created_view(&mut self, namespace: IggyNamespace) -> Option<u32> {
if let Some(&created_view) = self.partition_created_views.get(&namespace) {
return Some(created_view);
@@ -1872,7 +1871,7 @@ fn materialise_partition(
// the recorded view survives a replica restart. A deleted incarnation's store
// must not reach its successor, and metadata replayed behind the store waits for
// repair to catch it up.
- let superblock = {
+ let (superblock, first_initialization) = {
let mut stores = replica.partition_superblocks.borrow_mut();
if let Some(stored) = stores.get(&namespace).map(|(incarnation, _)| *incarnation) {
match stored.cmp(&epoch) {
@@ -1884,12 +1883,16 @@ fn materialise_partition(
Ordering::Equal => {}
}
}
- Rc::clone(
+ // Store creation and shard initialization run synchronously, with no
+ // simulated crash between them. Keep this record even if history is lost.
+ let first_initialization = !stores.contains_key(&namespace);
+ let superblock = Rc::clone(
&stores
.entry(namespace)
.or_insert_with(|| (epoch, Rc::default()))
.1,
- )
+ );
+ (superblock, first_initialization)
};
let recovered_state = superblock
.read_latest_sync()
@@ -1904,7 +1907,7 @@ fn materialise_partition(
Some(superblock),
recovered_state,
retained,
- PartitionMaterialisation::new(epoch, created_view)
+ PartitionMaterialisation::new(epoch, created_view, first_initialization)
.with_consumer_offsets_max(consumer_offsets_max),
);
for shard in &replica.shards {
@@ -2503,9 +2506,8 @@ mod tests {
assert_eq!(replica.partition_superblocks.borrow()[&fixture].0, newer);
}
- /// A recreated fixture topic starts its partition offsets again, and its view
- /// at the metadata view that created it, which the per-tick marks must not
- /// read as a regression.
+ /// A recreated fixture topic starts its offsets again at its chosen
+ /// creation view, which the per-tick marks must not read as a regression.
#[test]
fn given_a_recreated_fixture_when_checked_should_start_its_marks_again() {
const SENDS: usize = 3;
@@ -2741,7 +2743,7 @@ mod tests {
None,
None,
None,
- PartitionMaterialisation::new(named + 1, created_view),
+ PartitionMaterialisation::new(named + 1, created_view, true),
);
assert_eq!(sim.partition_incarnation(FORGED, fixture), Some(named + 1));
@@ -4300,22 +4302,11 @@ mod tests {
);
}
- /// A partition group materialised AFTER a metadata election starts in the
- /// metadata plane's view, so both planes name the same primary.
- ///
- /// Left at view 0 the group names replica 0 whatever the metadata plane has
- /// got to. Nothing on the wire can express a partition primary
- /// (`ClusterNode` carries one cluster-wide `role`) and partition ops route
- /// within a node rather than to a peer, so the node clients are sent to
- /// refuses every write to that group and the SDK burns its budget
- /// rediscovering the same wrong answer.
- ///
- /// The simulator reaches this where the integration tests cannot: no
- /// client, no transport, just the two planes' views read directly. It is
- /// also the only place the SEED itself is asserted rather than inferred
- /// from a send succeeding.
+ /// Manual fixture seeding chooses the current metadata view. Materializing
+ /// that fixture must preserve the choice on every replica. This tests the
+ /// creation-view handoff, not the production placement selector.
#[test]
- fn given_a_metadata_election_when_a_group_materialises_should_seed_the_metadata_view() {
+ fn given_a_chosen_creation_view_when_a_group_materialises_should_seed_that_view() {
server_common::MemoryPool::init_pool(&server_common::MemoryPoolSettings {
enabled: false,
size: iggy_common::IggyByteSize::from(0u64),
@@ -4348,13 +4339,10 @@ mod tests {
.expect("a live replica must own metadata consensus");
assert_ne!(
metadata_primary, 0,
- "crashing replica 0 must have moved the metadata plane off view 0; with the \
- primary back at replica 0 both planes agree and the split cannot show"
+ "the fixture needs a chosen view whose primary differs from the default replica 0"
);
- // Materialise a brand-new group. Every live replica seeds from the view
- // the create was committed in, which production reads off the committed
- // partition.
+ // The manual fixture chooses this metadata view as its creation view.
let namespace = IggyNamespace::new(1, 1, 0);
sim.init_partition(namespace);
@@ -4363,9 +4351,7 @@ mod tests {
.expect("the group must exist on a live replica after materialisation");
assert_eq!(
partition_primary, metadata_primary,
- "a group materialised after a metadata election must name the same primary as the \
- metadata plane; seeded at view 0 instead it names replica 0, which no client can \
- be routed to"
+ "materialization must preserve the primary selected by the fixture's creation view"
);
// Per replica, not just the aggregate: the seed is read locally on each
@@ -4387,8 +4373,7 @@ mod tests {
assert_eq!(
seeded_primary, metadata_primary,
"replica {replica_idx} seeded its group at view {}, naming replica \
- {seeded_primary} primary while the metadata plane names {metadata_primary}; \
- replicas that seed different views disagree on their own group's primary",
+ {seeded_primary} instead of the fixture's chosen primary {metadata_primary}",
state.view
);
}
@@ -4520,6 +4505,124 @@ mod tests {
);
}
+ #[test]
+ fn given_committed_unmaterialized_groups_when_restarted_should_complete_their_first_lifecycle()
+ {
+ const PROGRESS_STEPS: usize = 4_000;
+ let (mut sim, client) = cluster(0x4649_5253);
+ let namespace = IggyNamespace::new(0, 0, 0);
+ sim.register_client_with_primary(&client);
+ complete_metadata_op(&mut sim, &client, client.create_stream("late"));
+ complete_metadata_op(&mut sim, &client, client.create_topic("late", "empty", 1));
+ complete_metadata_op(&mut sim, &client, client.create_stream("replay-fence"));
+ for replica in &sim.replicas {
+ assert!(replica.partition_superblocks.borrow().is_empty());
+ assert!(
+ !replica
+ .partition_shard(namespace)
+ .plane
+ .partitions()
+ .contains(&namespace)
+ );
+ }
+ for replica in 0..sim.replica_count {
+ sim.replica_crash(replica);
+ }
+ for replica in 0..sim.replica_count {
+ sim.replica_restart(replica);
+ let metadata = sim.replicas[usize::from(replica)].shards[0]
+ .plane
+ .metadata();
+ let epoch = metadata
+ .mux_stm
+ .streams()
+ .created_revision_for_namespace(namespace)
+ .expect("the committed create must survive metadata replay");
+ assert!(epoch > 0 && epoch <= metadata.applied_frontier().recovered_revision());
+ }
+ sim.register_client_with_primary(&client);
+ let primary = sim
+ .metadata_primary_index()
+ .expect("metadata has a live primary");
+ let reply = submit_and_wait_for_reply(
+ &mut sim,
+ client.client_id(),
+ primary,
+ client.delete_topic("late", "empty"),
+ );
+ assert_eq!(
+ metadata::stm::result::result_code(reply.body()),
+ Some(IggyError::TransientNotCommitted.as_code())
+ );
+ let intent_op = reply.header().op;
+ assert!(
+ (0..PROGRESS_STEPS).any(|_| {
+ sim.step();
+ sim.replicas.iter().all(|replica| {
+ !replica.shards[0]
+ .plane
+ .metadata()
+ .mux_stm
+ .streams()
+ .lifecycle_pending(intent_op)
+ })
+ }),
+ "a never-materialized committed group must initialize and finish its delete after restart"
+ );
+ }
+
+ #[test]
+ fn given_initialized_groups_when_retained_history_is_erased_should_remain_nonvoting() {
+ const PROGRESS_STEPS: usize = 2_000;
+ let (mut sim, client) = cluster(0x4552_4153);
+ let namespace = IggyNamespace::new(0, 0, 0);
+ sim.register_client_with_primary(&client);
+ complete_metadata_op(&mut sim, &client, client.create_stream("initialized"));
+ complete_metadata_op(
+ &mut sim,
+ &client,
+ client.create_topic("initialized", "history", 1),
+ );
+ sim.init_partition(namespace);
+ sim.discover_partition_contexts(&client);
+ commit_sends_everywhere(&mut sim, &client, namespace, 1);
+ complete_metadata_op(&mut sim, &client, client.create_stream("replay-fence"));
+ for replica in 0..sim.replica_count {
+ sim.replica_crash(replica);
+ let replica = &sim.replicas[usize::from(replica)];
+ assert!(
+ replica
+ .partition_superblocks
+ .borrow()
+ .contains_key(&namespace)
+ );
+ replica
+ .partition_shard(namespace)
+ .plane
+ .partitions()
+ .remove(&namespace);
+ replica.partition_logs.borrow_mut().remove(&namespace);
+ }
+ for replica in 0..sim.replica_count {
+ sim.replica_restart(replica);
+ }
+ for _ in 0..PROGRESS_STEPS {
+ sim.step();
+ }
+ for replica in &sim.replicas {
+ let partitions = replica.partition_shard(namespace).plane.partitions();
+ let partition = partitions
+ .get_by_ns(&namespace)
+ .expect("an initialized group's surviving store is reopened");
+ assert!(
+ !partition.consensus().recovery_election_allowed(),
+ "missing retained history must not count as first initialization"
+ );
+ assert_eq!(partition.consensus().status(), Status::Recovering);
+ assert_eq!(partition.consensus().commit_min(), 0);
+ }
+ }
+
/// A replica that advanced its view, persisted it through the superblock gate,
/// then crashed recovers that view from its own disk, not a fresh 0. The
/// split-brain guarantee: a replica never forgets a view it acted in. Impossible
@@ -4777,8 +4880,9 @@ mod tests {
// the deterministic trace. Ownership fencing now refuses group offset
// writes without an installed owner, changing the partition commit trace.
// External groups expand the consumer-kind draw from two choices to three.
+ // Rebalance probes consume network randomness and change the scheduled trace.
assert_eq!(
- h1, 0xECC6_9F76_2D47_8F12,
+ h1, 0x5601_E3DA_532E_7677,
"workload reply hash drifted from locked baseline"
);
}
@@ -5833,7 +5937,7 @@ mod tests {
None,
None,
None,
- PartitionMaterialisation::new(0, 0),
+ PartitionMaterialisation::new(0, 0, true),
);
});
executor.run_until_stalled(POLL_BUDGET); // grow while the borrow is live
@@ -5874,7 +5978,7 @@ mod tests {
None,
None,
None,
- PartitionMaterialisation::new(0, 0),
+ PartitionMaterialisation::new(0, 0, true),
);
});
executor.run_until_stalled(POLL_BUDGET);
@@ -7244,9 +7348,11 @@ mod tests {
/// Asserts a transient was seen, so this cannot pass on a path that never produces
/// one.
#[test]
+ #[allow(clippy::too_many_lines)]
fn shell_workload_survives_result_framed_transient_rejections() {
use crate::workload::{
FaultInjector, Workload,
+ actions::Action,
options::{ActionWeights, WorkloadOptions},
oracle, run_with_faults,
};
@@ -7258,10 +7364,64 @@ mod tests {
let replica_count: u8 = 3;
let client_id: u128 = 1;
- // Hand-picked: of seeds 1..=40 under these options, ten reached a transient.
- // Crashing the primary under a lossy network is necessary but not sufficient,
- // so the seed cannot be arbitrary. Re-scan if the PRNG streams are remapped.
let seed = 2;
+ {
+ const SAMPLE_ATTEMPTS: usize = 16;
+ let mut sim = Simulator::with_shards_shell(
+ usize::from(replica_count),
+ 1,
+ std::iter::once(client_id),
+ packet::PacketSimulatorOptions {
+ node_count: replica_count,
+ client_count: 1,
+ seed,
+ ..packet::PacketSimulatorOptions::default()
+ },
+ );
+ let client = SimClient::new(client_id);
+ sim.shell_login(&client);
+ let mut options = WorkloadOptions::new(seed, replica_count, vec![]);
+ options.weights = ActionWeights::new(&[(Action::CreateStream, 100)]);
+ let mut workload = Workload::new(options);
+ let (target, request) = (0..SAMPLE_ATTEMPTS)
+ .find_map(|_| workload.build_request(&client))
+ .expect("a fresh stream can be created without existing metadata");
+ let request_id = request.header().request;
+
+ // Admission must refuse the request before the workload sees any reply.
+ sim.metadata_consensus(usize::from(target))
+ .expect("target hosts metadata")
+ .begin_state_transfer_await();
+ let reply = submit_and_wait_for_reply(&mut sim, client_id, target, request);
+ assert_eq!(reply.header().request, request_id);
+ assert_eq!(reply.header().status, 0);
+ assert_eq!(
+ iggy_binary_protocol::consensus::result_code(reply.body()),
+ Some(iggy_common::IggyError::TransientNotAccepted.as_code()),
+ );
+ assert!(workload.on_reply(&reply).is_empty());
+ assert_eq!(workload.auditor.stats().transient_rejections, 1);
+ assert_eq!(workload.total_in_flight(), 1);
+
+ sim.metadata_consensus(usize::from(target))
+ .expect("target hosts metadata")
+ .set_state_transfer_stage(consensus::StateTransferStage::Idle);
+ let mut invariants = crate::workload::invariants::Invariants::new();
+ assert!(
+ oracle::drive_to_quiesce(
+ &mut sim,
+ &mut workload,
+ &[client],
+ 1_000,
+ &mut invariants,
+ ),
+ "{}",
+ oracle::quiesce_failure_report(&sim, &workload),
+ );
+ assert_eq!(workload.auditor.stats().commits(Action::CreateStream), 1);
+ assert_eq!(workload.total_in_flight(), 0);
+ }
+
let network_opts = packet::PacketSimulatorOptions {
node_count: replica_count,
client_count: 1,
@@ -7294,8 +7454,6 @@ mod tests {
let mut options = WorkloadOptions::new(seed, replica_count, vec![ns]);
options.weights = ActionWeights::uniform();
- // Crashing the primary is what puts a live request on a replica that
- // cannot place it, which is where the transient comes from.
options.crash_per_tick_ratio = 0.05;
options.restart_per_tick_ratio = 0.08;
options.spare_primary = false;
@@ -7314,12 +7472,6 @@ mod tests {
&mut invariants,
);
- assert!(
- wl.auditor.stats().transient_rejections > 0,
- "no request was answered with a result-framed transient rejection, so the \
- path this test exists to cover never ran"
- );
-
assert!(
oracle::drive_to_quiesce(&mut sim, &mut wl, &clients, 50_000, &mut invariants),
"{}",
@@ -7974,14 +8126,20 @@ mod tests {
/// IGGY-66 acceptance: per-partition consensus independence. Blocking `ns_a`'s
/// `PrepareOk` acks and filling its pipeline to `PIPELINE_PREPARE_QUEUE_MAX`
/// wedges it for want of quorum, `ns_b` still commits, and lifting the block
- /// drains `ns_a` completely.
+ /// recovers every `ns_a` operation, replaying its identity if leadership moves.
#[test]
+ #[allow(clippy::too_many_lines)]
fn per_partition_consensus_independence() {
use consensus::PIPELINE_PREPARE_QUEUE_MAX;
use iggy_binary_protocol::{Command, PrepareOkHeader};
use packet::Packet;
+ use std::collections::HashSet;
use std::sync::atomic::{AtomicU64, Ordering};
+ const DRAIN_STEPS: usize = 800;
+ const RESOLVE_STEPS: usize = 800;
+ const RETRY_INTERVAL: usize = 100;
+
// The link predicate is a plain fn pointer (no captures), so the
// namespace under blockade travels through a static. Owned by
// this test alone; other tests never install drop predicates.
@@ -8041,8 +8199,10 @@ mod tests {
// Fill ns_a's pipeline exactly to the cap (one more would be
// rejected at preflight and generate a reply, muddying the
// no-replies assertion below).
+ let mut retained = Vec::with_capacity(clients.len());
for (sequence, client) in clients.iter().enumerate() {
let msg = client.send_messages(ns_a, &[Bytes::from(format!("wedged-{sequence}"))]);
+ retained.push(msg.deep_copy());
sim.submit_request(client.client_id(), 0, msg.into_generic());
}
for _ in 0..100 {
@@ -8080,23 +8240,57 @@ mod tests {
*sim.network
.link_drop_packet_fn(ProcessId::Replica(backup), ProcessId::Replica(0)) = None;
}
- let mut drained_replies = 0usize;
- for _ in 0..800 {
- for reply in sim.step() {
- // Only ns_a replies are outstanding once ns_b committed
- // above, so every reply counts toward the drain.
- if reply.header().request != ns_b_request {
- drained_replies += 1;
+ let mut committed = HashSet::new();
+ // Rebalancing can cancel original waiters and discard uncommitted work.
+ // Resolve the remaining identities at the current primary without
+ // minting new requests or counting duplicate replies as progress.
+ for step in 0..DRAIN_STEPS + RESOLVE_STEPS {
+ if committed.len() == PIPELINE_PREPARE_QUEUE_MAX {
+ break;
+ }
+ if step >= DRAIN_STEPS
+ && step % RETRY_INTERVAL == 0
+ && let Some(primary) = (0..replica_count).find(|replica| {
+ sim.partition_consensus_state(usize::from(*replica), ns_a)
+ .is_some_and(|state| state.is_primary && state.status == Status::Normal)
+ })
+ {
+ for request in &retained {
+ let identity = (request.header().client, request.header().request);
+ if !committed.contains(&identity) {
+ sim.submit_request(identity.0, primary, request.deep_copy().into_generic());
+ }
}
}
- if drained_replies == PIPELINE_PREPARE_QUEUE_MAX {
- break;
+ for reply in sim.step() {
+ let identity = (reply.header().client, reply.header().request);
+ assert!(retained.iter().any(|request| {
+ (request.header().client, request.header().request) == identity
+ }));
+ if reply.header().status == 0 {
+ committed.insert(identity);
+ } else {
+ assert!(
+ workload::TransientRejection::from_code(reply.header().status).is_some(),
+ "unexpected recovery reply: {:?}",
+ reply.header()
+ );
+ }
}
}
assert_eq!(
- drained_replies, PIPELINE_PREPARE_QUEUE_MAX,
+ committed.len(),
+ PIPELINE_PREPARE_QUEUE_MAX,
"every wedged ns_a send must commit once acks flow again"
);
+ for _ in 0..100 {
+ sim.step();
+ }
+ for replica in 0..usize::from(replica_count) {
+ let offsets = sim.offsets(replica, ns_a).unwrap();
+ assert_eq!(offsets.commit_offset, PIPELINE_PREPARE_QUEUE_MAX as u64 - 1);
+ assert_eq!(offsets.write_offset, offsets.commit_offset);
+ }
}
/// `SendMessages` workload at 3 replicas x 4 shards drains, converges
@@ -9370,13 +9564,21 @@ mod partition_repair_driver_tests {
*sim.network
.link_drop_packet_fn(ProcessId::Replica(0), ProcessId::Replica(LAGGING)) =
Some(starve_commit_edge);
-
- produce(&mut sim, &client, namespace, GAP_SENDS, "gap");
+ // Evict before the repair debounce can heal the hole during produce.
+ produce(&mut sim, &client, namespace, STRAND_SENDS, "gap");
+ let withheld = WITHHELD_OP.load(Ordering::Relaxed);
assert_ne!(
- WITHHELD_OP.load(Ordering::Relaxed),
- 0,
+ withheld, 0,
"no partition prepare crossed the chain link, so the fault never armed"
);
+ let (_, _, commit_min, commit_max) = group_state(&sim, LAGGING, namespace);
+ assert!(
+ commit_min < withheld
+ && withheld <= commit_max
+ && !journal_holds(&sim, LAGGING, namespace, withheld),
+ "op {withheld} must still be a committed hole before eviction \
+ (walkable to {commit_min} of {commit_max})"
+ );
// Compact the serving side past the gap. This plane's journal is
// memory-only, so wiping it IS its retention floor moving: the serve
@@ -9393,14 +9595,27 @@ mod partition_repair_driver_tests {
partition.log.journal().inner.clear_all();
}
- for _ in 0..QUIET_STEPS {
+ // A reordered RepairDone can precede RangeEvicted, requiring a retry.
+ // This budget remains below the heartbeat timeout with the short burst.
+ let mut repair_armed = false;
+ for _ in 0..STRAND_QUIET_STEPS {
sim.step();
+ repair_armed |= sim.replicas[usize::from(LAGGING)]
+ .partition_shard(namespace)
+ .plane
+ .partitions()
+ .get_by_ns(&namespace)
+ .is_some_and(|partition| partition.repair.is_some());
if transfer_armed(&sim, LAGGING, namespace) {
break;
}
}
let (status, view, ..) = group_state(&sim, LAGGING, namespace);
+ assert!(
+ repair_armed,
+ "the tick driver never armed the repair session"
+ );
assert_eq!(
view, 0,
"a view change armed the recovery instead of the tick-armed repair session"
diff --git a/core/simulator/src/packet.rs b/core/simulator/src/packet.rs
index 29ea461d2..cb7e9daca 100644
--- a/core/simulator/src/packet.rs
+++ b/core/simulator/src/packet.rs
@@ -335,7 +335,7 @@ pub struct PacketSimulator {
/// One past the highest [`Command`] discriminant, sizing [`COMMAND_LABELS`] and
/// the delivery counters. Raising it is part of adding a command.
-pub const COMMAND_COUNT_MAX: usize = 33;
+pub const COMMAND_COUNT_MAX: usize = 34;
/// Names for each [`Command`] discriminant, so a coverage report reads as
/// protocol rather than as integers. Indexed by discriminant; the trailing
@@ -374,6 +374,7 @@ pub const COMMAND_LABELS: [&str; COMMAND_COUNT_MAX] = [
"ConsumerSessionHeartbeat",
"SessionRetirementProgress",
"ForwardCompletion",
+ "PrimaryRebalance",
];
const _: () = {
@@ -1035,6 +1036,35 @@ mod tests {
assert_eq!(delivered[0].to, ProcessId::Replica(1));
}
+ #[test]
+ fn given_every_command_when_delivered_should_count_it_under_its_protocol_name() {
+ let mut simulator = PacketSimulator::new(PacketSimulatorOptions {
+ one_way_delay_min: 1,
+ one_way_delay_mean: 1,
+ node_count: 2,
+ seed: 42,
+ ..Default::default()
+ });
+ for command in ALLOW_ALL {
+ simulator.submit(
+ ProcessId::Replica(0),
+ ProcessId::Replica(1),
+ create_test_message_with_command(command),
+ );
+ }
+ for _ in 0..20 {
+ simulator.tick();
+ }
+ let delivered = simulator.step();
+ assert_eq!(delivered.len(), COMMAND_COUNT_MAX);
+ for packet in delivered {
+ let command = packet.message.header().command;
+ let index = command as usize;
+ assert_eq!(COMMAND_LABELS[index], format!("{command:?}"));
+ assert_eq!(simulator.command_counts()[index], 1);
+ }
+ }
+
#[test]
fn test_partition_drops_not_buffers() {
// Verify that packets sent during a partition are dropped, not buffered
diff --git a/foreign/node/README.md b/foreign/node/README.md
index b7c6880bd..43ed48920 100644
--- a/foreign/node/README.md
+++ b/foreign/node/README.md
@@ -22,7 +22,7 @@ note: previous works on node.js http client has been moved to [iggy-node-http-cl
npm i --save apache-iggy@edge
```
-Use matching SDK and server builds from the coordinated VSR release. Older builds are incompatible. This release requires fresh server storage (`IGGY-OWNERSHIP-HISTORY-6`); existing incompatible data is refused unchanged. For a local server with the example credentials, follow the [example setup](../../examples/node/README.md#running-examples).
+Use matching SDK and server builds from the coordinated VSR release. Older builds are incompatible. This release requires fresh server storage (`IGGY-OWNERSHIP-HISTORY-7`); existing incompatible data is refused unchanged. For a local server with the example credentials, follow the [example setup](../../examples/node/README.md#running-examples).
## basic usage