test(scanner): verify persisted progress across remote writes

This commit is contained in:
overtrue
2026-12-02 12:16:55 +08:00
parent 0b8201a84c
commit e2c609d58e
2 changed files with 282 additions and 0 deletions
+1
View File
@@ -46,6 +46,7 @@ mod scanner_heal_topology_test;
mod scanner_heal_topology_tier_test;
mod scanner_peer_bucket_fixture;
mod scanner_peer_bucket_test;
mod scanner_remote_progress_test;
mod site_replication_test;
mod table_catalog_test;
mod upgrade_test;
@@ -0,0 +1,281 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
//! Follow one persisted scanner source across cycles while a different node
//! acknowledges unrelated writes. The fixture owns all four server processes.
use super::harness::{DistCluster, DistLayout, TestResult};
use crate::common::admin_request;
use crate::storage_api::scanner_peer_bucket::{RUSTFS_META_BUCKET, calc_shard_size};
use aws_sdk_s3::primitives::ByteStream;
use futures::{StreamExt, TryStreamExt, stream};
use rustfs_data_usage::{BUCKET_SCAN_PROGRESS_MAX_BYTES, BucketScanProgressSource, BucketScanStage, bucket_scan_progress_path};
use rustfs_filemeta::FileMeta;
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::time::{Instant, sleep, timeout};
const LONG: &str = "long-scanner-progress";
const OTHER: &str = "unrelated-writer";
const OBJECTS: u64 = 96;
const WIDTH: u64 = 32;
// The small source object occupies one erasure stripe in our single set.
// Ignore an in-flight publication until all sixteen disks name the same ETag.
// A malformed frame or a bad checksum is a fixture failure.
fn disk_sample(cluster: &DistCluster) -> TestResult<Option<BucketScanProgressSource>> {
let key = bucket_scan_progress_path(LONG);
let mut revision = None;
let mut shards = BTreeMap::new();
for drive in cluster.cluster.nodes.iter().flat_map(|node| &node.data_dirs) {
let object = Path::new(drive).join(RUSTFS_META_BUCKET).join(&key);
let raw = match std::fs::read(object.join("xl.meta")) {
Ok(raw) => raw,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(err.into()),
};
let info = FileMeta::load(&raw)?.into_fileinfo(RUSTFS_META_BUCKET, &key, "", true, false, true)?;
info.validate_for_metadata_read()?;
let size = usize::try_from(info.size)?;
let ec = &info.erasure;
if !(1..=BUCKET_SCAN_PROGRESS_MAX_BYTES).contains(&size)
|| size > ec.block_size
|| info.parts.len() != 1
|| ec.data_blocks == 0
|| ec.data_blocks.checked_add(ec.parity_blocks) != Some(16)
|| !(1..=16).contains(&ec.index)
{
return Err("unexpected scanner progress stripe".into());
}
let identity = (
info.get_etag()
.filter(|etag| !etag.is_empty())
.ok_or("missing scanner ETag")?,
size,
ec.data_blocks,
);
if revision.as_ref().is_some_and(|old| *old != identity) {
return Ok(None);
}
revision = Some(identity);
let part = &info.parts[0];
let framed = if info.inline_data() {
info.data.as_ref().ok_or("missing inline scanner shard")?.to_vec()
} else {
let path = object
.join(info.data_dir.ok_or("missing scanner data directory")?.to_string())
.join(format!("part.{}", part.number));
match std::fs::read(path) {
Ok(bytes) => bytes,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(err.into()),
}
};
let checksum = ec.get_checksum_info(part.number).algorithm;
let header = checksum.size();
if header == 0
|| framed.len() != header + calc_shard_size(size, ec.data_blocks)
|| checksum.hash_encode(&framed[header..]).as_ref() != &framed[..header]
{
return Err("scanner progress shard checksum or length mismatch".into());
}
if shards.insert(ec.index, framed[header..].to_vec()).is_some() {
return Err("two disks reported the same scanner shard index".into());
}
}
if shards.len() != 16 {
return Err("expected sixteen distinct scanner progress shards".into());
}
let (_, size, data) = revision.ok_or("missing scanner progress drives")?;
let mut bytes = Vec::with_capacity(size);
for index in 1..=data {
bytes.extend_from_slice(shards.get(&index).ok_or("missing scanner data shard")?);
}
bytes.truncate(size);
let sample: BucketScanProgressSource = serde_json::from_slice(&bytes)?;
if sample.version != rustfs_data_usage::BUCKET_SCAN_PROGRESS_VERSION
|| sample.updated_at == 0
|| sample.movement_generation.is_none()
|| sample.bucket != LONG
|| sample.bucket_incarnation.is_empty()
|| sample.pool_index != 0
|| sample.set_index != 0
{
return Err("unexpected persisted scanner source identity".into());
}
Ok(Some(sample))
}
async fn coordinator(cluster: &DistCluster) -> TestResult<Option<usize>> {
let mut nodes = Vec::new();
for (index, node) in cluster.cluster.nodes.iter().enumerate() {
let (status, body) = admin_request(
&node.url,
http::Method::GET,
"/rustfs/admin/v3/scanner/status",
None,
&cluster.cluster.access_key,
&cluster.cluster.secret_key,
)
.await?;
if !status.is_success() {
return Err(format!("scanner status returned {status}").into());
}
let observed: Value = serde_json::from_str(&body)?;
if observed["metrics"]["leader_lock_held_by_this_process"].as_bool() == Some(true) {
nodes.push(index);
}
}
Ok((nodes.len() == 1).then(|| nodes[0]))
}
fn same_source(a: &BucketScanProgressSource, b: &BucketScanProgressSource) -> bool {
a.bucket_incarnation == b.bucket_incarnation
&& a.set_layout == b.set_layout
&& a.pool_index == b.pool_index
&& a.set_index == b.set_index
&& a.scanner_epoch == b.scanner_epoch
&& a.publication_epoch == b.publication_epoch
&& a.movement_generation == b.movement_generation
}
fn scanning_count(sample: &BucketScanProgressSource) -> Option<u64> {
let count = sample.objects?;
(sample.stage == BucketScanStage::Scanning && (1..OBJECTS).contains(&count) && sample.size == Some(WIDTH * count))
.then_some(count)
}
#[tokio::test(flavor = "multi_thread")]
async fn long_bucket_persists_three_cycles_during_unrelated_remote_puts() -> TestResult {
let mut cluster = DistCluster::new_stopped_with_env(
DistLayout::FourByFour,
&[
("RUSTFS_UNSAFE_BYPASS_DISK_CHECK", "true"),
("RUSTFS_ERASURE_SET_DRIVE_COUNT", "16"),
("RUSTFS_SCANNER_ENABLED", "false"),
("RUST_LOG", "rustfs=info,rustfs_notify=debug,rustfs::server::http=warn"),
("RUSTFS_SCANNER_CYCLE", "2"),
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
("RUSTFS_SCANNER_CYCLE_MAX_OBJECTS", "32"),
("RUSTFS_SCANNER_BUCKET_QUANTUM_OBJECTS", "8"),
],
)
.await?;
let root = PathBuf::from(&cluster.cluster.temp_dir);
cluster.cluster.start().await?;
let seed = cluster.client(0)?;
for bucket in [LONG, OTHER] {
seed.create_bucket().bucket(bucket).send().await?;
}
stream::iter(0..OBJECTS)
.map(Ok)
.try_for_each_concurrent(6, |index| {
let client = seed.clone();
async move {
client
.put_object()
.bucket(LONG)
.key(format!("prefix-{index:04}/entry"))
.body(ByteStream::from(vec![u8::try_from(index)?; usize::try_from(WIDTH)?]))
.send()
.await?;
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
}
})
.await?;
cluster.cluster.stop();
cluster.cluster.set_env("RUSTFS_SCANNER_ENABLED", "true");
cluster.cluster.start().await?;
let leader = timeout(Duration::from_secs(120), async {
loop {
if let Some(leader) = coordinator(&cluster).await? {
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(leader);
}
sleep(Duration::from_millis(500)).await;
}
})
.await??;
let nodes = &cluster.cluster.nodes;
let pids: BTreeSet<_> = nodes
.iter()
.filter_map(|node| node.process.as_ref().map(std::process::Child::id))
.collect();
if nodes.len() != 4 || pids.len() != 4 || nodes.iter().any(|node| node.data_dirs.len() != 4) {
return Err("the native scanner fixture requires four live processes and four drives per node".into());
}
let ingress = (leader + 1) % cluster.cluster.nodes.len();
let writer = cluster.client(ingress)?;
let reader = cluster.client(leader)?;
let mut history: Vec<(BucketScanProgressSource, u64)> = Vec::new();
let end = Instant::now() + Duration::from_secs(420);
let mut writes = 0_u64;
while history.len() < 3 {
if Instant::now() >= end {
return Err(
format!("fewer than three consecutive persisted cycles after {writes} unrelated PUTs: {history:?}").into(),
);
}
let before = disk_sample(&cluster)?;
writes += 1;
writer
.put_object()
.bucket(OTHER)
.key("changing")
.body(ByteStream::from(writes.to_be_bytes().to_vec()))
.send()
.await?;
let after = disk_sample(&cluster)?;
if let (Some(a), Some(b)) = (before, after)
&& same_source(&a, &b)
&& a.scanner_cycle == b.scanner_cycle
&& let (Some(first), Some(last)) = (scanning_count(&a), scanning_count(&b))
&& first <= last
&& history.last().is_none_or(|(prev, _)| prev.scanner_cycle != b.scanner_cycle)
{
if history.last().is_some_and(|(prev, _)| {
!same_source(prev, &b)
|| prev.scanner_cycle.checked_add(1) != Some(b.scanner_cycle)
|| prev.objects >= Some(first)
}) {
history.clear();
}
history.push((b, writes));
}
sleep(Duration::from_millis(400)).await;
}
assert_eq!(coordinator(&cluster).await?, Some(leader));
let body = reader
.get_object()
.bucket(OTHER)
.key("changing")
.send()
.await?
.body
.collect()
.await?
.into_bytes();
assert_eq!(&body[..], &writes.to_be_bytes());
assert_eq!(
reader.list_objects_v2().bucket(LONG).send().await?.contents().len(),
usize::try_from(OBJECTS)?
);
let endpoints: Vec<_> = cluster.cluster.nodes.iter().map(|node| node.address.clone()).collect();
let points: Vec<_> = history
.iter()
.map(|(s, ack)| json!({"cycle":s.scanner_cycle,"objects":s.objects,"bytes":s.size,"ack":ack}))
.collect();
let epoch = history[0].0.scanner_epoch;
drop(cluster);
assert!(!root.try_exists()?);
for endpoint in endpoints {
assert!(tokio::net::TcpStream::connect(endpoint).await.is_err());
}
println!(
"usage_assertion: {}",
json!({"case_id":"USAGE-02","assertion_id":"USAGE-02-A01","status":"PASS","evidence":{"coordinator_node":leader,"writer_node":ingress,"epoch":epoch,"remote_puts":writes,"persisted_progress":points,"verified_drives":16}})
);
println!("usage_cleanup: {}", json!({"case_id":"USAGE-02","status":"PASS","fixture_removed":true}));
Ok(())
}