Compare commits

...

3 Commits

Author SHA1 Message Date
loverustfs f59daa1500 ci: require execution evidence for production ECStore recovery tests 2026-12-02 20:00:31 +08:00
loverustfs f956f54ceb test(ecstore): verify durable overwrite and multipart replay on simulated disks
Require the armed crash paths to fire and preserve the generation acknowledged to the caller. Store per-drive publication evidence so completion retries after power loss can verify the original upload and reject absent or misplaced witnesses.
2026-12-02 20:00:31 +08:00
loverustfs ffe40451c1 fix(kms): skip Transit directories when listing keys
Keep the BYOK wrapping-key directory out of key pagination so the deletion sweep can continue. Refs rustfs/rustfs#9846.
2026-12-02 19:34:25 +08:00
7 changed files with 582 additions and 75 deletions
+13
View File
@@ -382,6 +382,19 @@ jobs:
} > artifacts/workspace/doctest-diagnostics.txt
exit "${status}"
- name: Verify production ECStore crash and recovery
if: needs.classify-changes.outputs.mode == 'full'
env:
CARGO_BUILD_JOBS: "2"
run: |
dst=(--locked -p rustfs-ecstore --features dst --test dst_production_ecstore --profile ci)
mkdir -p artifacts/workspace/dst
cargo nextest list "${dst[@]}" --message-format json > artifacts/workspace/dst/selection.json
rm -f target/nextest/ci/junit.xml
trap 'if [[ -f target/nextest/ci/junit.xml ]]; then cp target/nextest/ci/junit.xml artifacts/workspace/dst/junit.xml; fi' EXIT
cargo nextest run "${dst[@]}" --no-tests fail --retries 0
python3 scripts/ci_test_artifact.py evidence --dst artifacts/workspace/dst/selection.json target/nextest/ci/junit.xml
- name: Upload test reports and diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+313 -53
View File
@@ -70,6 +70,12 @@ use crate::disk::{
endpoint::Endpoint,
error::{DiskError, Error, Result},
format::FormatV3,
multipart_source::{
MULTIPART_SOURCE_PROTOCOL_VERSION, MultipartProofKind, MultipartPublicationResult, MultipartSourceOperation,
MultipartSourcePhase, MultipartSourceProof, MultipartSourceRequest, MultipartSourceResponse, MultipartSourceSnapshot,
MultipartUndoCapability, ProofVerificationContext, PublicationIdentity, SourceConditionV1, capture_source_condition,
publication_identity, require_source_condition, strip_transport_condition,
},
part_transaction_path, validate_delete_recovery_options, validate_format_control_path,
};
use crate::erasure::coding::{self, bitrot_verify};
@@ -78,6 +84,8 @@ use crate::set_disk::SetDisks;
use crate::store::init_format::save_format_file;
const DST_DELETE_TX_DIR: &str = ".rustfs.sys/dst-del-tx";
const DST_MULTIPART_STATE: &str = ".dst-mpu-consumed";
const DST_MULTIPART_ANCHOR: &str = ".dst-mpu-retirement-anchor";
const DEFAULT_SIM_CAPACITY_BYTES: u64 = 10 * 1024 * 1024 * 1024;
fn sim_to_io_err(err: SimErr) -> IoError {
@@ -210,6 +218,22 @@ struct SimDeleteTxRecord {
backup_xl: Option<Vec<u8>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SimMultipartAnchor {
disk_id: Uuid,
physical_slot: usize,
publication: PublicationIdentity,
original_sha256: [u8; 32],
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SimMultipartState {
anchor: SimMultipartAnchor,
capability_sha256: Option<[u8; 32]>,
}
/// Deterministic simulated disk implementing production [`DiskAPI`] directly
/// on top of [`SimDiskIo`].
#[derive(Clone)]
@@ -226,6 +250,7 @@ pub struct DstSimDisk {
scanning: Arc<AtomicU32>,
delete_tx_lock: Arc<tokio::sync::Mutex<()>>,
cas_lock: Arc<tokio::sync::Mutex<()>>,
multipart_publication_lock: Arc<tokio::sync::Mutex<()>>,
configured_capacity: Arc<RwLock<Option<u64>>>,
multipart_proof_authority: Arc<RwLock<Option<crate::disk::multipart_source::ProofVerificationContext>>>,
}
@@ -281,6 +306,7 @@ impl DstSimDisk {
scanning: Arc::new(AtomicU32::new(0)),
delete_tx_lock: Arc::new(tokio::sync::Mutex::new(())),
cas_lock: Arc::new(tokio::sync::Mutex::new(())),
multipart_publication_lock: Arc::new(tokio::sync::Mutex::new(())),
configured_capacity: Arc::new(RwLock::new(None)),
multipart_proof_authority: Arc::new(RwLock::new(None)),
}
@@ -299,6 +325,12 @@ impl DstSimDisk {
&self.sim
}
/// Returns the simulator-only retirement witness path for fault injection.
pub fn multipart_retirement_anchor_path(volume: &str, object: &str, data_dir: Uuid) -> Result<String> {
let target_dir = join_vol_path(volume, object)?;
Ok(format!("{target_dir}/{data_dir}/{DST_MULTIPART_ANCHOR}"))
}
pub fn crash_registry(&self) -> &CrashRegistry {
&self.crash_registry
}
@@ -431,6 +463,241 @@ impl DstSimDisk {
Ok(())
}
fn multipart_authority(&self) -> Result<ProofVerificationContext> {
self.multipart_proof_authority
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone()
.ok_or(DiskError::UnsupportedDisk)
}
async fn sync_multipart_source_absence(&self, mut path: &str) -> Result<()> {
while let Some((parent, _)) = path.rsplit_once('/') {
match self.sim.stat(parent).await {
Ok(contents) if contents.is_dir => return self.fsync_parent_chain(parent).await,
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
Err(SimErr::NotFound(_)) => path = parent,
Err(error) => return Err(map_sim_err(error)),
}
}
self.fsync_parent_chain("").await
}
async fn prepare_multipart_anchor(
&self,
source_dir: &str,
src_path: &str,
target: (&str, &str),
fi: &FileInfo,
publication: PublicationIdentity,
) -> Result<SimMultipartAnchor> {
self.multipart_authority()?;
let condition = require_source_condition(fi)?;
if publication.lineage.path != src_path
|| (publication.lineage.bucket.as_str(), publication.lineage.object.as_str()) != target
|| condition.attach(&mut fi.clone())? != publication
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
{
return Err(DiskError::ConditionalDeleteConflict);
}
match self.sim.stat(&format!("{source_dir}/{DST_MULTIPART_STATE}")).await {
Err(SimErr::NotFound(_)) => {}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
}
let original = self
.sim
.read_file(&format!("{source_dir}/{STORAGE_FORMAT_FILE}"))
.await
.map_err(map_sim_err)?;
let original_fi = get_file_info(
&original,
RUSTFS_META_MULTIPART_BUCKET,
src_path,
&publication.lineage.original_version_id.unwrap_or_default().to_string(),
FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: true,
},
)?;
if capture_source_condition(target.0, target.1, src_path, &original_fi, publication.attempt)? != condition
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&original_fi.erasure.index)
{
return Err(DiskError::ConditionalDeleteConflict);
}
Ok(SimMultipartAnchor {
disk_id: self.get_disk_id().await?.ok_or(DiskError::InconsistentDisk)?,
physical_slot: self.disk_idx,
publication,
original_sha256: Sha256::digest(original).into(),
})
}
fn multipart_snapshot(
anchor: &SimMultipartAnchor,
revision: u64,
phase: MultipartSourcePhase,
record: &[u8],
target: &[u8],
capability_sha256: Option<[u8; 32]>,
) -> MultipartSourceSnapshot {
let state_sha256: [u8; 32] = Sha256::digest(record).into();
let mut inventory = Sha256::new();
inventory.update(state_sha256);
inventory.update(Sha256::digest(target));
MultipartSourceSnapshot {
disk_id: anchor.disk_id,
physical_slot: anchor.physical_slot,
lineage: anchor.publication.lineage.clone(),
generation: anchor.publication.source_generation,
revision,
phase,
state_sha256,
head_sha256: None,
inventory_sha256: inventory.finalize().into(),
capability_sha256,
publication: Some(anchor.publication.clone()),
}
}
async fn publish_multipart_witness(
&self,
source_dir: &str,
target_dir: &str,
anchor: SimMultipartAnchor,
target: &[u8],
) -> Result<MultipartPublicationResult> {
let authority = self.multipart_authority()?;
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", anchor.publication.final_data_dir);
let anchor_bytes = rmp_serde::to_vec_named(&anchor).map_err(Error::other)?;
self.write_durable_file(&anchor_path, Bytes::from(anchor_bytes)).await?;
let undo_capability = MultipartUndoCapability::new();
let state = SimMultipartState {
anchor,
capability_sha256: Some(undo_capability.digest()),
};
let record = rmp_serde::to_vec_named(&state).map_err(Error::other)?;
// The fsync of the source directory also persists removal of its old
// xl.meta name, which was renamed to the destination during commit.
self.write_durable_file(&format!("{source_dir}/{DST_MULTIPART_STATE}"), Bytes::copy_from_slice(&record))
.await?;
let snapshot = Self::multipart_snapshot(
&state.anchor,
1,
MultipartSourcePhase::ConsumedUnsealed,
&record,
target,
state.capability_sha256,
);
let publication = state.anchor.publication;
let proof = MultipartSourceProof::issue(&authority, MultipartProofKind::Published, publication.attempt, None, snapshot)?;
Ok(MultipartPublicationResult {
publication,
proof,
undo_capability,
})
}
async fn confirm_multipart_witness(
&self,
path: &str,
publication: &PublicationIdentity,
challenge: Uuid,
) -> Result<MultipartSourceProof> {
self.ensure_online()?;
publication.lineage.validate()?;
if publication.lineage.path != path || challenge.is_nil() {
return Err(DiskError::ConditionalDeleteConflict);
}
let _guard = self.multipart_publication_lock.lock().await;
let authority = self.multipart_authority()?;
let lineage = &publication.lineage;
let source_dir = join_vol_path(RUSTFS_META_MULTIPART_BUCKET, path)?;
let target_dir = join_vol_path(&lineage.bucket, &lineage.object)?;
let target_meta = format!("{target_dir}/{STORAGE_FORMAT_FILE}");
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", publication.final_data_dir);
let anchor_raw = self.sim.read_file(&anchor_path).await.map_err(map_sim_err)?;
let anchor: SimMultipartAnchor = rmp_serde::from_slice(&anchor_raw).map_err(Error::other)?;
if Some(anchor.disk_id) != self.get_disk_id().await?
|| anchor.physical_slot != self.disk_idx
|| anchor.publication != *publication
{
return Err(DiskError::ConditionalDeleteConflict);
}
let target = self.sim.read_file(&target_meta).await.map_err(map_sim_err)?;
let fi = get_file_info(
&target,
&lineage.bucket,
&lineage.object,
&publication.version_id.unwrap_or_default().to_string(),
FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: true,
},
)?;
let condition = SourceConditionV1 {
lineage: lineage.clone(),
generation: publication.source_generation,
attempt: publication.attempt,
};
let geometry = &lineage.geometry;
if publication_identity(&fi)?.as_ref() != Some(publication)
|| condition.attach(&mut fi.clone())? != *publication
|| geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
|| fi.erasure.distribution != geometry.distribution
|| fi.erasure.data_blocks != geometry.data_blocks
|| fi.erasure.parity_blocks != geometry.parity_blocks
|| fi.erasure.block_size != geometry.block_size
{
return Err(DiskError::ConditionalDeleteConflict);
}
if !fi.inline_data() && fi.size > 0 {
let verified = self.verify_file(&lineage.bucket, &lineage.object, &fi).await?;
if verified.results.iter().any(|result| *result != CHECK_PART_SUCCESS) {
return Err(DiskError::FileCorrupt);
}
}
self.sim.fsync_file(&target_meta).await.map_err(map_sim_err)?;
self.fsync_parent_chain(&target_dir).await?;
let (kind, snapshot) = match self.sim.stat(&source_dir).await {
Err(SimErr::NotFound(_)) => {
self.sync_multipart_source_absence(&source_dir).await?;
(
MultipartProofKind::RootMissingTerminal,
Self::multipart_snapshot(&anchor, 0, MultipartSourcePhase::RootMissing, &anchor_raw, &target, None),
)
}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => {
match self.sim.stat(&format!("{source_dir}/{STORAGE_FORMAT_FILE}")).await {
Err(SimErr::NotFound(_)) => {}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
}
let state_path = format!("{source_dir}/{DST_MULTIPART_STATE}");
let mut raw = self.sim.read_file(&state_path).await.map_err(map_sim_err)?;
let mut state: SimMultipartState = rmp_serde::from_slice(&raw).map_err(Error::other)?;
if state.anchor != anchor {
return Err(DiskError::ConditionalDeleteConflict);
}
if state.capability_sha256.take().is_some() {
raw = Bytes::from(rmp_serde::to_vec_named(&state).map_err(Error::other)?);
self.write_durable_file(&state_path, raw.clone()).await?;
}
(
MultipartProofKind::TerminalTarget,
Self::multipart_snapshot(&anchor, 2, MultipartSourcePhase::LocalTerminalSeal, &raw, &target, None),
)
}
};
MultipartSourceProof::issue(&authority, kind, challenge, None, snapshot)
}
fn load_filemeta_preserving_inline(raw: &[u8]) -> Result<FileMeta> {
let (mut fm, inline_buf) = FileMeta::load_with_borrowed_inline_data(raw)?;
if !inline_buf.is_empty() {
@@ -1428,7 +1695,7 @@ impl DiskAPI for DstSimDisk {
&self,
src_volume: &str,
src_path: &str,
file_info: FileInfo,
mut file_info: FileInfo,
dst_volume: &str,
dst_path: &str,
) -> Result<RenameDataResp> {
@@ -1442,6 +1709,23 @@ impl DiskAPI for DstSimDisk {
let bkp_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
let src_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE}");
let multipart = src_volume == RUSTFS_META_MULTIPART_BUCKET;
let _multipart_guard = if multipart {
Some(self.multipart_publication_lock.lock().await)
} else {
None
};
let publication = if multipart { publication_identity(&file_info)? } else { None };
let multipart_anchor = if let Some(publication) = publication {
let anchor = self
.prepare_multipart_anchor(&src_dir, src_path, (dst_volume, dst_path), &file_info, publication)
.await?;
strip_transport_condition(&mut file_info.metadata);
Some(anchor)
} else {
None
};
let existing_raw = match self.sim.read_file(&dst_meta).await {
Ok(b) => Some(b),
Err(SimErr::NotFound(_)) => None,
@@ -1484,20 +1768,15 @@ impl DiskAPI for DstSimDisk {
self.sim.create_dir_all(&src_dir).await.map_err(map_sim_err)?;
self.sim.create_dir_all(&dst_dir).await.map_err(map_sim_err)?;
let multipart_pub_identity = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
crate::disk::multipart_source::publication_identity(&file_info)?
} else {
None
};
let has_external_parts =
!file_info.inline_data() && file_info.data.as_ref().is_none_or(|d| d.is_empty()) && file_info.size > 0;
if has_external_parts
&& let Some(data_dir) = file_info.data_dir
&& !data_dir.is_nil()
{
let src_data_dir = multipart_pub_identity
let src_data_dir = multipart_anchor
.as_ref()
.map(|p| p.lineage.original_data_dir)
.map(|anchor| anchor.publication.lineage.original_data_dir)
.unwrap_or(data_dir);
let src_data = format!("{src_dir}/{src_data_dir}");
let dst_data = format!("{dst_dir}/{data_dir}");
@@ -1533,7 +1812,10 @@ impl DiskAPI for DstSimDisk {
self.check_crash_point(CrashPoint::RenameAfterBackupBeforeMetaCommit, dst_volume, dst_path)?;
self.sim.write_file(&src_meta, new_meta_bytes).await.map_err(map_sim_err)?;
self.sim
.write_file(&src_meta, new_meta_bytes.clone())
.await
.map_err(map_sim_err)?;
self.sim.fsync_file(&src_meta).await.map_err(map_sim_err)?;
self.sim.rename(&src_meta, &dst_meta).await.map_err(map_sim_err)?;
@@ -1545,50 +1827,12 @@ impl DiskAPI for DstSimDisk {
let _ = self.sim.remove_dir_all(&src_dir).await;
}
let multipart_source = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
let publication = crate::disk::multipart_source::publication_identity(&file_info)?;
let authority = self
.multipart_proof_authority
.read()
.unwrap_or_else(|p| p.into_inner())
.clone();
if let (Some(publication), Some(authority)) = (publication, authority) {
let disk_id = self
.disk_id
.read()
.unwrap_or_else(|p| p.into_inner())
.ok_or(DiskError::InconsistentDisk)?;
let undo_capability = crate::disk::multipart_source::MultipartUndoCapability::new();
let snapshot = crate::disk::multipart_source::MultipartSourceSnapshot {
disk_id,
physical_slot: self.disk_idx,
lineage: publication.lineage.clone(),
generation: publication.source_generation,
revision: 1,
phase: crate::disk::multipart_source::MultipartSourcePhase::ConsumedUnsealed,
state_sha256: [0; 32],
head_sha256: None,
inventory_sha256: [0; 32],
capability_sha256: Some(undo_capability.digest()),
publication: Some(publication.clone()),
};
let proof = crate::disk::multipart_source::MultipartSourceProof::issue(
&authority,
crate::disk::multipart_source::MultipartProofKind::Published,
Uuid::new_v4(),
None,
snapshot,
)?;
Some(Box::new(crate::disk::multipart_source::MultipartPublicationResult {
publication,
proof,
undo_capability,
}))
} else {
None
}
} else {
None
let multipart_source = match multipart_anchor {
Some(anchor) => Some(Box::new(
self.publish_multipart_witness(&src_dir, &dst_dir, anchor, &new_meta_bytes)
.await?,
)),
None => None,
};
Ok(RenameDataResp {
@@ -1601,6 +1845,22 @@ impl DiskAPI for DstSimDisk {
})
}
async fn recover_multipart_source(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
if request.protocol_version != MULTIPART_SOURCE_PROTOCOL_VERSION {
return Err(DiskError::UnsupportedDisk);
}
match request.operation {
MultipartSourceOperation::ConfirmTerminal {
expected: None,
publication,
challenge,
} => Ok(MultipartSourceResponse::TerminalConfirmed(
self.confirm_multipart_witness(&request.path, &publication, challenge).await?,
)),
_ => Err(DiskError::UnsupportedDisk),
}
}
async fn list_dir(&self, _origvolume: &str, volume: &str, dir_path: &str, count: i32) -> Result<Vec<String>> {
self.ensure_online()?;
self.ensure_volume_exists(volume).await?;
+154 -16
View File
@@ -379,9 +379,9 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
CrashPoint::RenameAfterDataRename,
CrashPoint::RenameAfterBackupBeforeMetaCommit,
CrashPoint::RenameAfterMetaCommit,
CrashPoint::MetaWriteAfterTmpBeforeRename,
];
let mut acknowledged_overwrites = 0;
for (seed_idx, &seed) in [0xC2A5_4001_u64, 0xC2A5_4002_u64, 0xC2A5_4003_u64, 0xC2A5_4004_u64]
.iter()
.enumerate()
@@ -457,8 +457,13 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
}
// Attempt overwrite `v2` (may succeed at quorum if only 1 drive crashed, or fail if >=2 crashed)
let _overwrite_outcome = put_bytes(&fixture, bucket, &key, &v2).await;
fixture.crash_registry.clear();
let overwrite = put_bytes(&fixture, bucket, &key, &v2).await;
for slot in 0..affected_drives {
assert!(
!fixture.crash_registry.take_if_armed_on_drive(point, &key, "dst-node0", slot),
"seed={seed:#x} key={key}: {point:?} did not fire on drive {slot}"
);
}
// Simulate simultaneous cluster-wide power outage & ALICE reboot!
fixture.crash_and_reboot_all();
@@ -475,18 +480,19 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
}
}
// INVARIANT 2: Old-or-New-Never-Mixed! Reading `key` must return 100% bit-exact `v1`
// OR 100% bit-exact `v2` — NEVER partial, zeroed, or mixed bytes!
let observed = get_bytes(&fixture, bucket, &key)
.await
.unwrap_or_else(|e| panic!("committed object {key} unreadable after ALICE crash at {point:?}: {e:?}"));
assert!(
observed == v1 || observed == v2,
"atomicity violation after ALICE crash at {point:?} (seed={seed:#x}): payloadlen={} matches neither v1 ({}) nor v2 ({})",
observed.len(),
v1.len(),
v2.len()
);
let observed = get_bytes(&fixture, bucket, &key).await.unwrap_or_else(|e| {
panic!("committed object {key} unreadable after ALICE crash at {point:?} (seed={seed:#x}): {e:?}")
});
if overwrite.is_ok() {
acknowledged_overwrites += 1;
assert!(observed == v2, "seed={seed:#x} key={key}: acknowledged overwrite lost after {point:?}");
} else {
// A fault can interrupt the reply after local publication completed.
assert!(
observed == v1 || observed == v2,
"seed={seed:#x} key={key}: torn overwrite after {point:?}: {overwrite:?}"
);
}
// INVARIANT 3: Production `heal_object` converges all 4 drives back to unanimous health,
// and previously untouched anchor objects remain 100% bit-exact!
@@ -513,6 +519,38 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
assert_eq!(get_bytes(&fixture, bucket, anchor_large_key).await.unwrap(), anchor_large_v1);
}
}
assert!(acknowledged_overwrites > 0, "no degraded overwrite received an ACK");
}
#[tokio::test]
async fn metadata_write_crash_preserves_published_metadata() {
let fixture = make_dst_sim_set_disks(0xC2A5_4005, 4, 2, None).await.unwrap();
let bucket = "dst-meta-crash";
let key = "metadata.bin";
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.unwrap();
put_bytes(&fixture, bucket, key, b"committed").await.unwrap();
let disk = &fixture.disks[0];
let sim = &fixture.sim_disks[0];
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
let path = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}");
let original = sim.sim().read_file(&path).await.unwrap();
let mut next = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
next.metadata.insert("x-amz-meta-probe".into(), "updated".into());
let point = CrashPoint::MetaWriteAfterTmpBeforeRename;
fixture.crash_registry.arm_on_drive(point, key, "dst-node0", 0);
assert!(disk.write_metadata("", bucket, key, next.clone()).await.is_err());
assert!(!fixture.crash_registry.take_if_armed_on_drive(point, key, "dst-node0", 0));
fixture.crash_and_reboot_all();
assert_eq!(sim.sim().read_file(&path).await.unwrap(), original);
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), b"committed");
disk.write_metadata("", bucket, key, next).await.unwrap();
fixture.crash_and_reboot_all();
let updated = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
assert_eq!(updated.metadata.get("x-amz-meta-probe").map(String::as_str), Some("updated"));
}
// ============================================================================
@@ -902,6 +940,10 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
// ------------------------------------------------------------------------
let mut before_cleanup_hits = 0usize;
for &seed in &[0x4D50_0101_u64, 0x4D50_0102_u64, 0x4D50_0103_u64, 0x4D50_0104_u64] {
let opts = ObjectOptions {
versioned: seed % 2 == 0,
..dst_object_options()
};
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
.await
.expect("dst sim SetDisks for multipart pre-cleanup cutpoint");
@@ -959,7 +1001,7 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
let crashed = fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts.clone(), &opts)
.await;
assert!(
crashed.is_err(),
@@ -985,6 +1027,21 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
"seed={seed:#x}: committed multipart payload must be bit-exact after pre-cleanup crash"
);
// A client that lost the completion response must recover the identity of
// the existing commit, including the version ID on a versioned bucket.
let published = fixture.set_disks.get_object_info(bucket, &key, &opts).await.unwrap();
assert_eq!(published.version_id.is_some(), opts.versioned);
let retried = fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
.await
.expect("complete retry after post-commit power loss");
assert!(retried.multipart_completion_replayed, "seed={seed:#x}: upload committed again");
assert_eq!(retried.version_id, published.version_id);
assert_eq!(retried.etag, published.etag);
assert_eq!(get_bytes(&fixture, bucket, &key).await.unwrap(), expected);
// Post-crash heal converges cleanly and every drive verifies both parts!
let (_heal_item, heal_err) = fixture
.set_disks
@@ -1016,6 +1073,13 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
vec![CHECK_PART_SUCCESS, CHECK_PART_SUCCESS],
"drive {slot} must pass HighwayHash256S verification for both parts"
);
let raw = disk.read_all(bucket, &format!("{key}/{STORAGE_FORMAT_FILE}")).await.unwrap();
let versions = FileMeta::load(&raw)
.unwrap()
.get_all_file_info_versions(bucket, &key, true)
.unwrap();
assert_eq!(versions.versions.len(), 1, "drive {slot}: duplicate multipart commit");
assert_eq!(versions.versions[0].version_id, published.version_id);
}
}
assert_eq!(
@@ -1023,3 +1087,77 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
"fault.multipart_crashed_before_cleanup must hit across all 4 seeds"
);
}
#[tokio::test]
async fn multipart_replay_rejects_missing_or_other_disk_anchor() {
let fixture = make_dst_sim_set_disks(0x671, 4, 2, None).await.unwrap();
let bucket = "dst-mpu-anchor";
let key = "published";
let opts = dst_object_options();
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.unwrap();
let upload = fixture.set_disks.new_multipart_upload(bucket, key, &opts).await.unwrap();
let expected = deterministic_payload(0x671, key, 128 * 1024);
let mut payload = PutObjReader::from_vec(expected.clone());
let part = fixture
.set_disks
.put_object_part(bucket, key, &upload.upload_id, 1, &mut payload, &opts)
.await
.unwrap();
let parts = vec![CompletePart {
part_num: 1,
etag: part.etag,
..Default::default()
}];
let complete = || {
fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, key, &upload.upload_id, parts.clone(), &opts)
};
let published = complete().await.unwrap();
fixture.crash_and_reboot_all();
let replayed = complete().await.expect("all four witnesses are available");
assert!(replayed.multipart_completion_replayed);
assert_eq!(replayed.etag, published.etag);
let info = fixture.disks[0]
.read_version("", bucket, key, "", &ReadOptions::default())
.await
.unwrap();
let anchor =
rustfs_ecstore::api::dst::DstSimDisk::multipart_retirement_anchor_path(bucket, key, info.data_dir.unwrap()).unwrap();
let (parent, _) = anchor.rsplit_once('/').unwrap();
let disks = &fixture.sim_disks;
let own_0 = disks[0].sim().read_file(&anchor).await.unwrap();
let own_1 = disks[1].sim().read_file(&anchor).await.unwrap();
let foreign = disks[2].sim().read_file(&anchor).await.unwrap();
for disk in &disks[..2] {
disk.sim().remove_file(&anchor).await.unwrap();
disk.sim().fsync_dir(parent).await.unwrap();
}
fixture.crash_and_reboot_all();
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), expected);
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
disks[0].sim().write_file(&anchor, foreign).await.unwrap();
disks[0].sim().fsync_file(&anchor).await.unwrap();
disks[0].sim().fsync_dir(parent).await.unwrap();
fixture.crash_and_reboot_all();
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
for (disk, own) in disks[..2].iter().zip([own_0, own_1]) {
disk.sim().write_file(&anchor, own).await.unwrap();
disk.sim().fsync_file(&anchor).await.unwrap();
disk.sim().fsync_dir(parent).await.unwrap();
}
fixture.crash_and_reboot_all();
let replayed = complete()
.await
.expect("each restored witness belongs to its own physical disk");
assert!(replayed.multipart_completion_replayed);
assert_eq!(replayed.etag, published.etag);
}
+68 -1
View File
@@ -1428,6 +1428,9 @@ impl VaultTransitKmsClient {
}
})
.await?;
// Transit LIST also returns directory entries, including the BYOK
// wrapping-key directory. Only actual key names belong in the cursor.
all_keys.retain(|key| !key.ends_with('/'));
// Vault's own LIST ordering is not part of its contract, so the sort is
// what makes the marker a stable cursor across calls.
all_keys.sort_unstable();
@@ -2068,6 +2071,70 @@ mod tests {
serde_json::to_value(&response).expect("serialize transit key read response")
}
#[tokio::test]
async fn list_skips_byok_directories_before_pagination() {
let listed = serde_json::json!({ "keys": ["zulu", "import/", "import", "alpha", "versions/"] });
let metadata = metadata_read_data(&TransitKeyMetadata::from_create_request(&CreateKeyRequest::default()));
let (vault, client) = scripted_client(vec![
ScriptedResponse::ok(listed.clone()),
ScriptedResponse::ok(transit_key_read_data("alpha")),
ScriptedResponse::ok(metadata.clone()),
ScriptedResponse::ok(transit_key_read_data("import")),
ScriptedResponse::ok(metadata.clone()),
ScriptedResponse::ok(listed),
ScriptedResponse::ok(transit_key_read_data("zulu")),
ScriptedResponse::ok(metadata),
])
.await;
let first = client
.list_keys(
&ListKeysRequest {
limit: Some(2),
..Default::default()
},
None,
)
.await
.expect("list the first page despite directory entries");
assert_eq!(first.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["alpha", "import"]);
assert_eq!(first.next_marker.as_deref(), Some("import"));
assert!(first.truncated);
assert!(first.unreadable_key_ids.is_empty());
let last = client
.list_keys(
&ListKeysRequest {
limit: Some(2),
marker: first.next_marker,
..Default::default()
},
None,
)
.await
.expect("a sweep can continue past the wrapping-key directory");
assert_eq!(last.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["zulu"]);
assert!(last.next_marker.is_none());
assert!(!last.truncated);
assert!(last.unreadable_key_ids.is_empty());
assert_eq!(vault.requests().len(), 8, "only actual keys should be described");
}
#[tokio::test]
async fn list_with_only_the_byok_directory_is_empty() {
let (vault, client) = scripted_client(vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/"] }))]).await;
let listed = client
.list_keys(&ListKeysRequest::default(), None)
.await
.expect("the wrapping-key directory is not a KMS key");
assert!(listed.keys.is_empty());
assert!(listed.next_marker.is_none());
assert!(!listed.truncated);
assert!(listed.unreadable_key_ids.is_empty());
assert_eq!(vault.requests().len(), 1, "a directory must not be described");
}
/// A listing must not silently shrink when the backend is the problem.
///
/// Before the per-key classification this path used `?`, so any describe
@@ -2076,7 +2143,7 @@ mod tests {
/// about it. A transit mount that stops answering must still fail loudly.
#[tokio::test]
async fn list_fails_when_a_transit_key_read_is_unavailable() {
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["key-a"] }))];
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/", "key-a"] }))];
for _ in 0..3 {
responses.push(ScriptedResponse::error(503, "temporarily unavailable"));
}
+2
View File
@@ -22,6 +22,8 @@ Specialized boundary, hardware and alternate-feature lanes run only on the sched
Workspace Clippy runs on every event with a selected workspace Rust job, pull requests included, in its own `Workspace Clippy` job. It runs beside `Workspace Lint and Build` instead of in front of it, because check-mode metadata and the linked test binaries share no compiler output; `scripts/ci_gate.py --check-workflow` rejects a workflow in which the archive producer or any archive consumer waits for the lint, or in which the lint leaves the aggregate. `Workspace Lint and Build` keeps its name as the archive producer: it creates the exact test archive and runs doctests; `Workspace tests` consumes the archive without rebuilding it. `cache-warm.yml` warms Clippy's check artifacts under `ci-dev` with the same invocation to reuse compatible dependency artifacts. `make pre-commit` does not run Clippy. Select local Clippy targets, features, and documentation exemptions from the root `AGENTS.md` verification tier; the workspace command below reproduces the CI lane and is not a universal pre-push requirement.
Full-scope runs also execute the production ECStore suite in `dst_production_ecstore` against simulated disks with `--features dst`. It checks the durability of acknowledged writes, metadata publication, and multipart retries with valid, missing, or misplaced per-drive evidence. The workspace producer retains the nextest listing and JUnit report and verifies that every required case passed.
Serial ILM tests run at the end of `workspace-tests` for the `full` scope, consuming the same verified archive as ordinary workspace tests. The existing ignored-test filter and `-j1` remain; `--profile default` keeps the no-retry execution and preserves the separate core CI JUnit report. Any ILM failure fails the consumer and required aggregate. Logs remain in the workspace test evidence artifact. There is no separate ILM compilation or cache restore.
`required-checks` runs even after failed or skipped dependencies. `scripts/ci_gate.py verify` rejects missing jobs, unexpected jobs, failure, cancellation, and unexpected skips; optional lanes are required only on their declared events. `Workspace Clippy` is the workspace lint, `Workspace Lint and Build` and `Workspace tests` are the ordinary Rust producer and consumer, while `Test and Lint` uniquely names the aggregate. New validation jobs must update both its direct dependencies and the script contract. A report-only lane is registered in `REPORT_ONLY_JOBS` instead: it stays out of the aggregate, must keep its distinguishing environment, and must keep the steps it reruns identical to the required job it mirrors. Test this wiring and its failure cases with `python3 scripts/ci_gate.py --self-test`.
+19 -3
View File
@@ -24,6 +24,16 @@ CORE_TESTS = {
"head_object_consistency_test::head_object_consistency_after_write_and_multipart_and_presigned_head",
"storage_class_capability_test::tests::historical_label_only_metadata_is_standard_without_hiding_a_real_transition_tier",
}
DST_SUITE = "rustfs-ecstore::dst_production_ecstore"
DST_TESTS = {
"dst_prod_test1_quorum_put_get_delete_offline_and_enospc",
"dst_prod_test2_physical_bitrot_highwayhash_detect_reconstruct_and_heal",
"dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixed",
"metadata_write_crash_preserves_published_metadata",
"dst_prod_test4_deterministic_multiseed_concurrent_chaos_and_replay_equivalence",
"dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_before_cleanup",
"multipart_replay_rejects_missing_or_other_disk_anchor",
}
def output(*args):
@@ -151,12 +161,16 @@ def selected_tests(listing):
return selected
def verify_execution(listing, junit, core=False):
def verify_execution(listing, junit, core=False, dst=False):
inventory = json.loads(Path(listing).read_text())
expected = selected_tests(inventory)
known = {(binary, name) for binary, suite in inventory["rust-suites"].items() for name in suite["testcases"]}
if core and (len(expected) != len(CORE_TESTS) or {name for _, name in expected} != CORE_TESTS):
raise ValueError("core contract must select exactly the write/read, denial and restart proofs")
if dst:
missing = {(DST_SUITE, name) for name in DST_TESTS} - expected
if missing:
raise ValueError(f"missing production DST tests: {sorted(missing)}")
report = ET.parse(junit).getroot()
if report.tag != "testsuites" or report.get("failures") != "0" or report.get("errors") != "0":
raise ValueError("test report must be a successful nextest run")
@@ -201,7 +215,9 @@ def main():
child = sub.add_parser("evidence")
child.add_argument("listing", type=Path)
child.add_argument("junit", type=Path)
child.add_argument("--core", action="store_true")
required = child.add_mutually_exclusive_group()
required.add_argument("--core", action="store_true")
required.add_argument("--dst", action="store_true")
args = parser.parse_args()
try:
if args.command == "build":
@@ -221,7 +237,7 @@ def main():
"doc": [*selection, "--doc"], "warm": ["--no-run", *selection]}[args.operation]
subprocess.run(command, cwd=ROOT, check=True)
else:
print(f"Verified {verify_execution(args.listing, args.junit, args.core)} test executions")
print(f"Verified {verify_execution(args.listing, args.junit, args.core, args.dst)} test executions")
except (OSError, ValueError, KeyError, TypeError, ET.ParseError, subprocess.CalledProcessError) as error:
print(f"verification artifact: {error}", file=sys.stderr)
return 1
+13 -2
View File
@@ -244,10 +244,10 @@ class ExecutionEvidenceTests(unittest.TestCase):
self.listing = listing([("crate-a", "one", False), ("crate-b", "two", False), ("crate-b", "ignored", True)])
self.report = junit([("crate-a", "one", None), ("crate-b", "two", None)])
def verify(self, listing_value=None, report=None, *, core=False):
def verify(self, listing_value=None, report=None, *, core=False, dst=False):
self.listing_file.write_text(json.dumps(self.listing if listing_value is None else listing_value))
ET.ElementTree(self.report if report is None else report).write(self.junit_file)
return artifact.verify_execution(self.listing_file, self.junit_file, core=core)
return artifact.verify_execution(self.listing_file, self.junit_file, core=core, dst=dst)
def test_exact_selected_set_and_known_ignored_cases(self):
self.assertEqual(self.verify(), 2)
@@ -321,6 +321,17 @@ class ExecutionEvidenceTests(unittest.TestCase):
with self.subTest(attribute=attribute), self.assertRaises(ValueError):
self.verify(report=report)
def test_dst_rejects_a_green_report_with_a_missing_required_test(self):
cases = [(artifact.DST_SUITE, name) for name in sorted(artifact.DST_TESTS)]
for selected in [cases, cases[:-1]]:
inventory = listing([(suite, name, False) for suite, name in selected])
report = junit([(suite, name, None) for suite, name in selected])
if selected == cases:
self.assertEqual(self.verify(inventory, report, dst=True), len(cases))
else:
with self.assertRaisesRegex(ValueError, "missing production DST tests"):
self.verify(inventory, report, dst=True)
def test_core_requires_exactly_three_selected_proofs(self):
names = sorted(artifact.CORE_TESTS)
core_listing = listing([("e2e", name, False) for name in names])