mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-30 12:53:08 +00:00
fix(ecstore): reject incomplete erasure reconstruction (#9770)
* fix(ecstore): reject incomplete erasure reconstruction Require exact shard geometry and complete data for zero parity. Reject missing decode backends and enforce the source quorum for verified reconstruction while preserving recoverable exact-quorum reads. Co-Authored-By: heihutu <heihutu@gmail.com> Co-Authored-By: zhi22915 <qiuzgang@gmail.com> Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com> * perf(ecstore): streamline erasure reconstruction Validate shard geometry and presence once at the reconstruction boundary. Skip payload inspection for complete data and use direct indexed access when extracting recovered legacy shards. Preserve quorum, parity verification, and HotPath attribution for verified reads. Co-Authored-By: heihutu <heihutu@gmail.com> Co-Authored-By: zhi22915 <qiuzgang@gmail.com> Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com> * perf(ecstore): avoid parity copies in verified reads Compare surviving parity against regenerated bytes without cloning or overwriting the sources. Reuse the SIMD workspace for legacy parity and use one contiguous scratch buffer for modern parity. Still materialize missing parity and reject inconsistent sources before stripe emission. Co-Authored-By: heihutu <heihutu@gmail.com> Co-Authored-By: zhi22915 <qiuzgang@gmail.com> Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com> * chore(ci): shrink error formatting baseline Co-Authored-By: heihutu <heihutu@gmail.com> Co-Authored-By: zhi22915 <qiuzgang@gmail.com> Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com> * test(iam): use ArcSwap for policy plugin state Co-Authored-By: heihutu <heihutu@gmail.com> Co-Authored-By: zhi22915 <qiuzgang@gmail.com> Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com> * fix(ecstore): enforce empty shard quorum and stage parity Co-Authored-By: heihutu <heihutu@gmail.com> Co-Authored-By: zhi22915 <qiuzgang@gmail.com> Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com> --------- Co-authored-by: heihutu <heihutu@gmail.com> Co-authored-by: zhi22915 <qiuzgang@gmail.com> Co-authored-by: qunjiazhu <qunjiazhu@gmail.com> Co-authored-by: RustFS <hello@rustfs.com> Co-authored-by: Chris An <anzhengchao@gmail.com>
This commit is contained in:
@@ -15,6 +15,7 @@
|
||||
use crate::erasure::codec::shard_buf::ShardBytes;
|
||||
use crate::erasure::codec::workspace::RustfsCodecDecodeWorkspace;
|
||||
use crate::erasure::coding::Erasure;
|
||||
use crate::erasure::coding::erasure::{data_reconstruction_sources, recover_empty_payload_data_shards};
|
||||
use rustfs_erasure_codec::galois_8::ReedSolomon;
|
||||
use smallvec::SmallVec;
|
||||
use std::io;
|
||||
@@ -55,44 +56,6 @@ pub(crate) trait ErasureDecodeEngine: Send + Sync + 'static {
|
||||
) -> io::Result<&'static str>;
|
||||
}
|
||||
|
||||
fn data_shards_complete<S: ShardBytes>(shards: &[Option<S>], data_shards: usize) -> bool {
|
||||
shards.len() >= data_shards && shards.iter().take(data_shards).all(Option::is_some)
|
||||
}
|
||||
|
||||
fn recover_empty_payload_data_shards<S: ShardBytes>(
|
||||
shards: &mut [Option<S>],
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> io::Result<bool> {
|
||||
let expected_shards = data_shards + parity_shards;
|
||||
if shards.len() != expected_shards {
|
||||
return Err(io::Error::other(format!(
|
||||
"invalid shard count: got {}, expected {}",
|
||||
shards.len(),
|
||||
expected_shards
|
||||
)));
|
||||
}
|
||||
|
||||
let mut present_shards = 0usize;
|
||||
for shard in shards.iter().filter_map(Option::as_ref) {
|
||||
present_shards += 1;
|
||||
if !shard.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
if present_shards == 0 || present_shards < data_shards {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
for shard in shards.iter_mut().take(data_shards) {
|
||||
if shard.is_none() {
|
||||
*shard = Some(S::from(Vec::new()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct LegacyDecodeWorkspace {
|
||||
shard_len: usize,
|
||||
@@ -163,12 +126,12 @@ impl ErasureDecodeEngine for LegacyEcDecodeEngine {
|
||||
shards: &mut [Option<S>],
|
||||
_workspace: &mut Self::Workspace,
|
||||
) -> io::Result<&'static str> {
|
||||
if data_shards_complete(shards, self.erasure.data_shards) {
|
||||
return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE);
|
||||
}
|
||||
|
||||
self.erasure.decode_data_with_reconstruction_verification(shards)?;
|
||||
Ok(GET_RECONSTRUCT_OUTCOME_LEGACY_CALLED)
|
||||
let reconstructed = self.erasure.decode_data_with_reconstruction_verification(shards)?;
|
||||
Ok(if reconstructed {
|
||||
GET_RECONSTRUCT_OUTCOME_LEGACY_CALLED
|
||||
} else {
|
||||
GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,41 +153,19 @@ impl RustfsCodecDecodeEngine {
|
||||
})
|
||||
}
|
||||
|
||||
fn codec(&self) -> io::Result<Option<Arc<ReedSolomon>>> {
|
||||
if self.parity_shards == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
fn codec(&self) -> io::Result<&ReedSolomon> {
|
||||
if let Some(codec) = self.codec.get() {
|
||||
return Ok(Some(Arc::clone(codec)));
|
||||
return Ok(codec);
|
||||
}
|
||||
|
||||
let codec = Arc::new(
|
||||
ReedSolomon::new(self.data_shards, self.parity_shards)
|
||||
.map_err(|err| io::Error::other(format!("Failed to create RustFS codec decode engine: {err:?}")))?,
|
||||
);
|
||||
if self.codec.set(Arc::clone(&codec)).is_err() {
|
||||
return Ok(self.codec.get().map(Arc::clone).or(Some(codec)));
|
||||
}
|
||||
Ok(Some(codec))
|
||||
Ok(self.codec.get_or_init(|| codec))
|
||||
}
|
||||
|
||||
fn needs_source_parity_verification<S: ShardBytes>(&self, shards: &[Option<S>]) -> bool {
|
||||
let missing_data_source = shards.iter().take(self.data_shards).any(|shard| shard.is_none());
|
||||
let available_shards = shards.iter().filter(|shard| shard.is_some()).count();
|
||||
missing_data_source && available_shards > self.data_shards
|
||||
}
|
||||
|
||||
fn verify_source_parity<S: ShardBytes>(
|
||||
&self,
|
||||
codec: &ReedSolomon,
|
||||
shards: &[Option<S>],
|
||||
needs_verification: bool,
|
||||
) -> io::Result<()> {
|
||||
if !needs_verification {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
fn verify_source_parity<S: ShardBytes>(&self, codec: &ReedSolomon, shards: &[Option<S>]) -> io::Result<()> {
|
||||
// All slots must be present here: the verification path reconstructs
|
||||
// missing parity alongside data (see `reconstruct_into`), so a `None`
|
||||
// slot is an internal invariant violation, not a degraded-read state.
|
||||
@@ -291,45 +232,61 @@ impl ErasureDecodeEngine for RustfsCodecDecodeEngine {
|
||||
shards: &mut [Option<S>],
|
||||
_workspace: &mut Self::Workspace,
|
||||
) -> io::Result<&'static str> {
|
||||
if data_shards_complete(shards, self.data_shards) {
|
||||
let Some(available) = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)? else {
|
||||
return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE);
|
||||
}
|
||||
if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? {
|
||||
};
|
||||
if recover_empty_payload_data_shards(shards, self.data_shards) {
|
||||
return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_EMPTY_PAYLOAD);
|
||||
}
|
||||
|
||||
if let Some(codec) = self.codec()? {
|
||||
let needs_source_parity_verification = self.needs_source_parity_verification(shards);
|
||||
// The codec works on plain vectors: hand it the shard bytes (a
|
||||
// move for heap buffers, a copy out of arena blocks) and put the
|
||||
// results back. Reconstruction is the rare path, so the copy is
|
||||
// acceptable.
|
||||
let mut owned: Vec<Option<Vec<u8>>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect();
|
||||
let vec_shards = owned.as_mut_slice();
|
||||
if needs_source_parity_verification {
|
||||
// Rebuild missing parity together with missing data so the
|
||||
// shard set is complete for `verify`. Rebuilt parity is
|
||||
// consistent with the reconstructed data by construction, so
|
||||
// the verification below is equivalent to checking only the
|
||||
// originally-present source parity — the same semantics as the
|
||||
// legacy `decode_data_with_reconstruction_verification` path.
|
||||
// Rebuilding only data here would leave missing parity slots
|
||||
// as `None` and misreport a recoverable degraded read (for
|
||||
// example one missing data shard plus one missing parity
|
||||
// shard) as an inconsistent-source failure.
|
||||
codec
|
||||
.reconstruct_opt(vec_shards)
|
||||
.map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}")))?;
|
||||
} else {
|
||||
codec
|
||||
.reconstruct_data_opt(vec_shards)
|
||||
.map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}")))?;
|
||||
}
|
||||
for (slot, shard) in shards.iter_mut().zip(owned) {
|
||||
*slot = shard.map(S::from);
|
||||
}
|
||||
self.verify_source_parity(&codec, shards, needs_source_parity_verification)?;
|
||||
let needs_source_parity_verification = available > self.data_shards;
|
||||
let codec = self.codec()?;
|
||||
let mut missing_parity: SmallVec<[usize; 16]> = SmallVec::new();
|
||||
if needs_source_parity_verification {
|
||||
missing_parity.extend(
|
||||
shards
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(self.data_shards)
|
||||
.filter_map(|(index, slot)| slot.is_none().then_some(index)),
|
||||
);
|
||||
}
|
||||
// The codec works on plain vectors: hand it the shard bytes (a
|
||||
// move for heap buffers, a copy out of arena blocks) and put the
|
||||
// results back. Reconstruction is the rare path, so the copy is
|
||||
// acceptable.
|
||||
let mut owned: Vec<Option<Vec<u8>>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect();
|
||||
let result = if needs_source_parity_verification {
|
||||
// Rebuild missing parity together with missing data so the
|
||||
// shard set is complete for `verify`. Rebuilt parity is
|
||||
// consistent with the reconstructed data by construction, so
|
||||
// the verification below is equivalent to checking only the
|
||||
// originally-present source parity — the same semantics as the
|
||||
// legacy `decode_data_with_reconstruction_verification` path.
|
||||
// Rebuilding only data here would leave missing parity slots
|
||||
// as `None` and misreport a recoverable degraded read (for
|
||||
// example one missing data shard plus one missing parity
|
||||
// shard) as an inconsistent-source failure.
|
||||
codec.reconstruct_opt(owned.as_mut_slice())
|
||||
} else {
|
||||
codec.reconstruct_data_opt(owned.as_mut_slice())
|
||||
}
|
||||
.map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}")))
|
||||
.and_then(|()| {
|
||||
if needs_source_parity_verification {
|
||||
self.verify_source_parity(codec, &owned)?;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
if result.is_err() {
|
||||
for index in missing_parity {
|
||||
owned[index] = None;
|
||||
}
|
||||
}
|
||||
for (slot, shard) in shards.iter_mut().zip(owned) {
|
||||
*slot = shard.map(S::from);
|
||||
}
|
||||
result?;
|
||||
|
||||
Ok(GET_RECONSTRUCT_OUTCOME_RUSTFS_CALLED)
|
||||
}
|
||||
@@ -483,7 +440,7 @@ mod tests {
|
||||
fn data_shards_complete_ignores_parity_slots() {
|
||||
let shards = vec![Some(vec![1]), Some(vec![2]), None];
|
||||
|
||||
assert!(data_shards_complete(&shards, 2));
|
||||
assert_eq!(data_reconstruction_sources(&shards, 2, 1).expect("complete data"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -491,8 +448,8 @@ mod tests {
|
||||
let missing_data = vec![Some(vec![1]), None, Some(vec![3])];
|
||||
let short = vec![Some(vec![1])];
|
||||
|
||||
assert!(!data_shards_complete(&missing_data, 2));
|
||||
assert!(!data_shards_complete(&short, 2));
|
||||
assert_eq!(data_reconstruction_sources(&missing_data, 2, 1).expect("valid shape"), Some(2));
|
||||
assert!(data_reconstruction_sources(&short, 2, 1).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -585,18 +542,22 @@ mod tests {
|
||||
#[test]
|
||||
fn rustfs_codec_decode_engine_errors_on_insufficient_shards_like_legacy() {
|
||||
let erasure = Erasure::new(4, 2, 16);
|
||||
let mut legacy_shards = encoded_shards(&erasure, b"insufficient shards must fail");
|
||||
let mut rustfs_shards = legacy_shards.clone();
|
||||
for index in [0, 1, 2] {
|
||||
legacy_shards[index] = None;
|
||||
rustfs_shards[index] = None;
|
||||
}
|
||||
|
||||
let legacy = LegacyEcDecodeEngine::new(erasure.clone());
|
||||
let rustfs = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created");
|
||||
for payload in [b"".as_slice(), b"insufficient shards must fail"] {
|
||||
let mut original = encoded_shards(&erasure, payload);
|
||||
original[..3].fill(None);
|
||||
let mut legacy_shards = original.clone();
|
||||
let mut rustfs_shards = original.clone();
|
||||
|
||||
assert!(reconstruct_with(&legacy, &mut legacy_shards).is_err());
|
||||
assert!(reconstruct_with(&rustfs, &mut rustfs_shards).is_err());
|
||||
let legacy_error = reconstruct_with(&legacy, &mut legacy_shards).expect_err("legacy needs quorum");
|
||||
let rustfs_error = reconstruct_with(&rustfs, &mut rustfs_shards).expect_err("native needs quorum");
|
||||
assert_eq!(legacy_error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(rustfs_error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(legacy_shards, original);
|
||||
assert_eq!(rustfs_shards, original);
|
||||
}
|
||||
assert!(!rustfs.codec_is_initialized());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -653,12 +614,14 @@ mod tests {
|
||||
panic!("test parity shard should be present");
|
||||
};
|
||||
corrupt_parity[0] ^= 0x80;
|
||||
let source_parity = shards[erasure.data_shards..].to_vec();
|
||||
|
||||
let engine = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created");
|
||||
let err = reconstruct_with(&engine, &mut shards).expect_err("corrupt surviving parity must still be rejected");
|
||||
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
|
||||
assert!(err.to_string().contains("inconsistent read source shards"));
|
||||
assert_eq!(&shards[erasure.data_shards..], source_parity);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -774,19 +737,33 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rustfs_codec_decode_engine_returns_called_without_parity_codec() {
|
||||
fn streaming_decode_engines_reject_incomplete_zero_parity_shards() {
|
||||
fn check<E: ErasureDecodeEngine>(engine: &E) {
|
||||
let mut workspace = engine.prepare_workspace(4).expect("workspace should be prepared");
|
||||
for malformed in [
|
||||
vec![None, Some(vec![2; 4])],
|
||||
vec![Some(vec![2; 4]); 3],
|
||||
vec![None, Some(Vec::new())],
|
||||
] {
|
||||
let mut shards = malformed.clone();
|
||||
let error = engine
|
||||
.reconstruct_into(&mut shards, &mut workspace)
|
||||
.expect_err("invalid shard set");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(shards, malformed);
|
||||
}
|
||||
|
||||
let mut shards = vec![Some(vec![2; 4]); 2];
|
||||
let outcome = engine.reconstruct_into(&mut shards, &mut workspace).expect("complete data");
|
||||
assert_eq!(outcome, GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE);
|
||||
assert_eq!(shards, vec![Some(vec![2; 4]); 2]);
|
||||
}
|
||||
|
||||
let erasure = Erasure::new(2, 0, 16);
|
||||
let engine = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created");
|
||||
let mut workspace = engine.prepare_workspace(4).expect("workspace should be prepared");
|
||||
let mut shards = vec![None, Some(vec![2, 2, 2, 2])];
|
||||
|
||||
let outcome = engine
|
||||
.reconstruct_into(&mut shards, &mut workspace)
|
||||
.expect("zero parity engine should not allocate codec");
|
||||
|
||||
assert_eq!(outcome, GET_RECONSTRUCT_OUTCOME_RUSTFS_CALLED);
|
||||
assert!(shards[0].is_none());
|
||||
check(&engine);
|
||||
assert!(!engine.codec_is_initialized());
|
||||
check(&LegacyEcDecodeEngine::new(erasure));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4396,6 +4396,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zero_parity_full_and_prefix_reads_reject_an_incomplete_stripe_before_output() {
|
||||
let block_size = 64;
|
||||
for data_shards in [1, 4] {
|
||||
let erasure = Erasure::new(data_shards, 0, block_size);
|
||||
let shard_size = erasure.shard_size();
|
||||
for length in [block_size, shard_size / 2] {
|
||||
let mut output = Vec::new();
|
||||
let readers = make_test_readers(data_shards, shard_size, 1, &HashAlgorithm::HighwayHash256, &[], &[]).await;
|
||||
let (written, error) = erasure.decode(&mut output, readers, 0, length, block_size).await;
|
||||
assert!(error.is_none(), "complete stripe: {error:?}");
|
||||
assert_eq!(written, length);
|
||||
assert_eq!(output.len(), length);
|
||||
|
||||
let last = [data_shards - 1];
|
||||
for (missing, corrupt) in [(&last[..], &[][..]), (&[][..], &last[..])] {
|
||||
output.clear();
|
||||
let readers =
|
||||
make_test_readers(data_shards, shard_size, 1, &HashAlgorithm::HighwayHash256, missing, corrupt).await;
|
||||
let (written, error) = erasure.decode(&mut output, readers, 0, length, block_size).await;
|
||||
assert_eq!(
|
||||
error.expect("incomplete stripe must fail").to_string(),
|
||||
Error::ErasureReadQuorum.to_string()
|
||||
);
|
||||
assert_eq!(written, 0);
|
||||
assert!(output.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn copy_source_below_read_quorum_fails_before_output() {
|
||||
|
||||
@@ -246,6 +246,22 @@ impl LegacyReedSolomonEncoder {
|
||||
return Ok(());
|
||||
}
|
||||
let shard_len = shards[0].len();
|
||||
let (data, parity) = shards
|
||||
.split_at_mut_checked(self.data_shards)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing data shards for SIMD encoding"))?;
|
||||
self.with_encoded_parity(data.iter().map(|shard| &**shard), shard_len, |result| {
|
||||
for (output, recovery) in parity.iter_mut().zip(result.recovery_iter()) {
|
||||
output.copy_from_slice(recovery);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn with_encoded_parity<'a, T>(
|
||||
&self,
|
||||
data: impl IntoIterator<Item = &'a [u8]>,
|
||||
shard_len: usize,
|
||||
use_parity: impl FnOnce(&reed_solomon_simd::EncoderResult<'_>) -> T,
|
||||
) -> io::Result<T> {
|
||||
let cached_encoder = self
|
||||
.encoder_cache
|
||||
.write()
|
||||
@@ -274,7 +290,7 @@ impl LegacyReedSolomonEncoder {
|
||||
},
|
||||
)?;
|
||||
let encoder = &mut workspace.codec;
|
||||
for (i, shard) in shards.iter().enumerate().take(self.data_shards) {
|
||||
for (i, shard) in data.into_iter().enumerate() {
|
||||
encoder
|
||||
.add_original_shard(shard)
|
||||
.map_err(|e| io::Error::other(format!("Failed to add shard {i}: {e:?}")))?;
|
||||
@@ -282,11 +298,7 @@ impl LegacyReedSolomonEncoder {
|
||||
let result = encoder
|
||||
.encode()
|
||||
.map_err(|e| io::Error::other(format!("SIMD encoding failed: {e:?}")))?;
|
||||
for (i, recovery_shard) in result.recovery_iter().enumerate() {
|
||||
if i + self.data_shards < shards.len() {
|
||||
shards[i + self.data_shards].copy_from_slice(recovery_shard);
|
||||
}
|
||||
}
|
||||
let output = use_parity(&result);
|
||||
drop(result);
|
||||
if self.should_cache_workspace(shard_len) {
|
||||
let mut cache = self
|
||||
@@ -297,20 +309,10 @@ impl LegacyReedSolomonEncoder {
|
||||
*cache = Some(workspace);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn reconstruct_data<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? {
|
||||
return Ok(());
|
||||
}
|
||||
// Every data shard present: nothing to rebuild. The conversions
|
||||
// below would copy each shard out of its arena block and hand back
|
||||
// heap buffers, which also defeats the zero-copy emit.
|
||||
if shards.iter().take(self.data_shards).all(Option::is_some) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
fn reconstruct_missing_data<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
let shard_len = shards
|
||||
.iter()
|
||||
.find_map(|s| s.as_ref().map(|v| v.len()))
|
||||
@@ -361,14 +363,12 @@ impl LegacyReedSolomonEncoder {
|
||||
.decode()
|
||||
.map_err(|e| io::Error::other(format!("SIMD decode error: {e:?}")))?;
|
||||
|
||||
for (i, shard_opt) in shards.iter_mut().enumerate() {
|
||||
if shard_opt.is_none() && i < self.data_shards {
|
||||
for (restored_index, restored_data) in result.restored_original_iter() {
|
||||
if restored_index == i {
|
||||
*shard_opt = Some(S::from(restored_data.to_vec()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (index, shard) in shards[..self.data_shards].iter_mut().enumerate() {
|
||||
if shard.is_none() {
|
||||
let restored = result
|
||||
.restored_original(index)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing data shard after SIMD reconstruction"))?;
|
||||
*shard = Some(S::from(restored.to_vec()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,11 +387,6 @@ impl LegacyReedSolomonEncoder {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reconstruct<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
self.reconstruct_data(shards)?;
|
||||
self.encode_parity(shards)
|
||||
}
|
||||
|
||||
fn verify(&self, shards: &[&[u8]]) -> io::Result<bool> {
|
||||
let expected_shards = self.data_shards + self.parity_shards;
|
||||
if shards.len() != expected_shards {
|
||||
@@ -430,6 +425,25 @@ impl LegacyReedSolomonEncoder {
|
||||
fn encode_parity<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
encode_parity_shards(shards, self.data_shards, self.parity_shards, |shards| self.encode(shards))
|
||||
}
|
||||
|
||||
fn verify_and_rebuild_parity<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<Option<usize>> {
|
||||
verify_rebuilt_parity(shards, self.data_shards, |data, parity, shard_len| {
|
||||
self.with_encoded_parity(data.iter().copied(), shard_len, |result| {
|
||||
let mismatch = parity
|
||||
.iter()
|
||||
.zip(result.recovery_iter())
|
||||
.position(|(slot, rebuilt)| slot.as_ref().is_some_and(|source| source.as_slice() != rebuilt));
|
||||
if mismatch.is_none() {
|
||||
for (slot, rebuilt) in parity.iter_mut().zip(result.recovery_iter()) {
|
||||
if slot.is_none() {
|
||||
*slot = Some(S::from(rebuilt.to_vec()));
|
||||
}
|
||||
}
|
||||
}
|
||||
mismatch
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Reed-Solomon encoder using rustfs-erasure-codec
|
||||
@@ -485,31 +499,36 @@ impl ReedSolomonEncoder {
|
||||
}
|
||||
|
||||
/// Reconstruct missing data shards.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error for incorrect shard counts, insufficient source
|
||||
/// shards, or failed reconstruction.
|
||||
pub fn reconstruct_data<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? {
|
||||
let sources = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)?;
|
||||
if self.parity_shards == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
// Every data shard present: nothing to rebuild. The conversions
|
||||
// below would copy each shard out of its arena block and hand back
|
||||
// heap buffers, which also defeats the zero-copy emit.
|
||||
if shards.iter().take(self.data_shards).all(Option::is_some) {
|
||||
return Ok(());
|
||||
let rs = self
|
||||
.encoder
|
||||
.as_deref()
|
||||
.ok_or_else(|| io::Error::other("missing Reed-Solomon encoder"))?;
|
||||
if sources.is_some() && !recover_empty_payload_data_shards(shards, self.data_shards) {
|
||||
Self::reconstruct_missing_data(rs, shards)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
if let Some(ref rs) = self.encoder {
|
||||
// The codec works on plain vectors: a move for vectors, a copy out
|
||||
// of arena blocks (reconstruction is the rare path).
|
||||
let mut owned: Vec<Option<Vec<u8>>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect();
|
||||
let result = rs
|
||||
.reconstruct_data(owned.as_mut_slice())
|
||||
.map_err(|e| io::Error::other(format!("Reed-Solomon reconstruct failed: {e:?}")));
|
||||
for (slot, shard) in shards.iter_mut().zip(owned) {
|
||||
*slot = shard.map(S::from);
|
||||
}
|
||||
result
|
||||
} else {
|
||||
Ok(())
|
||||
fn reconstruct_missing_data<S: ShardBytes>(rs: &ReedSolomon, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
// The codec works on plain vectors: a move for vectors, a copy out
|
||||
// of arena blocks (reconstruction is the rare path).
|
||||
let mut owned: Vec<Option<Vec<u8>>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect();
|
||||
let result = rs
|
||||
.reconstruct_data(owned.as_mut_slice())
|
||||
.map_err(|e| io::Error::other(format!("Reed-Solomon reconstruct failed: {e:?}")));
|
||||
for (slot, shard) in shards.iter_mut().zip(owned) {
|
||||
*slot = shard.map(S::from);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reconstruct missing data shards and regenerate parity shards.
|
||||
@@ -544,6 +563,44 @@ impl ReedSolomonEncoder {
|
||||
fn encode_parity<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
encode_parity_shards(shards, self.data_shards, self.parity_shards, |shards| self.encode(shards))
|
||||
}
|
||||
|
||||
fn verify_and_rebuild_parity<S: ShardBytes>(&self, rs: &ReedSolomon, shards: &mut [Option<S>]) -> io::Result<Option<usize>> {
|
||||
verify_rebuilt_parity(shards, self.data_shards, |data, parity, shard_len| {
|
||||
let missing_count = parity.iter().filter(|slot| slot.is_none()).count();
|
||||
let source_count = parity.len() - missing_count;
|
||||
let scratch_len = shard_len.checked_mul(source_count).ok_or(io::ErrorKind::OutOfMemory)?;
|
||||
let mut scratch = vec![0; scratch_len];
|
||||
let mut rebuilt: SmallVec<[S; 16]> = (0..missing_count).map(|_| S::from(vec![0; shard_len])).collect();
|
||||
|
||||
let mut source_outputs = scratch.chunks_exact_mut(shard_len);
|
||||
let mut missing_outputs = rebuilt.iter_mut().map(ShardBytes::as_mut_slice);
|
||||
let mut outputs: SmallVec<[&mut [u8]; 16]> = SmallVec::with_capacity(parity.len());
|
||||
for slot in parity.iter() {
|
||||
let output = if slot.is_some() {
|
||||
source_outputs.next()
|
||||
} else {
|
||||
missing_outputs.next()
|
||||
};
|
||||
outputs.push(output.ok_or_else(|| io::Error::other("missing parity verification output"))?);
|
||||
}
|
||||
rs.encode_sep(data, &mut outputs)
|
||||
.map_err(|error| io::Error::other(format!("Reed-Solomon encode failed: {error:?}")))?;
|
||||
drop(outputs);
|
||||
|
||||
let mismatch = parity
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, slot)| slot.as_ref().map(|source| (index, source)))
|
||||
.zip(scratch.chunks_exact(shard_len))
|
||||
.find_map(|((index, source), expected)| (source.as_slice() != expected).then_some(index));
|
||||
if mismatch.is_none() {
|
||||
for (slot, shard) in parity.iter_mut().filter(|slot| slot.is_none()).zip(rebuilt) {
|
||||
*slot = Some(shard);
|
||||
}
|
||||
}
|
||||
Ok(mismatch)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn cached_modern_reed_solomon(data_shards: usize, parity_shards: usize) -> Result<Arc<ReedSolomon>, rustfs_erasure_codec::Error> {
|
||||
@@ -666,29 +723,79 @@ where
|
||||
encode(shard_refs)
|
||||
}
|
||||
|
||||
fn recover_empty_payload_data_shards<S: ShardBytes>(
|
||||
// Keep surviving parity read-only. Backends can compare against their own
|
||||
// encoding workspace or generate into scratch without copying the sources.
|
||||
fn verify_rebuilt_parity<S: ShardBytes>(
|
||||
shards: &mut [Option<S>],
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> io::Result<bool> {
|
||||
let expected_shards = data_shards + parity_shards;
|
||||
if shards.len() != expected_shards {
|
||||
return Err(io::Error::other(format!(
|
||||
"invalid shard count: got {}, expected {}",
|
||||
shards.len(),
|
||||
expected_shards
|
||||
)));
|
||||
}
|
||||
|
||||
let mut has_present_shard = false;
|
||||
for shard in shards.iter().filter_map(|shard| shard.as_ref()) {
|
||||
has_present_shard = true;
|
||||
if !shard.is_empty() {
|
||||
return Ok(false);
|
||||
rebuild: impl FnOnce(&[&[u8]], &mut [Option<S>], usize) -> io::Result<Option<usize>>,
|
||||
) -> io::Result<Option<usize>> {
|
||||
let (data, parity) = shards.split_at_mut(data_shards);
|
||||
let shard_len = data
|
||||
.first()
|
||||
.and_then(Option::as_ref)
|
||||
.map(ShardBytes::len)
|
||||
.ok_or_else(|| io::Error::other("missing data shard after reconstruction"))?;
|
||||
let mut inputs: SmallVec<[&[u8]; 16]> = SmallVec::with_capacity(data.len());
|
||||
for slot in data {
|
||||
let shard = slot
|
||||
.as_ref()
|
||||
.ok_or_else(|| io::Error::other("missing data shard after reconstruction"))?;
|
||||
if shard.len() != shard_len {
|
||||
return Err(io::Error::other("inconsistent shard length after reconstruction"));
|
||||
}
|
||||
inputs.push(shard.as_slice());
|
||||
}
|
||||
if !has_present_shard {
|
||||
return Ok(false);
|
||||
if parity.iter().flatten().any(|shard| shard.len() != shard_len) {
|
||||
return Err(io::Error::other("inconsistent shard length after reconstruction"));
|
||||
}
|
||||
if shard_len == 0 {
|
||||
for slot in parity {
|
||||
slot.get_or_insert_with(|| S::from(Vec::new()));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
rebuild(&inputs, parity, shard_len)
|
||||
}
|
||||
|
||||
/// Returns the available source count when any data shard needs reconstruction.
|
||||
/// Complete data returns `None` without scanning the parity slots.
|
||||
pub(crate) fn data_reconstruction_sources<S>(
|
||||
shards: &[Option<S>],
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> io::Result<Option<usize>> {
|
||||
let expected = data_shards.checked_add(parity_shards).ok_or(io::ErrorKind::InvalidData)?;
|
||||
if shards.len() != expected {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("invalid shard count: got {}, expected {expected}", shards.len()),
|
||||
));
|
||||
}
|
||||
if shards[..data_shards].iter().all(Option::is_some) {
|
||||
return Ok(None);
|
||||
}
|
||||
if parity_shards == 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "missing data shard with zero parity"));
|
||||
}
|
||||
let available = shards.iter().flatten().count();
|
||||
if available < data_shards {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"insufficient source shards to reconstruct data",
|
||||
));
|
||||
}
|
||||
Ok(Some(available))
|
||||
}
|
||||
|
||||
/// Recovers an empty stripe after its source quorum has been established.
|
||||
pub(crate) fn recover_empty_payload_data_shards<S: ShardBytes>(shards: &mut [Option<S>], data_shards: usize) -> bool {
|
||||
let mut present = shards.iter().flatten();
|
||||
let Some(first) = present.next() else {
|
||||
return false;
|
||||
};
|
||||
if !first.is_empty() || present.any(|shard| !shard.is_empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for shard in shards.iter_mut().take(data_shards) {
|
||||
@@ -696,7 +803,22 @@ fn recover_empty_payload_data_shards<S: ShardBytes>(
|
||||
*shard = Some(S::from(Vec::new()));
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum DecodeMode {
|
||||
Data,
|
||||
All,
|
||||
Verified,
|
||||
VerifiedLockstep,
|
||||
}
|
||||
|
||||
fn validate_decoder_geometry(expected: (usize, usize), actual: (usize, usize)) -> io::Result<()> {
|
||||
if expected != actual {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "erasure decoder geometry mismatch"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Erasure coding utility for data reliability using Reed-Solomon codes.
|
||||
@@ -1001,106 +1123,110 @@ impl Erasure {
|
||||
/// # Arguments
|
||||
/// * `shards` - Mutable slice of optional shard data. Missing shards should be `None`.
|
||||
///
|
||||
/// # Returns
|
||||
/// Ok if reconstruction succeeds, error otherwise.
|
||||
/// # Errors
|
||||
/// Returns an error for an incorrect shard count, insufficient source
|
||||
/// shards, or failed reconstruction.
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub fn decode_data<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
if self.parity_shards > 0 {
|
||||
if self.uses_legacy {
|
||||
if let Some(encoder) = self.legacy_encoder.as_ref() {
|
||||
encoder.reconstruct_data(shards)?;
|
||||
} else {
|
||||
warn!("parity_shards > 0, uses_legacy but legacy_encoder is None");
|
||||
}
|
||||
} else if let Some(encoder) = self.encoder.as_ref() {
|
||||
encoder.reconstruct_data(shards)?;
|
||||
} else {
|
||||
warn!("parity_shards > 0, but encoder is None");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
self.decode_shards(shards, DecodeMode::Data).map(drop)
|
||||
}
|
||||
|
||||
/// Decode and reconstruct missing data shards, then regenerate parity shards.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error for an incorrect shard count, failed reconstruction,
|
||||
/// or failed parity generation.
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub fn decode_data_and_parity<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
if self.parity_shards > 0 {
|
||||
if self.uses_legacy {
|
||||
if let Some(encoder) = self.legacy_encoder.as_ref() {
|
||||
encoder.reconstruct(shards)?;
|
||||
} else {
|
||||
warn!("parity_shards > 0, uses_legacy but legacy_encoder is None");
|
||||
}
|
||||
} else if let Some(encoder) = self.encoder.as_ref() {
|
||||
encoder.reconstruct(shards)?;
|
||||
} else {
|
||||
warn!("parity_shards > 0, but encoder is None");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
self.decode_shards(shards, DecodeMode::All).map(drop)
|
||||
}
|
||||
|
||||
pub(crate) fn decode_data_with_reconstruction_verification<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
|
||||
self.decode_data_with_reconstruction_verification_policy(shards, false)
|
||||
/// Returns whether any data shard had to be reconstructed.
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub(crate) fn decode_data_with_reconstruction_verification<S: ShardBytes>(
|
||||
&self,
|
||||
shards: &mut [Option<S>],
|
||||
) -> io::Result<bool> {
|
||||
self.decode_shards(shards, DecodeMode::Verified)
|
||||
}
|
||||
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub(crate) fn decode_data_with_reconstruction_verification_for_lockstep<S: ShardBytes>(
|
||||
&self,
|
||||
shards: &mut [Option<S>],
|
||||
) -> io::Result<()> {
|
||||
self.decode_data_with_reconstruction_verification_policy(shards, true)
|
||||
) -> io::Result<bool> {
|
||||
self.decode_shards(shards, DecodeMode::VerifiedLockstep)
|
||||
}
|
||||
|
||||
fn decode_data_with_reconstruction_verification_policy<S: ShardBytes>(
|
||||
&self,
|
||||
shards: &mut [Option<S>],
|
||||
require_surplus_source: bool,
|
||||
) -> io::Result<()> {
|
||||
let missing_data_source = shards.iter().take(self.data_shards).any(|shard| shard.is_none());
|
||||
let available_shards = shards.iter().filter(|shard| shard.is_some()).count();
|
||||
if require_surplus_source && missing_data_source && available_shards == self.data_shards {
|
||||
fn decode_shards<S: ShardBytes>(&self, shards: &mut [Option<S>], mode: DecodeMode) -> io::Result<bool> {
|
||||
let sources = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)?;
|
||||
if self.parity_shards == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
if matches!(mode, DecodeMode::VerifiedLockstep) && sources == Some(self.data_shards) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"insufficient source shards to verify reconstructed data",
|
||||
));
|
||||
}
|
||||
let source_parity = if missing_data_source && available_shards > self.data_shards {
|
||||
shards
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(self.data_shards)
|
||||
.filter_map(|(index, shard)| shard.as_ref().map(|shard| (index, shard.as_slice().to_vec())))
|
||||
.collect::<Vec<_>>()
|
||||
let verify_parity = matches!(mode, DecodeMode::Verified | DecodeMode::VerifiedLockstep)
|
||||
&& sources.is_some_and(|available| available > self.data_shards);
|
||||
let missing = sources.is_some();
|
||||
let needs_decode = |shards: &mut [Option<S>]| missing && !recover_empty_payload_data_shards(shards, self.data_shards);
|
||||
let geometry = (self.data_shards, self.parity_shards);
|
||||
let mismatch = if self.uses_legacy {
|
||||
let encoder = self
|
||||
.legacy_encoder
|
||||
.as_ref()
|
||||
.ok_or_else(|| io::Error::other("missing legacy erasure encoder"))?;
|
||||
validate_decoder_geometry(geometry, (encoder.data_shards, encoder.parity_shards))?;
|
||||
if needs_decode(shards) {
|
||||
encoder.reconstruct_missing_data(shards)?;
|
||||
}
|
||||
if verify_parity {
|
||||
encoder.verify_and_rebuild_parity(shards)?
|
||||
} else {
|
||||
if matches!(mode, DecodeMode::All) {
|
||||
encoder.encode_parity(shards)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
} else {
|
||||
Vec::new()
|
||||
let encoder = self
|
||||
.encoder
|
||||
.as_ref()
|
||||
.ok_or_else(|| io::Error::other("missing erasure encoder"))?;
|
||||
validate_decoder_geometry(geometry, (encoder.data_shards, encoder.parity_shards))?;
|
||||
let rs = encoder
|
||||
.encoder
|
||||
.as_deref()
|
||||
.ok_or_else(|| io::Error::other("missing Reed-Solomon encoder"))?;
|
||||
if needs_decode(shards) {
|
||||
ReedSolomonEncoder::reconstruct_missing_data(rs, shards)?;
|
||||
}
|
||||
if verify_parity {
|
||||
encoder.verify_and_rebuild_parity(rs, shards)?
|
||||
} else {
|
||||
if matches!(mode, DecodeMode::All) {
|
||||
encoder.encode_parity(shards)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
if source_parity.is_empty() {
|
||||
return self.decode_data(shards);
|
||||
if let Some(index) = mismatch {
|
||||
let index = self.data_shards + index;
|
||||
warn!(
|
||||
shard_index = index,
|
||||
data_shards = self.data_shards,
|
||||
parity_shards = self.parity_shards,
|
||||
"erasure decode rejected inconsistent read source shards"
|
||||
);
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "inconsistent read source shards"));
|
||||
}
|
||||
|
||||
self.decode_data_and_parity(shards)?;
|
||||
for (index, source) in source_parity {
|
||||
let Some(rebuilt) = shards[index].as_ref() else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"missing rebuilt parity shard after read verification",
|
||||
));
|
||||
};
|
||||
if rebuilt.as_slice() != source.as_slice() {
|
||||
warn!(
|
||||
shard_index = index,
|
||||
data_shards = self.data_shards,
|
||||
parity_shards = self.parity_shards,
|
||||
"erasure decode rejected inconsistent read source shards"
|
||||
);
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "inconsistent read source shards"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Ok(missing)
|
||||
}
|
||||
|
||||
pub(crate) fn verify_data_and_parity<S: ShardBytes>(&self, shards: &[Option<S>]) -> io::Result<bool> {
|
||||
@@ -1341,7 +1467,7 @@ mod tests {
|
||||
let mut decoded = vec![None, Some(shards[1].clone()), Some(shards[2].clone())];
|
||||
let (resources, _) = test_resource_units(1);
|
||||
with_optional_resource_unit(Some(resources.with_memory_budget(memory.clone())), async {
|
||||
codec.reconstruct_data(&mut decoded).expect("accounted decoder");
|
||||
codec.reconstruct_missing_data(&mut decoded).expect("accounted decoder");
|
||||
})
|
||||
.await;
|
||||
assert_eq!(decoded[0].as_deref(), Some(shards[0].as_slice()));
|
||||
@@ -1896,10 +2022,7 @@ mod tests {
|
||||
assert!(err.to_string().contains("inconsistent shard length"));
|
||||
|
||||
let mut no_present_empty_payload: Vec<Option<Vec<u8>>> = vec![None, None, None];
|
||||
assert!(
|
||||
!recover_empty_payload_data_shards(&mut no_present_empty_payload, 2, 1)
|
||||
.expect("all-missing empty payload marker should not be synthesized")
|
||||
);
|
||||
assert!(!recover_empty_payload_data_shards(&mut no_present_empty_payload, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2113,6 +2236,185 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_parity_reconstruction_requires_exact_geometry_and_all_data() {
|
||||
type Decode<'a> = (&'a str, &'a dyn Fn(&mut [Option<Vec<u8>>]) -> io::Result<()>);
|
||||
|
||||
for data_shards in [1, 4] {
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Erasure::new_with_options(data_shards, 0, 64, uses_legacy);
|
||||
let encoder = ReedSolomonEncoder::new(data_shards, 0).expect("zero parity encoder");
|
||||
let decoders: [Decode<'_>; 6] = [
|
||||
("data", &|shards| erasure.decode_data(shards)),
|
||||
("data and parity", &|shards| erasure.decode_data_and_parity(shards)),
|
||||
("verified", &|shards| {
|
||||
erasure.decode_data_with_reconstruction_verification(shards).map(drop)
|
||||
}),
|
||||
("lockstep", &|shards| {
|
||||
erasure
|
||||
.decode_data_with_reconstruction_verification_for_lockstep(shards)
|
||||
.map(drop)
|
||||
}),
|
||||
("direct data", &|shards| encoder.reconstruct_data(shards)),
|
||||
("direct data and parity", &|shards| encoder.reconstruct(shards)),
|
||||
];
|
||||
let complete = vec![Some(vec![42]); data_shards];
|
||||
let empty_payload = vec![Some(Vec::new()); data_shards];
|
||||
let mut missing = complete.clone();
|
||||
missing[data_shards - 1] = None;
|
||||
let mut missing_from_empty = empty_payload.clone();
|
||||
missing_from_empty[data_shards - 1] = None;
|
||||
let mut overlong = complete.clone();
|
||||
overlong.push(None);
|
||||
for (name, decode) in decoders {
|
||||
for malformed in [&complete[..data_shards - 1], &overlong, &missing, &missing_from_empty] {
|
||||
let mut shards = malformed.to_vec();
|
||||
let error = decode(&mut shards).expect_err(name);
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{name}: {error}");
|
||||
assert_eq!(shards, malformed, "{name} must reject before mutation");
|
||||
}
|
||||
for expected in [&complete, &empty_payload] {
|
||||
let mut shards = expected.clone();
|
||||
decode(&mut shards).expect(name);
|
||||
assert_eq!(&shards, expected, "{name} must preserve complete data");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_data_decode_does_not_read_payloads() {
|
||||
struct Present;
|
||||
|
||||
impl AsRef<[u8]> for Present {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
panic!("complete data must not enter payload inspection");
|
||||
}
|
||||
}
|
||||
impl AsMut<[u8]> for Present {
|
||||
fn as_mut(&mut self) -> &mut [u8] {
|
||||
panic!("complete data must not be rewritten");
|
||||
}
|
||||
}
|
||||
impl From<Vec<u8>> for Present {
|
||||
fn from(_: Vec<u8>) -> Self {
|
||||
panic!("complete data must not allocate replacement shards");
|
||||
}
|
||||
}
|
||||
impl ShardBytes for Present {
|
||||
fn into_vec(self) -> Vec<u8> {
|
||||
panic!("complete data must not be copied");
|
||||
}
|
||||
}
|
||||
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Erasure::new_with_options(2, 2, 64, uses_legacy);
|
||||
let mut shards = [Some(Present), Some(Present), None, Some(Present)];
|
||||
erasure.decode_data(&mut shards).expect("complete data");
|
||||
assert!(
|
||||
!erasure
|
||||
.decode_data_with_reconstruction_verification(&mut shards)
|
||||
.expect("complete data"),
|
||||
"missing parity must not trigger data reconstruction"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconstruction_errors_when_selected_encoder_is_absent() {
|
||||
for uses_legacy in [false, true] {
|
||||
let mut erasure = Erasure::new_with_options(2, 1, 64, uses_legacy);
|
||||
let mut shards = vec![Some(vec![1]); 3];
|
||||
erasure.encoder = None;
|
||||
erasure.legacy_encoder = None;
|
||||
assert_eq!(
|
||||
erasure.decode_data(&mut shards).expect_err("missing encoder").kind(),
|
||||
io::ErrorKind::Other
|
||||
);
|
||||
assert_eq!(
|
||||
erasure
|
||||
.decode_data_and_parity(&mut shards)
|
||||
.expect_err("missing encoder")
|
||||
.kind(),
|
||||
io::ErrorKind::Other
|
||||
);
|
||||
assert_eq!(
|
||||
erasure
|
||||
.decode_data_with_reconstruction_verification(&mut shards)
|
||||
.expect_err("missing encoder")
|
||||
.kind(),
|
||||
io::ErrorKind::Other
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconstruction_rejects_mismatched_decoder_geometry() {
|
||||
for uses_legacy in [false, true] {
|
||||
let mut erasure = Erasure::new_with_options(2, 2, 64, uses_legacy);
|
||||
erasure.data_shards = 3;
|
||||
erasure.parity_shards = 1;
|
||||
let original = [Some(vec![1]), Some(vec![2]), Some(vec![3]), Some(vec![4])];
|
||||
let mut shards = original.clone();
|
||||
let error = erasure
|
||||
.decode_data_and_parity(&mut shards)
|
||||
.expect_err("encoder dimensions differ");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(shards, original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconstruction_requires_read_quorum_even_for_empty_shards() {
|
||||
let below_quorum = [Some(Vec::new()), None, None];
|
||||
let exact_quorum = [None, Some(Vec::new()), Some(Vec::new())];
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Erasure::new_with_options(2, 1, 64, uses_legacy);
|
||||
for mode in [
|
||||
DecodeMode::Data,
|
||||
DecodeMode::All,
|
||||
DecodeMode::Verified,
|
||||
DecodeMode::VerifiedLockstep,
|
||||
] {
|
||||
let mut shards = below_quorum.clone();
|
||||
let error = erasure
|
||||
.decode_shards(&mut shards, mode)
|
||||
.expect_err("one empty source is below quorum");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(shards, below_quorum);
|
||||
}
|
||||
for mode in [DecodeMode::Data, DecodeMode::All, DecodeMode::Verified] {
|
||||
let mut shards = exact_quorum.clone();
|
||||
assert!(
|
||||
erasure
|
||||
.decode_shards(&mut shards, mode)
|
||||
.expect("two empty sources meet quorum")
|
||||
);
|
||||
assert_eq!(shards, [Some(Vec::new()), Some(Vec::new()), Some(Vec::new())]);
|
||||
}
|
||||
let mut shards = exact_quorum.clone();
|
||||
let error = erasure
|
||||
.decode_data_with_reconstruction_verification_for_lockstep(&mut shards)
|
||||
.expect_err("lockstep requires a surplus source for reconstruction");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(shards, exact_quorum);
|
||||
}
|
||||
let encoder = ReedSolomonEncoder::new(2, 1).expect("2+1 encoder");
|
||||
let mut shards = below_quorum.clone();
|
||||
let error = encoder
|
||||
.reconstruct_data(&mut shards)
|
||||
.expect_err("a direct reconstruction also needs quorum");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(shards, below_quorum);
|
||||
|
||||
let mut shards = exact_quorum;
|
||||
encoder
|
||||
.reconstruct_data(&mut shards)
|
||||
.expect("direct empty reconstruction at quorum");
|
||||
assert_eq!(shards, [Some(Vec::new()), Some(Vec::new()), Some(Vec::new())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_data_and_parity_rejects_wrong_shard_count() {
|
||||
for uses_legacy in [false, true] {
|
||||
@@ -2132,18 +2434,44 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn decode_data_with_verification_rejects_corrupt_surplus_parity() {
|
||||
let erasure = Erasure::new(3, 2, 128);
|
||||
let data = b"verified reads must fail closed on stale surplus parity";
|
||||
let encoded = erasure.encode_data(data).expect("encode should succeed");
|
||||
let mut shards = optional_shards(&encoded);
|
||||
shards[1] = None;
|
||||
shards[erasure.data_shards].as_mut().expect("parity shard should be present")[0] ^= 0x7d;
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Erasure::new_with_options(3, 3, 128, uses_legacy);
|
||||
let data = b"verified reads must fail closed on stale surplus parity";
|
||||
let encoded = erasure.encode_data(data).expect("encode should succeed");
|
||||
let mut shards = optional_shards(&encoded);
|
||||
shards[1] = None;
|
||||
shards[erasure.data_shards] = None;
|
||||
shards[erasure.data_shards + 1].as_mut().expect("source parity")[0] ^= 0x7d;
|
||||
let source_parity = shards[erasure.data_shards..].to_vec();
|
||||
|
||||
let err = erasure
|
||||
.decode_data_with_reconstruction_verification(&mut shards)
|
||||
.expect_err("verified decode must reject inconsistent parity");
|
||||
let err = erasure
|
||||
.decode_data_with_reconstruction_verification(&mut shards)
|
||||
.expect_err("verified decode must reject inconsistent parity");
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(&shards[erasure.data_shards..], source_parity);
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
|
||||
#[test]
|
||||
fn verified_decode_restores_missing_parity_with_surplus_sources() {
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Erasure::new_with_options(4, 3, 128, uses_legacy);
|
||||
for payload in [b"".as_slice(), b"reconstruct both a data shard and a parity shard"] {
|
||||
let encoded = erasure.encode_data(payload).expect("encode should succeed");
|
||||
let expected = optional_shards(&encoded);
|
||||
let mut shards = expected.clone();
|
||||
shards[1] = None;
|
||||
shards[erasure.data_shards + 1] = None;
|
||||
|
||||
assert!(
|
||||
erasure
|
||||
.decode_data_with_reconstruction_verification(&mut shards)
|
||||
.expect("enough sources"),
|
||||
"data reconstruction must be reported"
|
||||
);
|
||||
assert_eq!(shards, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -49,6 +49,8 @@ fn inherent_hotpath_measurements_have_cpu_attribution_types() {
|
||||
"encode_data_bytes_mut",
|
||||
"decode_data",
|
||||
"decode_data_and_parity",
|
||||
"decode_data_with_reconstruction_verification",
|
||||
"decode_data_with_reconstruction_verification_for_lockstep",
|
||||
] {
|
||||
assert_measured_as(ERASURE, "Erasure", function);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
12|crates/ecstore/src/data_usage/mod.rs
|
||||
5|crates/ecstore/src/disk/local.rs
|
||||
1|crates/ecstore/src/disk/mod.rs
|
||||
5|crates/ecstore/src/erasure/codec/bridge.rs
|
||||
3|crates/ecstore/src/erasure/codec/bridge.rs
|
||||
1|crates/ecstore/src/erasure/coding/decode_reader.rs
|
||||
8|crates/ecstore/src/erasure/coding/encode.rs
|
||||
25|crates/ecstore/src/erasure/coding/erasure.rs
|
||||
|
||||
Reference in New Issue
Block a user