diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e525acd7..2c0c771f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2355,6 +2355,13 @@ jobs: grep -q '^test result: ok. 11 passed' /tmp/native-outcomes.log cargo test --locked --lib cluster::meta_snapshot_file::tests::native_journal:: -- --test-threads=1 2>&1 | tee /tmp/native-journal.log grep -q '^test result: ok. 1 passed' /tmp/native-journal.log + - name: physical storage authority and recovery + run: | + set -euo pipefail + cargo test --locked --lib cluster::native_storage_authority::tests:: -- --test-threads=1 2>&1 | tee /tmp/storage-authority.log + grep -q '^test result: ok. 12 passed' /tmp/storage-authority.log + cargo test --locked --lib cluster::chunk_log_tests::storage_incarnation_tests:: -- --test-threads=1 2>&1 | tee /tmp/storage-incarnation.log + grep -q '^test result: ok. 1 passed' /tmp/storage-incarnation.log - name: per-member initialization survives read repair and restart run: | set -euo pipefail diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2be9165a..b7d1081e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,10 +75,10 @@ The **network chunk consensus** job runs identity, routing, process, recovery, c capacity, shutdown, and metadata-health tests with the chunk consensus feature. The coupled quorum test additionally enables metadata consensus and starts three voters for each service. -Across these jobs, the workflow explicitly names 248 individual tests. It also +Across these jobs, the workflow explicitly names 249 individual tests. It also runs grouped library filters and integration targets. -**CI does not run the suite.** It compiles everything and runs those 248 guards plus grouped tests and integration targets. A green +**CI does not run the suite.** It compiles everything and runs those 249 guards plus grouped tests and integration targets. A green tick means the tree builds and those guards hold; it does not mean the suite passed. Run `tools/suite_gate.sh` yourself. diff --git a/docs/native-storage-authority.md b/docs/native-storage-authority.md new file mode 100644 index 00000000..0b741b65 --- /dev/null +++ b/docs/native-storage-authority.md @@ -0,0 +1,28 @@ +# Physical storage authority + +Log wire protocol 5 binds every initialized member operation to a persistent +16-byte physical storage incarnation. The storage probe returns that incarnation; +callers must retain the admitted value in their authoritative membership state. +A replacement creates a new value and refuses delayed requests naming the old one. +The native protocol never falls back to protocol 4. + +A checksummed binary protobuf registry reserves each namespace before creating its +LOG file. After durable initialization, a second transition marks it ready. An +atomic checksummed anchor commits the exact registry length, sequence and history +digest before acknowledgement. Recovery rejects missing files, truncated committed +history, unknown versions, noncanonical records and checksum damage. An unanchored +suffix cannot authorize a member and is truncated during recovery. + +A ready namespace with missing data cannot be initialized as an empty member. +Existing unowned files cannot be adopted. Older wire requests cannot access an +owned native namespace, including after restart. Pending creation can be retried +only with its original allocation, generation, epoch and initialization value. +The registry has one resident entry per chunk; startup replays this index. Steady +appends and reads perform indexed checks and add no registry records or fsyncs. +Retired entries retain their ownership; reclamation and index compaction remain +part of the retirement protocol. + +This storage primitive does not grant object ownership or metadata authority. +The metadata membership representation, actual pinned reader, safe replacement +catchup, full handoff and native object RPC routing still need their coupled +implementation. Feature bit 7 and the default object backend remain unchanged. diff --git a/src/cluster/chunk_log_tests.rs b/src/cluster/chunk_log_tests.rs index c469b151..37460e2f 100644 --- a/src/cluster/chunk_log_tests.rs +++ b/src/cluster/chunk_log_tests.rs @@ -851,3 +851,6 @@ mod published_reader_tests; #[path = "initialized_member_binding_tests.rs"] mod initialized_member_binding_tests; + +#[path = "storage_incarnation_tests.rs"] +mod storage_incarnation_tests; diff --git a/src/cluster/log_chunk_store.rs b/src/cluster/log_chunk_store.rs index b2feee2a..7f57a165 100644 --- a/src/cluster/log_chunk_store.rs +++ b/src/cluster/log_chunk_store.rs @@ -6,7 +6,7 @@ //! records, so the node keeps no length table and a restart needs no recovery pass beyond opening //! a chunk when something asks for it. use super::log_op::{ - LogOpReply, LogOpRequest, FLAG_SEAL_SHA256, OP_APPEND, OP_IDENTITY, OP_READ, OP_SEAL, OP_TAIL, OP_TRUNCATE, OP_INITIALIZE, OP_FENCE, + LogOpReply, LogOpRequest, FLAG_SEAL_SHA256, OP_APPEND, OP_IDENTITY, OP_READ, OP_SEAL, OP_TAIL, OP_TRUNCATE, OP_INITIALIZE, OP_FENCE, OP_STORAGE, }; use crate::log_chunk::{LogChunk, LogError, RecordCache}; use crate::ObjectError; @@ -45,6 +45,8 @@ pub struct LogChunkStore { commits: u64, syncer: fn(&File) -> std::io::Result<()>, publication_writes: bool, + native_authority_present: bool, + native_authority: Option, publication_payload_limit: usize, // Release ownership after all cached chunk handles. directory_lock: Option>, @@ -186,6 +188,8 @@ impl LogChunkStore { commits: 0, syncer: sync_data, publication_writes: false, + native_authority_present: super::native_storage_authority::NativeStorageAuthority::path(dir).try_exists()?, + native_authority: None, publication_payload_limit: super::log_op::MAX_OP_DATA + 256, }) } @@ -195,6 +199,15 @@ impl LogChunkStore { pub(crate) fn set_publication_writes(&mut self, enabled: bool) { self.publication_writes = enabled; } pub(crate) fn set_publication_payload_limit(&mut self, limit: usize) { self.publication_payload_limit = limit; } + fn native_authority(&mut self) -> Result<&mut super::native_storage_authority::NativeStorageAuthority,ObjectError> { + self.claim_directory()?; + if self.native_authority.is_none() { + self.native_authority=Some(super::native_storage_authority::NativeStorageAuthority::open(&self.dir) + .map_err(|e| ObjectError::Corruption(format!("native storage authority recovery failed: {e}")))?); + self.native_authority_present=true; + } + Ok(self.native_authority.as_mut().unwrap()) + } /// Chunks open now. #[cfg(test)] pub fn open_chunks(&self) -> usize { @@ -314,6 +327,10 @@ impl LogChunkStore { { return Ok(None); } + if request.version==5 && self.native_authority.as_ref().is_some_and(|a| a.is_ready(request.volume,request.chunk)) + && path.metadata().map_err(|e| ObjectError::Corruption(e.to_string()))?.len()==0 { + return Err(ObjectError::Corruption("initialized native storage file is empty".into())); + } let opened = LogChunk::open(&path, request.generation, LOG_CHUNK_LIMIT) .map_err(to_object_error)?; let sealed = opened.sealed().is_some(); @@ -407,12 +424,41 @@ impl LogChunkStore { commit: bool, ) -> Result { request.validate()?; - if request.version == 4 && request.is_mutation() && !self.publication_writes { + if request.version >= 4 && request.is_mutation() && !self.publication_writes { return Err(ObjectError::PreconditionFailed("publication wire writes are disabled".into())); } + if self.native_authority_present { self.native_authority()?; } + if request.version==5 && request.op==OP_STORAGE { + let root=self.native_authority()?.incarnation().map_err(|e| ObjectError::Corruption(e.to_string()))?; + return Ok(LogOpReply { publication_supported:true,publication_protocol:5, + publication_writes_enabled:self.publication_writes,publication_payload_limit:self.publication_payload_limit as u64, + storage_hi:u64::from_le_bytes(root[..8].try_into().unwrap()),storage_lo:u64::from_le_bytes(root[8..].try_into().unwrap()),..Default::default() }); + } + if request.version!=5 && self.native_authority.as_ref().is_some_and(|a| a.contains(request.volume,request.chunk)) { + return Err(ObjectError::PreconditionFailed("native storage requires a physical incarnation".into())); + } + if request.version==5 { + let path=self.path(request.volume,request.chunk); + let exists=if request.op==OP_INITIALIZE { path.try_exists().map_err(|e| ObjectError::Corruption(e.to_string()))? } else { false }; + let authority=self.native_authority()?; + authority.verify_incarnation(request.storage_incarnation().unwrap()).map_err(|e| ObjectError::PreconditionFailed(e.to_string()))?; + let initialization=request.initialization_tag().ok_or_else(|| ObjectError::InvalidArgument("native request lacks initialization".into()))?; + if request.op==OP_INITIALIZE { + authority.begin(super::native_storage_authority::StorageOwner { volume:request.volume,chunk:request.chunk,generation:request.generation,epoch:request.epoch,initialization:initialization.to_vec(),state:1 },exists) + .map_err(|e| ObjectError::PreconditionFailed(e.to_string()))?; + } else { + authority.authorize(request.volume,request.chunk,request.generation,initialization).map_err(|e| ObjectError::PreconditionFailed(e.to_string()))?; + } + } let key = (request.volume, request.chunk); let mut dirtied = false; - let reply = self.apply_inner(request, commit, &mut dirtied)?; + let mut reply = self.apply_inner(request, commit, &mut dirtied)?; + if request.version==5 { + let authority=self.native_authority()?; + if request.op==OP_INITIALIZE { authority.complete(request.volume,request.chunk).map_err(|e| ObjectError::Corruption(e.to_string()))?; } + let root=authority.incarnation().map_err(|e| ObjectError::Corruption(e.to_string()))?; + reply.storage_hi=u64::from_le_bytes(root[..8].try_into().unwrap());reply.storage_lo=u64::from_le_bytes(root[8..].try_into().unwrap()); + } if request.op == OP_SEAL { self.trim_sealed(None); } @@ -433,19 +479,24 @@ impl LogChunkStore { let key = (request.volume, request.chunk); let writes_enabled = self.publication_writes; let payload_limit = self.publication_payload_limit; - let create = request.is_mutation() && (request.version != 4 || request.op == OP_INITIALIZE); + let completed_creation = request.version==5 && request.op==OP_INITIALIZE + && self.native_authority.as_ref().is_some_and(|a| a.is_ready(request.volume,request.chunk)); + let create = request.is_mutation() && (request.version < 4 || request.op == OP_INITIALIZE); let Some(chunk) = self.chunk(request, create)? else { // a chunk this replica has never held: it is empty, and asking creates nothing - if request.version == 4 && (request.is_mutation() || matches!(request.op,OP_READ|OP_IDENTITY)) { + if request.version == 5 || (request.version >= 4 && (request.is_mutation() || matches!(request.op,OP_READ|OP_IDENTITY))) { return Err(ObjectError::PreconditionFailed("publication member is absent; verified history transfer is required".into())); } return Ok(LogOpReply { publication_supported: request.version >= 3, - publication_protocol: if request.version==4 {4} else {0}, - publication_writes_enabled: request.version==4 && writes_enabled, - publication_payload_limit: if request.version==4 {payload_limit as u64} else {0}, + publication_protocol: if request.version>=4 {request.version} else {0}, + publication_writes_enabled: request.version>=4 && writes_enabled, + publication_payload_limit: if request.version>=4 {payload_limit as u64} else {0}, ..LogOpReply::default() }); }; + if completed_creation && chunk.publication_initialization()!=request.initialization_tag() { + return Err(ObjectError::Corruption("completed native initialization is missing from storage".into())); + } // Wire versions 1 and 2 cannot express object publication boundaries. Their reads // must refuse these files rather than exposing an unpublished physical prefix. if chunk.has_publication_records() && request.version < 3 { @@ -453,7 +504,7 @@ impl LogChunkStore { "publication-aware log protocol is required".into(), )); } - if request.version == 4 && request.op != OP_INITIALIZE && (request.is_mutation() || matches!(request.op,OP_READ|OP_IDENTITY)) { + if request.version >= 4 && request.op != OP_INITIALIZE && (request.is_mutation() || matches!(request.op,OP_READ|OP_IDENTITY) || (request.version==5 && request.op==OP_TAIL)) { if chunk.publication_initialization() != request.initialization_tag() { return Err(ObjectError::PreconditionFailed("publication initialization identity differs".into())); } @@ -468,7 +519,7 @@ impl LogChunkStore { if commit { chunk.commit().map_err(to_object_error)?; } else { *dirtied=true; } } OP_APPEND => { - if request.version == 4 { + if request.version >= 4 { chunk.append_published(request.epoch,request.offset,&request.data,request.attempt_tag().expect("validated identified append"),request.published_length) } else if let Some(tag) = request.attempt_tag() { chunk.append_identified(request.epoch, request.offset, &request.data, tag) @@ -482,7 +533,7 @@ impl LogChunkStore { } } OP_SEAL => { - if request.version == 4 { + if request.version >= 4 { chunk.seal_publication(request.epoch, request.flags & FLAG_SEAL_SHA256 != 0) } else { chunk.seal(request.epoch, request.flags & FLAG_SEAL_SHA256 != 0) }.map_err(to_object_error)?; } @@ -525,12 +576,12 @@ impl LogChunkStore { publication_mode: request.version >= 3 && chunk.has_publication_records(), publication_supported: request.version >= 3, chunk_present: request.version >= 3, - publication_protocol: if request.version==4 {4} else {0}, - publication_writes_enabled: request.version==4 && writes_enabled, - publication_payload_limit: if request.version==4 {payload_limit as u64} else {0}, + publication_protocol: if request.version>=4 {request.version} else {0}, + publication_writes_enabled: request.version>=4 && writes_enabled, + publication_payload_limit: if request.version>=4 {payload_limit as u64} else {0}, ..Default::default() }; - if request.version == 4 { + if request.version >= 4 { if let Some(tag) = chunk.publication_initialization() { reply.initialization_present=true; reply.initialization_hi=u64::from_le_bytes(tag[..8].try_into().unwrap()); diff --git a/src/cluster/log_op.rs b/src/cluster/log_op.rs index a103d335..ec988398 100644 --- a/src/cluster/log_op.rs +++ b/src/cluster/log_op.rs @@ -21,6 +21,8 @@ pub const OP_IDENTITY: u32 = 6; pub const OP_INITIALIZE: u32 = 7; /// Fence while retaining this member's complete prefix. No client-selected length. pub const OP_FENCE: u32 = 8; +/// Physical storage incarnation probe for native creation and membership qualification. +pub const OP_STORAGE: u32 = 9; /// Seal: also record the SHA-256 of the sealed bytes. pub const FLAG_SEAL_SHA256: u32 = 1; /// One record, and one read, carry at most this many bytes. @@ -65,6 +67,10 @@ pub struct LogOpRequest { pub initialization_hi: u64, #[prost(fixed64, tag = "15")] pub initialization_lo: u64, + #[prost(fixed64, tag = "16")] + pub storage_hi: u64, + #[prost(fixed64, tag = "17")] + pub storage_lo: u64, } /// The chunk as it stands after the operation. @@ -128,9 +134,30 @@ pub struct LogOpReply { pub publication_writes_enabled: bool, #[prost(uint64, tag = "25")] pub publication_payload_limit: u64, + #[prost(fixed64, tag = "26")] + pub storage_hi: u64, + #[prost(fixed64, tag = "27")] + pub storage_lo: u64, } impl LogOpRequest { + pub fn storage_probe() -> Self { + Self { version: 5, op: OP_STORAGE, ..Default::default() } + } + /// Bind a publication operation to its authoritative physical member. No fallback. + pub fn for_storage(mut self, incarnation: [u8;16], initialization: [u8;16]) -> Self { + self.version=5; + self.storage_hi=u64::from_le_bytes(incarnation[..8].try_into().unwrap()); + self.storage_lo=u64::from_le_bytes(incarnation[8..].try_into().unwrap()); + if self.op != OP_INITIALIZE { + self.initialization_hi=u64::from_le_bytes(initialization[..8].try_into().unwrap()); + self.initialization_lo=u64::from_le_bytes(initialization[8..].try_into().unwrap()); + } + self + } + pub fn storage_incarnation(&self) -> Option<[u8;16]> { + (self.version==5 && self.op!=OP_STORAGE).then(|| tag_bytes(self.storage_hi,self.storage_lo)) + } pub fn is_mutation(&self) -> bool { matches!( self.op, @@ -138,6 +165,23 @@ impl LogOpRequest { ) } pub fn validate(&self) -> Result<(), ObjectError> { + if self.version == 5 { + if self.op == OP_STORAGE { + if self.volume != 0 || self.chunk != 0 || self.generation != 0 || self.epoch != 0 + || self.offset != 0 || self.length != 0 || self.flags != 0 || !self.data.is_empty() + || self.attempt_hi != 0 || self.attempt_lo != 0 || self.published_length != 0 + || self.initialization_hi != 0 || self.initialization_lo != 0 + || self.storage_hi != 0 || self.storage_lo != 0 { + return Err(ObjectError::InvalidArgument("invalid physical storage probe".into())); + } + return Ok(()); + } + if self.storage_hi == 0 && self.storage_lo == 0 { + return Err(ObjectError::InvalidArgument("native request lacks physical storage identity".into())); + } + } else if self.storage_hi != 0 || self.storage_lo != 0 { + return Err(ObjectError::InvalidArgument("physical identity requires protocol 5".into())); + } ChunkId::new(self.volume, self.chunk)?; let old_fields = self.published_length == 0 && self.initialization_hi == 0 @@ -156,13 +200,13 @@ impl LogOpRequest { && self.attempt_lo == 0 && matches!(self.op, OP_TAIL | OP_READ | OP_IDENTITY) } - 4 => { + 4 | 5 => { matches!(self.op, OP_APPEND | OP_INITIALIZE | OP_FENCE | OP_SEAL) || (self.published_length == 0 && self.attempt_hi == 0 && self.attempt_lo == 0 && (matches!(self.op, OP_READ | OP_IDENTITY) - || (old_fields && self.op == OP_TAIL))) + || ((old_fields || self.version == 5) && self.op == OP_TAIL))) } _ => false, }; @@ -174,7 +218,7 @@ impl LogOpRequest { && self.data.len() <= MAX_OP_DATA && self.length == 0 && self.flags == 0 - && (self.version != 4 + && (self.version < 4 || self .offset .checked_add(self.data.len() as u64) @@ -184,7 +228,7 @@ impl LogOpRequest { })) } OP_INITIALIZE => { - self.version == 4 + self.version >= 4 && self.epoch != 0 && self.offset == 0 && self.length == 0 @@ -195,7 +239,7 @@ impl LogOpRequest { && self.initialization_lo == 0 } OP_FENCE => { - self.version == 4 + self.version >= 4 && self.epoch != 0 && self.offset == 0 && self.length == 0 @@ -211,7 +255,7 @@ impl LogOpRequest { && self.length == 0 && self.flags & !FLAG_SEAL_SHA256 == 0 && self.data.is_empty() - && (self.version != 4 + && (self.version < 4 || (self.published_length == 0 && self.attempt_hi == 0 && self.attempt_lo == 0)) @@ -469,7 +513,7 @@ impl LogOpRequest { } } pub fn initialization_tag(&self) -> Option<[u8; 16]> { - (self.version == 4 && (self.is_mutation() || matches!(self.op, OP_READ | OP_IDENTITY))) + (self.version >= 4 && (self.is_mutation() || matches!(self.op, OP_READ | OP_IDENTITY) || (self.version == 5 && self.op == OP_TAIL))) .then(|| { if self.op == OP_INITIALIZE { tag_bytes(self.attempt_hi, self.attempt_lo) @@ -479,7 +523,7 @@ impl LogOpRequest { }) } pub fn attempt_tag(&self) -> Option<[u8; 16]> { - (matches!(self.version, 2 | 4) && self.op == OP_APPEND) + (matches!(self.version, 2 | 4 | 5) && self.op == OP_APPEND) .then(|| tag_bytes(self.attempt_hi, self.attempt_lo)) } pub fn seal(volume: u64, chunk: u64, generation: u32, epoch: u64, with_sha256: bool) -> Self { @@ -545,7 +589,13 @@ pub struct PublishedPrefixObservation { } impl LogOpReply { + pub fn storage_incarnation(&self) -> Option<[u8;16]> { + (self.publication_protocol==5 && (self.storage_hi!=0 || self.storage_lo!=0)) + .then(|| tag_bytes(self.storage_hi,self.storage_lo)) + } + fn protocol_shape_valid(&self) -> bool { + if (self.publication_protocol==5) != (self.storage_hi!=0 || self.storage_lo!=0) { return false; } match self.publication_protocol { 0 => { self.initialization_hi == 0 @@ -554,7 +604,7 @@ impl LogOpReply { && !self.publication_writes_enabled && self.publication_payload_limit == 0 } - 4 => { + 4 | 5 => { self.publication_payload_limit != 0 && (!self.publication_writes_enabled || self.publication_payload_limit >= MIN_PUBLICATION_PAYLOAD_BYTES as u64) @@ -574,6 +624,10 @@ impl LogOpReply { && self.publication_writes_enabled && self.has_publication_observation() } + pub fn has_storage_write_protocol(&self, incarnation:[u8;16]) -> bool { + self.storage_incarnation()==Some(incarnation) && self.publication_writes_enabled + && self.has_publication_observation() + } /// Conservative per-record capacity. A writer selects the minimum across its members /// before fragmenting an attempt; descriptors must remain stable across retries. pub fn publication_record_capacity(&self) -> Option { @@ -586,7 +640,7 @@ impl LogOpReply { Some(capacity.min(MAX_OP_DATA)) } pub fn publication_initialization(&self) -> Option<[u8; 16]> { - (self.publication_protocol == 4 + (matches!(self.publication_protocol,4|5) && self.initialization_present && self.has_publication_observation()) .then(|| tag_bytes(self.initialization_hi, self.initialization_lo)) diff --git a/src/cluster/log_protobuf_decode.rs b/src/cluster/log_protobuf_decode.rs index cee07fd3..692f1699 100644 --- a/src/cluster/log_protobuf_decode.rs +++ b/src/cluster/log_protobuf_decode.rs @@ -30,6 +30,8 @@ const REQUEST_FIELDS: &[Field] = &[ Field::U64, Field::Fixed64, Field::Fixed64, + Field::Fixed64, + Field::Fixed64, ]; const REPLY_FIELDS: &[Field] = &[ Field::U64, @@ -57,10 +59,12 @@ const REPLY_FIELDS: &[Field] = &[ Field::U32, Field::Bool, Field::U64, + Field::Fixed64, + Field::Fixed64, ]; struct Fields { - scalars: [u64; 26], - bytes: [(usize, usize); 26], + scalars: [u64; 28], + bytes: [(usize, usize); 28], } fn varint(bytes: &[u8], position: &mut usize) -> Option { let mut value = 0; @@ -79,8 +83,8 @@ fn varint(bytes: &[u8], position: &mut usize) -> Option { } fn parse(bytes: &[u8], schema: &[Field]) -> Option { let mut fields = Fields { - scalars: [0; 26], - bytes: [(0, 0); 26], + scalars: [0; 28], + bytes: [(0, 0); 28], }; let mut position = 0; let mut previous = 0; @@ -129,7 +133,7 @@ fn field_bytes<'a>(bytes: &'a [u8], range: (usize, usize)) -> &'a [u8] { &bytes[range.0..range.1] } -fn request_value(scalars: [u64; 26], data: Vec) -> LogOpRequest { +fn request_value(scalars: [u64; 28], data: Vec) -> LogOpRequest { LogOpRequest { version: scalars[1] as u32, op: scalars[2] as u32, @@ -146,10 +150,12 @@ fn request_value(scalars: [u64; 26], data: Vec) -> LogOpRequest { published_length: scalars[13], initialization_hi: scalars[14], initialization_lo: scalars[15], + storage_hi: scalars[16], + storage_lo: scalars[17], } } -fn reply_value(scalars: [u64; 26], sha256: Vec, data: Vec) -> LogOpReply { +fn reply_value(scalars: [u64; 28], sha256: Vec, data: Vec) -> LogOpReply { LogOpReply { length: scalars[1], durable_length: scalars[2], @@ -176,6 +182,8 @@ fn reply_value(scalars: [u64; 26], sha256: Vec, data: Vec) -> LogOpReply publication_protocol: scalars[23] as u32, publication_writes_enabled: scalars[24] == 1, publication_payload_limit: scalars[25], + storage_hi: scalars[26], + storage_lo: scalars[27], } } diff --git a/src/cluster/mod.rs b/src/cluster/mod.rs index 7f038411..4c1c0847 100644 --- a/src/cluster/mod.rs +++ b/src/cluster/mod.rs @@ -254,6 +254,7 @@ mod replica_payload_relocation; mod log_op; #[cfg(feature = "replica-server")] mod log_chunk_store; +mod native_storage_authority; pub use log_op::{LogOpReply, LogOpRequest, PublishedPrefixObservation}; #[cfg(feature = "replica-server")] mod chunk_log; diff --git a/src/cluster/native_storage_authority.rs b/src/cluster/native_storage_authority.rs new file mode 100644 index 00000000..5b7bd67e --- /dev/null +++ b/src/cluster/native_storage_authority.rs @@ -0,0 +1,403 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 MatrixArkAI +//! Durable creation ownership. The anchor commits a checksummed registry prefix before ACK. +//! One entry per chunk transition; appends and reads only consult the resident index. +use prost::Message; +use ring::rand::{SecureRandom, SystemRandom}; +use std::collections::BTreeMap; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +const REGISTRY_MAGIC: &[u8] = b"MOSRSOWNER1"; +const ANCHOR_MAGIC: &[u8] = b"MOSRSANCHOR1"; +const MAX_RECORD: usize = 512; +const PENDING: u32 = 1; +const READY: u32 = 2; +const RETIRED: u32 = 3; +fn invalid(s: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, s) +} +fn digest(bytes: &[u8]) -> [u8; 32] { + crate::chunk_integrity::sha256(bytes) +} +fn sync_directory(path: &Path) -> io::Result<()> { + #[cfg(unix)] + File::open(path)?.sync_all()?; + #[cfg(not(unix))] + let _ = path; + Ok(()) +} +#[derive(Clone, PartialEq, Eq, Message)] +pub(super) struct StorageOwner { + #[prost(uint64, tag = "1")] + pub volume: u64, + #[prost(uint64, tag = "2")] + pub chunk: u64, + #[prost(uint32, tag = "3")] + pub generation: u32, + #[prost(uint64, tag = "4")] + pub epoch: u64, + #[prost(bytes = "vec", tag = "5")] + pub initialization: Vec, + #[prost(uint32, tag = "6")] + pub state: u32, +} +impl StorageOwner { + fn validate(&self) -> io::Result<()> { + crate::ChunkId::new(self.volume, self.chunk) + .map_err(|_| invalid("invalid owner coordinates"))?; + if self.generation == 0 + || self.epoch == 0 + || self.initialization.len() != 16 + || self.initialization.iter().all(|b| *b == 0) + || !matches!(self.state, PENDING | READY | RETIRED) + { + return Err(invalid("invalid native storage owner")); + } + Ok(()) + } + fn same_identity(&self, other: &Self) -> bool { + self.volume == other.volume + && self.chunk == other.chunk + && self.generation == other.generation + && self.epoch == other.epoch + && self.initialization == other.initialization + } +} +#[derive(Clone, PartialEq, Message)] +struct Entry { + #[prost(uint32, tag = "1")] + version: u32, + #[prost(uint64, tag = "2")] + sequence: u64, + #[prost(bytes = "vec", tag = "3")] + previous: Vec, + #[prost(message, optional, tag = "4")] + owner: Option, +} +#[derive(Clone, PartialEq, Message)] +struct Anchor { + #[prost(uint32, tag = "1")] + version: u32, + #[prost(bytes = "vec", tag = "2")] + incarnation: Vec, + #[prost(uint64, tag = "3")] + length: u64, + #[prost(uint64, tag = "4")] + sequence: u64, + #[prost(bytes = "vec", tag = "5")] + digest: Vec, +} +pub(super) struct NativeStorageAuthority { + directory: PathBuf, + registry: File, + anchor: Anchor, + owners: BTreeMap<(u64, u64), StorageOwner>, + poisoned: bool, +} +impl NativeStorageAuthority { + pub(super) fn path(root: &Path) -> PathBuf { + root.join(".native-authority") + } + pub(super) fn open(root: &Path) -> io::Result { + let directory = Self::path(root); + let fresh = match std::fs::create_dir(&directory) { + Ok(()) => { + sync_directory(root)?; + true + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => false, + Err(e) => return Err(e), + }; + let mut registry = OpenOptions::new() + .read(true) + .write(true) + .create_new(fresh) + .open(directory.join("owners"))?; + let anchor = if fresh { + let mut incarnation = [0; 16]; + SystemRandom::new() + .fill(&mut incarnation) + .map_err(|_| invalid("storage randomness unavailable"))?; + if incarnation == [0; 16] { + return Err(invalid("storage randomness returned zero")); + } + let mut header = REGISTRY_MAGIC.to_vec(); + header.extend_from_slice(&incarnation); + registry.write_all(&header)?; + registry.sync_all()?; + sync_directory(&directory)?; + let anchor = Anchor { + version: 1, + incarnation: incarnation.to_vec(), + length: header.len() as u64, + sequence: 0, + digest: digest(&header).to_vec(), + }; + Self::persist_anchor(&directory, &anchor)?; + anchor + } else { + Self::read_anchor(&directory)? + }; + if anchor.version != 1 + || anchor.incarnation.len() != 16 + || anchor.incarnation.iter().all(|b| *b == 0) + || anchor.digest.len() != 32 + || anchor.length < (REGISTRY_MAGIC.len() + 16) as u64 + || registry.metadata()?.len() < anchor.length + { + return Err(invalid("invalid native storage anchor")); + } + registry.seek(SeekFrom::Start(0))?; + let mut header = vec![0; REGISTRY_MAGIC.len() + 16]; + registry.read_exact(&mut header)?; + if !header.starts_with(REGISTRY_MAGIC) + || header[REGISTRY_MAGIC.len()..] != anchor.incarnation + { + return Err(invalid("storage identity differs from registry")); + } + let mut position = header.len() as u64; + let mut previous = digest(&header); + let mut sequence = 0; + let mut owners = BTreeMap::new(); + while position < anchor.length { + if anchor.length - position < 4 { + return Err(invalid("truncated committed storage entry")); + } + let mut size = [0; 4]; + registry.read_exact(&mut size)?; + let size = u32::from_be_bytes(size) as usize; + if size == 0 || size > MAX_RECORD || anchor.length - position < 4 + size as u64 + 32 { + return Err(invalid("invalid committed storage entry size")); + } + let mut payload = vec![0; size]; + registry.read_exact(&mut payload)?; + let mut checksum = [0; 32]; + registry.read_exact(&mut checksum)?; + if digest(&payload) != checksum { + return Err(invalid("storage entry checksum differs")); + } + let entry = Entry::decode(payload.as_slice()) + .map_err(|_| invalid("invalid storage entry protobuf"))?; + if entry.encode_to_vec() != payload + || entry.version != 1 + || entry.sequence != sequence + 1 + || entry.previous != previous + { + return Err(invalid( + "storage entry history is not canonical and consecutive", + )); + } + let owner = entry + .owner + .ok_or_else(|| invalid("storage entry lacks owner"))?; + Self::check_transition(&owners, &owner)?; + owners.insert((owner.volume, owner.chunk), owner); + sequence += 1; + previous = checksum; + position += 4 + size as u64 + 32; + } + if sequence != anchor.sequence || previous.as_slice() != anchor.digest { + return Err(invalid("storage anchor does not bind committed history")); + } + // Data-file changes follow an anchored PENDING entry. An unanchored suffix cannot + // authorize creation or reads, and may be removed after an interrupted commit. + if registry.metadata()?.len() != position { + registry.set_len(position)?; + registry.sync_all()?; + } + registry.seek(SeekFrom::Start(position))?; + Ok(Self { + directory, + registry, + anchor, + owners, + poisoned: false, + }) + } + fn read_anchor(directory: &Path) -> io::Result { + let mut bytes = Vec::new(); + File::open(directory.join("anchor"))? + .take(2049) + .read_to_end(&mut bytes)?; + if bytes.len() > 2048 + || bytes.len() < ANCHOR_MAGIC.len() + 32 + || !bytes.starts_with(ANCHOR_MAGIC) + { + return Err(invalid("invalid storage anchor envelope")); + } + let end = bytes.len() - 32; + if digest(&bytes[..end]).as_slice() != &bytes[end..] { + return Err(invalid("storage anchor checksum differs")); + } + let payload = &bytes[ANCHOR_MAGIC.len()..end]; + let anchor = + Anchor::decode(payload).map_err(|_| invalid("invalid storage anchor protobuf"))?; + if anchor.encode_to_vec() != payload { + return Err(invalid("noncanonical storage anchor")); + } + Ok(anchor) + } + fn persist_anchor(directory: &Path, anchor: &Anchor) -> io::Result<()> { + let mut bytes = ANCHOR_MAGIC.to_vec(); + anchor + .encode(&mut bytes) + .map_err(|_| invalid("storage anchor encoding failed"))?; + bytes.extend_from_slice(&digest(&bytes)); + let mut file = OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(directory.join("anchor.pending"))?; + file.write_all(&bytes)?; + file.sync_all()?; + drop(file); + std::fs::rename(directory.join("anchor.pending"), directory.join("anchor"))?; + sync_directory(directory) + } + fn check_transition( + owners: &BTreeMap<(u64, u64), StorageOwner>, + owner: &StorageOwner, + ) -> io::Result<()> { + owner.validate()?; + match owners.get(&(owner.volume, owner.chunk)) { + None if owner.state == PENDING => Ok(()), + Some(old) + if old.same_identity(owner) + && ((old.state == PENDING && owner.state == READY) + || (old.state != RETIRED && owner.state == RETIRED)) => + { + Ok(()) + } + _ => Err(invalid("native storage ownership cannot be reassigned")), + } + } + fn healthy(&self) -> io::Result<()> { + if self.poisoned { + Err(invalid("native storage authority needs recovery")) + } else { + Ok(()) + } + } + fn commit(&mut self, owner: StorageOwner) -> io::Result<()> { + self.healthy()?; + Self::check_transition(&self.owners, &owner)?; + let sequence = self + .anchor + .sequence + .checked_add(1) + .ok_or_else(|| invalid("storage sequence exhausted"))?; + let entry = Entry { + version: 1, + sequence, + previous: self.anchor.digest.clone(), + owner: Some(owner.clone()), + }; + let payload = entry.encode_to_vec(); + if payload.len() > MAX_RECORD { + return Err(invalid("storage entry too large")); + } + let checksum = digest(&payload); + let mut next = self.anchor.clone(); + next.sequence = sequence; + next.length = next + .length + .checked_add(4 + payload.len() as u64 + 32) + .ok_or_else(|| invalid("storage registry exhausted"))?; + next.digest = checksum.to_vec(); + self.poisoned = true; + self.registry + .write_all(&(payload.len() as u32).to_be_bytes())?; + self.registry.write_all(&payload)?; + self.registry.write_all(&checksum)?; + self.registry.sync_all()?; + Self::persist_anchor(&self.directory, &next)?; + self.anchor = next; + self.owners.insert((owner.volume, owner.chunk), owner); + self.poisoned = false; + Ok(()) + } + pub(super) fn incarnation(&self) -> io::Result<[u8; 16]> { + self.healthy()?; + Ok(self.anchor.incarnation.as_slice().try_into().unwrap()) + } + pub(super) fn is_ready(&self, volume: u64, chunk: u64) -> bool { + self.owners + .get(&(volume, chunk)) + .is_some_and(|o| o.state == READY) + } + pub(super) fn contains(&self, volume: u64, chunk: u64) -> bool { + self.owners.contains_key(&(volume, chunk)) + } + pub(super) fn verify_incarnation(&self, incarnation: [u8; 16]) -> io::Result<()> { + if self.incarnation()? != incarnation { + return Err(invalid("physical storage incarnation differs")); + } + Ok(()) + } + pub(super) fn begin(&mut self, mut owner: StorageOwner, file_exists: bool) -> io::Result<()> { + self.healthy()?; + owner.state = PENDING; + owner.validate()?; + if let Some(old) = self.owners.get(&(owner.volume, owner.chunk)) { + if !old.same_identity(&owner) + || old.state == RETIRED + || (old.state == READY && !file_exists) + { + return Err(invalid( + "initialized storage cannot be recreated or reassigned", + )); + } + return Ok(()); + } + if file_exists { + return Err(invalid( + "unowned existing file cannot become native storage", + )); + } + self.commit(owner) + } + pub(super) fn complete(&mut self, volume: u64, chunk: u64) -> io::Result<()> { + let mut owner = self + .owners + .get(&(volume, chunk)) + .cloned() + .ok_or_else(|| invalid("native storage creation was not reserved"))?; + if owner.state == READY { + return self.healthy(); + } + owner.state = READY; + self.commit(owner) + } + pub(super) fn authorize( + &self, + volume: u64, + chunk: u64, + generation: u32, + initialization: [u8; 16], + ) -> io::Result<()> { + self.healthy()?; + if !self.owners.get(&(volume, chunk)).is_some_and(|o| { + o.state == READY && o.generation == generation && o.initialization == initialization + }) { + return Err(invalid("native storage member is not qualified")); + } + Ok(()) + } + #[cfg(test)] + fn retire(&mut self, volume: u64, chunk: u64) -> io::Result<()> { + let mut owner = self + .owners + .get(&(volume, chunk)) + .cloned() + .ok_or_else(|| invalid("native retirement lacks its owner"))?; + if owner.state == RETIRED { + return self.healthy(); + } + owner.state = RETIRED; + self.commit(owner) + } +} +#[cfg(test)] +#[path = "native_storage_authority_tests.rs"] +mod tests; diff --git a/src/cluster/native_storage_authority_tests.rs b/src/cluster/native_storage_authority_tests.rs new file mode 100644 index 00000000..8d5bcaec --- /dev/null +++ b/src/cluster/native_storage_authority_tests.rs @@ -0,0 +1,321 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 MatrixArkAI +use super::*; +use std::sync::atomic::{AtomicU64, Ordering}; +static NEXT: AtomicU64 = AtomicU64::new(0); +struct Directory(PathBuf); +impl Directory { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "native-authority-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir(&p).unwrap(); + Self(p) + } +} +impl Drop for Directory { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} +fn owner() -> StorageOwner { + StorageOwner { + volume: 3, + chunk: 11, + generation: 1, + epoch: 9, + initialization: vec![7; 16], + state: PENDING, + } +} +#[test] +fn reservation_and_ready_identity_survive_reopen() { + let d = Directory::new(); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + let root = a.incarnation().unwrap(); + a.begin(owner(), false).unwrap(); + assert!(a.authorize(3, 11, 1, [7; 16]).is_err()); + drop(a); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + assert_eq!(a.incarnation().unwrap(), root); + a.begin(owner(), false).unwrap(); + a.complete(3, 11).unwrap(); + a.authorize(3, 11, 1, [7; 16]).unwrap(); + drop(a); + let a = NativeStorageAuthority::open(&d.0).unwrap(); + a.authorize(3, 11, 1, [7; 16]).unwrap(); + assert!(a.authorize(3, 11, 2, [7; 16]).is_err()); + assert!(a.authorize(3, 11, 1, [8; 16]).is_err()); +} +#[test] +fn ready_and_retired_namespaces_cannot_be_recreated_or_reassigned() { + let d = Directory::new(); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + a.begin(owner(), false).unwrap(); + a.complete(3, 11).unwrap(); + assert!(a.begin(owner(), false).is_err()); + a.begin(owner(), true).unwrap(); + let mut wrong = owner(); + wrong.generation = 2; + assert!(a.begin(wrong, true).is_err()); + a.retire(3, 11).unwrap(); + assert!(a.authorize(3, 11, 1, [7; 16]).is_err()); + assert!(a.begin(owner(), false).is_err()); + drop(a); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + assert!(a.begin(owner(), false).is_err()); +} +#[test] +fn unowned_existing_files_cannot_be_adopted_as_native_members() { + let d = Directory::new(); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + assert!(a.begin(owner(), true).is_err()); + assert!(!a.contains(3, 11)); +} +#[test] +fn new_physical_storage_refuses_an_old_incarnation() { + let first = Directory::new(); + let old = NativeStorageAuthority::open(&first.0) + .unwrap() + .incarnation() + .unwrap(); + let second = Directory::new(); + let fresh = NativeStorageAuthority::open(&second.0).unwrap(); + assert_ne!(fresh.incarnation().unwrap(), old); + assert!(fresh.verify_incarnation(old).is_err()); +} +#[test] +fn committed_registry_truncation_and_missing_files_fail_closed() { + for fault in 0..4 { + let d = Directory::new(); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + a.begin(owner(), false).unwrap(); + let pending = a.anchor.length; + a.complete(3, 11).unwrap(); + drop(a); + let directory = NativeStorageAuthority::path(&d.0); + match fault { + 0 => OpenOptions::new() + .write(true) + .open(directory.join("owners")) + .unwrap() + .set_len(pending) + .unwrap(), + 1 => std::fs::remove_file(directory.join("owners")).unwrap(), + 2 => std::fs::remove_file(directory.join("anchor")).unwrap(), + _ => { + let mut b = std::fs::read(directory.join("owners")).unwrap(); + let n = b.len(); + b[n - 1] ^= 1; + std::fs::write(directory.join("owners"), b).unwrap(); + } + } + assert!( + NativeStorageAuthority::open(&d.0).is_err(), + "accepted fault {fault}" + ); + } +} +#[test] +fn unanchored_suffix_is_removed_without_authorizing_a_member() { + let d = Directory::new(); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + a.begin(owner(), false).unwrap(); + let length = a.anchor.length; + drop(a); + let path = NativeStorageAuthority::path(&d.0).join("owners"); + OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(b"unfinished") + .unwrap(); + let a = NativeStorageAuthority::open(&d.0).unwrap(); + assert_eq!(std::fs::metadata(path).unwrap().len(), length); + assert!(a.authorize(3, 11, 1, [7; 16]).is_err()); +} +#[test] +fn failed_anchor_commit_poisoning_is_recovered_from_the_committed_prefix() { + let d = Directory::new(); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + a.begin(owner(), false).unwrap(); + let pending = NativeStorageAuthority::path(&d.0).join("anchor.pending"); + std::fs::create_dir(&pending).unwrap(); + assert!(a.complete(3, 11).is_err()); + assert!(a.incarnation().is_err()); + assert!(a.authorize(3, 11, 1, [7; 16]).is_err()); + drop(a); + let mut a = NativeStorageAuthority::open(&d.0).unwrap(); + assert!(a.authorize(3, 11, 1, [7; 16]).is_err()); + std::fs::remove_dir(pending).unwrap(); + a.complete(3, 11).unwrap(); + a.authorize(3, 11, 1, [7; 16]).unwrap(); +} +#[test] +fn anchor_unknown_version_and_unknown_fields_are_rejected() { + for unknown in [false, true] { + let d = Directory::new(); + let a = NativeStorageAuthority::open(&d.0).unwrap(); + let mut anchor = a.anchor.clone(); + let directory = a.directory.clone(); + drop(a); + if unknown { + let mut b = ANCHOR_MAGIC.to_vec(); + anchor.encode(&mut b).unwrap(); + b.extend_from_slice(&[0x78, 1]); + let hash = digest(&b); + b.extend_from_slice(&hash); + std::fs::write(directory.join("anchor"), b).unwrap(); + } else { + anchor.version = 2; + NativeStorageAuthority::persist_anchor(&directory, &anchor).unwrap(); + } + assert!(NativeStorageAuthority::open(&d.0).is_err()); + } +} + +fn store(path: &Path) -> super::super::log_chunk_store::LogChunkStore { + let mut s = super::super::log_chunk_store::LogChunkStore::open(path).unwrap(); + s.set_publication_writes(true); + s +} +fn probe(s: &mut super::super::log_chunk_store::LogChunkStore) -> [u8; 16] { + s.apply(&super::super::log_op::LogOpRequest::storage_probe()) + .unwrap() + .storage_incarnation() + .unwrap() +} +fn initialize(root: [u8; 16]) -> super::super::log_op::LogOpRequest { + super::super::log_op::LogOpRequest::initialize_publication(3, 11, 1, 9, [7; 16]) + .for_storage(root, [7; 16]) +} +#[test] +fn native_wire_identity_and_owned_payload_decoders_are_canonical() { + use super::super::log_op::{LogOpReply, LogOpRequest}; + let request = initialize([8; 16]); + request.validate().unwrap(); + let encoded = request.encode_to_vec(); + assert_eq!(LogOpRequest::from_payload(&encoded).unwrap(), request); + assert_eq!(LogOpRequest::from_payload_owned(encoded).unwrap(), request); + let mut wrong = request.clone(); + wrong.version = 4; + assert!(wrong.validate().is_err()); + let probe = LogOpRequest::storage_probe(); + assert_eq!( + LogOpRequest::from_payload(&probe.encode_to_vec()).unwrap(), + probe + ); + let d = Directory::new(); + let mut s = store(&d.0); + let root = probe_storage(&mut s); + let reply = s.apply(&initialize(root)).unwrap(); + let encoded = reply.encode_to_vec(); + assert_eq!(LogOpReply::from_payload(&encoded).unwrap(), reply); + assert_eq!(LogOpReply::from_payload_owned(encoded).unwrap(), reply); +} +fn probe_storage(s: &mut super::super::log_chunk_store::LogChunkStore) -> [u8; 16] { + probe(s) +} +#[test] +fn native_wire_prevents_legacy_access_and_preserves_identity_after_restart() { + use super::super::log_op::LogOpRequest; + let d = Directory::new(); + let mut s = store(&d.0); + let root = probe(&mut s); + s.apply(&initialize(root)).unwrap(); + s.apply( + &LogOpRequest::append_published(3, 11, 1, 9, 0, b"abcd".to_vec(), [3; 16], 4, [7; 16]) + .for_storage(root, [7; 16]), + ) + .unwrap(); + let registry = NativeStorageAuthority::path(&d.0).join("owners"); + let size = std::fs::metadata(®istry).unwrap().len(); + for i in 1..=20u64 { + s.apply( + &LogOpRequest::append_published( + 3, + 11, + 1, + 9, + i * 4, + vec![i as u8; 4], + [i as u8; 16], + i * 4 + 4, + [7; 16], + ) + .for_storage(root, [7; 16]), + ) + .unwrap(); + } + assert_eq!( + std::fs::metadata(®istry).unwrap().len(), + size, + "steady writes must not append ownership receipts" + ); + assert!(s.apply(&LogOpRequest::publication_tail(3, 11, 1)).is_err()); + drop(s); + let mut s = store(&d.0); + assert_eq!(probe(&mut s), root); + let tail = s + .apply(&LogOpRequest::publication_tail(3, 11, 1).for_storage(root, [7; 16])) + .unwrap(); + assert_eq!(tail.published_length, 84); + assert_eq!(tail.storage_incarnation(), Some(root)); + assert!(s + .apply(&LogOpRequest::initialize_publication(3, 11, 1, 9, [7; 16])) + .is_err()); +} +#[test] +fn lost_published_file_is_never_reinitialized_as_an_empty_native_vote() { + use super::super::log_op::LogOpRequest; + for truncate in [false, true] { + let d = Directory::new(); + let mut s = store(&d.0); + let root = probe(&mut s); + s.apply(&initialize(root)).unwrap(); + drop(s); + let path = d.0.join("0000000000000003-000000000000000b.log"); + if truncate { + OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(0) + .unwrap(); + } else { + std::fs::remove_file(&path).unwrap(); + } + let mut s = store(&d.0); + assert_eq!(probe(&mut s), root); + assert!(s.apply(&initialize(root)).is_err()); + assert!(s + .apply(&LogOpRequest::publication_tail(3, 11, 1).for_storage(root, [7; 16])) + .is_err()); + assert_eq!(path.exists(), truncate); + } +} +#[test] +fn physical_replacement_rejects_stale_initialization_and_unowned_adoption() { + use super::super::log_op::LogOpRequest; + let first = Directory::new(); + let mut old = store(&first.0); + let root = probe(&mut old); + old.apply(&initialize(root)).unwrap(); + let replacement = Directory::new(); + let mut fresh = store(&replacement.0); + let next = probe(&mut fresh); + assert_ne!(root, next); + assert!(fresh.apply(&initialize(root)).is_err()); + assert!(fresh + .apply(&LogOpRequest::publication_tail(3, 11, 1).for_storage(root, [7; 16])) + .is_err()); + fresh + .apply(&LogOpRequest::initialize_publication(3, 11, 1, 9, [7; 16])) + .unwrap(); + assert!(fresh.apply(&initialize(next)).is_err()); + assert!(fresh + .apply(&LogOpRequest::publication_tail(3, 11, 1).for_storage(next, [7; 16])) + .is_err()); +} diff --git a/src/cluster/storage_incarnation_tests.rs b/src/cluster/storage_incarnation_tests.rs new file mode 100644 index 00000000..a70747b6 --- /dev/null +++ b/src/cluster/storage_incarnation_tests.rs @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 MatrixArkAI +use super::*; +#[test] +fn stale_creation_after_physical_loss_cannot_supply_an_empty_native_vote() { + let directory = Directory::new(); + let start = |path: &Path, addr: &str| { + Node::start_with_options( + path, + addr, + ReplicaNodeOptions { + publication_writes: true, + ..Default::default() + }, + ) + }; + let mut nodes: Vec<_> = (0..3) + .map(|i| start(&directory.0.join(format!("n{i}")), "127.0.0.1:0")) + .collect(); + let call = |node: &Node, request: LogOpRequest| { + RemoteReplicaClient::connect(&node.addr, &options()) + .unwrap() + .log_call(request) + }; + let roots: Vec<_> = nodes + .iter() + .map(|node| { + call(node, LogOpRequest::storage_probe()) + .unwrap() + .storage_incarnation() + .unwrap() + }) + .collect(); + let initializations = [[7; 16], [8; 16], [9; 16]]; + for i in 0..3 { + call( + &nodes[i], + LogOpRequest::initialize_publication(V, C, 1, 1, initializations[i]) + .for_storage(roots[i], initializations[i]), + ) + .unwrap(); + if i < 2 { + call( + &nodes[i], + LogOpRequest::append_published( + V, + C, + 1, + 1, + 0, + b"abcd".to_vec(), + [11; 16], + 4, + initializations[i], + ) + .for_storage(roots[i], initializations[i]), + ) + .unwrap(); + } + } + for i in 0..2 { + let reply = call( + &nodes[i], + LogOpRequest::publication_tail(V, C, 1).for_storage(roots[i], initializations[i]), + ) + .unwrap(); + assert_eq!( + reply + .initialized_publication_prefix(initializations[i]) + .unwrap() + .length, + 4 + ); + } + let read = call( + &nodes[0], + LogOpRequest::read_initialized_publication(V, C, 1, 0, 4, initializations[0]) + .for_storage(roots[0], initializations[0]), + ) + .unwrap(); + assert_eq!(read.data, b"abcd"); + nodes[0].halt(); + nodes[1].halt(); + let path = nodes[0].dir.clone(); + assert!(path.starts_with(&directory.0) && path != directory.0); + std::fs::remove_dir_all(&path).unwrap(); + nodes[0] = start(&path, &nodes[0].addr); + let replacement = call(&nodes[0], LogOpRequest::storage_probe()) + .unwrap() + .storage_incarnation() + .unwrap(); + assert_ne!(replacement, roots[0]); + let delayed = LogOpRequest::initialize_publication(V, C, 1, 1, initializations[0]) + .for_storage(roots[0], initializations[0]); + assert!(call(&nodes[0], delayed).is_err()); + assert!(call( + &nodes[0], + LogOpRequest::publication_tail(V, C, 1).for_storage(roots[0], initializations[0]) + ) + .is_err()); + let remaining = call( + &nodes[2], + LogOpRequest::publication_tail(V, C, 1).for_storage(roots[2], initializations[2]), + ) + .unwrap(); + assert_eq!(remaining.published_length, 0); + // One surviving empty member cannot turn replacement storage into a second qualified vote. + assert!(!remaining.has_storage_write_protocol(roots[0])); +} diff --git a/src/repo_guard_tests.rs b/src/repo_guard_tests.rs index e7f1c5c1..0254516d 100644 --- a/src/repo_guard_tests.rs +++ b/src/repo_guard_tests.rs @@ -797,6 +797,8 @@ fn every_durable_format_constant_is_accounted_for() { "MOSRSMETA23", "MOSRSMETA24", "MOSRSMETA25", + "MOSRSOWNER1", + "MOSRSANCHOR1", "MOSRSCHUNKS1", "MOSRSFEATURES1", "MOSRSLEASES1", @@ -940,7 +942,7 @@ fn every_durable_format_constant_is_accounted_for() { ); assert_eq!( found.len(), - 118, + 120, "the count is pinned as well, so a rename that happens to swap two names cannot pass" ); }