Skip to main content

ant_node/storage/
migration.rs

1//! Moving a node off LMDB and onto the file store without losing a chunk.
2//!
3//! LMDB never returns a deleted page to the filesystem. Disk comes back exactly once,
4//! when `chunks.mdb` is removed whole, so a node cannot free space by deleting chunks
5//! and cannot compact its way out either (compaction needs free space equal to the live
6//! data, which is the same condition). That single fact shapes everything here.
7//!
8//! # The two ways this could lose data, and why neither can happen
9//!
10//! 1. **A node deletes its LMDB before the chunks are safely in files.** Retirement is
11//!    gated on the file store already holding every key the node still claims, and on
12//!    the existing retention contract: a key the node is still answerable for under a
13//!    gossiped commitment vetoes the delete.
14//! 2. **Every node sheds the same chunk at once.** A node only sheds when it cannot fit
15//!    its own payload, and it sheds by close-group rank, furthest first. A chunk has
16//!    exactly one 7th-closest and one 6th-closest holder, so it is only ever a shed
17//!    candidate for two of its seven holders, and the staged rollout brings that to one.
18//!
19//! # Three releases
20//!
21//! Slashing is the *auditor's* decision, so a node cannot protect itself from being
22//! penalised for a shed. Everyone else has to stop first, which is why this lands over
23//! three releases rather than one:
24//!
25//! | Release | Penalise not holding a close-group chunk? | [`MigrationConfig::retire_legacy`] |
26//! |---|---|---|
27//! | First: stop that one penalty | no | `false` |
28//! | Second: migrate | no | `true` |
29//! | Third: restore it | yes | `true` |
30//!
31//! The penalty column is not a field here. It lives once, in
32//! [`crate::replication::config::RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY`], and both
33//! the auditors that apply it and the shedder that depends on it being withheld read that
34//! same switch. Two copies would let a node shed while its peers still penalised.
35//!
36//! Audits keep running and keep recording throughout. What the first release withholds is narrow and
37//! deliberate: only the penalty for *not holding a close-group chunk*. The
38//! commitment-bound subtree audit still penalises in every release, because the whole
39//! migration turns on a node's reduced commitment still being binding. The record those
40//! audits keep is also how we will know when the third release is safe to ship.
41
42use crate::ant_protocol::XorName;
43use crate::error::{Error, Result};
44use crate::logging::{debug, info, warn};
45use crate::replication::config::{storage_admission_width, ReplicationConfig};
46use crate::replication::pruning::{
47    prove_peers_hold_records, prune_proofs_needed, target_peers_reported_present,
48};
49use crate::storage::chunk_store::{ChunkStore, VerifyReport};
50use saorsa_core::identity::PeerId;
51use saorsa_core::P2PNode;
52use serde::{Deserialize, Serialize};
53use std::collections::{HashMap, HashSet};
54use std::path::{Path, PathBuf};
55use std::sync::Arc;
56use std::time::{Duration, Instant};
57use std::time::{SystemTime, UNIX_EPOCH};
58use tokio_util::sync::CancellationToken;
59
60/// Filename of the persisted migration marker, under the node root.
61pub const MIGRATION_STATE_FILE: &str = "migration-state.json";
62
63/// Marker schema this build writes and understands.
64const STATE_SCHEMA: u32 = 1;
65
66/// Floor on [`MigrationConfig::retire_delay_hours`].
67///
68/// `GOSSIP_ANSWERABILITY_TTL` is three hours at a one-hour rotation cadence, so a
69/// commitment that named a shed key stops being answerable three hours after it was last
70/// gossiped. Four hours clears that with an hour to spare.
71pub const MIN_RETIRE_DELAY_HOURS: u64 = 4;
72
73/// How long between attempts to reopen an environment this node has lost its handle to.
74///
75/// Each attempt scans every key in it, so retrying on every tick would spend a large store
76/// entirely on failing to open it.
77const HANDLE_RECOVERY_INTERVAL: Duration = Duration::from_mins(5);
78
79/// The longest one node may hold the volume migration lock before giving others a turn.
80///
81/// Every branch that waits rather than works is meant to give the lock back on its own.
82/// This is the backstop for the one that does not: without it, a node stuck on a condition
83/// that never resolves stops every other node sharing the disk from ever starting, for the
84/// whole release. Longer than a copy pass and a verification take, so it never interrupts
85/// a node that is genuinely working.
86const MAX_VOLUME_LOCK_HOLD: Duration = Duration::from_hours(6);
87
88/// How long a node stands back after the cap takes the volume lock off it.
89///
90/// Long enough that another node waiting on the lock actually gets it, rather than losing
91/// the race to the node that has just been holding it for six hours.
92const VOLUME_LOCK_COOLDOWN: Duration = Duration::from_mins(2);
93
94/// How many commitment rebuilds must be observed after the node commits to its
95/// file-backed set before the legacy environment may be retired.
96///
97/// One proves the builder read the new set. Two proves it published and survived a
98/// rotation, which is what makes the retention window meaningful.
99pub const REQUIRED_REBUILDS_BEFORE_RETIRE: u32 = 2;
100
101/// Operator-facing controls for the migration.
102// Four independent switches, three of which are operator controls and one of which is a
103// release constant. Collapsing them into an enum would tie choices together that are
104// deliberately separate.
105#[allow(clippy::struct_excessive_bools)]
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct MigrationConfig {
108    /// Run the background copier at all.
109    ///
110    /// Turning this off leaves a node reading the union of both stores forever. It never
111    /// frees the LMDB's disk, so it is an escape hatch rather than a supported mode.
112    #[serde(default = "default_true")]
113    pub enabled: bool,
114
115    /// Write every new chunk to the legacy environment as well as the file store.
116    ///
117    /// Costs roughly a gigabyte per node per month at the observed fill rate, and buys
118    /// the ability to roll the fleet back: a chunk uploaded during the bridge to holders
119    /// that all revert to a pre-migration build would otherwise be gone from every one
120    /// of them. Automatically irrelevant once the legacy environment is retired.
121    #[serde(default = "default_true")]
122    pub dual_write_legacy: bool,
123
124    /// Allow a node that cannot fit its payload to drop its furthest keys.
125    ///
126    /// An operator who would rather add disk than shed can set this to `false`. The node
127    /// then keeps both stores and never frees the LMDB's space.
128    #[serde(default = "default_true")]
129    pub allow_shed: bool,
130
131    /// Delete `chunks.mdb` once the retirement gate is satisfied.
132    ///
133    /// **On in this release**, because it is the only step that returns disk. It is also
134    /// the only destructive step in the whole migration and the only one that cannot be
135    /// undone, which is why everything in front of it is a gate: the wave the node is
136    /// assigned to, the shed hold, the reduced commitment reaching the close group,
137    /// possession of every chunk being given up proven elsewhere, a re-read of every
138    /// remaining chunk, and a retention delay on top.
139    ///
140    /// Deliberately never serialised. A node writes its effective configuration back to
141    /// disk, so shipping this as an ordinary field would bake R1's `false` into every
142    /// operator's config file and R2 would then never retire anything. The release phase
143    /// belongs to the build, not to the operator's file. `ANT_MIGRATION_RETIRE_LEGACY`
144    /// overrides it for a canary.
145    #[serde(skip, default = "release_retire_legacy")]
146    pub retire_legacy: bool,
147
148    /// Hours after this build first starts before a node may shed anything.
149    ///
150    /// Long enough for peers still on a pre-R1 build to upgrade, because one of those
151    /// still penalises a shedder at the full audit weight.
152    #[serde(default = "default_shed_hold_hours")]
153    pub shed_hold_hours: u64,
154
155    /// Hours between committing to the file-backed key set and deleting `chunks.mdb`.
156    ///
157    /// Clamped up to [`MIN_RETIRE_DELAY_HOURS`]. Longer buys a rollback window on nodes
158    /// that can afford to hold both copies.
159    #[serde(default = "default_retire_delay_hours")]
160    pub retire_delay_hours: u64,
161
162    /// Free megabytes the copier leaves untouched, on top of the disk reserve.
163    ///
164    /// The copier stops here rather than filling to the brink, so a node that is
165    /// mid-migration still has room to accept a chunk it is paid for.
166    #[serde(default = "default_copier_slack_mb")]
167    pub copier_slack_mb: u64,
168
169    /// Copy rate ceiling, in mebibytes per second.
170    ///
171    /// The quiet responsible audit lane is where audit timeouts actually cost trust, and
172    /// an unthrottled copier competing with it for I/O is the fastest way to turn a
173    /// storage migration into an audit incident.
174    #[serde(default = "default_copier_throttle_mib_per_sec")]
175    pub copier_throttle_mib_per_sec: u64,
176
177    /// Hours between one migration wave opening and the next.
178    ///
179    /// A close group is split into waves so that only
180    /// [`CONCURRENT_MIGRATIONS_PER_GROUP`] of it give chunks up at a time. This is how
181    /// long a wave gets to finish copying, retiring and refetching before the next one may
182    /// start. Only nodes that have to give something up wait for their wave; a node with
183    /// room migrates immediately.
184    #[serde(default = "default_wave_hours")]
185    pub wave_hours: u64,
186
187    /// Seconds between copier ticks.
188    #[serde(default = "default_tick_secs")]
189    pub tick_secs: u64,
190
191    /// Chunks copied per tick before yielding.
192    #[serde(default = "default_batch_chunks")]
193    pub batch_chunks: usize,
194
195    /// Where the volume lock lives, overriding the filesystem this node's root sits on.
196    ///
197    /// `None` in production, which keys the lock by device id so every node on one disk
198    /// serialises against the others. Tests set it so a test's migration contends only
199    /// with its own, rather than with every other test sharing the machine's filesystem.
200    ///
201    /// Never serialised: it exists to scope a test, not to configure a node.
202    #[serde(skip)]
203    pub lock_dir: Option<PathBuf>,
204}
205
206const fn default_true() -> bool {
207    true
208}
209
210/// Whether this build deletes the legacy environment once the gate is satisfied.
211///
212/// **`true` in this release.** Deleting `chunks.mdb` is the only step that returns disk,
213/// and a build that ships with it off is a migration that never finishes: the fleet
214/// already deleted 2.29M chunks out of LMDB and got back nothing, because LMDB does not
215/// return freed pages to the filesystem. Every gate in front of this is still enforced,
216/// and `ANT_MIGRATION_RETIRE_LEGACY=0` turns it off on a single node if one is ever
217/// needed to hold both stores.
218pub const RELEASE_RETIRE_LEGACY: bool = true;
219
220/// Environment override for the directory the per-volume migration lock lives in.
221///
222/// Set this where the default cannot work, and the default cannot work wherever the nodes
223/// sharing a disk do not share a `/tmp`. Our own multi-node hosts are exactly that case:
224/// the systemd unit sets `PrivateTmp=true`, which gives every unit a tmpfs of its own, so
225/// each node creates the same lock filename in a different filesystem, every one of them
226/// takes it, and the lock serialises nothing. Point every node on a host at one directory
227/// they can all write and the lock does what it is for.
228///
229/// The directory must be writable by the node. A path that cannot be used is reported and
230/// the node migrates unserialised, which is the same answer as having no lock, so a typo
231/// here is loud rather than silent.
232pub const LOCK_DIR_ENV: &str = "ANT_MIGRATION_LOCK_DIR";
233
234/// Environment override for [`RELEASE_RETIRE_LEGACY`], for a canary node.
235pub const RETIRE_LEGACY_ENV: &str = "ANT_MIGRATION_RETIRE_LEGACY";
236
237/// Read a boolean override from the environment, falling back to the build constant.
238fn env_override(name: &str, build_default: bool) -> bool {
239    let Ok(raw) = std::env::var(name) else {
240        return build_default;
241    };
242    match raw.trim().to_ascii_lowercase().as_str() {
243        "1" | "true" | "yes" | "on" => true,
244        "0" | "false" | "no" | "off" => false,
245        other => {
246            warn!("{name}={other} is not a boolean; using the build default {build_default}");
247            build_default
248        }
249    }
250}
251
252/// The retirement switch for this build, after any environment override.
253fn release_retire_legacy() -> bool {
254    env_override(RETIRE_LEGACY_ENV, RELEASE_RETIRE_LEGACY)
255}
256
257const fn default_shed_hold_hours() -> u64 {
258    72
259}
260
261const fn default_retire_delay_hours() -> u64 {
262    MIN_RETIRE_DELAY_HOURS
263}
264
265const fn default_wave_hours() -> u64 {
266    24
267}
268
269const fn default_copier_slack_mb() -> u64 {
270    2048
271}
272
273const fn default_copier_throttle_mib_per_sec() -> u64 {
274    32
275}
276
277const fn default_tick_secs() -> u64 {
278    30
279}
280
281const fn default_batch_chunks() -> usize {
282    64
283}
284
285impl Default for MigrationConfig {
286    fn default() -> Self {
287        Self {
288            enabled: true,
289            dual_write_legacy: true,
290            allow_shed: true,
291            retire_legacy: release_retire_legacy(),
292            shed_hold_hours: default_shed_hold_hours(),
293            retire_delay_hours: default_retire_delay_hours(),
294            wave_hours: default_wave_hours(),
295            copier_slack_mb: default_copier_slack_mb(),
296            copier_throttle_mib_per_sec: default_copier_throttle_mib_per_sec(),
297            tick_secs: default_tick_secs(),
298            batch_chunks: default_batch_chunks(),
299            lock_dir: None,
300        }
301    }
302}
303
304impl MigrationConfig {
305    /// The retire delay, never shorter than the retention contract allows.
306    #[must_use]
307    pub fn effective_retire_delay_hours(&self) -> u64 {
308        self.retire_delay_hours.max(MIN_RETIRE_DELAY_HOURS)
309    }
310
311    /// Copier slack in bytes.
312    #[must_use]
313    pub fn copier_slack_bytes(&self) -> u64 {
314        self.copier_slack_mb.saturating_mul(1024 * 1024)
315    }
316}
317
318/// Where a node is in the migration.
319///
320/// The phase is persisted, but only as a *decision* record. Everything derivable from
321/// the filesystem is re-derived at every start: which keys are still legacy-only is
322/// simply "in the LMDB and not in the file store", so an interrupted copy resumes for
323/// free with no progress bookkeeping to corrupt.
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "snake_case")]
326pub enum MigrationPhase {
327    /// Copying the legacy environment into files. Reads are the union of both stores,
328    /// writes go to files, and the commitment still covers everything.
329    Bridging,
330    /// The node has settled on what it will keep and commits only to its file-backed
331    /// keys. It keeps serving the rest from LMDB until they stop being answerable.
332    Committed,
333    /// No legacy environment. Steady state, and where every fresh node starts.
334    FilesOnly,
335}
336
337/// The persisted migration marker.
338///
339/// Two facts genuinely need to survive a restart: when this build first ran (so the shed
340/// hold is not restarted by a reboot loop) and when the node committed to its file-backed
341/// set (so the retirement clock is not either). Everything else is re-derived.
342#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
343pub struct MigrationState {
344    /// Marker schema version.
345    pub schema: u32,
346    /// Where the node is.
347    pub phase: MigrationPhase,
348    /// Unix seconds when this build first started on this node.
349    pub first_start_unix: u64,
350    /// Unix seconds when the node committed to its file-backed key set.
351    pub committed_at_unix: Option<u64>,
352    /// Commitment rebuilds observed since committing.
353    pub rebuilds_since_commit: u32,
354    /// How many keys the node decided not to keep, for the operator's benefit.
355    pub shed_key_count: u64,
356    /// How many chunks the file store held when the node committed.
357    ///
358    /// Cross-checked at open. A marker claiming the node is past the copying stage while
359    /// the file store is far emptier than it said means the two disagree about reality,
360    /// and the filesystem wins.
361    #[serde(default)]
362    pub kept_key_count: u64,
363}
364
365impl MigrationState {
366    /// A fresh marker for a node that has just started.
367    #[must_use]
368    pub fn new(phase: MigrationPhase) -> Self {
369        Self {
370            schema: STATE_SCHEMA,
371            phase,
372            first_start_unix: now_unix(),
373            committed_at_unix: None,
374            rebuilds_since_commit: 0,
375            shed_key_count: 0,
376            kept_key_count: 0,
377        }
378    }
379
380    /// Load the marker, writing a fresh one if there is none.
381    ///
382    /// Persisting immediately matters: `first_start_unix` is what the shed hold counts
383    /// from, and a marker that is only written at the first phase change would reset that
384    /// clock on every restart before then, so a node that restarts more often than the
385    /// hold would never become eligible to shed and never finish migrating.
386    pub fn load_or_create(root_dir: &Path, phase: MigrationPhase) -> Self {
387        let state = Self::load_or_new(root_dir, phase);
388        // Written whenever the disk does not already hold what this process is going to
389        // use, rather than only when there is no file at all. A marker that is present but
390        // could not be used is replaced in memory and was previously left on disk, so the
391        // next start read the same bad file and stamped `first_start_unix` afresh. That is
392        // precisely the reset this function exists to prevent, and it is worse than the
393        // one it does prevent: it repeats. Three ways in, all of them leaving a file that
394        // exists: a truncated or otherwise unparseable marker, one from a newer schema, and
395        // one whose clock is impossible and is corrected by `with_sane_clocks`.
396        //
397        // A node restarting more often than the shed hold then never becomes eligible to
398        // shed and never finishes migrating, and a node short of disk is exactly the node
399        // that restarts.
400        let raw = std::fs::read(state_path(root_dir)).ok();
401        let on_disk = raw
402            .as_deref()
403            .and_then(|bytes| serde_json::from_slice::<Self>(bytes).ok());
404        if on_disk.as_ref() == Some(&state) {
405            return state;
406        }
407        // The schema is read on its own, from the raw JSON, rather than taken from a
408        // successful parse into today's struct. A marker from a genuinely newer build is
409        // exactly the one least likely to parse into it: a phase this build has no name
410        // for, a field that changed type, a field that went away. Reading the schema only
411        // when the whole thing parses means the markers most worth keeping are the ones
412        // that would be written over.
413        let newer_schema = raw
414            .as_deref()
415            .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(bytes).ok())
416            .and_then(|value| value.get("schema").and_then(serde_json::Value::as_u64))
417            .filter(|schema| *schema > u64::from(STATE_SCHEMA));
418        if let Some(schema) = newer_schema {
419            let Some(kept) = free_kept_marker_path(root_dir, schema) else {
420                warn!(
421                    "A newer migration marker (schema {schema}) is here and every name to \
422                     keep it under is taken. Leaving it, which means the shed hold restarts \
423                     on every boot until it is dealt with"
424                );
425                return state;
426            };
427            if let Err(e) = std::fs::rename(state_path(root_dir), &kept) {
428                warn!(
429                    "Could not move the newer migration marker aside ({e}); leaving it, \
430                     which means the shed hold restarts on every boot until it is dealt with"
431                );
432                return state;
433            }
434            info!(
435                "Kept the newer migration marker as {} and started one this build can use",
436                kept.display()
437            );
438        }
439        if let Err(e) = state.save(root_dir) {
440            warn!("Could not write the migration marker: {e}");
441        }
442        state
443    }
444
445    /// Load the marker, or start a fresh one.
446    ///
447    /// An unreadable marker is replaced rather than fatal: it is a hint, and every fact
448    /// it holds is either recoverable or conservative to reset. Losing it restarts the
449    /// shed hold and the retirement clock, which delays a migration and never rushes one.
450    pub fn load_or_new(root_dir: &Path, phase: MigrationPhase) -> Self {
451        let path = state_path(root_dir);
452        let Ok(bytes) = std::fs::read(&path) else {
453            return Self::new(phase);
454        };
455        match serde_json::from_slice::<Self>(&bytes) {
456            Ok(state) if state.schema <= STATE_SCHEMA => state.with_sane_clocks(),
457            Ok(state) => {
458                warn!(
459                    "Migration marker {} was written by a newer build (schema {}); \
460                     starting a fresh one",
461                    path.display(),
462                    state.schema
463                );
464                Self::new(phase)
465            }
466            Err(e) => {
467                warn!(
468                    "Migration marker {} is unreadable ({e}); starting a fresh one. \
469                     The shed hold and retirement clock restart from now.",
470                    path.display()
471                );
472                Self::new(phase)
473            }
474        }
475    }
476
477    /// Persist the marker so a reader sees either the old content or the new.
478    ///
479    /// # Errors
480    ///
481    /// Returns [`Error::Storage`] if the marker cannot be written.
482    pub fn save(&self, root_dir: &Path) -> Result<()> {
483        let path = state_path(root_dir);
484        let bytes = serde_json::to_vec_pretty(self)
485            .map_err(|e| Error::Storage(format!("Failed to encode migration marker: {e}")))?;
486        crate::storage::file_store::write_file_durably(&path, &bytes)?;
487        debug!("Migration marker updated: phase {:?}", self.phase);
488        Ok(())
489    }
490
491    /// Replace timestamps that cannot be true with "now".
492    ///
493    /// Zero and future values both make a hold vacuous, and a node whose clock was not
494    /// yet synchronised at first boot writes zero without anyone tampering. Resetting to
495    /// now delays a migration, which is the safe direction.
496    #[must_use]
497    fn with_sane_clocks(mut self) -> Self {
498        let now = now_unix();
499        if self.first_start_unix == 0 || self.first_start_unix > now {
500            warn!("Migration marker has an implausible first-start time; restarting the hold");
501            self.first_start_unix = now;
502        }
503        self.committed_at_unix = self.committed_at_unix.map(|at| {
504            if at == 0 || at > now {
505                warn!("Migration marker has an implausible commit time; restarting the clock");
506                now
507            } else {
508                at
509            }
510        });
511        self
512    }
513
514    /// Whether the shed hold has elapsed.
515    #[must_use]
516    pub fn shed_hold_elapsed(&self, config: &MigrationConfig) -> bool {
517        let hold = config.shed_hold_hours.saturating_mul(3600);
518        now_unix().saturating_sub(self.first_start_unix) >= hold
519    }
520
521    /// Whether the retirement delay has elapsed since committing.
522    #[must_use]
523    pub fn retire_delay_elapsed(&self, config: &MigrationConfig) -> bool {
524        let Some(at) = self.committed_at_unix else {
525            return false;
526        };
527        let delay = config.effective_retire_delay_hours().saturating_mul(3600);
528        now_unix().saturating_sub(at) >= delay
529    }
530}
531
532/// A name to keep a newer marker under that nothing is using yet.
533///
534/// The plain `.schema-N` name is deterministic, so a node downgraded twice would otherwise
535/// write over the marker it kept the first time, or fail the rename and restart the hold on
536/// every boot. Returns `None` if every name is taken, which the caller reports rather than
537/// destroying anything.
538fn free_kept_marker_path(root_dir: &Path, schema: u64) -> Option<PathBuf> {
539    for attempt in 0..16u32 {
540        // Appended, not `with_extension`, which would replace the `.json` and leave a name
541        // that no longer says what the file is.
542        let mut candidate = state_path(root_dir).into_os_string();
543        candidate.push(format!(".schema-{schema}"));
544        if attempt > 0 {
545            candidate.push(format!(".{attempt}"));
546        }
547        let candidate = PathBuf::from(candidate);
548        // `symlink_metadata`, not `try_exists`. The latter follows links, so a dangling
549        // symbolic link at this name reads as nothing being there while `rename` would
550        // happily replace it. Anything at all, of any kind, means pick another name.
551        if std::fs::symlink_metadata(&candidate).is_err() {
552            return Some(candidate);
553        }
554    }
555    None
556}
557
558/// Path of the persisted marker.
559#[must_use]
560pub fn state_path(root_dir: &Path) -> PathBuf {
561    root_dir.join(MIGRATION_STATE_FILE)
562}
563
564/// Seconds since the Unix epoch, saturating at zero if the clock is before it.
565#[must_use]
566pub fn now_unix() -> u64 {
567    SystemTime::now()
568        .duration_since(UNIX_EPOCH)
569        .map_or(0, |d| d.as_secs())
570}
571
572/// A host-wide advisory lock that serialises migrations sharing one volume.
573///
574/// Twelve nodes on one 492 GiB volume each need roughly their live payload free to copy
575/// and each return rather more when they retire, so one at a time the host gains space
576/// and the queue accelerates. All twelve at once need twelve times the space and all
577/// twelve stall. The lock is taken non-blocking: a node that cannot get it simply waits
578/// for the next tick.
579///
580/// Where the lock file sits is `lock_path_for`'s decision (private, so this is not a
581/// link), and this doc used to describe
582/// a branch of it that a running node almost never reaches: the parent of the node root is
583/// the last resort, taken only when the root's own metadata cannot be read. What a node
584/// normally uses is the host's temporary directory keyed by the volume's device id, or the
585/// directory named by [`LOCK_DIR_ENV`] when one is set.
586///
587/// Which of those is right is a fact about the deployment that no node can check for
588/// itself, and getting it wrong is silent: every node takes a lock of its own and reports
589/// success. That is why the path is logged when the lock is taken, and why a host whose
590/// nodes do not share a `/tmp` has to be told where the lock lives.
591///
592/// The directory has to be one only the node's own user can write. A predictable path in a
593/// world-writable `/tmp` can be created and held by any local user, who could then keep
594/// every node on the host from ever migrating.
595#[derive(Debug)]
596pub struct VolumeLock {
597    /// The held file. Dropping it releases the lock.
598    file: std::fs::File,
599    /// Where it lives, for logging.
600    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
601    path: PathBuf,
602}
603
604/// The result of asking for the volume lock.
605pub enum LockAttempt {
606    /// This node has it.
607    Acquired(VolumeLock),
608    /// Another node on the volume is migrating. Wait.
609    Busy,
610    /// No lock is possible here at all, so proceed unserialised.
611    ///
612    /// Kept distinct from `Busy` because conflating the two silently strands any node
613    /// whose parent directory is not writable: it would wait forever for a lock nobody
614    /// holds.
615    Unavailable,
616}
617
618impl VolumeLock {
619    /// Try to take the lock for the volume hosting `root_dir`.
620    #[must_use]
621    pub fn try_acquire(root_dir: &Path, scope: Option<&Path>) -> LockAttempt {
622        use fs2::FileExt;
623        let path = scope.map_or_else(
624            || lock_path_for(root_dir),
625            |dir| dir.join("ant-migration.lock"),
626        );
627        let file = match std::fs::OpenOptions::new()
628            .write(true)
629            .create(true)
630            .truncate(false)
631            .open(&path)
632        {
633            Ok(f) => f,
634            Err(e) => {
635                warn!(
636                    "Could not create the migration lock at {}: {e}. This node will \
637                     migrate without serialising against others on the same volume, so \
638                     watch its free space.",
639                    path.display()
640                );
641                return LockAttempt::Unavailable;
642            }
643        };
644        match file.try_lock_exclusive() {
645            Ok(()) => {
646                // Info, not debug. Whether the lock is doing anything depends on whether
647                // the neighbours on this disk can see the same path, which is a deployment
648                // fact no node can check. Printing the path is what lets somebody answer it
649                // from a log rather than by reading a unit file.
650                info!("Took the volume migration lock at {}", path.display());
651                LockAttempt::Acquired(Self { file, path })
652            }
653            // Only contention means another node is migrating. Everything else, a
654            // filesystem that does not implement locking at all being the one that
655            // matters, is a lock this node will never get, and reporting it as contention
656            // would leave it waiting forever for a holder that does not exist.
657            Err(e) if is_lock_contention(&e) => LockAttempt::Busy,
658            Err(e) => {
659                warn!(
660                    "Could not lock {}: {e}. This node will migrate without serialising \
661                     against others on the same volume, so watch its free space.",
662                    path.display()
663                );
664                LockAttempt::Unavailable
665            }
666        }
667    }
668}
669
670/// Is this the error a lock held by someone else produces?
671fn is_lock_contention(e: &std::io::Error) -> bool {
672    e.kind() == std::io::ErrorKind::WouldBlock
673        || (e.raw_os_error().is_some()
674            && e.raw_os_error() == fs2::lock_contended_error().raw_os_error())
675}
676
677/// Where the lock for the volume hosting `root_dir` lives.
678///
679/// Keyed by the filesystem, not by the path. Two nodes on one host are configured with
680/// different roots by definition, so a lock beside the root serialises a node against
681/// nobody: `/srv/node-a/data` and `/srv/node-b/data` would take two different locks on one
682/// disk and copy at the same time, which is the case the lock exists to prevent.
683///
684/// The device id names the filesystem, and the host's temporary directory is somewhere
685/// every node on that host can reach. If the device cannot be read, this falls back to a
686/// lock beside the root: weaker, but never worse than having none.
687///
688/// **That last sentence is only true where the nodes share a `/tmp`.** Where they do not,
689/// each computes the same name in a filesystem of its own, every one of them takes it, and
690/// the lock serialises nothing while logging that it worked. `PrivateTmp=true` in a systemd
691/// unit does exactly that, and our own worker unit sets it. There is no way to tell from
692/// inside one process whether the `/tmp` it can see is the one its neighbours see, so this
693/// cannot be detected here and has to be configured: [`LOCK_DIR_ENV`] names a directory
694/// every node on the host can reach, and is consulted first.
695fn lock_path_for(root_dir: &Path) -> PathBuf {
696    lock_path_with(root_dir, std::env::var(LOCK_DIR_ENV).ok().as_deref())
697}
698
699/// The same decision, with the configured directory passed in rather than read.
700///
701/// Split so it can be tested without touching process-wide environment. A test that set
702/// `TMPDIR` to stage the private-`/tmp` case would change where every other test's
703/// `TempDir` lands, and then delete it underneath them: run in parallel that takes out
704/// dozens of unrelated tests with LMDB failures that look like anything but their cause.
705fn lock_path_with(root_dir: &Path, configured: Option<&str>) -> PathBuf {
706    // Before anything derived, because an operator who has set this knows something about
707    // the host that this function cannot find out.
708    if let Some(dir) = configured {
709        let dir = dir.trim();
710        if !dir.is_empty() {
711            return Path::new(dir).join("ant-migration.lock");
712        }
713    }
714    #[cfg(unix)]
715    {
716        use std::os::unix::fs::MetadataExt;
717        if let Ok(meta) = std::fs::metadata(root_dir) {
718            return std::env::temp_dir().join(format!("ant-migration-{}.lock", meta.dev()));
719        }
720    }
721    // Resolved first, because a relative root has no volume in it to read. Two nodes
722    // started from different working directories on one drive would otherwise each fall
723    // through to a lock beside their own root, which serialises neither against the other.
724    #[cfg(not(unix))]
725    let resolved = std::fs::canonicalize(root_dir).unwrap_or_else(|_| root_dir.to_path_buf());
726    #[cfg(not(unix))]
727    let root_dir = resolved.as_path();
728    // Off Unix, the volume root: the drive or share the path starts from. Not as precise
729    // as a device id, since a mount point below it belongs to another volume, but it
730    // groups the ordinary case of several nodes under one drive letter, which is what a
731    // lock beside each node's own root does not.
732    #[cfg(not(unix))]
733    {
734        use std::path::Component;
735        if let Some(Component::Prefix(prefix)) = root_dir.components().next() {
736            let key: String = prefix
737                .as_os_str()
738                .to_string_lossy()
739                .chars()
740                .filter(char::is_ascii_alphanumeric)
741                .collect();
742            if !key.is_empty() {
743                return std::env::temp_dir().join(format!("ant-migration-{key}.lock"));
744            }
745        }
746    }
747    root_dir
748        .parent()
749        .unwrap_or(root_dir)
750        .join("ant-migration.lock")
751}
752
753impl Drop for VolumeLock {
754    fn drop(&mut self) {
755        use fs2::FileExt;
756        if let Err(e) = FileExt::unlock(&self.file) {
757            debug!(
758                "Releasing the migration lock {} failed: {e}",
759                self.path.display()
760            );
761        }
762    }
763}
764
765/// Summary of what the copier moved during one pass.
766#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
767pub struct CopyReport {
768    /// Chunks copied into the file store.
769    pub copied: u64,
770    /// Bytes copied.
771    pub bytes: u64,
772    /// Keys skipped because the legacy bytes did not hash to their address, or were
773    /// larger than a chunk may be.
774    pub unusable: u64,
775    /// Keys that could not be copied for a reason that may clear on a later pass.
776    pub failed: u64,
777    /// Keys that had vanished from the legacy store between the scan and the copy.
778    pub vanished: u64,
779    /// Whether the pass stopped because free space reached the slack floor.
780    pub stopped_for_space: bool,
781}
782
783impl CopyReport {
784    /// Fold another pass into this one.
785    pub fn merge(&mut self, other: Self) {
786        self.copied += other.copied;
787        self.bytes += other.bytes;
788        self.unusable += other.unusable;
789        self.failed += other.failed;
790        self.vanished += other.vanished;
791        self.stopped_for_space |= other.stopped_for_space;
792    }
793}
794
795/// How many waves a close group is divided into, so that at most
796/// [`CONCURRENT_MIGRATIONS_PER_GROUP`] of it are giving chunks up at once.
797#[must_use]
798pub fn migration_wave_count(close_group_size: usize) -> u64 {
799    let group = close_group_size.max(1) as u64;
800    let per_wave = CONCURRENT_MIGRATIONS_PER_GROUP.max(1) as u64;
801    group.div_ceil(per_wave).max(1)
802}
803
804/// Which wave this node belongs to, derived from its own ID.
805///
806/// Deterministic and needs no coordination, which is the point: a node cannot ask its
807/// close group "are you migrating?" without a protocol change, and the answer would be
808/// stale by the time it arrived. Hashing the peer ID spreads the members of any group
809/// across the waves without anybody agreeing on anything.
810///
811/// It is a stagger, not a guarantee. Seven IDs hashed into four waves will not always land
812/// two, two, two, one. What makes it safe rather than merely tidy is that it composes with
813/// the possession gate: a node whose turn has come still cannot give a chunk up until its
814/// neighbours have proven they hold it, so an unlucky wave waits instead of over-shedding.
815#[must_use]
816pub fn migration_wave_for(self_id: Option<&PeerId>, close_group_size: usize) -> u64 {
817    let waves = migration_wave_count(close_group_size);
818    let Some(peer) = self_id else {
819        return 0;
820    };
821    let digest = blake3::hash(&[MIGRATION_WAVE_DOMAIN, peer.as_bytes().as_slice()].concat());
822    let mut head = [0u8; 8];
823    head.copy_from_slice(digest.as_bytes().get(..8).unwrap_or(&[0u8; 8]));
824    u64::from_le_bytes(head) % waves
825}
826
827/// Domain separator so the wave assignment cannot be confused with any other use of a
828/// hashed peer ID.
829const MIGRATION_WAVE_DOMAIN: &[u8] = b"ant-node/storage-migration-wave/v1";
830
831/// Whether this node's wave has opened yet.
832///
833/// Wave `w` opens `w * wave_hours` after this build first started on this node. A node
834/// that has room for everything never consults this: it copies and retires without ever
835/// being unable to serve, so it is not part of the problem the waves exist to solve.
836#[must_use]
837pub fn wave_has_opened(state: &MigrationState, config: &MigrationConfig, wave: u64) -> bool {
838    now_unix() >= wave_opens_at(state, config, wave)
839}
840
841/// When a given wave opens, in Unix seconds.
842///
843/// Measured from the END of the shed hold, not from first start. Measured from the start
844/// the two settings cancel each other out: with a 72 hour hold and 24 hour waves, waves
845/// would open at 0, 24, 48 and 72 hours while nothing at all may shed until hour 72, so
846/// every wave would be open the moment the first one could act and the whole close group
847/// would migrate together. That is the pile-up the waves exist to prevent.
848#[must_use]
849pub fn wave_opens_at(state: &MigrationState, config: &MigrationConfig, wave: u64) -> u64 {
850    state
851        .first_start_unix
852        .saturating_add(config.shed_hold_hours.saturating_mul(3600))
853        .saturating_add(wave.saturating_mul(config.wave_hours.saturating_mul(3600)))
854}
855
856/// Order keys closest-first by XOR distance from this node.
857///
858/// Shedding walks this list from the far end, so the keys a node gives up are the ones it
859/// is furthest from, and therefore the ones its close group covers best.
860#[must_use]
861pub fn rank_closest_first(mut keys: Vec<XorName>, self_xor: Option<XorName>) -> Vec<XorName> {
862    let Some(me) = self_xor else {
863        // No identity available (devnet, unit tests). Ascending key order is stable and
864        // deterministic, which is all the copier needs.
865        keys.sort_unstable();
866        return keys;
867    };
868    keys.sort_unstable_by_key(|k| crate::client::xor_distance(k, &me));
869    keys
870}
871
872/// Structured field marking every line the fleet gate for R3 is read from.
873///
874/// R3 ships when the fleet shows migrations have finished, so these lines have to be
875/// queryable rather than merely readable. One field name, three values.
876pub const MIGRATION_EVENT: &str = "migration_event";
877
878/// Log the operator-facing summary of a completed migration.
879///
880/// `freed_bytes` is what the retired environment held, which is what the deletion running
881/// in the background will return. The line that says the space is actually back is
882/// `migration_event = "space_returned"`, emitted by that deletion when it finishes. Two
883/// lines rather than one because the deletion of a large environment takes minutes, and a
884/// node that reports the disk back before it is back is a node whose operator cannot tell
885/// a slow deletion from a failed one.
886pub fn log_migration_complete(kept: u64, shed: u64, freed_bytes: u64) {
887    #[allow(clippy::cast_precision_loss)] // display only
888    let freed_gib = freed_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
889    if shed == 0 {
890        info!(
891            migration_event = "complete",
892            kept,
893            shed,
894            freed_bytes,
895            "Storage migration complete: {kept} chunks now in the file store, nothing shed, \
896             {freed_gib:.2} GiB being returned to the filesystem"
897        );
898    } else {
899        info!(
900            migration_event = "complete",
901            kept,
902            shed,
903            freed_bytes,
904            "Storage migration complete: kept {kept} chunks, shed {shed} that would not fit, \
905             {freed_gib:.2} GiB being returned to the filesystem. The shed keys are the ones this \
906             node was furthest from; replication will refetch what still belongs here now \
907             that there is room."
908        );
909    }
910}
911
912// ────────────────────────────────────────────────────────────────────────────
913// The driver
914// ────────────────────────────────────────────────────────────────────────────
915
916/// How many positions from the end of the admission group a node may give up.
917///
918/// A chunk has exactly one holder at each rank, so restricting shedding to the last two
919/// positions means only two of its holders ever consider dropping it, and the staged
920/// rollout brings that to one. Without this rule the property is only statistical:
921/// every holder could be short of space at once, each shed the same chunk, and the
922/// per-volume lock would not know, because it serialises one volume and this is a
923/// network-wide question.
924///
925/// Measured against [`storage_admission_width`], not the close group, so the migration is
926/// never more willing to drop a chunk than the pruner is. The pruner treats the wider
927/// group as strictly in-range and refuses to delete inside it; shedding ranks that the
928/// pruner protects would make a one-off migration weaker than the thing that runs every
929/// day.
930pub const SHEDDABLE_TAIL_RANKS: usize = 2;
931
932/// How many nodes of one close group may be giving chunks up at the same time.
933///
934/// The close group is the unit that matters, not the volume and not the fleet. If every
935/// holder of a chunk migrates at once, none of them can prove to the others that a copy
936/// survives, and the whole group deadlocks waiting on each other. Holding it to two means
937/// the other five are steady, can answer possession challenges, and are still serving the
938/// chunk while the two rebuild.
939pub const CONCURRENT_MIGRATIONS_PER_GROUP: usize = 2;
940
941/// How many keys a refusal names, so the log stays readable.
942const REFUSAL_SAMPLE: usize = 4;
943
944/// How recently a peer must have published a commitment to be trusted as a holder.
945///
946/// Commitments rotate hourly and are gossiped on the neighbour-sync cadence, so a peer
947/// that has not published one for this long is not simply quiet: it has either stopped
948/// speaking the protocol or retired its commitment and not yet rotated a new one. The
949/// second is exactly what a node in the middle of its own migration looks like, and
950/// counting it as a holder is how two migrating nodes could each conclude the other was
951/// covering the chunk.
952const COMMITMENT_FRESHNESS: Duration = Duration::from_hours(2);
953
954/// How many keys one possession round asks about.
955///
956/// The round batches by peer, so this bounds the size of a single request rather than the
957/// number of requests.
958const POSSESSION_BATCH_KEYS: usize = 256;
959
960/// How long to wait before re-evaluating a shed decision that was refused.
961const SHED_REEVALUATION_INTERVAL: Duration = Duration::from_mins(10);
962
963/// How many copied chunks between operator-facing progress lines.
964const PROGRESS_LOG_EVERY: usize = 500;
965
966/// How long a clean pre-retirement verification stays usable.
967///
968/// Chunks written since the pass were content-checked on the way in and flushed, so the
969/// only thing the window exposes is bit rot in the last half hour, which is the ordinary
970/// risk of any file and is caught on read.
971const VERIFICATION_REUSE_WINDOW: Duration = Duration::from_mins(30);
972
973/// The network facts the driver needs, kept behind one type so the store itself stays
974/// free of any knowledge of routing or commitments.
975pub struct MigrationContext {
976    /// Routing, for close-group rank and possession checks. `None` in devnet and tests.
977    pub p2p: Option<Arc<P2PNode>>,
978    /// This node's peer ID.
979    pub self_id: Option<PeerId>,
980    /// This node's address in the key space, for ordering the copy closest-first.
981    pub self_xor: Option<XorName>,
982    /// The responder commitment state, which owns the retention contract.
983    pub commitment: Option<Arc<crate::replication::commitment_state::ResponderCommitmentState>>,
984    /// Replication settings, for the possession round that gates shedding.
985    pub replication: Option<Arc<ReplicationConfig>>,
986    /// Neighbour-sync state, which the possession challenge needs.
987    pub sync_state: Option<Arc<tokio::sync::RwLock<crate::replication::types::NeighborSyncState>>>,
988    /// Coordinator for the possession challenges.
989    pub audit_challenge_coordinator:
990        Option<Arc<crate::replication::audit_coordinator::AuditChallengeCoordinator>>,
991    /// What this node last heard each peer commit to.
992    ///
993    /// Used to require that a peer trusted to hold a chunk is currently publishing a
994    /// claim, rather than sitting between a retired commitment and its next rotation,
995    /// which is precisely the state a node in the middle of its own migration is in.
996    pub peer_commitments: Option<
997        Arc<
998            tokio::sync::RwLock<
999                HashMap<PeerId, crate::replication::commitment_state::PeerCommitmentRecord>,
1000            >,
1001        >,
1002    >,
1003    /// Close-group width.
1004    pub close_group_size: usize,
1005}
1006
1007/// How many of the peers auditing this node now have seen its reduced commitment.
1008///
1009/// `received` is who was sent the current root, `current` is the close group as routing
1010/// sees it at this moment. Only the overlap counts. A peer that received the root and has
1011/// since left is not going to audit this node, and a peer that has since joined has never
1012/// seen the root, so neither is evidence that shedding is safe.
1013fn enough_of_the_group_knows(
1014    received: &HashSet<PeerId>,
1015    current: &[PeerId],
1016    needed: usize,
1017) -> bool {
1018    if needed == 0 {
1019        return false;
1020    }
1021    current.iter().filter(|p| received.contains(*p)).count() >= needed
1022}
1023
1024impl MigrationContext {
1025    /// How many peers of the close group must have seen the reduced commitment.
1026    ///
1027    /// The same tolerance the pruner applies to possession proofs: all of them for a group
1028    /// of one or two, one short of the group otherwise, so a single unreachable peer
1029    /// cannot veto the migration forever without accepting an uninformed close group.
1030    #[must_use]
1031    pub fn commitment_recipients_needed(&self) -> usize {
1032        prune_proofs_needed(self.close_group_size.saturating_sub(1))
1033    }
1034
1035    /// Have enough of this node's close group actually received its reduced commitment?
1036    ///
1037    /// A rotation is not the same as neighbours knowing. Until they have seen the smaller
1038    /// key set they keep auditing against the one this node used to hold, so giving a
1039    /// chunk up before then turns a legitimate migration into a wave of audit failures.
1040    pub async fn neighbours_know_the_commitment(&self) -> bool {
1041        let needed = self.commitment_recipients_needed();
1042        if needed == 0 {
1043            return false;
1044        }
1045        let Some(state) = self.commitment.as_ref() else {
1046            return false;
1047        };
1048        let received = state.current_delivered_peers();
1049        if received.is_empty() {
1050            return false;
1051        }
1052        // Counted against the group as it stands now, not as it stood when the root went
1053        // out. A peer that has since left knowing this node's reduced commitment says
1054        // nothing about the peers that will actually audit it, and letting a departed
1055        // peer satisfy the gate is how a node gives chunks up while its real neighbours
1056        // still hold it to the larger key set.
1057        let Some(current) = self.current_close_group().await else {
1058            return false;
1059        };
1060        enough_of_the_group_knows(&received, &current, needed)
1061    }
1062
1063    /// This node's close group as routing sees it now, or `None` if the view is too thin
1064    /// to be evidence about a group at all.
1065    async fn current_close_group(&self) -> Option<Vec<PeerId>> {
1066        let (Some(p2p), Some(me), Some(self_xor)) = (
1067            self.p2p.as_ref(),
1068            self.self_id.as_ref(),
1069            self.self_xor.as_ref(),
1070        ) else {
1071            return None;
1072        };
1073        // Self-inclusive, then self filtered out. The self-excluding call would return
1074        // `close_group_size` *remote* peers, one more than the group actually has, and the
1075        // threshold is computed from a group that includes this node. Four real
1076        // neighbours plus one peer outside the group would then clear a bar meant to
1077        // require five real ones.
1078        let closest = p2p
1079            .dht_manager()
1080            .find_closest_nodes_local_with_self(self_xor, self.close_group_size)
1081            .await;
1082        let peers: Vec<PeerId> = closest
1083            .iter()
1084            .map(|n| n.peer_id)
1085            .filter(|p| p != me)
1086            .collect();
1087        if peers.len() + 1 < self.close_group_size {
1088            return None;
1089        }
1090        Some(peers)
1091    }
1092
1093    /// Is this key still answerable under a retained commitment slot?
1094    ///
1095    /// This is the pruner's existing veto, reused verbatim: a key the node could still
1096    /// be challenged on must not lose its last local copy.
1097    #[must_use]
1098    pub fn still_answerable(&self, key: &XorName) -> bool {
1099        self.commitment
1100            .as_ref()
1101            .is_some_and(|state| state.is_held(key))
1102    }
1103
1104    /// The width this node measures ranks against: the admission group, not the close
1105    /// group.
1106    #[must_use]
1107    pub fn shed_width(&self) -> usize {
1108        storage_admission_width(self.close_group_size)
1109    }
1110
1111    /// This node's position in `key`'s admission group.
1112    pub async fn close_group_rank(&self, key: &XorName) -> GroupRank {
1113        let (Some(p2p), Some(me)) = (self.p2p.as_ref(), self.self_id.as_ref()) else {
1114            return GroupRank::Unknown;
1115        };
1116        let closest = p2p
1117            .dht_manager()
1118            .find_closest_nodes_local_with_self(key, self.shed_width())
1119            .await;
1120        closest
1121            .iter()
1122            .position(|n| n.peer_id == *me)
1123            .map_or(GroupRank::Outside, GroupRank::Inside)
1124    }
1125
1126    /// May this node give up `key` without risking its last replica?
1127    ///
1128    /// Only if it is outside the admission group entirely, or sits in that group's last
1129    /// [`SHEDDABLE_TAIL_RANKS`] positions. Never when the answer is unknown.
1130    pub async fn may_shed(&self, key: &XorName) -> bool {
1131        rank_is_sheddable(self.close_group_rank(key).await, self.shed_width())
1132    }
1133}
1134
1135/// Where this node sits in a key's admission group.
1136///
1137/// `Unknown` is deliberately distinct from `Outside`. Collapsing the two would turn "this
1138/// node has no routing table to consult" into "no other node is closer", which is a
1139/// licence to give up every chunk on no evidence whatsoever.
1140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1141pub enum GroupRank {
1142    /// This node is at this position, counting from the closest.
1143    Inside(usize),
1144    /// This node is not among the closest for this key.
1145    Outside,
1146    /// Routing state is unavailable, so the question cannot be answered.
1147    Unknown,
1148}
1149
1150/// Which of `keys` this node has no proof anyone else is holding.
1151///
1152/// This is the gate on giving a chunk up at all, and it is deliberately the **same**
1153/// evidence the pruner demands before it deletes: cryptographic possession proofs from
1154/// all but one of the key's current close group, which is six of seven at
1155/// production width.
1156///
1157/// Rank alone was not enough. Being far from a chunk says something about who *should*
1158/// hold it, not about who *does*, and during a fleet-wide migration the nodes that should
1159/// hold it are exactly the ones that may also be short of space. Nor is the cheap
1160/// `VerificationRequest` enough: it carries a self-reported `present: bool`, and a node
1161/// that has silently lost a chunk still answers yes. The challenge here makes a peer
1162/// return a digest over a nonce it has never seen, which it cannot do without the bytes.
1163///
1164/// Returns the keys that failed, so the caller can name them. An empty result means every
1165/// key asked about is proven to live somewhere else.
1166///
1167/// Without routing state, every key is unconfirmed: no view of the network is no evidence.
1168pub async fn unconfirmed_by_neighbours(
1169    store: &Arc<ChunkStore>,
1170    context: &MigrationContext,
1171    keys: &[XorName],
1172) -> Vec<XorName> {
1173    let (Some(p2p), Some(self_id), Some(config), Some(sync_state), Some(coordinator)) = (
1174        context.p2p.as_ref(),
1175        context.self_id.as_ref(),
1176        context.replication.as_ref(),
1177        context.sync_state.as_ref(),
1178        context.audit_challenge_coordinator.as_ref(),
1179    ) else {
1180        return keys.to_vec();
1181    };
1182
1183    let local_key_count =
1184        usize::try_from(store.current_chunks().unwrap_or(0)).unwrap_or(usize::MAX);
1185    let dht = p2p.dht_manager();
1186    let mut unconfirmed = Vec::new();
1187
1188    for batch in keys.chunks(POSSESSION_BATCH_KEYS) {
1189        // Ask only the peers that are currently closest to each key. A proof from a peer
1190        // that has since moved out of the group is not evidence the chunk will stay there.
1191        let mut targets_by_key: HashMap<XorName, Vec<PeerId>> = HashMap::new();
1192        let mut keys_by_peer: HashMap<PeerId, Vec<XorName>> = HashMap::new();
1193        for key in batch {
1194            // Self-inclusive, matching the pruner, whose evidence this is. The
1195            // self-excluding call returns one peer more than the key's group holds, and a
1196            // proof from a peer outside it is not evidence the chunk stays in it.
1197            let closest = dht
1198                .find_closest_nodes_local_with_self(key, config.close_group_size)
1199                .await;
1200            let peers: Vec<PeerId> = closest
1201                .iter()
1202                .map(|n| n.peer_id)
1203                .filter(|p| p != self_id)
1204                .collect();
1205            for peer in &peers {
1206                keys_by_peer.entry(*peer).or_default().push(*key);
1207            }
1208            targets_by_key.insert(*key, peers);
1209        }
1210
1211        let proofs = prove_peers_hold_records(
1212            &keys_by_peer,
1213            local_key_count,
1214            store,
1215            p2p,
1216            config,
1217            sync_state,
1218            coordinator,
1219        )
1220        .await;
1221
1222        // A proof is necessary but not sufficient. The peer must also be currently
1223        // publishing a commitment, so a node that has retired its own and not yet rotated
1224        // a replacement, which is what a node mid-migration looks like, is not counted as
1225        // the reason this node may give a chunk up.
1226        let publishing = peers_publishing_a_recent_commitment(context).await;
1227
1228        for key in batch {
1229            let group = targets_by_key.get(key).map_or(&[][..], Vec::as_slice);
1230
1231            // The lookup is self-inclusive, and this node is giving the chunk up, so a
1232            // full group is `close_group_size` peers none of which is this node. Fewer
1233            // than that is a routing view too thin to be evidence about the group at all,
1234            // which is what a table looks like shortly after a restart. This node still
1235            // appearing in the group means it is not outside it after all, and the
1236            // decision to give the chunk up was taken against a view that has since
1237            // changed.
1238            if group.len() < config.close_group_size {
1239                unconfirmed.push(*key);
1240                continue;
1241            }
1242
1243            // The threshold comes from the configured group size, never from whichever
1244            // subset happens to qualify, nor from however many peers routing returned.
1245            // Deriving it from the filtered list is how two last holders destroy a chunk
1246            // between them: each sees only the other publishing, so each needs exactly one
1247            // proof, each gets it from the other, and both delete. Deriving it from the
1248            // observed length is the same mistake more quietly: a view that has lost a
1249            // peer lowers the bar exactly when it should not be trusted.
1250            let needed = prune_proofs_needed(config.close_group_size);
1251            let qualifying: Vec<PeerId> = group
1252                .iter()
1253                .filter(|p| publishing.contains(*p))
1254                .copied()
1255                .collect();
1256            if !target_peers_reported_present(key, &qualifying, &proofs, needed) {
1257                unconfirmed.push(*key);
1258            }
1259        }
1260    }
1261    unconfirmed
1262}
1263
1264/// The peers this node has heard a commitment from recently enough to trust as holders.
1265async fn peers_publishing_a_recent_commitment(context: &MigrationContext) -> HashSet<PeerId> {
1266    let Some(records) = context.peer_commitments.as_ref() else {
1267        return HashSet::new();
1268    };
1269    records
1270        .read()
1271        .await
1272        .iter()
1273        .filter(|(_, record)| {
1274            record.last_commitment().is_some()
1275                && record.received_at.elapsed() < COMMITMENT_FRESHNESS
1276        })
1277        .map(|(peer, _)| *peer)
1278        .collect()
1279}
1280
1281/// Whether a position in the admission group may be given up.
1282///
1283/// Split out from the routing lookup so the rule itself is testable without a network.
1284/// `width` is [`storage_admission_width`], not the close-group size: a key this node is
1285/// outside the admission group for is one the pruner would delete anyway, and inside it
1286/// only the last [`SHEDDABLE_TAIL_RANKS`] positions may go.
1287#[must_use]
1288pub fn rank_is_sheddable(rank: GroupRank, width: usize) -> bool {
1289    // A group no wider than the tail has no tail to give up. Saturating alone would set
1290    // the threshold to zero and make every member sheddable, which is the opposite of
1291    // what a narrow group needs.
1292    let protected_below = if width <= SHEDDABLE_TAIL_RANKS {
1293        width
1294    } else {
1295        width - SHEDDABLE_TAIL_RANKS
1296    };
1297    match rank {
1298        // No routing to ask. Never a licence: a node with no view of the network has no
1299        // grounds at all for believing anyone else holds the chunk.
1300        GroupRank::Unknown => false,
1301        GroupRank::Outside => true,
1302        GroupRank::Inside(rank) => rank >= protected_below,
1303    }
1304}
1305
1306/// Whether this store needs a migration driver at all.
1307///
1308/// The single predicate both the spawn site and its test use, so "should this node be
1309/// migrating" cannot be answered one way by the wiring and another way by what checks it.
1310#[must_use]
1311pub fn should_migrate(store: &Arc<ChunkStore>) -> bool {
1312    // Or has a removal to finish, or has something at the environment's path it could not
1313    // open. A node whose retirement was interrupted has no handle and nothing left to
1314    // copy, but its disk has not come back. A node whose environment is a link to storage
1315    // that was not mounted at startup has neither, and its chunks come back when the
1316    // storage does; without a driver it would stay blind to them until a restart.
1317    store.has_legacy() || store.has_cleanup_pending() || store.legacy_dir_is_on_disk()
1318}
1319
1320/// Runs the migration to completion, then returns.
1321///
1322/// Everything it does is idempotent and derived from the filesystem, so a crash at any
1323/// point costs at most the work of one tick.
1324pub async fn run(store: Arc<ChunkStore>, context: MigrationContext, shutdown: CancellationToken) {
1325    let config = store.migration_config().clone();
1326    if !worth_starting(&store, &config) {
1327        return;
1328    }
1329
1330    let tick = Duration::from_secs(config.tick_secs.max(1));
1331    let mut volume_lock: Option<VolumeLock> = None;
1332    let mut held = LockHold::default();
1333    let mut next_shed_evaluation = Instant::now();
1334    let mut next_handle_recovery = Instant::now();
1335    // A clean verification is a full re-read of everything both stores hold. If
1336    // retirement is then deferred (a read still holds the legacy handle), re-hashing on
1337    // every tick would be minutes of disk for nothing, so a recent pass is reused.
1338    let mut verified: Option<(VerifyReport, Instant)> = None;
1339
1340    loop {
1341        tokio::select! {
1342            () = shutdown.cancelled() => {
1343                debug!("Storage migration stopping for shutdown");
1344                return;
1345            }
1346            () = tokio::time::sleep(tick) => {}
1347        }
1348
1349        // Never hold the volume against the rest of the machine for longer than this,
1350        // whatever the node is waiting on. Dropping it costs a tick: if nobody else wants
1351        // it, the branches below take it straight back.
1352        if held.has_overstayed() {
1353            debug!(
1354                "Held the volume migration lock for {} hour(s); giving it back so any \
1355                 other node on this volume gets a turn",
1356                MAX_VOLUME_LOCK_HOLD.as_secs() / 3600
1357            );
1358            volume_lock = None;
1359            held.give_up();
1360        }
1361
1362        // Cleanup first. It can put an unmarked directory back under the live name, and
1363        // recovery is what gives the node a handle to it; the other order leaves that
1364        // until the next tick, and the completion check in between would see no handle
1365        // and no pending cleanup and call the migration finished.
1366        let cleanup = cleanup_state(&store);
1367        // Before anything reads the key set: a write that nobody waited for leaves a
1368        // note behind, and only the disk can say what became of it.
1369        store.reconcile_pending_writes().await;
1370        maybe_recover_lost_handle(&store, &mut next_handle_recovery).await;
1371        if cleanup == CleanupState::Finished && !store.has_legacy() {
1372            info!("Storage migration finished; nothing left on disk to clean up");
1373            return;
1374        }
1375
1376        match store.migration_phase() {
1377            // Nothing left to migrate. Whether there is anything left to clean up is
1378            // decided at the top of the loop, which is also where this returns from.
1379            MigrationPhase::FilesOnly => {
1380                volume_lock = None;
1381                held.released();
1382            }
1383            MigrationPhase::Bridging => {
1384                // Held from the first copy through retirement, not released in between:
1385                // a node that let go after copying would let its eleven neighbours start
1386                // theirs before it had returned a byte, which is the exact pile-up the
1387                // lock exists to prevent. The one exception is a node that has become
1388                // permanently stuck (see below), which must not go on excluding the
1389                // others for a release.
1390                if matches!(
1391                    take_volume_lock(
1392                        &mut volume_lock,
1393                        &mut held,
1394                        store.root_dir(),
1395                        config.lock_dir.as_deref(),
1396                    ),
1397                    LockStep::WaitATick
1398                ) {
1399                    continue;
1400                }
1401                if bridge_tick(
1402                    &store,
1403                    &context,
1404                    &config,
1405                    &mut next_shed_evaluation,
1406                    &shutdown,
1407                )
1408                .await
1409                {
1410                    // The copier ran. That is the volume lock being used rather than held.
1411                    held.note_disk_work();
1412                } else {
1413                    // Copying is blocked on something only an operator can change, so
1414                    // stop holding the volume lock against the other nodes here.
1415                    volume_lock = None;
1416                    held.released();
1417                }
1418            }
1419            MigrationPhase::Committed => {
1420                // A node that restarted in this phase has no lock, and the work below
1421                // (copying anything that must be kept, then re-reading the whole store to
1422                // verify it) is exactly the disk-heavy work the lock exists to serialise.
1423                if matches!(
1424                    take_volume_lock(
1425                        &mut volume_lock,
1426                        &mut held,
1427                        store.root_dir(),
1428                        config.lock_dir.as_deref(),
1429                    ),
1430                    LockStep::WaitATick
1431                ) {
1432                    continue;
1433                }
1434                match retire_tick(&store, &context, &config, &mut verified, &shutdown).await {
1435                    // Not a return. The environment is gone from the node's point of
1436                    // view, but its directory is still being deleted in the background,
1437                    // and if that fails there has to be something left to try again. The
1438                    // loop exits at the top once nothing is pending.
1439                    RetireOutcome::Done => {
1440                        volume_lock = None;
1441                        held.released();
1442                    }
1443                    // Time spent reading or copying is the volume lock doing its job, not
1444                    // a node sitting on it. The cap is there for a node that waits, and
1445                    // restarting a full verification because a large store took longer
1446                    // than the cap would be the cap causing the problem it prevents.
1447                    RetireOutcome::Working => held.note_disk_work(),
1448                    RetireOutcome::Waiting => {}
1449                    RetireOutcome::NoWorkToSerialise => {
1450                        // Nothing this node can do will return space, so holding the
1451                        // volume lock only stops its neighbours from trying. In R1, where
1452                        // retirement is switched off entirely, holding it would mean one
1453                        // node per volume copies and the other eleven do nothing for the
1454                        // whole release.
1455                        volume_lock = None;
1456                        held.released();
1457                    }
1458                }
1459            }
1460        }
1461    }
1462}
1463
1464/// Should the driver run at all, and say why in the log if not?
1465fn worth_starting(store: &Arc<ChunkStore>, config: &MigrationConfig) -> bool {
1466    if !config.enabled {
1467        warn!(
1468            "Storage migration is disabled. This node will keep reading both stores and \
1469             will never return the legacy environment's disk space."
1470        );
1471        return false;
1472    }
1473    // The same question the spawn site asks. A different one here means a driver that is
1474    // started and then returns immediately, which is how a node whose environment is a
1475    // link to storage that was not mounted yet ends up never picking it up.
1476    if !should_migrate(store) {
1477        debug!("No legacy chunk environment; nothing to migrate");
1478        return false;
1479    }
1480
1481    let to_copy = store.legacy_only_keys().len();
1482    info!(
1483        migration_event = "start",
1484        to_copy,
1485        legacy_bytes = store.legacy_bytes(),
1486        "Storage migration starting: {to_copy} chunk(s) still only in the legacy \
1487         environment, {:.2} GiB to reclaim",
1488        bytes_to_gib(store.legacy_bytes())
1489    );
1490    true
1491}
1492
1493/// Retry any removal that did not finish, and say whether the driver is done.
1494///
1495/// Runs independently of the phase. A removal that could not finish leaves nothing to
1496/// migrate but a disk that has not come back, and the reasons it failed (a name already
1497/// taken, a directory that could not be flushed, a scanner holding a handle) are the kind
1498/// that clear on their own.
1499fn cleanup_state(store: &Arc<ChunkStore>) -> CleanupState {
1500    if store.has_cleanup_pending() {
1501        store.retry_cleanup();
1502    }
1503    if store.has_cleanup_pending() || store.legacy_dir_is_on_disk() {
1504        return CleanupState::Pending;
1505    }
1506    CleanupState::Finished
1507}
1508
1509/// Whether anything is left on disk for the driver to see through.
1510#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1511enum CleanupState {
1512    /// Something is still there.
1513    Pending,
1514    /// Nothing is.
1515    Finished,
1516}
1517
1518/// Put a lost legacy handle back, if there is one to put back.
1519///
1520/// A node that lost its handle to an environment still on disk cannot read the chunks that
1521/// live only there. The cause is usually transient, so this runs every tick rather than
1522/// leaving the node half-blind until somebody restarts it.
1523async fn maybe_recover_lost_handle(store: &Arc<ChunkStore>, next_attempt: &mut Instant) {
1524    if Instant::now() < *next_attempt {
1525        return;
1526    }
1527    if store.recover_lost_legacy_handle().await {
1528        info!("Reopened the legacy chunk environment; the migration continues");
1529        *next_attempt = Instant::now();
1530        return;
1531    }
1532    // Backed off, because each attempt scans the whole environment and a cause that has
1533    // not cleared in half a minute is unlikely to clear in the next.
1534    *next_attempt = Instant::now() + HANDLE_RECOVERY_INTERVAL;
1535}
1536
1537/// How long this node has had the volume migration lock, and when it may ask again.
1538///
1539/// Split out because the rule is easy to get wrong in one branch and not another: a
1540/// branch that takes the lock without recording when, or that gives it up without a
1541/// cooldown, silently opts out of the cap that stops one node holding a whole machine.
1542#[derive(Default)]
1543struct LockHold {
1544    /// When the lock was taken, or when it was last used for real disk work.
1545    since: Option<Instant>,
1546    /// Before this, do not ask for it again.
1547    cooldown_until: Option<Instant>,
1548}
1549
1550impl LockHold {
1551    /// Record that the lock has just been taken.
1552    fn taken(&mut self) {
1553        self.since = Some(Instant::now());
1554    }
1555
1556    /// Record that it is no longer held.
1557    fn released(&mut self) {
1558        self.since = None;
1559    }
1560
1561    /// Record that this tick used the lock for what it is for.
1562    ///
1563    /// Copying and verifying are the exclusive disk work the lock exists to serialise, so
1564    /// time spent on them is not time spent sitting on it. Without this a node with a
1565    /// large store would have the cap fire in the middle of a verification pass and
1566    /// restart it, which is the cap causing the problem it prevents.
1567    fn note_disk_work(&mut self) {
1568        self.since = Some(Instant::now());
1569    }
1570
1571    /// Has this node held the lock past the cap without using it?
1572    fn has_overstayed(&self) -> bool {
1573        self.since
1574            .is_some_and(|at| at.elapsed() >= MAX_VOLUME_LOCK_HOLD)
1575    }
1576
1577    /// Give the lock up and stand back so somebody else can take it.
1578    fn give_up(&mut self) {
1579        self.since = None;
1580        self.cooldown_until = Some(Instant::now() + VOLUME_LOCK_COOLDOWN);
1581    }
1582
1583    /// May this node ask for the lock yet?
1584    fn may_ask(&self) -> bool {
1585        self.cooldown_until
1586            .is_none_or(|until| Instant::now() >= until)
1587    }
1588}
1589
1590/// What taking the volume lock produced for the driver loop.
1591enum LockStep {
1592    /// Held, or not needed because none is possible here.
1593    Proceed,
1594    /// Someone else has it. Try again next tick.
1595    WaitATick,
1596}
1597
1598/// Take the volume lock if it is not already held, stamping when it was taken.
1599///
1600/// One place, because the stamp is what stops a node holding the volume against every
1601/// other node on the machine, and a branch that acquires without stamping silently opts
1602/// out of that.
1603fn take_volume_lock(
1604    lock: &mut Option<VolumeLock>,
1605    held: &mut LockHold,
1606    root_dir: &Path,
1607    scope: Option<&Path>,
1608) -> LockStep {
1609    if lock.is_some() {
1610        return LockStep::Proceed;
1611    }
1612    // After giving the volume up at the cap, stand back for a moment. Reacquiring in the
1613    // same breath would hand nobody anything.
1614    if !held.may_ask() {
1615        return LockStep::WaitATick;
1616    }
1617    match VolumeLock::try_acquire(root_dir, scope) {
1618        LockAttempt::Acquired(taken) => {
1619            *lock = Some(taken);
1620            held.taken();
1621            LockStep::Proceed
1622        }
1623        LockAttempt::Busy => {
1624            debug!("Another node on this volume is migrating; waiting");
1625            LockStep::WaitATick
1626        }
1627        // No lock is possible here, so waiting for one would strand this node
1628        // permanently. Proceed; the slack floor is the backstop.
1629        LockAttempt::Unavailable => LockStep::Proceed,
1630    }
1631}
1632
1633/// One pass of the copier. Returns `false` when this node cannot make progress that
1634/// needs the volume to itself.
1635async fn bridge_tick(
1636    store: &Arc<ChunkStore>,
1637    context: &MigrationContext,
1638    config: &MigrationConfig,
1639    next_shed_evaluation: &mut Instant,
1640    shutdown: &CancellationToken,
1641) -> bool {
1642    let remaining = store.legacy_only_keys();
1643    if remaining.is_empty() {
1644        if let Err(e) = store.commit_to_files() {
1645            // Not progress, and not something exclusive disk access fixes. Saying it was
1646            // would reset the hold cap every tick and let this node keep the volume from
1647            // every other node on the machine for as long as the failure lasts.
1648            warn!(
1649                "Everything is copied but the migration commitment could not be recorded: \
1650                 {e}. Retrying on the next tick."
1651            );
1652            return false;
1653        }
1654        return true;
1655    }
1656
1657    let ordered = rank_closest_first(remaining, context.self_xor);
1658    let batch: Vec<XorName> = ordered
1659        .into_iter()
1660        .take(config.batch_chunks.max(1))
1661        .collect();
1662    let report = match store
1663        .copy_batch(
1664            &batch,
1665            config.copier_slack_bytes(),
1666            config.copier_throttle_mib_per_sec,
1667            shutdown,
1668        )
1669        .await
1670    {
1671        Ok(report) => report,
1672        Err(e) => {
1673            // Still retried every tick, but the volume lock goes back: if this is
1674            // permanent, holding it would block every other node on the volume on a node
1675            // that is getting nowhere.
1676            warn!("Storage migration copy failed: {e}. Retrying on the next tick.");
1677            return false;
1678        }
1679    };
1680
1681    if report.copied > 0 {
1682        debug!(
1683            "Storage migration copied {} chunk(s) ({:.2} GiB) this pass",
1684            report.copied,
1685            bytes_to_gib(report.bytes)
1686        );
1687        // A migration runs for hours. One periodic line at info level is what an operator
1688        // watching a node actually sees, and what says the copier has not silently stalled.
1689        let left = store.legacy_only_keys().len();
1690        if left % PROGRESS_LOG_EVERY < usize::try_from(report.copied).unwrap_or(usize::MAX) {
1691            let no_rollback = store.writes_without_a_rollback_copy();
1692            info!(
1693                migration_event = "progress",
1694                remaining = left,
1695                no_rollback_copy = no_rollback,
1696                "Storage migration: {left} chunk(s) left to copy out of the legacy \
1697                 environment, {no_rollback} write(s) made without a rollback copy"
1698            );
1699        }
1700    }
1701    if report.unusable > 0 {
1702        warn!(
1703            "{} chunk(s) in the legacy environment did not match their own address and \
1704             were dropped from the key set",
1705            report.unusable
1706        );
1707    }
1708
1709    if report.stopped_for_space {
1710        // Out of space. Whatever happens next, this node is not going to write more until
1711        // something changes, so it stops excluding its neighbours from the volume. That
1712        // covers the 72-hour shed hold as well as an outright refusal: holding the lock
1713        // for three days would leave every other node on the volume unmigrated.
1714        if Instant::now() < *next_shed_evaluation {
1715            return false;
1716        }
1717        *next_shed_evaluation = Instant::now() + SHED_REEVALUATION_INTERVAL;
1718        return evaluate_shed(store, context, config).await;
1719    }
1720    true
1721}
1722
1723/// Decide whether the node may give up what it could not copy.
1724async fn evaluate_shed(
1725    store: &Arc<ChunkStore>,
1726    context: &MigrationContext,
1727    config: &MigrationConfig,
1728) -> bool {
1729    let remaining = store.legacy_only_keys();
1730    let short_by = remaining.len();
1731
1732    // Read from the one switch the auditors read, not from a second copy of it. There
1733    // used to be two constants of the same name with two environment overrides, one on
1734    // each side of this decision, and nothing coupling them: a node could have been
1735    // willing to shed while every peer was still applying the full penalty, which is the
1736    // exact outcome the release ordering exists to prevent.
1737    if !crate::replication::config::close_group_storage_penalty_suspended() {
1738        warn!(
1739            "This node cannot fit {short_by} chunk(s) in the file store, but this release \
1740             has audit penalties switched back on, so giving anything up now would be \
1741             penalised by every peer. Keeping both stores. Add disk, or migrate this node \
1742             on a build that still suspends penalties."
1743        );
1744        return false;
1745    }
1746
1747    if !config.allow_shed {
1748        warn!(
1749            "This node cannot fit {short_by} chunk(s) in the file store and shedding is \
1750             turned off. Add disk, or set storage.migration.allow_shed. Until then it \
1751             keeps serving from both stores and the legacy environment stays."
1752        );
1753        return false;
1754    }
1755
1756    let state = store.migration_state();
1757
1758    // Wait for this node's turn. A close group is split into waves so at most
1759    // CONCURRENT_MIGRATIONS_PER_GROUP of it are giving chunks up at once; if all seven
1760    // holders went together, none could prove to the others that a copy survived and the
1761    // whole group would sit deadlocked waiting on each other. Only nodes that have to give
1762    // something up wait: a node with room has already copied everything and retired.
1763    let wave = migration_wave_for(context.self_id.as_ref(), context.close_group_size);
1764    if !wave_has_opened(&state, config, wave) {
1765        info!(
1766            "This node is {short_by} chunk(s) short of disk and is in migration wave {wave} \
1767             of {}. Its turn opens {} hour(s) after this build first started, so the rest of \
1768             its close group stays steady and can keep serving what it is about to give up.",
1769            migration_wave_count(context.close_group_size),
1770            config
1771                .shed_hold_hours
1772                .saturating_add(wave.saturating_mul(config.wave_hours))
1773        );
1774        return false;
1775    }
1776
1777    // Kept as its own check even though the wave now starts after it: the hold is about
1778    // peers on an older build still applying the penalty, the wave is about the close
1779    // group being able to cover for whoever moves. Different reasons, both required.
1780    if !state.shed_hold_elapsed(config) {
1781        info!(
1782            "This node is {short_by} chunk(s) short of disk. Holding for {} hour(s) after \
1783             first start before giving any up, so peers still on an older build have \
1784             upgraded and stopped penalising a shed.",
1785            config.shed_hold_hours
1786        );
1787        return false;
1788    }
1789
1790    // First filter, and the cheap one: a node never gives up a chunk it is near the front
1791    // of the group for. In practice it rarely fires, by construction, because the copier
1792    // walks closest-first, so whatever is left when the disk fills is the far end of the
1793    // list. Finding a protected key still uncopied means the node could not fit even the
1794    // chunks it is closest to, which is exactly when it must not shed anything.
1795    let mut protected = Vec::new();
1796    for key in &remaining {
1797        if !context.may_shed(key).await {
1798            protected.push(*key);
1799            if protected.len() >= REFUSAL_SAMPLE {
1800                break;
1801            }
1802        }
1803    }
1804    if !protected.is_empty() {
1805        let sample: Vec<String> = protected.iter().map(hex::encode).collect();
1806        warn!(
1807            "This node is {short_by} chunk(s) short of disk, and at least {} of them are \
1808             chunks it is near the front of the group for (for example {}). It will not \
1809             give those up. The legacy environment stays and its disk is not returned \
1810             until storage is added.",
1811            protected.len(),
1812            sample.join(", ")
1813        );
1814        return false;
1815    }
1816
1817    // Second filter, and the one that decides it: proof that somebody else holds every
1818    // chunk this node is about to give up. Being far from a chunk is not evidence
1819    // that a copy exists. During a fleet-wide migration the nodes that ought to hold it
1820    // are exactly the ones that may also be out of disk, so the question has to be asked
1821    // rather than inferred.
1822    info!(
1823        "Checking that other nodes hold the {short_by} chunk(s) this node cannot fit, \
1824         before giving any of them up"
1825    );
1826    let unconfirmed = unconfirmed_by_neighbours(store, context, &remaining).await;
1827    if !unconfirmed.is_empty() {
1828        let sample: Vec<String> = unconfirmed
1829            .iter()
1830            .take(REFUSAL_SAMPLE)
1831            .map(hex::encode)
1832            .collect();
1833        warn!(
1834            "{} of the {short_by} chunk(s) this node cannot fit could not be proven to \
1835             exist anywhere else (for example {}). Nothing is given up and the legacy \
1836             environment stays. Add disk, or wait for replication to place them.",
1837            unconfirmed.len(),
1838            sample.join(", ")
1839        );
1840        return false;
1841    }
1842
1843    info!(
1844        migration_event = "shed",
1845        shed = short_by,
1846        "Every one of the {short_by} chunk(s) this node cannot fit is proven to be held \
1847         elsewhere. Committing to what it can hold. They stay readable from the legacy \
1848         environment until it is removed, and replication refetches whatever still belongs \
1849         here once there is room."
1850    );
1851    if let Err(e) = store.commit_to_files() {
1852        warn!("Could not record the migration commitment: {e}");
1853        return false;
1854    }
1855    true
1856}
1857
1858/// The keys still only in the legacy store that this node is too close to give up.
1859async fn keys_this_node_must_not_give_up(
1860    store: &Arc<ChunkStore>,
1861    context: &MigrationContext,
1862) -> Vec<XorName> {
1863    let mut must_keep = Vec::new();
1864    for key in store.legacy_only_keys() {
1865        if !context.may_shed(&key).await {
1866            must_keep.push(key);
1867        }
1868    }
1869    must_keep
1870}
1871
1872/// Re-ask every network gate, after verification and immediately before the deletion.
1873///
1874/// Verification re-reads the whole store and can run for hours. A gate satisfied before it
1875/// started says nothing about the moment of deletion: peers leave, replicas are pruned
1876/// elsewhere, and a write whose file half failed adds a fresh legacy-only key that has
1877/// faced none of these checks. This is the last point at which the answer can still be
1878/// acted on, so it is the point at which it has to be true.
1879async fn every_gate_still_holds(
1880    store: &Arc<ChunkStore>,
1881    context: &MigrationContext,
1882    candidates: &std::collections::BTreeSet<XorName>,
1883) -> Option<RetireOutcome> {
1884    // A key that joined the legacy-only set since the snapshot was taken has been through
1885    // none of this. Stop now rather than asking the gates about a set that has already
1886    // moved; the next tick copies it and takes a fresh snapshot.
1887    let live: std::collections::BTreeSet<XorName> = store.legacy_only_keys().into_iter().collect();
1888    if live != *candidates {
1889        debug!(
1890            "Legacy environment not retired: the set changed while the gates were being \
1891             checked ({} keys then, {} now)",
1892            candidates.len(),
1893            live.len()
1894        );
1895        return Some(RetireOutcome::Waiting);
1896    }
1897    if !keys_this_node_must_not_give_up(store, context)
1898        .await
1899        .is_empty()
1900    {
1901        debug!("Legacy environment not retired: the shed rule changed during verification");
1902        return Some(RetireOutcome::Waiting);
1903    }
1904    if let Some(outcome) = shedding_is_still_safe(store, context, candidates).await {
1905        return Some(outcome);
1906    }
1907    // And the retention contract once more, for the same reason.
1908    if let Some(reason) = store.retirement_blocker(|k| context.still_answerable(k)) {
1909        debug!("Legacy environment not retired: {reason}");
1910        return Some(RetireOutcome::Waiting);
1911    }
1912    None
1913}
1914
1915/// The last two questions before anything is deleted, asked in this order because the
1916/// order is the safety argument: reduce the claim, let the group learn it, then give the
1917/// chunks up.
1918///
1919/// Returns `Some` with the reason to stop, or `None` when it is safe to proceed.
1920async fn shedding_is_still_safe(
1921    store: &Arc<ChunkStore>,
1922    context: &MigrationContext,
1923    shedding: &std::collections::BTreeSet<XorName>,
1924) -> Option<RetireOutcome> {
1925    // Nothing below is reached until the node has reduced its commitment (the phase
1926    // is `Committed`) and that reduction has been rebuilt and published. What remains
1927    // is to confirm the close group has actually *received* it, and that the chunks
1928    // being given up still exist elsewhere. Only then is anything deleted.
1929    if !shedding.is_empty() {
1930        // A rotation is not the same as neighbours knowing. Until they have the
1931        // smaller key set they keep auditing this node against the one it used to
1932        // hold, and a wave of audit failures is as damaging as losing the chunks.
1933        // Asked only when there is a commitment to deliver. A node whose file-backed set
1934        // is empty commits to nothing, so there is no hash for a neighbour to acknowledge
1935        // and this gate would never open, stranding its disk for good. Nothing is lost by
1936        // skipping it: the gate exists to stop neighbours auditing this node against a key
1937        // set it no longer holds, and a node claiming nothing cannot fail such an audit.
1938        // The possession check below, which proves every chunk being given up still exists
1939        // elsewhere, is the gate that protects the data, and it still runs.
1940        let commits_to_nothing = store
1941            .committable_keys()
1942            .await
1943            .is_ok_and(|keys| keys.is_empty());
1944        if commits_to_nothing {
1945            info!(
1946                "This node's file-backed set is empty, so it commits to nothing and has \
1947                 no reduced commitment for its close group to receive. Proceeding to the \
1948                 possession check on the {} chunk(s) it is giving up.",
1949                shedding.len()
1950            );
1951        } else if !context.neighbours_know_the_commitment().await {
1952            info!(
1953                "Holding: {} of this node's close group must receive its reduced \
1954                 commitment before it gives up {} chunk(s). {} have it so far.",
1955                context.commitment_recipients_needed(),
1956                shedding.len(),
1957                context
1958                    .commitment
1959                    .as_ref()
1960                    .map_or(0, |s| s.current_delivered_peer_count())
1961            );
1962            // Give the volume back while waiting on this. It is a network condition, not
1963            // a disk one, and it may never resolve: holding the lock through it would let
1964            // one node stop every other node on the machine from ever starting.
1965            return Some(RetireOutcome::NoWorkToSerialise);
1966        }
1967        // Asked again here, not only when the node committed. Hours pass in between,
1968        // the group moves, and a peer that held a copy then may not now. This is the
1969        // last moment at which the answer still matters.
1970        let ordered: Vec<XorName> = shedding.iter().copied().collect();
1971        let unconfirmed = unconfirmed_by_neighbours(store, context, &ordered).await;
1972        if !unconfirmed.is_empty() {
1973            let sample: Vec<String> = unconfirmed
1974                .iter()
1975                .take(REFUSAL_SAMPLE)
1976                .map(hex::encode)
1977                .collect();
1978            warn!(
1979                "{} of the {} chunk(s) this node is giving up can no longer be proven \
1980                 to exist elsewhere (for example {}). The legacy environment stays.",
1981                unconfirmed.len(),
1982                shedding.len(),
1983                sample.join(", ")
1984            );
1985            return Some(RetireOutcome::NoWorkToSerialise);
1986        }
1987    }
1988    None
1989}
1990
1991/// What one pass of the retirement gate concluded.
1992enum RetireOutcome {
1993    /// The legacy environment is gone. The driver is finished.
1994    Done,
1995    /// Exclusive disk work happened this tick: copying, or re-reading the store to verify
1996    /// it. Keep the volume, and count the time as time spent using it rather than time
1997    /// spent holding it.
1998    Working,
1999    /// Still working towards it, but waiting on a clock rather than on the disk. Keep the
2000    /// volume, because the node is about to need it, but let the hold cap run.
2001    Waiting,
2002    /// Blocked on something no amount of exclusive disk access will fix.
2003    NoWorkToSerialise,
2004}
2005
2006/// When this node last said out loud that its migration needs a person.
2007static LAST_OPERATOR_WARNING: parking_lot::Mutex<Option<Instant>> = parking_lot::Mutex::new(None);
2008
2009/// How often to repeat it. Often enough to be noticed, rarely enough not to drown the log.
2010const OPERATOR_WARNING_INTERVAL: Duration = Duration::from_hours(1);
2011
2012/// Should the "this needs a person" warning be repeated now?
2013///
2014/// The condition it reports is checked on every tick and does not clear on its own, so
2015/// without this it would be a line every thirty seconds for as long as the node runs.
2016fn operator_should_hear_again() -> bool {
2017    let mut last = LAST_OPERATOR_WARNING.lock();
2018    let now = Instant::now();
2019    if last.is_some_and(|at| now.duration_since(at) < OPERATOR_WARNING_INTERVAL) {
2020        return false;
2021    }
2022    *last = Some(now);
2023    true
2024}
2025
2026/// The retention contract, asked before anything else in the tick.
2027///
2028/// `Some` with what the driver should do, or `None` when nothing is in the way.
2029fn blocked_before_the_gates(
2030    store: &Arc<ChunkStore>,
2031    context: &MigrationContext,
2032    config: &MigrationConfig,
2033) -> Option<RetireOutcome> {
2034    let reason = store.retirement_blocker(|k| context.still_answerable(k))?;
2035    // Three blockers no amount of exclusive disk access will clear: an environment this
2036    // node cannot read, one it cannot classify at all, and one it must not delete because
2037    // it is a link to somewhere else. Each needs a person, so give the volume back to the
2038    // nodes that can use it and say so where an operator will see it rather than at debug.
2039    if store.has_lost_its_legacy_handle()
2040        || store.legacy_cannot_be_classified()
2041        || store.legacy_is_a_link()
2042    {
2043        if operator_should_hear_again() {
2044            warn!(
2045                migration_event = "needs_an_operator",
2046                "The legacy chunk environment will not be retired automatically: {reason}"
2047            );
2048        }
2049        return Some(RetireOutcome::NoWorkToSerialise);
2050    }
2051    debug!("Legacy environment not retired yet: {reason}");
2052    Some(if config.retire_legacy {
2053        RetireOutcome::Waiting
2054    } else {
2055        // Retirement is switched off on this node, so it will never free its disk here
2056        // however long it waits.
2057        RetireOutcome::NoWorkToSerialise
2058    })
2059}
2060
2061/// One pass of the retirement gate.
2062async fn retire_tick(
2063    store: &Arc<ChunkStore>,
2064    context: &MigrationContext,
2065    config: &MigrationConfig,
2066    verified: &mut Option<(VerifyReport, Instant)>,
2067    shutdown: &CancellationToken,
2068) -> RetireOutcome {
2069    if let Some(outcome) = blocked_before_the_gates(store, context, config) {
2070        return outcome;
2071    }
2072
2073    // Re-check the shed rule against live routing immediately before the destructive
2074    // step, not once when the node committed hours ago. Two things put a key back into
2075    // the legacy-only set after that decision: a file that failed verification and is now
2076    // served from the legacy copy, and a write whose file half failed. Neither went
2077    // through the rank check, and both would be thrown away by the removal below.
2078    let must_keep = keys_this_node_must_not_give_up(store, context).await;
2079    if !must_keep.is_empty() {
2080        warn!(
2081            "{} chunk(s) are still only in the legacy environment and this node is too \
2082             close to them to give them up. Copying them before anything is removed.",
2083            must_keep.len()
2084        );
2085        match store
2086            .copy_batch(
2087                &must_keep,
2088                config.copier_slack_bytes(),
2089                config.copier_throttle_mib_per_sec,
2090                shutdown,
2091            )
2092            .await
2093        {
2094            Ok(report) if report.stopped_for_space => {
2095                warn!(
2096                    "Out of disk while copying {} chunk(s) this node must not give up. \
2097                     The legacy environment stays until there is room for them.",
2098                    must_keep.len()
2099                );
2100                *verified = None;
2101                return RetireOutcome::NoWorkToSerialise;
2102            }
2103            Ok(_) => {}
2104            Err(e) => {
2105                warn!("Could not copy the chunks this node must keep: {e}");
2106                *verified = None;
2107                return RetireOutcome::NoWorkToSerialise;
2108            }
2109        }
2110        // Anything copied changed the file store, so a previous verification no longer
2111        // covers it.
2112        *verified = None;
2113        return RetireOutcome::Working;
2114    }
2115
2116    // The real report from a recent pass, never a fabricated one. Reuse deliberately does
2117    // NOT refresh the window: re-arming it from a reused proof would let a node that
2118    // keeps deferring retirement run the verification exactly once and coast on it.
2119    let reusable = verified
2120        .filter(|(_, at)| at.elapsed() < VERIFICATION_REUSE_WINDOW)
2121        .map(|(proof, _)| proof);
2122    let proof = match reusable {
2123        Some(proof) => proof,
2124        None => match store
2125            .verify_before_retire(config.copier_throttle_mib_per_sec, shutdown)
2126            .await
2127        {
2128            Ok(proof) => {
2129                if proof.is_clean() {
2130                    *verified = Some((proof, Instant::now()));
2131                }
2132                proof
2133            }
2134            Err(e) => {
2135                // A pass that failed is not progress, however quickly it failed, and
2136                // treating it as work would let a node whose store cannot be read hold
2137                // the volume against every other node on the machine for good.
2138                warn!("Pre-retirement verification failed: {e}. Retrying on the next tick.");
2139                return RetireOutcome::NoWorkToSerialise;
2140            }
2141        },
2142    };
2143    if !proof.is_clean() {
2144        *verified = None;
2145        warn!(
2146            "Pre-retirement verification found {} chunk(s) that are damaged in the file \
2147             store and cannot be repaired from the legacy environment. The legacy \
2148             environment stays.",
2149            proof.unrepairable()
2150        );
2151        return RetireOutcome::NoWorkToSerialise;
2152    }
2153
2154    // Snapshotted BEFORE the gates, not after. Every gate below is asked about exactly
2155    // this set, and exactly this set is what the removal is permitted to destroy. Taken
2156    // afterwards, a key that joined between the last gate and the snapshot would be
2157    // counted as approved having passed nothing, which is the case the gates exist for.
2158    let approved: std::collections::BTreeSet<XorName> =
2159        store.legacy_only_keys().into_iter().collect();
2160
2161    if let Some(outcome) = every_gate_still_holds(store, context, &approved).await {
2162        return outcome;
2163    }
2164
2165    let kept = store.current_chunks().unwrap_or(0);
2166    let shed = store.migration_state().shed_key_count;
2167    match store
2168        .retire_legacy(
2169            &proof,
2170            &|k: &XorName| context.still_answerable(k),
2171            &approved,
2172        )
2173        .await
2174    {
2175        Ok(freed) => {
2176            log_migration_complete(kept, shed, freed);
2177            RetireOutcome::Done
2178        }
2179        Err(e) => {
2180            debug!("Legacy environment not retired yet: {e}");
2181            RetireOutcome::Waiting
2182        }
2183    }
2184}
2185
2186/// Convert a byte count to GiB for human-readable log messages.
2187#[allow(clippy::cast_precision_loss)] // display only
2188#[cfg_attr(not(feature = "logging"), allow(dead_code))]
2189fn bytes_to_gib(bytes: u64) -> f64 {
2190    bytes as f64 / (1024.0 * 1024.0 * 1024.0)
2191}
2192
2193#[cfg(test)]
2194#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2195mod tests {
2196    use super::*;
2197    use serial_test::serial;
2198    use tempfile::TempDir;
2199
2200    fn peer_id(byte: u8) -> PeerId {
2201        let mut bytes = [0u8; 32];
2202        if let Some(slot) = bytes.first_mut() {
2203            *slot = byte;
2204        }
2205        PeerId::from_bytes(bytes)
2206    }
2207
2208    /// The width shedding is measured against: the admission group, not the close group.
2209    const WIDTH: usize = storage_admission_width(7);
2210
2211    #[test]
2212    fn shedding_is_measured_against_the_width_the_pruner_protects() {
2213        // The pruner treats the admission group (close group plus its margin) as strictly
2214        // in-range and refuses to delete inside it. A one-off migration must not be more
2215        // willing to drop a chunk than the thing that runs every day.
2216        assert_eq!(WIDTH, storage_admission_width(7));
2217        assert!(
2218            storage_admission_width(7) > 7,
2219            "the admission group is wider than the close group"
2220        );
2221        // A rank the close group would have called sheddable is protected here.
2222        assert!(!rank_is_sheddable(GroupRank::Inside(5), WIDTH));
2223        assert!(!rank_is_sheddable(GroupRank::Inside(6), WIDTH));
2224    }
2225
2226    #[test]
2227    fn a_node_never_gives_up_a_chunk_it_is_among_the_closest_to() {
2228        // This node is one of the closest for these ranks. Giving one of them up is the
2229        // case where every short-of-space holder could drop the same chunk and take its
2230        // last replica, so it is refused outright.
2231        for rank in 0..WIDTH - SHEDDABLE_TAIL_RANKS {
2232            assert!(
2233                !rank_is_sheddable(GroupRank::Inside(rank), WIDTH),
2234                "rank {rank} must be protected"
2235            );
2236        }
2237        // The last two positions may be given up: a chunk has exactly one holder at each,
2238        // so it is only ever a candidate for two of its holders.
2239        for rank in WIDTH - SHEDDABLE_TAIL_RANKS..WIDTH {
2240            assert!(
2241                rank_is_sheddable(GroupRank::Inside(rank), WIDTH),
2242                "rank {rank} is in the tail and may be shed"
2243            );
2244        }
2245        // Out of range entirely: nothing to protect.
2246        assert!(rank_is_sheddable(GroupRank::Outside, WIDTH));
2247        // No routing to consult is never a licence.
2248        assert!(!rank_is_sheddable(GroupRank::Unknown, WIDTH));
2249    }
2250
2251    #[test]
2252    fn a_group_narrower_than_the_tail_protects_everything_in_it() {
2253        // A group with no tail has nothing to give up. Subtracting saturatingly would put
2254        // the threshold at zero and make every member sheddable, which is exactly
2255        // backwards for the narrowest groups.
2256        assert!(!rank_is_sheddable(GroupRank::Inside(0), 2));
2257        assert!(!rank_is_sheddable(GroupRank::Inside(0), 1));
2258        assert!(!rank_is_sheddable(GroupRank::Inside(1), 2));
2259        // Out of the group entirely is still out.
2260        assert!(rank_is_sheddable(GroupRank::Outside, 2));
2261        // And a group with a tail still has one.
2262        assert!(!rank_is_sheddable(GroupRank::Inside(0), 3));
2263        assert!(rank_is_sheddable(GroupRank::Inside(1), 3));
2264    }
2265
2266    #[test]
2267    fn the_marker_round_trips_and_a_corrupt_one_starts_over_conservatively() {
2268        let dir = TempDir::new().expect("temp dir");
2269        let mut state = MigrationState::new(MigrationPhase::Bridging);
2270        state.phase = MigrationPhase::Committed;
2271        state.shed_key_count = 12;
2272        state.committed_at_unix = Some(1_700_000_000);
2273        state.save(dir.path()).expect("save");
2274
2275        let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
2276        assert_eq!(loaded.phase, MigrationPhase::Committed);
2277        assert_eq!(loaded.shed_key_count, 12);
2278        assert_eq!(loaded.committed_at_unix, Some(1_700_000_000));
2279
2280        // An unreadable marker restarts the clocks rather than being fatal. Losing it
2281        // delays a migration and can never rush one.
2282        std::fs::write(state_path(dir.path()), b"not json").expect("corrupt");
2283        let recovered = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
2284        assert_eq!(recovered.phase, MigrationPhase::Bridging);
2285        assert_eq!(recovered.committed_at_unix, None);
2286    }
2287
2288    #[test]
2289    fn the_shed_hold_and_retirement_clocks_run_from_recorded_times() {
2290        let config = MigrationConfig {
2291            shed_hold_hours: 72,
2292            retire_delay_hours: MIN_RETIRE_DELAY_HOURS,
2293            ..MigrationConfig::default()
2294        };
2295
2296        let mut state = MigrationState::new(MigrationPhase::Bridging);
2297        assert!(!state.shed_hold_elapsed(&config), "just started");
2298        state.first_start_unix = now_unix().saturating_sub(73 * 3600);
2299        assert!(state.shed_hold_elapsed(&config));
2300
2301        assert!(
2302            !state.retire_delay_elapsed(&config),
2303            "never committed, so the clock has not started"
2304        );
2305        state.committed_at_unix = Some(now_unix().saturating_sub(3600));
2306        assert!(!state.retire_delay_elapsed(&config), "an hour is not four");
2307        state.committed_at_unix =
2308            Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
2309        assert!(state.retire_delay_elapsed(&config));
2310    }
2311
2312    #[test]
2313    fn only_one_node_on_a_volume_migrates_at_a_time() {
2314        let volume = TempDir::new().expect("temp dir");
2315        let node_a = volume.path().join("node-a");
2316        let node_b = volume.path().join("node-b");
2317        std::fs::create_dir_all(&node_a).expect("mkdir");
2318        std::fs::create_dir_all(&node_b).expect("mkdir");
2319
2320        let LockAttempt::Acquired(held) = VolumeLock::try_acquire(&node_a, None) else {
2321            panic!("the first node must take the lock");
2322        };
2323        assert!(
2324            matches!(VolumeLock::try_acquire(&node_b, None), LockAttempt::Busy),
2325            "a second node on the same volume must be told to wait, not that no lock exists"
2326        );
2327
2328        drop(held);
2329        assert!(
2330            matches!(
2331                VolumeLock::try_acquire(&node_b, None),
2332                LockAttempt::Acquired(_)
2333            ),
2334            "and take it once the first is done"
2335        );
2336    }
2337
2338    /// Seed a real LMDB chunk store, the way a node upgrading into this build has one.
2339    async fn seed_legacy(root: &std::path::Path, count: u32) -> Vec<XorName> {
2340        let lmdb = crate::storage::LmdbStorage::new(crate::storage::LmdbStorageConfig {
2341            root_dir: root.to_path_buf(),
2342            verify_on_read: true,
2343            max_map_size: 0,
2344            disk_reserve: 0,
2345        })
2346        .await
2347        .expect("open legacy");
2348        let mut keys = Vec::new();
2349        for i in 0..count {
2350            let content = format!("legacy-chunk-{i}").into_bytes();
2351            let addr = crate::client::compute_address(&content);
2352            lmdb.put(&addr, &content).await.expect("legacy put");
2353            keys.push(addr);
2354        }
2355        lmdb.wait_idle().await;
2356        drop(lmdb);
2357        keys
2358    }
2359
2360    /// The whole point, end to end: a node that starts with an LMDB chunk store and a
2361    /// disk to hold it finishes with the chunks in files and the LMDB gone.
2362    ///
2363    /// Driven by `run`, the same entry point node startup calls, rather than by poking the
2364    /// pieces. That matters: the wiring that calls it went missing once and every test
2365    /// passed, because they all built the store directly and a node with no legacy store
2366    /// starts no migration.
2367    #[tokio::test]
2368    async fn a_node_with_room_copies_everything_and_removes_the_legacy_store() {
2369        const CHUNKS: u32 = 24;
2370
2371        let tmp = TempDir::new().expect("temp dir");
2372        // Nested, so the volume lock this node takes lives in its own directory rather
2373        // than one shared with every other test running in parallel.
2374        let root = tmp.path().join("node");
2375        std::fs::create_dir_all(&root).expect("mkdir");
2376        let keys = seed_legacy(&root, CHUNKS).await;
2377
2378        let mut config = crate::storage::ChunkStoreConfig {
2379            root_dir: root.clone(),
2380            ..crate::storage::ChunkStoreConfig::test_default()
2381        };
2382        // Deliberately NOT setting `retire_legacy`. The shipped default has to be what
2383        // carries this all the way to a removed environment, or the release migrates every
2384        // node and reclaims nothing.
2385        config.migration.tick_secs = 1;
2386        // Scoped to this test's own directory. In production the lock is keyed by the
2387        // filesystem, so without this every test on this machine would serialise against
2388        // every other one that runs a migration.
2389        config.migration.lock_dir = Some(root.clone());
2390        config.migration.copier_throttle_mib_per_sec = 0;
2391        let store = Arc::new(
2392            crate::storage::ChunkStore::new(config)
2393                .await
2394                .expect("open store"),
2395        );
2396
2397        // Precondition: everything is in the legacy store and nothing is in files.
2398        assert!(store.has_legacy(), "the node must start with an LMDB store");
2399        assert_eq!(store.migration_phase(), MigrationPhase::Bridging);
2400        assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
2401        assert!(root.join("chunks.mdb").exists());
2402
2403        let shutdown = CancellationToken::new();
2404        let driver = tokio::spawn(run(
2405            Arc::clone(&store),
2406            MigrationContext {
2407                p2p: None,
2408                self_id: None,
2409                self_xor: None,
2410                commitment: None,
2411                replication: None,
2412                sync_state: None,
2413                audit_challenge_coordinator: None,
2414                peer_commitments: None,
2415                close_group_size: 7,
2416            },
2417            shutdown.clone(),
2418        ));
2419
2420        // The copier runs on its own and settles once nothing is left only in the legacy
2421        // store. This node has room, so it sheds nothing and needs no network at all.
2422        wait_for(
2423            &store,
2424            MigrationPhase::Committed,
2425            "the copier should finish",
2426        )
2427        .await;
2428        assert!(
2429            store.legacy_only_keys().is_empty(),
2430            "every chunk should have been copied"
2431        );
2432
2433        // Stand in for the commitment builder, which lives in the replication engine: the
2434        // retirement gate wants the reduced commitment published and its window elapsed.
2435        store.note_commitment_rebuilt();
2436        store.note_commitment_rebuilt();
2437        store.force_migration_state(|s| {
2438            s.committed_at_unix =
2439                Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
2440        });
2441
2442        wait_for(
2443            &store,
2444            MigrationPhase::FilesOnly,
2445            "retirement should complete",
2446        )
2447        .await;
2448        shutdown.cancel();
2449        let _ = tokio::time::timeout(Duration::from_secs(10), driver).await;
2450
2451        // The point of the whole exercise: the LMDB is gone from the filesystem.
2452        assert!(
2453            !root.join("chunks.mdb").exists(),
2454            "the legacy store must be removed, which is the only moment disk comes back"
2455        );
2456        assert!(!store.has_legacy());
2457
2458        // And nothing was lost: every chunk still reads, now out of a file.
2459        assert_eq!(store.current_chunks().expect("count"), u64::from(CHUNKS));
2460        for (i, key) in keys.iter().enumerate() {
2461            let expected = format!("legacy-chunk-{i}").into_bytes();
2462            assert_eq!(
2463                store.get(key).await.expect("get").expect("present"),
2464                expected,
2465                "chunk {i} did not survive the migration"
2466            );
2467        }
2468
2469        // In files, under the suffix shard its address names.
2470        let sample = keys.first().copied().expect("a key");
2471        let path = root
2472            .join(crate::storage::file_store::CHUNKS_DIR_NAME)
2473            .join(format!("{:02x}", sample.last().copied().unwrap_or(0)))
2474            .join(hex::encode(sample));
2475        assert!(path.exists(), "expected a chunk file at {}", path.display());
2476    }
2477
2478    /// The other half: a node that cannot fit its chunks and cannot prove anyone else
2479    /// holds them keeps both stores and deletes nothing.
2480    ///
2481    /// This is the case that must fail safe. The node is out of disk, so it would like to
2482    /// give chunks up, but with no view of the network it cannot show a single one exists
2483    /// elsewhere. Refusing costs it disk. Proceeding would cost the network data.
2484    #[tokio::test]
2485    async fn a_node_that_cannot_prove_its_chunks_are_safe_deletes_nothing() {
2486        const CHUNKS: u32 = 8;
2487
2488        let tmp = TempDir::new().expect("temp dir");
2489        let root = tmp.path().join("node");
2490        std::fs::create_dir_all(&root).expect("mkdir");
2491        let keys = seed_legacy(&root, CHUNKS).await;
2492
2493        let mut config = crate::storage::ChunkStoreConfig {
2494            root_dir: root.clone(),
2495            // Nothing will fit: the copier stops for space on its first chunk.
2496            disk_reserve: u64::MAX / 2,
2497            ..crate::storage::ChunkStoreConfig::test_default()
2498        };
2499        config.migration.retire_legacy = true;
2500        config.migration.tick_secs = 1;
2501        // Scoped to this test's own directory. In production the lock is keyed by the
2502        // filesystem, so without this every test on this machine would serialise against
2503        // every other one that runs a migration.
2504        config.migration.lock_dir = Some(root.clone());
2505        // Elapsed, so the hold is not what is doing the refusing here.
2506        config.migration.shed_hold_hours = 0;
2507        config.migration.wave_hours = 0;
2508        let store = Arc::new(
2509            crate::storage::ChunkStore::new(config)
2510                .await
2511                .expect("open store"),
2512        );
2513        assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
2514
2515        let shutdown = CancellationToken::new();
2516        let driver = tokio::spawn(run(
2517            Arc::clone(&store),
2518            MigrationContext {
2519                p2p: None,
2520                self_id: None,
2521                self_xor: None,
2522                commitment: None,
2523                replication: None,
2524                sync_state: None,
2525                audit_challenge_coordinator: None,
2526                peer_commitments: None,
2527                close_group_size: 7,
2528            },
2529            shutdown.clone(),
2530        ));
2531
2532        // Give it long enough to have tried, re-tried, and evaluated shedding.
2533        tokio::time::sleep(Duration::from_secs(5)).await;
2534        shutdown.cancel();
2535        let _ = tokio::time::timeout(Duration::from_secs(10), driver).await;
2536
2537        assert_eq!(
2538            store.migration_phase(),
2539            MigrationPhase::Bridging,
2540            "a node that cannot prove its chunks are held elsewhere must not commit"
2541        );
2542        assert!(
2543            root.join("chunks.mdb").exists(),
2544            "and must not remove the only copy of them"
2545        );
2546        assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
2547        for (i, key) in keys.iter().enumerate() {
2548            assert_eq!(
2549                store.get(key).await.expect("get").expect("present"),
2550                format!("legacy-chunk-{i}").into_bytes(),
2551                "chunk {i} must still be served throughout"
2552            );
2553        }
2554    }
2555
2556    /// Poll until the store reaches `phase`, or fail with what it reached instead.
2557    ///
2558    /// The deadline is generous because it is measured on the wall clock while the driver
2559    /// it is waiting on runs on the runtime. On a saturated machine both stretch, and a
2560    /// deadline sized for the work rather than for the contention turns a slow build into
2561    /// a failing test. The work itself is two ticks.
2562    async fn wait_for(store: &Arc<crate::storage::ChunkStore>, phase: MigrationPhase, what: &str) {
2563        let deadline = std::time::Instant::now() + Duration::from_mins(3);
2564        while std::time::Instant::now() < deadline {
2565            if store.migration_phase() == phase {
2566                return;
2567            }
2568            tokio::time::sleep(Duration::from_millis(100)).await;
2569        }
2570        panic!(
2571            "{what}: still in {:?} after the deadline, expected {phase:?}",
2572            store.migration_phase()
2573        );
2574    }
2575
2576    /// A marker that cannot be used is replaced on disk, not just in memory.
2577    ///
2578    /// The shed hold counts from `first_start_unix`, and the whole reason this is written
2579    /// at startup rather than at the first phase change is that a marker written later
2580    /// would restart that clock on every reboot. A marker that is present but unusable used
2581    /// to defeat that: it was replaced in memory and left on disk, so every start read the
2582    /// same bad file and stamped a fresh clock. A node restarting more often than the hold
2583    /// would then never become eligible to shed and never finish migrating, which is the
2584    /// failure the doc comment on `load_or_create` names.
2585    #[test]
2586    fn an_unusable_marker_is_replaced_on_disk_so_the_hold_does_not_restart() {
2587        for (name, bad) in [
2588            ("truncated", br#"{"schema":1,"phase":"brid"#.to_vec()),
2589            ("not json at all", b"\x00\x01\x02".to_vec()),
2590            (
2591                "a newer schema",
2592                serde_json::json!({
2593                    "schema": 9_999,
2594                    "phase": "bridging",
2595                    "first_start_unix": 1,
2596                    "committed_at_unix": null,
2597                    "rebuilds_since_commit": 0,
2598                    "shed_key_count": 0,
2599                    "kept_key_count": 0,
2600                })
2601                .to_string()
2602                .into_bytes(),
2603            ),
2604            // The one most worth keeping, and the one a parse into today's struct cannot
2605            // read: a phase this build has no name for, and a field it does not know.
2606            (
2607                "a newer schema this build cannot parse at all",
2608                serde_json::json!({
2609                    "schema": 9_999,
2610                    "phase": "some_phase_from_the_future",
2611                    "first_start_unix": 1,
2612                    "something_this_build_never_heard_of": {"a": 1},
2613                })
2614                .to_string()
2615                .into_bytes(),
2616            ),
2617        ] {
2618            let dir = TempDir::new().expect("temp dir");
2619            std::fs::write(state_path(dir.path()), &bad).expect("plant the bad marker");
2620
2621            let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2622            let written = std::fs::read(state_path(dir.path())).expect("read it back");
2623            assert_ne!(written, bad, "{name}: the unusable marker was left on disk");
2624            if name.starts_with("a newer schema") {
2625                // Moved aside rather than destroyed: it was written on purpose by a build
2626                // that knew more than this one.
2627                let mut kept = state_path(dir.path()).into_os_string();
2628                kept.push(".schema-9999");
2629                let kept = PathBuf::from(kept);
2630                assert_eq!(
2631                    std::fs::read(&kept).expect("the newer marker must be kept"),
2632                    bad,
2633                    "the newer marker was written over rather than set aside"
2634                );
2635            }
2636
2637            // And the clock survives the next start, which is the point of all this.
2638            let second = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2639            assert_eq!(
2640                second.first_start_unix, first.first_start_unix,
2641                "{name}: the shed hold restarted on the next boot"
2642            );
2643        }
2644    }
2645
2646    /// A marker whose clock is impossible is corrected on disk too.
2647    ///
2648    /// `with_sane_clocks` fixes a future-dated marker for the process that read it. Left
2649    /// there, the same correction is made again on every start, from a new now each time,
2650    /// which is the same repeating reset by another route.
2651    #[test]
2652    fn a_future_dated_marker_is_corrected_on_disk_not_only_in_memory() {
2653        let dir = TempDir::new().expect("temp dir");
2654        let ahead = now_unix().saturating_add(60 * 60 * 24 * 365);
2655        let planted = serde_json::json!({
2656            "schema": 1,
2657            "phase": "bridging",
2658            "first_start_unix": ahead,
2659            "committed_at_unix": null,
2660            "rebuilds_since_commit": 0,
2661            "shed_key_count": 0,
2662            "kept_key_count": 0,
2663        })
2664        .to_string();
2665        std::fs::write(state_path(dir.path()), &planted).expect("plant it");
2666
2667        let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2668        assert!(
2669            first.first_start_unix < ahead,
2670            "the clock should have been brought back to something possible"
2671        );
2672
2673        let reread: MigrationState =
2674            serde_json::from_slice(&std::fs::read(state_path(dir.path())).expect("read"))
2675                .expect("the marker on disk must now parse");
2676        assert_eq!(
2677            reread.first_start_unix, first.first_start_unix,
2678            "the correction was made in memory and not written back"
2679        );
2680    }
2681
2682    /// A marker that is already right is not rewritten on every start.
2683    ///
2684    /// The counterpart to the two above: persisting on disagreement must not turn into
2685    /// persisting unconditionally, which would put a write on every node's start path for
2686    /// nothing.
2687    #[test]
2688    fn a_usable_marker_is_left_exactly_as_it_is() {
2689        let dir = TempDir::new().expect("temp dir");
2690        let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2691
2692        // Written back out by hand in a shape this build would never produce: the same
2693        // facts, different spacing and key order. Comparing the bytes of a marker this
2694        // build wrote against the bytes after a second start proves nothing, because an
2695        // unconditional rewrite produces the same bytes and the test passes either way.
2696        // Something semantically equal but textually different is the only thing that can
2697        // tell "left alone" from "written again".
2698        let noncanonical = format!(
2699            "{{\"kept_key_count\":{},\"shed_key_count\":{},\"rebuilds_since_commit\":{},\
2700             \"committed_at_unix\":null,\"first_start_unix\":{},\"phase\":\"bridging\",\
2701             \"schema\":{}}}",
2702            first.kept_key_count,
2703            first.shed_key_count,
2704            first.rebuilds_since_commit,
2705            first.first_start_unix,
2706            first.schema
2707        );
2708        std::fs::write(state_path(dir.path()), &noncanonical).expect("write");
2709
2710        MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2711        assert_eq!(
2712            std::fs::read_to_string(state_path(dir.path())).expect("read"),
2713            noncanonical,
2714            "a marker that already said the right thing was rewritten for no reason"
2715        );
2716    }
2717
2718    /// Two nodes on one disk take the same lock, and the override is what makes that true
2719    /// where they do not share a `/tmp`.
2720    ///
2721    /// `lock_path_for` had no coverage at all, which is how it came to be right in a way
2722    /// that is false on our own fleet: every shipped test sets `lock_dir` and so never
2723    /// calls it. What the lock is for is one node copying at a time on a shared disk, so
2724    /// what has to be true is that two different node roots on one volume produce one path.
2725    ///
2726    /// Nothing here touches process-wide environment. An earlier version of this test set
2727    /// `TMPDIR` to stage the private-`/tmp` case, which moved every other test's temporary
2728    /// directory and then deleted it underneath them: sixty-three unrelated tests failed
2729    /// with LMDB errors that pointed nowhere near the cause.
2730    #[test]
2731    fn nodes_on_one_volume_agree_on_a_lock_path_when_they_are_told_where_it_is() {
2732        let volume = TempDir::new().expect("temp dir");
2733        let a = volume.path().join("node-0");
2734        let b = volume.path().join("node-1");
2735        std::fs::create_dir_all(&a).expect("mkdir");
2736        std::fs::create_dir_all(&b).expect("mkdir");
2737
2738        // With no override and one shared temporary directory, which is the case the
2739        // default is right for: two roots on one volume, one lock.
2740        assert_eq!(
2741            lock_path_with(&a, None),
2742            lock_path_with(&b, None),
2743            "two roots on one volume must share a lock when they share a /tmp"
2744        );
2745
2746        // Where they do not share one, the default gives each node a lock of its own and
2747        // every one of them takes it. That is the deployment hazard, and it is why the
2748        // override exists rather than something the code can detect.
2749        assert_ne!(
2750            lock_path_with(&a, Some("/tmp/private-to-node-0")),
2751            lock_path_with(&b, Some("/tmp/private-to-node-1")),
2752            "different lock directories must give different locks, or the override would \
2753             not be able to express anything"
2754        );
2755
2756        // And told where it lives, both land on it whatever their own root is.
2757        let told = volume.path().to_string_lossy().into_owned();
2758        let shared_a = lock_path_with(&a, Some(&told));
2759        let shared_b = lock_path_with(&b, Some(&told));
2760        assert_eq!(
2761            shared_a, shared_b,
2762            "nodes told where the lock lives must all use it"
2763        );
2764        assert!(shared_a.starts_with(volume.path()), "and use the one named");
2765        assert_eq!(
2766            lock_path_with(&a, Some("   ")),
2767            lock_path_with(&a, None),
2768            "an empty setting is not a location and must not be treated as one"
2769        );
2770
2771        // And the lock itself then does its job across the two roots.
2772        let LockAttempt::Acquired(held) = VolumeLock::try_acquire(&a, Some(volume.path())) else {
2773            panic!("the first node must take it");
2774        };
2775        assert!(
2776            matches!(
2777                VolumeLock::try_acquire(&b, Some(volume.path())),
2778                LockAttempt::Busy
2779            ),
2780            "the second must wait rather than copy alongside it"
2781        );
2782        drop(held);
2783        assert!(matches!(
2784            VolumeLock::try_acquire(&b, Some(volume.path())),
2785            LockAttempt::Acquired(_)
2786        ));
2787    }
2788
2789    /// A lock directory that cannot be written is reported, not silently ignored.
2790    ///
2791    /// The override is a deployment fact, so a typo in it must not read as "no lock needed
2792    /// here". `Unavailable` is the honest answer and it already warns; what this pins is
2793    /// that a bad override does not quietly fall back to a path that would appear to work.
2794    #[test]
2795    fn a_lock_directory_that_does_not_exist_is_unavailable_rather_than_ignored() {
2796        let dir = TempDir::new().expect("temp dir");
2797        let missing = dir.path().join("no-such-directory");
2798        assert!(matches!(
2799            VolumeLock::try_acquire(dir.path(), Some(&missing)),
2800            LockAttempt::Unavailable
2801        ));
2802    }
2803
2804    #[tokio::test]
2805    async fn the_driver_exits_immediately_when_there_is_nothing_to_migrate() {
2806        // The whole feature hangs off `run` being reachable from node startup. A port that
2807        // dropped that call once already, and nothing caught it, because a fresh node has
2808        // no legacy environment and every test built one directly. This asserts the entry
2809        // point is callable and terminates on its own for a node with nothing to do.
2810        let dir = TempDir::new().expect("temp dir");
2811        let store = Arc::new(
2812            crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
2813                root_dir: dir.path().to_path_buf(),
2814                ..crate::storage::ChunkStoreConfig::test_default()
2815            })
2816            .await
2817            .expect("open store"),
2818        );
2819        assert!(!store.has_legacy());
2820
2821        let context = MigrationContext {
2822            p2p: None,
2823            self_id: None,
2824            self_xor: None,
2825            commitment: None,
2826            replication: None,
2827            sync_state: None,
2828            audit_challenge_coordinator: None,
2829            peer_commitments: None,
2830            close_group_size: 7,
2831        };
2832        tokio::time::timeout(
2833            Duration::from_secs(5),
2834            run(store, context, CancellationToken::new()),
2835        )
2836        .await
2837        .expect("the driver must return rather than idle when there is nothing to migrate");
2838    }
2839
2840    #[tokio::test]
2841    async fn a_node_with_no_view_of_the_network_gives_up_nothing() {
2842        // Every field is `None`, which is what a devnet or a node whose routing is not up
2843        // yet looks like. No view of the network is no evidence, and the answer has to be
2844        // "keep everything" rather than "nobody is closer, so give it all away".
2845        let dir = TempDir::new().expect("temp dir");
2846        let store = Arc::new(
2847            crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
2848                root_dir: dir.path().to_path_buf(),
2849                ..crate::storage::ChunkStoreConfig::test_default()
2850            })
2851            .await
2852            .expect("open store"),
2853        );
2854        let context = MigrationContext {
2855            p2p: None,
2856            self_id: None,
2857            self_xor: None,
2858            commitment: None,
2859            replication: None,
2860            sync_state: None,
2861            audit_challenge_coordinator: None,
2862            peer_commitments: None,
2863            close_group_size: 7,
2864        };
2865
2866        let keys = vec![[1u8; 32], [2u8; 32], [3u8; 32]];
2867        let unconfirmed = unconfirmed_by_neighbours(&store, &context, &keys).await;
2868        assert_eq!(
2869            unconfirmed, keys,
2870            "with no routing state every key must count as unproven"
2871        );
2872        for key in &keys {
2873            assert!(
2874                !context.may_shed(key).await,
2875                "and none of them may be given up"
2876            );
2877        }
2878    }
2879
2880    #[test]
2881    fn the_possession_threshold_comes_from_the_whole_group_not_the_qualifying_subset() {
2882        use crate::replication::pruning::{prune_proofs_needed, target_peers_reported_present};
2883        use std::collections::{HashMap, HashSet};
2884
2885        // Seven holders. Deriving the bar from whichever peers happen to qualify is how
2886        // two last holders destroy a chunk between them: each sees only the other
2887        // publishing, so each needs exactly one proof, each gets it from the other, and
2888        // both delete. The bar must come from the group.
2889        let key = [7u8; 32];
2890        let group: Vec<PeerId> = (0..6u8).map(peer_id).collect();
2891        let only_one_qualifies: Vec<PeerId> = group.iter().take(1).copied().collect();
2892
2893        // That one peer does answer the challenge.
2894        let mut proofs: HashMap<XorName, HashSet<PeerId>> = HashMap::new();
2895        proofs.insert(key, only_one_qualifies.iter().copied().collect());
2896
2897        // The dangerous reading: bar taken from the qualifying subset, so one is enough.
2898        assert!(
2899            target_peers_reported_present(
2900                &key,
2901                &only_one_qualifies,
2902                &proofs,
2903                prune_proofs_needed(only_one_qualifies.len()),
2904            ),
2905            "this is the mistake being guarded against, shown here to be a real risk"
2906        );
2907
2908        // The correct reading: bar taken from the whole group, so one is nowhere near.
2909        assert!(
2910            !target_peers_reported_present(
2911                &key,
2912                &only_one_qualifies,
2913                &proofs,
2914                prune_proofs_needed(group.len()),
2915            ),
2916            "one proof must never satisfy a group of six"
2917        );
2918
2919        // And with the whole group answering, it passes.
2920        proofs.insert(key, group.iter().copied().collect());
2921        assert!(target_peers_reported_present(
2922            &key,
2923            &group,
2924            &proofs,
2925            prune_proofs_needed(group.len()),
2926        ));
2927    }
2928
2929    #[test]
2930    #[serial]
2931    fn shedding_reads_the_same_switch_the_auditors_read() {
2932        use crate::replication::config::{
2933            close_group_storage_penalty_suspended, set_close_group_storage_penalty_suspended,
2934        };
2935        // One switch, not two. There used to be a second constant of the same name with
2936        // its own environment override on this side of the decision, and nothing coupling
2937        // them: a node could have been willing to shed while every peer still applied the
2938        // full penalty, which is precisely what the release ordering exists to prevent.
2939        set_close_group_storage_penalty_suspended(true);
2940        assert!(close_group_storage_penalty_suspended());
2941        set_close_group_storage_penalty_suspended(false);
2942        assert!(!close_group_storage_penalty_suspended());
2943        set_close_group_storage_penalty_suspended(
2944            crate::replication::config::RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY,
2945        );
2946    }
2947
2948    #[test]
2949    fn a_close_group_is_split_into_enough_waves_to_bound_concurrent_migrations() {
2950        // Seven holders, two at a time, is four waves.
2951        assert_eq!(migration_wave_count(7), 4);
2952        assert_eq!(migration_wave_count(2), 1);
2953        assert_eq!(migration_wave_count(1), 1);
2954        // A degenerate width must still yield a usable wave count rather than dividing by
2955        // zero or collapsing to "everyone at once".
2956        assert_eq!(migration_wave_count(0), 1);
2957    }
2958
2959    #[test]
2960    fn wave_assignment_is_stable_per_node_and_spread_across_the_group() {
2961        use std::collections::HashMap;
2962        let waves = migration_wave_count(7);
2963
2964        // The same node always gets the same wave: a restart must not move a node into a
2965        // turn that has already passed.
2966        let peer = peer_id(7);
2967        assert_eq!(
2968            migration_wave_for(Some(&peer), 7),
2969            migration_wave_for(Some(&peer), 7)
2970        );
2971
2972        // And across many nodes every wave is used, so the group is genuinely staggered
2973        // rather than all landing together.
2974        let mut counts: HashMap<u64, usize> = HashMap::new();
2975        for b in 0..=255u8 {
2976            let w = migration_wave_for(Some(&peer_id(b)), 7);
2977            assert!(w < waves, "wave {w} outside 0..{waves}");
2978            *counts.entry(w).or_default() += 1;
2979        }
2980        assert_eq!(
2981            counts.len() as u64,
2982            waves,
2983            "every wave should be occupied, got {counts:?}"
2984        );
2985    }
2986
2987    #[test]
2988    fn waves_are_actually_staggered_under_the_shipped_defaults() {
2989        // The combination is what matters, not either setting alone. Measured from first
2990        // start, a 72 hour hold and 24 hour waves cancel out: waves would open at 0, 24,
2991        // 48 and 72 hours while nothing may shed until 72, so every wave is open the
2992        // moment the first one can act and the whole close group moves together. Measured
2993        // from the end of the hold, they stagger as intended.
2994        let config = MigrationConfig::default();
2995        assert_eq!(config.shed_hold_hours, 72);
2996        assert_eq!(config.wave_hours, 24);
2997
2998        let mut state = MigrationState::new(MigrationPhase::Bridging);
2999        let waves = migration_wave_count(7);
3000        assert_eq!(waves, 4);
3001
3002        // Nothing is open before the hold ends.
3003        state.first_start_unix = now_unix();
3004        for w in 0..waves {
3005            assert!(
3006                !wave_has_opened(&state, &config, w),
3007                "wave {w} opened too early"
3008            );
3009        }
3010
3011        // At the end of the hold, exactly the first wave is open.
3012        state.first_start_unix = now_unix().saturating_sub(72 * 3600 + 60);
3013        assert!(wave_has_opened(&state, &config, 0));
3014        for w in 1..waves {
3015            assert!(
3016                !wave_has_opened(&state, &config, w),
3017                "wave {w} must wait its turn, or the group migrates together"
3018            );
3019        }
3020
3021        // Each later wave opens one wave_hours after the one before it.
3022        for open in 1..waves {
3023            state.first_start_unix = now_unix().saturating_sub((72 + open * 24) * 3600 + 60);
3024            for w in 0..=open {
3025                assert!(wave_has_opened(&state, &config, w));
3026            }
3027            for w in open + 1..waves {
3028                assert!(!wave_has_opened(&state, &config, w));
3029            }
3030        }
3031    }
3032
3033    #[test]
3034    fn an_implausible_clock_restarts_the_holds_rather_than_voiding_them() {
3035        let dir = TempDir::new().expect("temp dir");
3036        let config = MigrationConfig::default();
3037
3038        // Zero is what a node with an unsynchronised clock writes at first boot, and it
3039        // would make every hold vacuous. So would a time in the future.
3040        let mut state = MigrationState::new(MigrationPhase::Committed);
3041        state.first_start_unix = 0;
3042        state.committed_at_unix = Some(0);
3043        state.save(dir.path()).expect("save");
3044
3045        let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
3046        assert!(
3047            !loaded.shed_hold_elapsed(&config),
3048            "the hold must not be void"
3049        );
3050        assert!(!loaded.retire_delay_elapsed(&config));
3051
3052        let mut future = MigrationState::new(MigrationPhase::Committed);
3053        future.first_start_unix = now_unix().saturating_add(10 * 365 * 24 * 3600);
3054        future.committed_at_unix = Some(future.first_start_unix);
3055        future.save(dir.path()).expect("save");
3056        let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
3057        assert!(!loaded.shed_hold_elapsed(&config));
3058        assert!(!loaded.retire_delay_elapsed(&config));
3059    }
3060
3061    #[test]
3062    fn copy_reports_accumulate_across_passes() {
3063        let mut total = CopyReport::default();
3064        total.merge(CopyReport {
3065            copied: 3,
3066            bytes: 300,
3067            ..CopyReport::default()
3068        });
3069        total.merge(CopyReport {
3070            copied: 2,
3071            bytes: 200,
3072            unusable: 1,
3073            stopped_for_space: true,
3074            ..CopyReport::default()
3075        });
3076        assert_eq!(total.copied, 5);
3077        assert_eq!(total.bytes, 500);
3078        assert_eq!(total.unusable, 1);
3079        assert!(total.stopped_for_space);
3080    }
3081    /// A peer that received the commitment and then left the group is not evidence.
3082    ///
3083    /// It is not going to audit this node, so counting it lets a node give chunks up
3084    /// while the neighbours who will audit it still hold it to the old, larger key set.
3085    #[test]
3086    fn a_departed_peer_that_knows_the_commitment_does_not_open_the_gate() {
3087        let received: HashSet<PeerId> = (0..6).map(peer_id).collect();
3088        let still_here: Vec<PeerId> = (0..3).map(peer_id).collect();
3089        let joined_since: Vec<PeerId> = (100..103).map(peer_id).collect();
3090        let current: Vec<PeerId> = still_here
3091            .iter()
3092            .chain(joined_since.iter())
3093            .copied()
3094            .collect();
3095
3096        // Six peers know it and the group is six wide, so a count that ignores who is
3097        // actually here would sail past the threshold.
3098        assert_eq!(received.len(), 6);
3099        assert_eq!(current.len(), 6);
3100        assert!(!enough_of_the_group_knows(&received, &current, 5));
3101
3102        // Only the three that are both here and informed count.
3103        assert!(enough_of_the_group_knows(&received, &current, 3));
3104        assert!(!enough_of_the_group_knows(&received, &current, 4));
3105    }
3106
3107    #[test]
3108    fn a_group_that_has_all_seen_the_commitment_opens_the_gate() {
3109        let group: Vec<PeerId> = (0..6).map(peer_id).collect();
3110        let received: HashSet<PeerId> = group.iter().copied().collect();
3111        assert!(enough_of_the_group_knows(&received, &group, 5));
3112    }
3113
3114    #[test]
3115    fn no_peer_ever_satisfies_a_zero_threshold() {
3116        let group: Vec<PeerId> = (0..6).map(peer_id).collect();
3117        let received: HashSet<PeerId> = group.iter().copied().collect();
3118        // A group this node cannot reason about must not be read as unanimous consent.
3119        assert!(!enough_of_the_group_knows(&received, &group, 0));
3120    }
3121
3122    /// The gate stays shut when routing cannot show a full close group at all.
3123    ///
3124    /// Without a routing view there is no way to tell an informed neighbour from a
3125    /// departed one, and an unanswerable question must not read as a yes.
3126    #[tokio::test]
3127    async fn without_a_routing_view_the_commitment_gate_stays_shut() {
3128        let context = MigrationContext {
3129            p2p: None,
3130            self_id: None,
3131            self_xor: None,
3132            commitment: None,
3133            replication: None,
3134            sync_state: None,
3135            audit_challenge_coordinator: None,
3136            peer_commitments: None,
3137            close_group_size: 7,
3138        };
3139        assert!(!context.neighbours_know_the_commitment().await);
3140    }
3141}