use crate::ant_protocol::XorName;
use crate::error::{Error, Result};
use crate::logging::{debug, info, warn};
use crate::replication::config::{storage_admission_width, ReplicationConfig};
use crate::replication::pruning::{
prove_peers_hold_records, prune_proofs_needed, target_peers_reported_present,
};
use crate::storage::chunk_store::{ChunkStore, VerifyReport};
use saorsa_core::identity::PeerId;
use saorsa_core::P2PNode;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio_util::sync::CancellationToken;
pub const MIGRATION_STATE_FILE: &str = "migration-state.json";
const STATE_SCHEMA: u32 = 1;
pub const MIN_RETIRE_DELAY_HOURS: u64 = 4;
const HANDLE_RECOVERY_INTERVAL: Duration = Duration::from_secs(300);
const MAX_VOLUME_LOCK_HOLD: Duration = Duration::from_secs(6 * 3600);
const VOLUME_LOCK_COOLDOWN: Duration = Duration::from_secs(120);
pub const REQUIRED_REBUILDS_BEFORE_RETIRE: u32 = 2;
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationConfig {
#[serde(default = "default_true")]
pub enabled: bool,
#[serde(default = "default_true")]
pub dual_write_legacy: bool,
#[serde(default = "default_true")]
pub allow_shed: bool,
#[serde(skip, default = "release_retire_legacy")]
pub retire_legacy: bool,
#[serde(default = "default_shed_hold_hours")]
pub shed_hold_hours: u64,
#[serde(default = "default_retire_delay_hours")]
pub retire_delay_hours: u64,
#[serde(default = "default_copier_slack_mb")]
pub copier_slack_mb: u64,
#[serde(default = "default_copier_throttle_mib_per_sec")]
pub copier_throttle_mib_per_sec: u64,
#[serde(default = "default_wave_hours")]
pub wave_hours: u64,
#[serde(default = "default_tick_secs")]
pub tick_secs: u64,
#[serde(default = "default_batch_chunks")]
pub batch_chunks: usize,
#[serde(skip)]
pub lock_dir: Option<PathBuf>,
}
const fn default_true() -> bool {
true
}
pub const RELEASE_RETIRE_LEGACY: bool = true;
pub const LOCK_DIR_ENV: &str = "ANT_MIGRATION_LOCK_DIR";
pub const RETIRE_LEGACY_ENV: &str = "ANT_MIGRATION_RETIRE_LEGACY";
fn env_override(name: &str, build_default: bool) -> bool {
let Ok(raw) = std::env::var(name) else {
return build_default;
};
match raw.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => true,
"0" | "false" | "no" | "off" => false,
other => {
warn!("{name}={other} is not a boolean; using the build default {build_default}");
build_default
}
}
}
fn release_retire_legacy() -> bool {
env_override(RETIRE_LEGACY_ENV, RELEASE_RETIRE_LEGACY)
}
const fn default_shed_hold_hours() -> u64 {
72
}
const fn default_retire_delay_hours() -> u64 {
MIN_RETIRE_DELAY_HOURS
}
const fn default_wave_hours() -> u64 {
24
}
const fn default_copier_slack_mb() -> u64 {
2048
}
const fn default_copier_throttle_mib_per_sec() -> u64 {
32
}
const fn default_tick_secs() -> u64 {
30
}
const fn default_batch_chunks() -> usize {
64
}
impl Default for MigrationConfig {
fn default() -> Self {
Self {
enabled: true,
dual_write_legacy: true,
allow_shed: true,
retire_legacy: release_retire_legacy(),
shed_hold_hours: default_shed_hold_hours(),
retire_delay_hours: default_retire_delay_hours(),
wave_hours: default_wave_hours(),
copier_slack_mb: default_copier_slack_mb(),
copier_throttle_mib_per_sec: default_copier_throttle_mib_per_sec(),
tick_secs: default_tick_secs(),
batch_chunks: default_batch_chunks(),
lock_dir: None,
}
}
}
impl MigrationConfig {
#[must_use]
pub fn effective_retire_delay_hours(&self) -> u64 {
self.retire_delay_hours.max(MIN_RETIRE_DELAY_HOURS)
}
#[must_use]
pub fn copier_slack_bytes(&self) -> u64 {
self.copier_slack_mb.saturating_mul(1024 * 1024)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MigrationPhase {
Bridging,
Committed,
FilesOnly,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MigrationState {
pub schema: u32,
pub phase: MigrationPhase,
pub first_start_unix: u64,
pub committed_at_unix: Option<u64>,
pub rebuilds_since_commit: u32,
pub shed_key_count: u64,
#[serde(default)]
pub kept_key_count: u64,
}
impl MigrationState {
#[must_use]
pub fn new(phase: MigrationPhase) -> Self {
Self {
schema: STATE_SCHEMA,
phase,
first_start_unix: now_unix(),
committed_at_unix: None,
rebuilds_since_commit: 0,
shed_key_count: 0,
kept_key_count: 0,
}
}
pub fn load_or_create(root_dir: &Path, phase: MigrationPhase) -> Self {
let state = Self::load_or_new(root_dir, phase);
let raw = std::fs::read(state_path(root_dir)).ok();
let on_disk = raw
.as_deref()
.and_then(|bytes| serde_json::from_slice::<Self>(bytes).ok());
if on_disk.as_ref() == Some(&state) {
return state;
}
let newer_schema = raw
.as_deref()
.and_then(|bytes| serde_json::from_slice::<serde_json::Value>(bytes).ok())
.and_then(|value| value.get("schema").and_then(serde_json::Value::as_u64))
.filter(|schema| *schema > u64::from(STATE_SCHEMA));
if let Some(schema) = newer_schema {
let Some(kept) = free_kept_marker_path(root_dir, schema) else {
warn!(
"A newer migration marker (schema {schema}) is here and every name to \
keep it under is taken. Leaving it, which means the shed hold restarts \
on every boot until it is dealt with"
);
return state;
};
if let Err(e) = std::fs::rename(state_path(root_dir), &kept) {
warn!(
"Could not move the newer migration marker aside ({e}); leaving it, \
which means the shed hold restarts on every boot until it is dealt with"
);
return state;
}
info!(
"Kept the newer migration marker as {} and started one this build can use",
kept.display()
);
}
if let Err(e) = state.save(root_dir) {
warn!("Could not write the migration marker: {e}");
}
state
}
pub fn load_or_new(root_dir: &Path, phase: MigrationPhase) -> Self {
let path = state_path(root_dir);
let Ok(bytes) = std::fs::read(&path) else {
return Self::new(phase);
};
match serde_json::from_slice::<Self>(&bytes) {
Ok(state) if state.schema <= STATE_SCHEMA => state.with_sane_clocks(),
Ok(state) => {
warn!(
"Migration marker {} was written by a newer build (schema {}); \
starting a fresh one",
path.display(),
state.schema
);
Self::new(phase)
}
Err(e) => {
warn!(
"Migration marker {} is unreadable ({e}); starting a fresh one. \
The shed hold and retirement clock restart from now.",
path.display()
);
Self::new(phase)
}
}
}
pub fn save(&self, root_dir: &Path) -> Result<()> {
let path = state_path(root_dir);
let bytes = serde_json::to_vec_pretty(self)
.map_err(|e| Error::Storage(format!("Failed to encode migration marker: {e}")))?;
crate::storage::file_store::write_file_durably(&path, &bytes)?;
debug!("Migration marker updated: phase {:?}", self.phase);
Ok(())
}
#[must_use]
fn with_sane_clocks(mut self) -> Self {
let now = now_unix();
if self.first_start_unix == 0 || self.first_start_unix > now {
warn!("Migration marker has an implausible first-start time; restarting the hold");
self.first_start_unix = now;
}
self.committed_at_unix = self.committed_at_unix.map(|at| {
if at == 0 || at > now {
warn!("Migration marker has an implausible commit time; restarting the clock");
now
} else {
at
}
});
self
}
#[must_use]
pub fn shed_hold_elapsed(&self, config: &MigrationConfig) -> bool {
let hold = config.shed_hold_hours.saturating_mul(3600);
now_unix().saturating_sub(self.first_start_unix) >= hold
}
#[must_use]
pub fn retire_delay_elapsed(&self, config: &MigrationConfig) -> bool {
let Some(at) = self.committed_at_unix else {
return false;
};
let delay = config.effective_retire_delay_hours().saturating_mul(3600);
now_unix().saturating_sub(at) >= delay
}
}
fn free_kept_marker_path(root_dir: &Path, schema: u64) -> Option<PathBuf> {
for attempt in 0..16u32 {
let mut candidate = state_path(root_dir).into_os_string();
candidate.push(format!(".schema-{schema}"));
if attempt > 0 {
candidate.push(format!(".{attempt}"));
}
let candidate = PathBuf::from(candidate);
if std::fs::symlink_metadata(&candidate).is_err() {
return Some(candidate);
}
}
None
}
#[must_use]
pub fn state_path(root_dir: &Path) -> PathBuf {
root_dir.join(MIGRATION_STATE_FILE)
}
#[must_use]
pub fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
#[derive(Debug)]
pub struct VolumeLock {
file: std::fs::File,
#[cfg_attr(not(feature = "logging"), allow(dead_code))]
path: PathBuf,
}
pub enum LockAttempt {
Acquired(VolumeLock),
Busy,
Unavailable,
}
impl VolumeLock {
#[must_use]
pub fn try_acquire(root_dir: &Path, scope: Option<&Path>) -> LockAttempt {
use fs2::FileExt;
let path = scope.map_or_else(
|| lock_path_for(root_dir),
|dir| dir.join("ant-migration.lock"),
);
let file = match std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(&path)
{
Ok(f) => f,
Err(e) => {
warn!(
"Could not create the migration lock at {}: {e}. This node will \
migrate without serialising against others on the same volume, so \
watch its free space.",
path.display()
);
return LockAttempt::Unavailable;
}
};
match file.try_lock_exclusive() {
Ok(()) => {
info!("Took the volume migration lock at {}", path.display());
LockAttempt::Acquired(Self { file, path })
}
Err(e) if is_lock_contention(&e) => LockAttempt::Busy,
Err(e) => {
warn!(
"Could not lock {}: {e}. This node will migrate without serialising \
against others on the same volume, so watch its free space.",
path.display()
);
LockAttempt::Unavailable
}
}
}
}
fn is_lock_contention(e: &std::io::Error) -> bool {
e.kind() == std::io::ErrorKind::WouldBlock
|| (e.raw_os_error().is_some()
&& e.raw_os_error() == fs2::lock_contended_error().raw_os_error())
}
fn lock_path_for(root_dir: &Path) -> PathBuf {
lock_path_with(root_dir, std::env::var(LOCK_DIR_ENV).ok().as_deref())
}
fn lock_path_with(root_dir: &Path, configured: Option<&str>) -> PathBuf {
if let Some(dir) = configured {
let dir = dir.trim();
if !dir.is_empty() {
return Path::new(dir).join("ant-migration.lock");
}
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let Ok(meta) = std::fs::metadata(root_dir) {
return std::env::temp_dir().join(format!("ant-migration-{}.lock", meta.dev()));
}
}
#[cfg(not(unix))]
let resolved = std::fs::canonicalize(root_dir).unwrap_or_else(|_| root_dir.to_path_buf());
#[cfg(not(unix))]
let root_dir = resolved.as_path();
#[cfg(not(unix))]
{
use std::path::Component;
if let Some(Component::Prefix(prefix)) = root_dir.components().next() {
let key: String = prefix
.as_os_str()
.to_string_lossy()
.chars()
.filter(char::is_ascii_alphanumeric)
.collect();
if !key.is_empty() {
return std::env::temp_dir().join(format!("ant-migration-{key}.lock"));
}
}
}
root_dir
.parent()
.unwrap_or(root_dir)
.join("ant-migration.lock")
}
impl Drop for VolumeLock {
fn drop(&mut self) {
use fs2::FileExt;
if let Err(e) = FileExt::unlock(&self.file) {
debug!(
"Releasing the migration lock {} failed: {e}",
self.path.display()
);
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CopyReport {
pub copied: u64,
pub bytes: u64,
pub unusable: u64,
pub failed: u64,
pub vanished: u64,
pub stopped_for_space: bool,
}
impl CopyReport {
pub fn merge(&mut self, other: Self) {
self.copied += other.copied;
self.bytes += other.bytes;
self.unusable += other.unusable;
self.failed += other.failed;
self.vanished += other.vanished;
self.stopped_for_space |= other.stopped_for_space;
}
}
#[must_use]
pub fn migration_wave_count(close_group_size: usize) -> u64 {
let group = close_group_size.max(1) as u64;
let per_wave = CONCURRENT_MIGRATIONS_PER_GROUP.max(1) as u64;
group.div_ceil(per_wave).max(1)
}
#[must_use]
pub fn migration_wave_for(self_id: Option<&PeerId>, close_group_size: usize) -> u64 {
let waves = migration_wave_count(close_group_size);
let Some(peer) = self_id else {
return 0;
};
let digest = blake3::hash(&[MIGRATION_WAVE_DOMAIN, peer.as_bytes().as_slice()].concat());
let mut head = [0u8; 8];
head.copy_from_slice(digest.as_bytes().get(..8).unwrap_or(&[0u8; 8]));
u64::from_le_bytes(head) % waves
}
const MIGRATION_WAVE_DOMAIN: &[u8] = b"ant-node/storage-migration-wave/v1";
#[must_use]
pub fn wave_has_opened(state: &MigrationState, config: &MigrationConfig, wave: u64) -> bool {
now_unix() >= wave_opens_at(state, config, wave)
}
#[must_use]
pub fn wave_opens_at(state: &MigrationState, config: &MigrationConfig, wave: u64) -> u64 {
state
.first_start_unix
.saturating_add(config.shed_hold_hours.saturating_mul(3600))
.saturating_add(wave.saturating_mul(config.wave_hours.saturating_mul(3600)))
}
#[must_use]
pub fn rank_closest_first(mut keys: Vec<XorName>, self_xor: Option<XorName>) -> Vec<XorName> {
let Some(me) = self_xor else {
keys.sort_unstable();
return keys;
};
keys.sort_unstable_by_key(|k| crate::client::xor_distance(k, &me));
keys
}
pub const MIGRATION_EVENT: &str = "migration_event";
pub fn log_migration_complete(kept: u64, shed: u64, freed_bytes: u64) {
#[allow(clippy::cast_precision_loss)] let freed_gib = freed_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
if shed == 0 {
info!(
migration_event = "complete",
kept,
shed,
freed_bytes,
"Storage migration complete: {kept} chunks now in the file store, nothing shed, \
{freed_gib:.2} GiB being returned to the filesystem"
);
} else {
info!(
migration_event = "complete",
kept,
shed,
freed_bytes,
"Storage migration complete: kept {kept} chunks, shed {shed} that would not fit, \
{freed_gib:.2} GiB being returned to the filesystem. The shed keys are the ones this \
node was furthest from; replication will refetch what still belongs here now \
that there is room."
);
}
}
pub const SHEDDABLE_TAIL_RANKS: usize = 2;
pub const CONCURRENT_MIGRATIONS_PER_GROUP: usize = 2;
const REFUSAL_SAMPLE: usize = 4;
const COMMITMENT_FRESHNESS: Duration = Duration::from_secs(2 * 3600);
const POSSESSION_BATCH_KEYS: usize = 256;
const SHED_REEVALUATION_INTERVAL: Duration = Duration::from_secs(600);
const PROGRESS_LOG_EVERY: usize = 500;
const VERIFICATION_REUSE_WINDOW: Duration = Duration::from_secs(1800);
pub struct MigrationContext {
pub p2p: Option<Arc<P2PNode>>,
pub self_id: Option<PeerId>,
pub self_xor: Option<XorName>,
pub commitment: Option<Arc<crate::replication::commitment_state::ResponderCommitmentState>>,
pub replication: Option<Arc<ReplicationConfig>>,
pub sync_state: Option<Arc<tokio::sync::RwLock<crate::replication::types::NeighborSyncState>>>,
pub audit_challenge_coordinator:
Option<Arc<crate::replication::audit_coordinator::AuditChallengeCoordinator>>,
pub peer_commitments: Option<
Arc<
tokio::sync::RwLock<
HashMap<PeerId, crate::replication::commitment_state::PeerCommitmentRecord>,
>,
>,
>,
pub close_group_size: usize,
}
fn enough_of_the_group_knows(
received: &HashSet<PeerId>,
current: &[PeerId],
needed: usize,
) -> bool {
if needed == 0 {
return false;
}
current.iter().filter(|p| received.contains(*p)).count() >= needed
}
impl MigrationContext {
#[must_use]
pub fn commitment_recipients_needed(&self) -> usize {
prune_proofs_needed(self.close_group_size.saturating_sub(1))
}
pub async fn neighbours_know_the_commitment(&self) -> bool {
let needed = self.commitment_recipients_needed();
if needed == 0 {
return false;
}
let Some(state) = self.commitment.as_ref() else {
return false;
};
let received = state.current_delivered_peers();
if received.is_empty() {
return false;
}
let Some(current) = self.current_close_group().await else {
return false;
};
enough_of_the_group_knows(&received, ¤t, needed)
}
async fn current_close_group(&self) -> Option<Vec<PeerId>> {
let (Some(p2p), Some(me), Some(self_xor)) = (
self.p2p.as_ref(),
self.self_id.as_ref(),
self.self_xor.as_ref(),
) else {
return None;
};
let closest = p2p
.dht_manager()
.find_closest_nodes_local_with_self(self_xor, self.close_group_size)
.await;
let peers: Vec<PeerId> = closest
.iter()
.map(|n| n.peer_id)
.filter(|p| p != me)
.collect();
if peers.len() + 1 < self.close_group_size {
return None;
}
Some(peers)
}
#[must_use]
pub fn still_answerable(&self, key: &XorName) -> bool {
self.commitment
.as_ref()
.is_some_and(|state| state.is_held(key))
}
#[must_use]
pub fn shed_width(&self) -> usize {
storage_admission_width(self.close_group_size)
}
pub async fn close_group_rank(&self, key: &XorName) -> GroupRank {
let (Some(p2p), Some(me)) = (self.p2p.as_ref(), self.self_id.as_ref()) else {
return GroupRank::Unknown;
};
let closest = p2p
.dht_manager()
.find_closest_nodes_local_with_self(key, self.shed_width())
.await;
closest
.iter()
.position(|n| n.peer_id == *me)
.map_or(GroupRank::Outside, GroupRank::Inside)
}
pub async fn may_shed(&self, key: &XorName) -> bool {
rank_is_sheddable(self.close_group_rank(key).await, self.shed_width())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GroupRank {
Inside(usize),
Outside,
Unknown,
}
pub async fn unconfirmed_by_neighbours(
store: &Arc<ChunkStore>,
context: &MigrationContext,
keys: &[XorName],
) -> Vec<XorName> {
let (Some(p2p), Some(self_id), Some(config), Some(sync_state), Some(coordinator)) = (
context.p2p.as_ref(),
context.self_id.as_ref(),
context.replication.as_ref(),
context.sync_state.as_ref(),
context.audit_challenge_coordinator.as_ref(),
) else {
return keys.to_vec();
};
let local_key_count =
usize::try_from(store.current_chunks().unwrap_or(0)).unwrap_or(usize::MAX);
let dht = p2p.dht_manager();
let mut unconfirmed = Vec::new();
for batch in keys.chunks(POSSESSION_BATCH_KEYS) {
let mut targets_by_key: HashMap<XorName, Vec<PeerId>> = HashMap::new();
let mut keys_by_peer: HashMap<PeerId, Vec<XorName>> = HashMap::new();
for key in batch {
let closest = dht
.find_closest_nodes_local_with_self(key, config.close_group_size)
.await;
let peers: Vec<PeerId> = closest
.iter()
.map(|n| n.peer_id)
.filter(|p| p != self_id)
.collect();
for peer in &peers {
keys_by_peer.entry(*peer).or_default().push(*key);
}
targets_by_key.insert(*key, peers);
}
let proofs = prove_peers_hold_records(
&keys_by_peer,
local_key_count,
store,
p2p,
config,
sync_state,
coordinator,
)
.await;
let publishing = peers_publishing_a_recent_commitment(context).await;
for key in batch {
let group = targets_by_key.get(key).map_or(&[][..], Vec::as_slice);
if group.len() < config.close_group_size {
unconfirmed.push(*key);
continue;
}
let needed = prune_proofs_needed(config.close_group_size);
let qualifying: Vec<PeerId> = group
.iter()
.filter(|p| publishing.contains(*p))
.copied()
.collect();
if !target_peers_reported_present(key, &qualifying, &proofs, needed) {
unconfirmed.push(*key);
}
}
}
unconfirmed
}
async fn peers_publishing_a_recent_commitment(context: &MigrationContext) -> HashSet<PeerId> {
let Some(records) = context.peer_commitments.as_ref() else {
return HashSet::new();
};
records
.read()
.await
.iter()
.filter(|(_, record)| {
record.last_commitment().is_some()
&& record.received_at.elapsed() < COMMITMENT_FRESHNESS
})
.map(|(peer, _)| *peer)
.collect()
}
#[must_use]
pub fn rank_is_sheddable(rank: GroupRank, width: usize) -> bool {
let protected_below = if width <= SHEDDABLE_TAIL_RANKS {
width
} else {
width - SHEDDABLE_TAIL_RANKS
};
match rank {
GroupRank::Unknown => false,
GroupRank::Outside => true,
GroupRank::Inside(rank) => rank >= protected_below,
}
}
#[must_use]
pub fn should_migrate(store: &Arc<ChunkStore>) -> bool {
store.has_legacy() || store.has_cleanup_pending() || store.legacy_dir_is_on_disk()
}
pub async fn run(store: Arc<ChunkStore>, context: MigrationContext, shutdown: CancellationToken) {
let config = store.migration_config().clone();
if !worth_starting(&store, &config) {
return;
}
let tick = Duration::from_secs(config.tick_secs.max(1));
let mut volume_lock: Option<VolumeLock> = None;
let mut held = LockHold::default();
let mut next_shed_evaluation = Instant::now();
let mut next_handle_recovery = Instant::now();
let mut verified: Option<(VerifyReport, Instant)> = None;
loop {
tokio::select! {
() = shutdown.cancelled() => {
debug!("Storage migration stopping for shutdown");
return;
}
() = tokio::time::sleep(tick) => {}
}
if held.has_overstayed() {
debug!(
"Held the volume migration lock for {} hour(s); giving it back so any \
other node on this volume gets a turn",
MAX_VOLUME_LOCK_HOLD.as_secs() / 3600
);
volume_lock = None;
held.give_up();
}
let cleanup = cleanup_state(&store);
store.reconcile_pending_writes().await;
maybe_recover_lost_handle(&store, &mut next_handle_recovery).await;
if cleanup == CleanupState::Finished && !store.has_legacy() {
info!("Storage migration finished; nothing left on disk to clean up");
return;
}
match store.migration_phase() {
MigrationPhase::FilesOnly => {
volume_lock = None;
held.released();
}
MigrationPhase::Bridging => {
if matches!(
take_volume_lock(
&mut volume_lock,
&mut held,
store.root_dir(),
config.lock_dir.as_deref(),
),
LockStep::WaitATick
) {
continue;
}
if bridge_tick(
&store,
&context,
&config,
&mut next_shed_evaluation,
&shutdown,
)
.await
{
held.note_disk_work();
} else {
volume_lock = None;
held.released();
}
}
MigrationPhase::Committed => {
if matches!(
take_volume_lock(
&mut volume_lock,
&mut held,
store.root_dir(),
config.lock_dir.as_deref(),
),
LockStep::WaitATick
) {
continue;
}
match retire_tick(&store, &context, &config, &mut verified, &shutdown).await {
RetireOutcome::Done => {
volume_lock = None;
held.released();
}
RetireOutcome::Working => held.note_disk_work(),
RetireOutcome::Waiting => {}
RetireOutcome::NoWorkToSerialise => {
volume_lock = None;
held.released();
}
}
}
}
}
}
fn worth_starting(store: &Arc<ChunkStore>, config: &MigrationConfig) -> bool {
if !config.enabled {
warn!(
"Storage migration is disabled. This node will keep reading both stores and \
will never return the legacy environment's disk space."
);
return false;
}
if !should_migrate(store) {
debug!("No legacy chunk environment; nothing to migrate");
return false;
}
let to_copy = store.legacy_only_keys().len();
info!(
migration_event = "start",
to_copy,
legacy_bytes = store.legacy_bytes(),
"Storage migration starting: {to_copy} chunk(s) still only in the legacy \
environment, {:.2} GiB to reclaim",
bytes_to_gib(store.legacy_bytes())
);
true
}
fn cleanup_state(store: &Arc<ChunkStore>) -> CleanupState {
if store.has_cleanup_pending() {
store.retry_cleanup();
}
if store.has_cleanup_pending() || store.legacy_dir_is_on_disk() {
return CleanupState::Pending;
}
CleanupState::Finished
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CleanupState {
Pending,
Finished,
}
async fn maybe_recover_lost_handle(store: &Arc<ChunkStore>, next_attempt: &mut Instant) {
if Instant::now() < *next_attempt {
return;
}
if store.recover_lost_legacy_handle().await {
info!("Reopened the legacy chunk environment; the migration continues");
*next_attempt = Instant::now();
return;
}
*next_attempt = Instant::now() + HANDLE_RECOVERY_INTERVAL;
}
#[derive(Default)]
struct LockHold {
since: Option<Instant>,
cooldown_until: Option<Instant>,
}
impl LockHold {
fn taken(&mut self) {
self.since = Some(Instant::now());
}
fn released(&mut self) {
self.since = None;
}
fn note_disk_work(&mut self) {
self.since = Some(Instant::now());
}
fn has_overstayed(&self) -> bool {
self.since
.is_some_and(|at| at.elapsed() >= MAX_VOLUME_LOCK_HOLD)
}
fn give_up(&mut self) {
self.since = None;
self.cooldown_until = Some(Instant::now() + VOLUME_LOCK_COOLDOWN);
}
fn may_ask(&self) -> bool {
!self
.cooldown_until
.is_some_and(|until| Instant::now() < until)
}
}
enum LockStep {
Proceed,
WaitATick,
}
fn take_volume_lock(
lock: &mut Option<VolumeLock>,
held: &mut LockHold,
root_dir: &Path,
scope: Option<&Path>,
) -> LockStep {
if lock.is_some() {
return LockStep::Proceed;
}
if !held.may_ask() {
return LockStep::WaitATick;
}
match VolumeLock::try_acquire(root_dir, scope) {
LockAttempt::Acquired(taken) => {
*lock = Some(taken);
held.taken();
LockStep::Proceed
}
LockAttempt::Busy => {
debug!("Another node on this volume is migrating; waiting");
LockStep::WaitATick
}
LockAttempt::Unavailable => LockStep::Proceed,
}
}
async fn bridge_tick(
store: &Arc<ChunkStore>,
context: &MigrationContext,
config: &MigrationConfig,
next_shed_evaluation: &mut Instant,
shutdown: &CancellationToken,
) -> bool {
let remaining = store.legacy_only_keys();
if remaining.is_empty() {
if let Err(e) = store.commit_to_files() {
warn!(
"Everything is copied but the migration commitment could not be recorded: \
{e}. Retrying on the next tick."
);
return false;
}
return true;
}
let ordered = rank_closest_first(remaining, context.self_xor);
let batch: Vec<XorName> = ordered
.into_iter()
.take(config.batch_chunks.max(1))
.collect();
let report = match store
.copy_batch(
&batch,
config.copier_slack_bytes(),
config.copier_throttle_mib_per_sec,
shutdown,
)
.await
{
Ok(report) => report,
Err(e) => {
warn!("Storage migration copy failed: {e}. Retrying on the next tick.");
return false;
}
};
if report.copied > 0 {
debug!(
"Storage migration copied {} chunk(s) ({:.2} GiB) this pass",
report.copied,
bytes_to_gib(report.bytes)
);
let left = store.legacy_only_keys().len();
if left % PROGRESS_LOG_EVERY < usize::try_from(report.copied).unwrap_or(usize::MAX) {
let no_rollback = store.writes_without_a_rollback_copy();
info!(
migration_event = "progress",
remaining = left,
no_rollback_copy = no_rollback,
"Storage migration: {left} chunk(s) left to copy out of the legacy \
environment, {no_rollback} write(s) made without a rollback copy"
);
}
}
if report.unusable > 0 {
warn!(
"{} chunk(s) in the legacy environment did not match their own address and \
were dropped from the key set",
report.unusable
);
}
if report.stopped_for_space {
if Instant::now() < *next_shed_evaluation {
return false;
}
*next_shed_evaluation = Instant::now() + SHED_REEVALUATION_INTERVAL;
return evaluate_shed(store, context, config).await;
}
true
}
async fn evaluate_shed(
store: &Arc<ChunkStore>,
context: &MigrationContext,
config: &MigrationConfig,
) -> bool {
let remaining = store.legacy_only_keys();
let short_by = remaining.len();
if !crate::replication::config::close_group_storage_penalty_suspended() {
warn!(
"This node cannot fit {short_by} chunk(s) in the file store, but this release \
has audit penalties switched back on, so giving anything up now would be \
penalised by every peer. Keeping both stores. Add disk, or migrate this node \
on a build that still suspends penalties."
);
return false;
}
if !config.allow_shed {
warn!(
"This node cannot fit {short_by} chunk(s) in the file store and shedding is \
turned off. Add disk, or set storage.migration.allow_shed. Until then it \
keeps serving from both stores and the legacy environment stays."
);
return false;
}
let state = store.migration_state();
let wave = migration_wave_for(context.self_id.as_ref(), context.close_group_size);
if !wave_has_opened(&state, config, wave) {
info!(
"This node is {short_by} chunk(s) short of disk and is in migration wave {wave} \
of {}. Its turn opens {} hour(s) after this build first started, so the rest of \
its close group stays steady and can keep serving what it is about to give up.",
migration_wave_count(context.close_group_size),
config
.shed_hold_hours
.saturating_add(wave.saturating_mul(config.wave_hours))
);
return false;
}
if !state.shed_hold_elapsed(config) {
info!(
"This node is {short_by} chunk(s) short of disk. Holding for {} hour(s) after \
first start before giving any up, so peers still on an older build have \
upgraded and stopped penalising a shed.",
config.shed_hold_hours
);
return false;
}
let mut protected = Vec::new();
for key in &remaining {
if !context.may_shed(key).await {
protected.push(*key);
if protected.len() >= REFUSAL_SAMPLE {
break;
}
}
}
if !protected.is_empty() {
let sample: Vec<String> = protected.iter().map(hex::encode).collect();
warn!(
"This node is {short_by} chunk(s) short of disk, and at least {} of them are \
chunks it is near the front of the group for (for example {}). It will not \
give those up. The legacy environment stays and its disk is not returned \
until storage is added.",
protected.len(),
sample.join(", ")
);
return false;
}
info!(
"Checking that other nodes hold the {short_by} chunk(s) this node cannot fit, \
before giving any of them up"
);
let unconfirmed = unconfirmed_by_neighbours(store, context, &remaining).await;
if !unconfirmed.is_empty() {
let sample: Vec<String> = unconfirmed
.iter()
.take(REFUSAL_SAMPLE)
.map(hex::encode)
.collect();
warn!(
"{} of the {short_by} chunk(s) this node cannot fit could not be proven to \
exist anywhere else (for example {}). Nothing is given up and the legacy \
environment stays. Add disk, or wait for replication to place them.",
unconfirmed.len(),
sample.join(", ")
);
return false;
}
info!(
migration_event = "shed",
shed = short_by,
"Every one of the {short_by} chunk(s) this node cannot fit is proven to be held \
elsewhere. Committing to what it can hold. They stay readable from the legacy \
environment until it is removed, and replication refetches whatever still belongs \
here once there is room."
);
if let Err(e) = store.commit_to_files() {
warn!("Could not record the migration commitment: {e}");
return false;
}
true
}
async fn keys_this_node_must_not_give_up(
store: &Arc<ChunkStore>,
context: &MigrationContext,
) -> Vec<XorName> {
let mut must_keep = Vec::new();
for key in store.legacy_only_keys() {
if !context.may_shed(&key).await {
must_keep.push(key);
}
}
must_keep
}
async fn every_gate_still_holds(
store: &Arc<ChunkStore>,
context: &MigrationContext,
candidates: &std::collections::BTreeSet<XorName>,
) -> Option<RetireOutcome> {
let live: std::collections::BTreeSet<XorName> = store.legacy_only_keys().into_iter().collect();
if live != *candidates {
debug!(
"Legacy environment not retired: the set changed while the gates were being \
checked ({} keys then, {} now)",
candidates.len(),
live.len()
);
return Some(RetireOutcome::Waiting);
}
if !keys_this_node_must_not_give_up(store, context)
.await
.is_empty()
{
debug!("Legacy environment not retired: the shed rule changed during verification");
return Some(RetireOutcome::Waiting);
}
if let Some(outcome) = shedding_is_still_safe(store, context, candidates).await {
return Some(outcome);
}
if let Some(reason) = store.retirement_blocker(|k| context.still_answerable(k)) {
debug!("Legacy environment not retired: {reason}");
return Some(RetireOutcome::Waiting);
}
None
}
async fn shedding_is_still_safe(
store: &Arc<ChunkStore>,
context: &MigrationContext,
shedding: &std::collections::BTreeSet<XorName>,
) -> Option<RetireOutcome> {
if !shedding.is_empty() {
let commits_to_nothing = store
.committable_keys()
.await
.is_ok_and(|keys| keys.is_empty());
if commits_to_nothing {
info!(
"This node's file-backed set is empty, so it commits to nothing and has \
no reduced commitment for its close group to receive. Proceeding to the \
possession check on the {} chunk(s) it is giving up.",
shedding.len()
);
} else if !context.neighbours_know_the_commitment().await {
info!(
"Holding: {} of this node's close group must receive its reduced \
commitment before it gives up {} chunk(s). {} have it so far.",
context.commitment_recipients_needed(),
shedding.len(),
context
.commitment
.as_ref()
.map_or(0, |s| s.current_delivered_peer_count())
);
return Some(RetireOutcome::NoWorkToSerialise);
}
let ordered: Vec<XorName> = shedding.iter().copied().collect();
let unconfirmed = unconfirmed_by_neighbours(store, context, &ordered).await;
if !unconfirmed.is_empty() {
let sample: Vec<String> = unconfirmed
.iter()
.take(REFUSAL_SAMPLE)
.map(hex::encode)
.collect();
warn!(
"{} of the {} chunk(s) this node is giving up can no longer be proven \
to exist elsewhere (for example {}). The legacy environment stays.",
unconfirmed.len(),
shedding.len(),
sample.join(", ")
);
return Some(RetireOutcome::NoWorkToSerialise);
}
}
None
}
enum RetireOutcome {
Done,
Working,
Waiting,
NoWorkToSerialise,
}
static LAST_OPERATOR_WARNING: parking_lot::Mutex<Option<Instant>> = parking_lot::Mutex::new(None);
const OPERATOR_WARNING_INTERVAL: Duration = Duration::from_secs(3600);
fn operator_should_hear_again() -> bool {
let mut last = LAST_OPERATOR_WARNING.lock();
let now = Instant::now();
if last.is_some_and(|at| now.duration_since(at) < OPERATOR_WARNING_INTERVAL) {
return false;
}
*last = Some(now);
true
}
fn blocked_before_the_gates(
store: &Arc<ChunkStore>,
context: &MigrationContext,
config: &MigrationConfig,
) -> Option<RetireOutcome> {
let reason = store.retirement_blocker(|k| context.still_answerable(k))?;
if store.has_lost_its_legacy_handle()
|| store.legacy_cannot_be_classified()
|| store.legacy_is_a_link()
{
if operator_should_hear_again() {
warn!(
migration_event = "needs_an_operator",
"The legacy chunk environment will not be retired automatically: {reason}"
);
}
return Some(RetireOutcome::NoWorkToSerialise);
}
debug!("Legacy environment not retired yet: {reason}");
Some(if config.retire_legacy {
RetireOutcome::Waiting
} else {
RetireOutcome::NoWorkToSerialise
})
}
async fn retire_tick(
store: &Arc<ChunkStore>,
context: &MigrationContext,
config: &MigrationConfig,
verified: &mut Option<(VerifyReport, Instant)>,
shutdown: &CancellationToken,
) -> RetireOutcome {
if let Some(outcome) = blocked_before_the_gates(store, context, config) {
return outcome;
}
let must_keep = keys_this_node_must_not_give_up(store, context).await;
if !must_keep.is_empty() {
warn!(
"{} chunk(s) are still only in the legacy environment and this node is too \
close to them to give them up. Copying them before anything is removed.",
must_keep.len()
);
match store
.copy_batch(
&must_keep,
config.copier_slack_bytes(),
config.copier_throttle_mib_per_sec,
shutdown,
)
.await
{
Ok(report) if report.stopped_for_space => {
warn!(
"Out of disk while copying {} chunk(s) this node must not give up. \
The legacy environment stays until there is room for them.",
must_keep.len()
);
*verified = None;
return RetireOutcome::NoWorkToSerialise;
}
Ok(_) => {}
Err(e) => {
warn!("Could not copy the chunks this node must keep: {e}");
*verified = None;
return RetireOutcome::NoWorkToSerialise;
}
}
*verified = None;
return RetireOutcome::Working;
}
let reusable = verified
.filter(|(_, at)| at.elapsed() < VERIFICATION_REUSE_WINDOW)
.map(|(proof, _)| proof);
let proof = match reusable {
Some(proof) => proof,
None => match store
.verify_before_retire(config.copier_throttle_mib_per_sec, shutdown)
.await
{
Ok(proof) => {
if proof.is_clean() {
*verified = Some((proof, Instant::now()));
}
proof
}
Err(e) => {
warn!("Pre-retirement verification failed: {e}. Retrying on the next tick.");
return RetireOutcome::NoWorkToSerialise;
}
},
};
if !proof.is_clean() {
*verified = None;
warn!(
"Pre-retirement verification found {} chunk(s) that are damaged in the file \
store and cannot be repaired from the legacy environment. The legacy \
environment stays.",
proof.unrepairable()
);
return RetireOutcome::NoWorkToSerialise;
}
let approved: std::collections::BTreeSet<XorName> =
store.legacy_only_keys().into_iter().collect();
if let Some(outcome) = every_gate_still_holds(store, context, &approved).await {
return outcome;
}
let kept = store.current_chunks().unwrap_or(0);
let shed = store.migration_state().shed_key_count;
match store
.retire_legacy(
&proof,
&|k: &XorName| context.still_answerable(k),
&approved,
)
.await
{
Ok(freed) => {
log_migration_complete(kept, shed, freed);
RetireOutcome::Done
}
Err(e) => {
debug!("Legacy environment not retired yet: {e}");
RetireOutcome::Waiting
}
}
}
#[allow(clippy::cast_precision_loss)] #[cfg_attr(not(feature = "logging"), allow(dead_code))]
fn bytes_to_gib(bytes: u64) -> f64 {
bytes as f64 / (1024.0 * 1024.0 * 1024.0)
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use serial_test::serial;
use tempfile::TempDir;
fn peer_id(byte: u8) -> PeerId {
let mut bytes = [0u8; 32];
if let Some(slot) = bytes.first_mut() {
*slot = byte;
}
PeerId::from_bytes(bytes)
}
const WIDTH: usize = storage_admission_width(7);
#[test]
fn shedding_is_measured_against_the_width_the_pruner_protects() {
assert_eq!(WIDTH, storage_admission_width(7));
assert!(
storage_admission_width(7) > 7,
"the admission group is wider than the close group"
);
assert!(!rank_is_sheddable(GroupRank::Inside(5), WIDTH));
assert!(!rank_is_sheddable(GroupRank::Inside(6), WIDTH));
}
#[test]
fn a_node_never_gives_up_a_chunk_it_is_among_the_closest_to() {
for rank in 0..WIDTH - SHEDDABLE_TAIL_RANKS {
assert!(
!rank_is_sheddable(GroupRank::Inside(rank), WIDTH),
"rank {rank} must be protected"
);
}
for rank in WIDTH - SHEDDABLE_TAIL_RANKS..WIDTH {
assert!(
rank_is_sheddable(GroupRank::Inside(rank), WIDTH),
"rank {rank} is in the tail and may be shed"
);
}
assert!(rank_is_sheddable(GroupRank::Outside, WIDTH));
assert!(!rank_is_sheddable(GroupRank::Unknown, WIDTH));
}
#[test]
fn a_group_narrower_than_the_tail_protects_everything_in_it() {
assert!(!rank_is_sheddable(GroupRank::Inside(0), 2));
assert!(!rank_is_sheddable(GroupRank::Inside(0), 1));
assert!(!rank_is_sheddable(GroupRank::Inside(1), 2));
assert!(rank_is_sheddable(GroupRank::Outside, 2));
assert!(!rank_is_sheddable(GroupRank::Inside(0), 3));
assert!(rank_is_sheddable(GroupRank::Inside(1), 3));
}
#[test]
fn the_marker_round_trips_and_a_corrupt_one_starts_over_conservatively() {
let dir = TempDir::new().expect("temp dir");
let mut state = MigrationState::new(MigrationPhase::Bridging);
state.phase = MigrationPhase::Committed;
state.shed_key_count = 12;
state.committed_at_unix = Some(1_700_000_000);
state.save(dir.path()).expect("save");
let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
assert_eq!(loaded.phase, MigrationPhase::Committed);
assert_eq!(loaded.shed_key_count, 12);
assert_eq!(loaded.committed_at_unix, Some(1_700_000_000));
std::fs::write(state_path(dir.path()), b"not json").expect("corrupt");
let recovered = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
assert_eq!(recovered.phase, MigrationPhase::Bridging);
assert_eq!(recovered.committed_at_unix, None);
}
#[test]
fn the_shed_hold_and_retirement_clocks_run_from_recorded_times() {
let config = MigrationConfig {
shed_hold_hours: 72,
retire_delay_hours: MIN_RETIRE_DELAY_HOURS,
..MigrationConfig::default()
};
let mut state = MigrationState::new(MigrationPhase::Bridging);
assert!(!state.shed_hold_elapsed(&config), "just started");
state.first_start_unix = now_unix().saturating_sub(73 * 3600);
assert!(state.shed_hold_elapsed(&config));
assert!(
!state.retire_delay_elapsed(&config),
"never committed, so the clock has not started"
);
state.committed_at_unix = Some(now_unix().saturating_sub(3600));
assert!(!state.retire_delay_elapsed(&config), "an hour is not four");
state.committed_at_unix =
Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
assert!(state.retire_delay_elapsed(&config));
}
#[test]
fn only_one_node_on_a_volume_migrates_at_a_time() {
let volume = TempDir::new().expect("temp dir");
let node_a = volume.path().join("node-a");
let node_b = volume.path().join("node-b");
std::fs::create_dir_all(&node_a).expect("mkdir");
std::fs::create_dir_all(&node_b).expect("mkdir");
let LockAttempt::Acquired(held) = VolumeLock::try_acquire(&node_a, None) else {
panic!("the first node must take the lock");
};
assert!(
matches!(VolumeLock::try_acquire(&node_b, None), LockAttempt::Busy),
"a second node on the same volume must be told to wait, not that no lock exists"
);
drop(held);
assert!(
matches!(
VolumeLock::try_acquire(&node_b, None),
LockAttempt::Acquired(_)
),
"and take it once the first is done"
);
}
async fn seed_legacy(root: &std::path::Path, count: u32) -> Vec<XorName> {
let lmdb = crate::storage::LmdbStorage::new(crate::storage::LmdbStorageConfig {
root_dir: root.to_path_buf(),
verify_on_read: true,
max_map_size: 0,
disk_reserve: 0,
})
.await
.expect("open legacy");
let mut keys = Vec::new();
for i in 0..count {
let content = format!("legacy-chunk-{i}").into_bytes();
let addr = crate::client::compute_address(&content);
lmdb.put(&addr, &content).await.expect("legacy put");
keys.push(addr);
}
lmdb.wait_idle().await;
drop(lmdb);
keys
}
#[tokio::test]
async fn a_node_with_room_copies_everything_and_removes_the_legacy_store() {
const CHUNKS: u32 = 24;
let tmp = TempDir::new().expect("temp dir");
let root = tmp.path().join("node");
std::fs::create_dir_all(&root).expect("mkdir");
let keys = seed_legacy(&root, CHUNKS).await;
let mut config = crate::storage::ChunkStoreConfig {
root_dir: root.clone(),
..crate::storage::ChunkStoreConfig::test_default()
};
config.migration.tick_secs = 1;
config.migration.lock_dir = Some(root.clone());
config.migration.copier_throttle_mib_per_sec = 0;
let store = Arc::new(
crate::storage::ChunkStore::new(config)
.await
.expect("open store"),
);
assert!(store.has_legacy(), "the node must start with an LMDB store");
assert_eq!(store.migration_phase(), MigrationPhase::Bridging);
assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
assert!(root.join("chunks.mdb").exists());
let shutdown = CancellationToken::new();
let driver = tokio::spawn(run(
Arc::clone(&store),
MigrationContext {
p2p: None,
self_id: None,
self_xor: None,
commitment: None,
replication: None,
sync_state: None,
audit_challenge_coordinator: None,
peer_commitments: None,
close_group_size: 7,
},
shutdown.clone(),
));
wait_for(
&store,
MigrationPhase::Committed,
"the copier should finish",
)
.await;
assert!(
store.legacy_only_keys().is_empty(),
"every chunk should have been copied"
);
store.note_commitment_rebuilt();
store.note_commitment_rebuilt();
store.force_migration_state(|s| {
s.committed_at_unix =
Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
});
wait_for(
&store,
MigrationPhase::FilesOnly,
"retirement should complete",
)
.await;
shutdown.cancel();
let _ = tokio::time::timeout(Duration::from_secs(10), driver).await;
assert!(
!root.join("chunks.mdb").exists(),
"the legacy store must be removed, which is the only moment disk comes back"
);
assert!(!store.has_legacy());
assert_eq!(store.current_chunks().expect("count"), u64::from(CHUNKS));
for (i, key) in keys.iter().enumerate() {
let expected = format!("legacy-chunk-{i}").into_bytes();
assert_eq!(
store.get(key).await.expect("get").expect("present"),
expected,
"chunk {i} did not survive the migration"
);
}
let sample = keys.first().copied().expect("a key");
let path = root
.join(crate::storage::file_store::CHUNKS_DIR_NAME)
.join(format!("{:02x}", sample.last().copied().unwrap_or(0)))
.join(hex::encode(sample));
assert!(path.exists(), "expected a chunk file at {}", path.display());
}
#[tokio::test]
async fn a_node_that_cannot_prove_its_chunks_are_safe_deletes_nothing() {
const CHUNKS: u32 = 8;
let tmp = TempDir::new().expect("temp dir");
let root = tmp.path().join("node");
std::fs::create_dir_all(&root).expect("mkdir");
let keys = seed_legacy(&root, CHUNKS).await;
let mut config = crate::storage::ChunkStoreConfig {
root_dir: root.clone(),
disk_reserve: u64::MAX / 2,
..crate::storage::ChunkStoreConfig::test_default()
};
config.migration.retire_legacy = true;
config.migration.tick_secs = 1;
config.migration.lock_dir = Some(root.clone());
config.migration.shed_hold_hours = 0;
config.migration.wave_hours = 0;
let store = Arc::new(
crate::storage::ChunkStore::new(config)
.await
.expect("open store"),
);
assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
let shutdown = CancellationToken::new();
let driver = tokio::spawn(run(
Arc::clone(&store),
MigrationContext {
p2p: None,
self_id: None,
self_xor: None,
commitment: None,
replication: None,
sync_state: None,
audit_challenge_coordinator: None,
peer_commitments: None,
close_group_size: 7,
},
shutdown.clone(),
));
tokio::time::sleep(Duration::from_secs(5)).await;
shutdown.cancel();
let _ = tokio::time::timeout(Duration::from_secs(10), driver).await;
assert_eq!(
store.migration_phase(),
MigrationPhase::Bridging,
"a node that cannot prove its chunks are held elsewhere must not commit"
);
assert!(
root.join("chunks.mdb").exists(),
"and must not remove the only copy of them"
);
assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
for (i, key) in keys.iter().enumerate() {
assert_eq!(
store.get(key).await.expect("get").expect("present"),
format!("legacy-chunk-{i}").into_bytes(),
"chunk {i} must still be served throughout"
);
}
}
async fn wait_for(store: &Arc<crate::storage::ChunkStore>, phase: MigrationPhase, what: &str) {
let deadline = std::time::Instant::now() + Duration::from_secs(180);
while std::time::Instant::now() < deadline {
if store.migration_phase() == phase {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!(
"{what}: still in {:?} after the deadline, expected {phase:?}",
store.migration_phase()
);
}
#[test]
fn an_unusable_marker_is_replaced_on_disk_so_the_hold_does_not_restart() {
for (name, bad) in [
("truncated", br#"{"schema":1,"phase":"brid"#.to_vec()),
("not json at all", b"\x00\x01\x02".to_vec()),
(
"a newer schema",
serde_json::json!({
"schema": 9_999,
"phase": "bridging",
"first_start_unix": 1,
"committed_at_unix": null,
"rebuilds_since_commit": 0,
"shed_key_count": 0,
"kept_key_count": 0,
})
.to_string()
.into_bytes(),
),
(
"a newer schema this build cannot parse at all",
serde_json::json!({
"schema": 9_999,
"phase": "some_phase_from_the_future",
"first_start_unix": 1,
"something_this_build_never_heard_of": {"a": 1},
})
.to_string()
.into_bytes(),
),
] {
let dir = TempDir::new().expect("temp dir");
std::fs::write(state_path(dir.path()), &bad).expect("plant the bad marker");
let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
let written = std::fs::read(state_path(dir.path())).expect("read it back");
assert_ne!(written, bad, "{name}: the unusable marker was left on disk");
if name.starts_with("a newer schema") {
let mut kept = state_path(dir.path()).into_os_string();
kept.push(".schema-9999");
let kept = PathBuf::from(kept);
assert_eq!(
std::fs::read(&kept).expect("the newer marker must be kept"),
bad,
"the newer marker was written over rather than set aside"
);
}
let second = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
assert_eq!(
second.first_start_unix, first.first_start_unix,
"{name}: the shed hold restarted on the next boot"
);
}
}
#[test]
fn a_future_dated_marker_is_corrected_on_disk_not_only_in_memory() {
let dir = TempDir::new().expect("temp dir");
let ahead = now_unix().saturating_add(60 * 60 * 24 * 365);
let planted = serde_json::json!({
"schema": 1,
"phase": "bridging",
"first_start_unix": ahead,
"committed_at_unix": null,
"rebuilds_since_commit": 0,
"shed_key_count": 0,
"kept_key_count": 0,
})
.to_string();
std::fs::write(state_path(dir.path()), &planted).expect("plant it");
let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
assert!(
first.first_start_unix < ahead,
"the clock should have been brought back to something possible"
);
let reread: MigrationState =
serde_json::from_slice(&std::fs::read(state_path(dir.path())).expect("read"))
.expect("the marker on disk must now parse");
assert_eq!(
reread.first_start_unix, first.first_start_unix,
"the correction was made in memory and not written back"
);
}
#[test]
fn a_usable_marker_is_left_exactly_as_it_is() {
let dir = TempDir::new().expect("temp dir");
let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
let noncanonical = format!(
"{{\"kept_key_count\":{},\"shed_key_count\":{},\"rebuilds_since_commit\":{},\
\"committed_at_unix\":null,\"first_start_unix\":{},\"phase\":\"bridging\",\
\"schema\":{}}}",
first.kept_key_count,
first.shed_key_count,
first.rebuilds_since_commit,
first.first_start_unix,
first.schema
);
std::fs::write(state_path(dir.path()), &noncanonical).expect("write");
MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
assert_eq!(
std::fs::read_to_string(state_path(dir.path())).expect("read"),
noncanonical,
"a marker that already said the right thing was rewritten for no reason"
);
}
#[test]
fn nodes_on_one_volume_agree_on_a_lock_path_when_they_are_told_where_it_is() {
let volume = TempDir::new().expect("temp dir");
let a = volume.path().join("node-0");
let b = volume.path().join("node-1");
std::fs::create_dir_all(&a).expect("mkdir");
std::fs::create_dir_all(&b).expect("mkdir");
assert_eq!(
lock_path_with(&a, None),
lock_path_with(&b, None),
"two roots on one volume must share a lock when they share a /tmp"
);
assert_ne!(
lock_path_with(&a, Some("/tmp/private-to-node-0")),
lock_path_with(&b, Some("/tmp/private-to-node-1")),
"different lock directories must give different locks, or the override would \
not be able to express anything"
);
let told = volume.path().to_string_lossy().into_owned();
let shared_a = lock_path_with(&a, Some(&told));
let shared_b = lock_path_with(&b, Some(&told));
assert_eq!(
shared_a, shared_b,
"nodes told where the lock lives must all use it"
);
assert!(shared_a.starts_with(volume.path()), "and use the one named");
assert_eq!(
lock_path_with(&a, Some(" ")),
lock_path_with(&a, None),
"an empty setting is not a location and must not be treated as one"
);
let LockAttempt::Acquired(held) = VolumeLock::try_acquire(&a, Some(volume.path())) else {
panic!("the first node must take it");
};
assert!(
matches!(
VolumeLock::try_acquire(&b, Some(volume.path())),
LockAttempt::Busy
),
"the second must wait rather than copy alongside it"
);
drop(held);
assert!(matches!(
VolumeLock::try_acquire(&b, Some(volume.path())),
LockAttempt::Acquired(_)
));
}
#[test]
fn a_lock_directory_that_does_not_exist_is_unavailable_rather_than_ignored() {
let dir = TempDir::new().expect("temp dir");
let missing = dir.path().join("no-such-directory");
assert!(matches!(
VolumeLock::try_acquire(dir.path(), Some(&missing)),
LockAttempt::Unavailable
));
}
#[tokio::test]
async fn the_driver_exits_immediately_when_there_is_nothing_to_migrate() {
let dir = TempDir::new().expect("temp dir");
let store = Arc::new(
crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
root_dir: dir.path().to_path_buf(),
..crate::storage::ChunkStoreConfig::test_default()
})
.await
.expect("open store"),
);
assert!(!store.has_legacy());
let context = MigrationContext {
p2p: None,
self_id: None,
self_xor: None,
commitment: None,
replication: None,
sync_state: None,
audit_challenge_coordinator: None,
peer_commitments: None,
close_group_size: 7,
};
tokio::time::timeout(
Duration::from_secs(5),
run(store, context, CancellationToken::new()),
)
.await
.expect("the driver must return rather than idle when there is nothing to migrate");
}
#[tokio::test]
async fn a_node_with_no_view_of_the_network_gives_up_nothing() {
let dir = TempDir::new().expect("temp dir");
let store = Arc::new(
crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
root_dir: dir.path().to_path_buf(),
..crate::storage::ChunkStoreConfig::test_default()
})
.await
.expect("open store"),
);
let context = MigrationContext {
p2p: None,
self_id: None,
self_xor: None,
commitment: None,
replication: None,
sync_state: None,
audit_challenge_coordinator: None,
peer_commitments: None,
close_group_size: 7,
};
let keys = vec![[1u8; 32], [2u8; 32], [3u8; 32]];
let unconfirmed = unconfirmed_by_neighbours(&store, &context, &keys).await;
assert_eq!(
unconfirmed, keys,
"with no routing state every key must count as unproven"
);
for key in &keys {
assert!(
!context.may_shed(key).await,
"and none of them may be given up"
);
}
}
#[test]
fn the_possession_threshold_comes_from_the_whole_group_not_the_qualifying_subset() {
use crate::replication::pruning::{prune_proofs_needed, target_peers_reported_present};
use std::collections::{HashMap, HashSet};
let key = [7u8; 32];
let group: Vec<PeerId> = (0..6u8).map(peer_id).collect();
let only_one_qualifies: Vec<PeerId> = group.iter().take(1).copied().collect();
let mut proofs: HashMap<XorName, HashSet<PeerId>> = HashMap::new();
proofs.insert(key, only_one_qualifies.iter().copied().collect());
assert!(
target_peers_reported_present(
&key,
&only_one_qualifies,
&proofs,
prune_proofs_needed(only_one_qualifies.len()),
),
"this is the mistake being guarded against, shown here to be a real risk"
);
assert!(
!target_peers_reported_present(
&key,
&only_one_qualifies,
&proofs,
prune_proofs_needed(group.len()),
),
"one proof must never satisfy a group of six"
);
proofs.insert(key, group.iter().copied().collect());
assert!(target_peers_reported_present(
&key,
&group,
&proofs,
prune_proofs_needed(group.len()),
));
}
#[test]
#[serial]
fn shedding_reads_the_same_switch_the_auditors_read() {
use crate::replication::config::{
close_group_storage_penalty_suspended, set_close_group_storage_penalty_suspended,
};
set_close_group_storage_penalty_suspended(true);
assert!(close_group_storage_penalty_suspended());
set_close_group_storage_penalty_suspended(false);
assert!(!close_group_storage_penalty_suspended());
set_close_group_storage_penalty_suspended(
crate::replication::config::RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY,
);
}
#[test]
fn a_close_group_is_split_into_enough_waves_to_bound_concurrent_migrations() {
assert_eq!(migration_wave_count(7), 4);
assert_eq!(migration_wave_count(2), 1);
assert_eq!(migration_wave_count(1), 1);
assert_eq!(migration_wave_count(0), 1);
}
#[test]
fn wave_assignment_is_stable_per_node_and_spread_across_the_group() {
use std::collections::HashMap;
let waves = migration_wave_count(7);
let peer = peer_id(7);
assert_eq!(
migration_wave_for(Some(&peer), 7),
migration_wave_for(Some(&peer), 7)
);
let mut counts: HashMap<u64, usize> = HashMap::new();
for b in 0..=255u8 {
let w = migration_wave_for(Some(&peer_id(b)), 7);
assert!(w < waves, "wave {w} outside 0..{waves}");
*counts.entry(w).or_default() += 1;
}
assert_eq!(
counts.len() as u64,
waves,
"every wave should be occupied, got {counts:?}"
);
}
#[test]
fn waves_are_actually_staggered_under_the_shipped_defaults() {
let config = MigrationConfig::default();
assert_eq!(config.shed_hold_hours, 72);
assert_eq!(config.wave_hours, 24);
let mut state = MigrationState::new(MigrationPhase::Bridging);
let waves = migration_wave_count(7);
assert_eq!(waves, 4);
state.first_start_unix = now_unix();
for w in 0..waves {
assert!(
!wave_has_opened(&state, &config, w),
"wave {w} opened too early"
);
}
state.first_start_unix = now_unix().saturating_sub(72 * 3600 + 60);
assert!(wave_has_opened(&state, &config, 0));
for w in 1..waves {
assert!(
!wave_has_opened(&state, &config, w),
"wave {w} must wait its turn, or the group migrates together"
);
}
for open in 1..waves {
state.first_start_unix = now_unix().saturating_sub((72 + open * 24) * 3600 + 60);
for w in 0..=open {
assert!(wave_has_opened(&state, &config, w));
}
for w in open + 1..waves {
assert!(!wave_has_opened(&state, &config, w));
}
}
}
#[test]
fn an_implausible_clock_restarts_the_holds_rather_than_voiding_them() {
let dir = TempDir::new().expect("temp dir");
let config = MigrationConfig::default();
let mut state = MigrationState::new(MigrationPhase::Committed);
state.first_start_unix = 0;
state.committed_at_unix = Some(0);
state.save(dir.path()).expect("save");
let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
assert!(
!loaded.shed_hold_elapsed(&config),
"the hold must not be void"
);
assert!(!loaded.retire_delay_elapsed(&config));
let mut future = MigrationState::new(MigrationPhase::Committed);
future.first_start_unix = now_unix().saturating_add(10 * 365 * 24 * 3600);
future.committed_at_unix = Some(future.first_start_unix);
future.save(dir.path()).expect("save");
let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
assert!(!loaded.shed_hold_elapsed(&config));
assert!(!loaded.retire_delay_elapsed(&config));
}
#[test]
fn copy_reports_accumulate_across_passes() {
let mut total = CopyReport::default();
total.merge(CopyReport {
copied: 3,
bytes: 300,
..CopyReport::default()
});
total.merge(CopyReport {
copied: 2,
bytes: 200,
unusable: 1,
stopped_for_space: true,
..CopyReport::default()
});
assert_eq!(total.copied, 5);
assert_eq!(total.bytes, 500);
assert_eq!(total.unusable, 1);
assert!(total.stopped_for_space);
}
#[test]
fn a_departed_peer_that_knows_the_commitment_does_not_open_the_gate() {
let received: HashSet<PeerId> = (0..6).map(peer_id).collect();
let still_here: Vec<PeerId> = (0..3).map(peer_id).collect();
let joined_since: Vec<PeerId> = (100..103).map(peer_id).collect();
let current: Vec<PeerId> = still_here
.iter()
.chain(joined_since.iter())
.copied()
.collect();
assert_eq!(received.len(), 6);
assert_eq!(current.len(), 6);
assert!(!enough_of_the_group_knows(&received, ¤t, 5));
assert!(enough_of_the_group_knows(&received, ¤t, 3));
assert!(!enough_of_the_group_knows(&received, ¤t, 4));
}
#[test]
fn a_group_that_has_all_seen_the_commitment_opens_the_gate() {
let group: Vec<PeerId> = (0..6).map(peer_id).collect();
let received: HashSet<PeerId> = group.iter().copied().collect();
assert!(enough_of_the_group_knows(&received, &group, 5));
}
#[test]
fn no_peer_ever_satisfies_a_zero_threshold() {
let group: Vec<PeerId> = (0..6).map(peer_id).collect();
let received: HashSet<PeerId> = group.iter().copied().collect();
assert!(!enough_of_the_group_knows(&received, &group, 0));
}
#[tokio::test]
async fn without_a_routing_view_the_commitment_gate_stays_shut() {
let context = MigrationContext {
p2p: None,
self_id: None,
self_xor: None,
commitment: None,
replication: None,
sync_state: None,
audit_challenge_coordinator: None,
peer_commitments: None,
close_group_size: 7,
};
assert!(!context.neighbours_know_the_commitment().await);
}
}