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_secs(300);
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_secs(6 * 3600);
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_secs(120);
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_secs(2 * 3600);
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_secs(600);
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_secs(1800);
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
1586            .cooldown_until
1587            .is_some_and(|until| Instant::now() < until)
1588    }
1589}
1590
1591/// What taking the volume lock produced for the driver loop.
1592enum LockStep {
1593    /// Held, or not needed because none is possible here.
1594    Proceed,
1595    /// Someone else has it. Try again next tick.
1596    WaitATick,
1597}
1598
1599/// Take the volume lock if it is not already held, stamping when it was taken.
1600///
1601/// One place, because the stamp is what stops a node holding the volume against every
1602/// other node on the machine, and a branch that acquires without stamping silently opts
1603/// out of that.
1604fn take_volume_lock(
1605    lock: &mut Option<VolumeLock>,
1606    held: &mut LockHold,
1607    root_dir: &Path,
1608    scope: Option<&Path>,
1609) -> LockStep {
1610    if lock.is_some() {
1611        return LockStep::Proceed;
1612    }
1613    // After giving the volume up at the cap, stand back for a moment. Reacquiring in the
1614    // same breath would hand nobody anything.
1615    if !held.may_ask() {
1616        return LockStep::WaitATick;
1617    }
1618    match VolumeLock::try_acquire(root_dir, scope) {
1619        LockAttempt::Acquired(taken) => {
1620            *lock = Some(taken);
1621            held.taken();
1622            LockStep::Proceed
1623        }
1624        LockAttempt::Busy => {
1625            debug!("Another node on this volume is migrating; waiting");
1626            LockStep::WaitATick
1627        }
1628        // No lock is possible here, so waiting for one would strand this node
1629        // permanently. Proceed; the slack floor is the backstop.
1630        LockAttempt::Unavailable => LockStep::Proceed,
1631    }
1632}
1633
1634/// One pass of the copier. Returns `false` when this node cannot make progress that
1635/// needs the volume to itself.
1636async fn bridge_tick(
1637    store: &Arc<ChunkStore>,
1638    context: &MigrationContext,
1639    config: &MigrationConfig,
1640    next_shed_evaluation: &mut Instant,
1641    shutdown: &CancellationToken,
1642) -> bool {
1643    let remaining = store.legacy_only_keys();
1644    if remaining.is_empty() {
1645        if let Err(e) = store.commit_to_files() {
1646            // Not progress, and not something exclusive disk access fixes. Saying it was
1647            // would reset the hold cap every tick and let this node keep the volume from
1648            // every other node on the machine for as long as the failure lasts.
1649            warn!(
1650                "Everything is copied but the migration commitment could not be recorded: \
1651                 {e}. Retrying on the next tick."
1652            );
1653            return false;
1654        }
1655        return true;
1656    }
1657
1658    let ordered = rank_closest_first(remaining, context.self_xor);
1659    let batch: Vec<XorName> = ordered
1660        .into_iter()
1661        .take(config.batch_chunks.max(1))
1662        .collect();
1663    let report = match store
1664        .copy_batch(
1665            &batch,
1666            config.copier_slack_bytes(),
1667            config.copier_throttle_mib_per_sec,
1668            shutdown,
1669        )
1670        .await
1671    {
1672        Ok(report) => report,
1673        Err(e) => {
1674            // Still retried every tick, but the volume lock goes back: if this is
1675            // permanent, holding it would block every other node on the volume on a node
1676            // that is getting nowhere.
1677            warn!("Storage migration copy failed: {e}. Retrying on the next tick.");
1678            return false;
1679        }
1680    };
1681
1682    if report.copied > 0 {
1683        debug!(
1684            "Storage migration copied {} chunk(s) ({:.2} GiB) this pass",
1685            report.copied,
1686            bytes_to_gib(report.bytes)
1687        );
1688        // A migration runs for hours. One periodic line at info level is what an operator
1689        // watching a node actually sees, and what says the copier has not silently stalled.
1690        let left = store.legacy_only_keys().len();
1691        if left % PROGRESS_LOG_EVERY < usize::try_from(report.copied).unwrap_or(usize::MAX) {
1692            let no_rollback = store.writes_without_a_rollback_copy();
1693            info!(
1694                migration_event = "progress",
1695                remaining = left,
1696                no_rollback_copy = no_rollback,
1697                "Storage migration: {left} chunk(s) left to copy out of the legacy \
1698                 environment, {no_rollback} write(s) made without a rollback copy"
1699            );
1700        }
1701    }
1702    if report.unusable > 0 {
1703        warn!(
1704            "{} chunk(s) in the legacy environment did not match their own address and \
1705             were dropped from the key set",
1706            report.unusable
1707        );
1708    }
1709
1710    if report.stopped_for_space {
1711        // Out of space. Whatever happens next, this node is not going to write more until
1712        // something changes, so it stops excluding its neighbours from the volume. That
1713        // covers the 72-hour shed hold as well as an outright refusal: holding the lock
1714        // for three days would leave every other node on the volume unmigrated.
1715        if Instant::now() < *next_shed_evaluation {
1716            return false;
1717        }
1718        *next_shed_evaluation = Instant::now() + SHED_REEVALUATION_INTERVAL;
1719        return evaluate_shed(store, context, config).await;
1720    }
1721    true
1722}
1723
1724/// Decide whether the node may give up what it could not copy.
1725async fn evaluate_shed(
1726    store: &Arc<ChunkStore>,
1727    context: &MigrationContext,
1728    config: &MigrationConfig,
1729) -> bool {
1730    let remaining = store.legacy_only_keys();
1731    let short_by = remaining.len();
1732
1733    // Read from the one switch the auditors read, not from a second copy of it. There
1734    // used to be two constants of the same name with two environment overrides, one on
1735    // each side of this decision, and nothing coupling them: a node could have been
1736    // willing to shed while every peer was still applying the full penalty, which is the
1737    // exact outcome the release ordering exists to prevent.
1738    if !crate::replication::config::close_group_storage_penalty_suspended() {
1739        warn!(
1740            "This node cannot fit {short_by} chunk(s) in the file store, but this release \
1741             has audit penalties switched back on, so giving anything up now would be \
1742             penalised by every peer. Keeping both stores. Add disk, or migrate this node \
1743             on a build that still suspends penalties."
1744        );
1745        return false;
1746    }
1747
1748    if !config.allow_shed {
1749        warn!(
1750            "This node cannot fit {short_by} chunk(s) in the file store and shedding is \
1751             turned off. Add disk, or set storage.migration.allow_shed. Until then it \
1752             keeps serving from both stores and the legacy environment stays."
1753        );
1754        return false;
1755    }
1756
1757    let state = store.migration_state();
1758
1759    // Wait for this node's turn. A close group is split into waves so at most
1760    // CONCURRENT_MIGRATIONS_PER_GROUP of it are giving chunks up at once; if all seven
1761    // holders went together, none could prove to the others that a copy survived and the
1762    // whole group would sit deadlocked waiting on each other. Only nodes that have to give
1763    // something up wait: a node with room has already copied everything and retired.
1764    let wave = migration_wave_for(context.self_id.as_ref(), context.close_group_size);
1765    if !wave_has_opened(&state, config, wave) {
1766        info!(
1767            "This node is {short_by} chunk(s) short of disk and is in migration wave {wave} \
1768             of {}. Its turn opens {} hour(s) after this build first started, so the rest of \
1769             its close group stays steady and can keep serving what it is about to give up.",
1770            migration_wave_count(context.close_group_size),
1771            config
1772                .shed_hold_hours
1773                .saturating_add(wave.saturating_mul(config.wave_hours))
1774        );
1775        return false;
1776    }
1777
1778    // Kept as its own check even though the wave now starts after it: the hold is about
1779    // peers on an older build still applying the penalty, the wave is about the close
1780    // group being able to cover for whoever moves. Different reasons, both required.
1781    if !state.shed_hold_elapsed(config) {
1782        info!(
1783            "This node is {short_by} chunk(s) short of disk. Holding for {} hour(s) after \
1784             first start before giving any up, so peers still on an older build have \
1785             upgraded and stopped penalising a shed.",
1786            config.shed_hold_hours
1787        );
1788        return false;
1789    }
1790
1791    // First filter, and the cheap one: a node never gives up a chunk it is near the front
1792    // of the group for. In practice it rarely fires, by construction, because the copier
1793    // walks closest-first, so whatever is left when the disk fills is the far end of the
1794    // list. Finding a protected key still uncopied means the node could not fit even the
1795    // chunks it is closest to, which is exactly when it must not shed anything.
1796    let mut protected = Vec::new();
1797    for key in &remaining {
1798        if !context.may_shed(key).await {
1799            protected.push(*key);
1800            if protected.len() >= REFUSAL_SAMPLE {
1801                break;
1802            }
1803        }
1804    }
1805    if !protected.is_empty() {
1806        let sample: Vec<String> = protected.iter().map(hex::encode).collect();
1807        warn!(
1808            "This node is {short_by} chunk(s) short of disk, and at least {} of them are \
1809             chunks it is near the front of the group for (for example {}). It will not \
1810             give those up. The legacy environment stays and its disk is not returned \
1811             until storage is added.",
1812            protected.len(),
1813            sample.join(", ")
1814        );
1815        return false;
1816    }
1817
1818    // Second filter, and the one that decides it: proof that somebody else holds every
1819    // chunk this node is about to give up. Being far from a chunk is not evidence
1820    // that a copy exists. During a fleet-wide migration the nodes that ought to hold it
1821    // are exactly the ones that may also be out of disk, so the question has to be asked
1822    // rather than inferred.
1823    info!(
1824        "Checking that other nodes hold the {short_by} chunk(s) this node cannot fit, \
1825         before giving any of them up"
1826    );
1827    let unconfirmed = unconfirmed_by_neighbours(store, context, &remaining).await;
1828    if !unconfirmed.is_empty() {
1829        let sample: Vec<String> = unconfirmed
1830            .iter()
1831            .take(REFUSAL_SAMPLE)
1832            .map(hex::encode)
1833            .collect();
1834        warn!(
1835            "{} of the {short_by} chunk(s) this node cannot fit could not be proven to \
1836             exist anywhere else (for example {}). Nothing is given up and the legacy \
1837             environment stays. Add disk, or wait for replication to place them.",
1838            unconfirmed.len(),
1839            sample.join(", ")
1840        );
1841        return false;
1842    }
1843
1844    info!(
1845        migration_event = "shed",
1846        shed = short_by,
1847        "Every one of the {short_by} chunk(s) this node cannot fit is proven to be held \
1848         elsewhere. Committing to what it can hold. They stay readable from the legacy \
1849         environment until it is removed, and replication refetches whatever still belongs \
1850         here once there is room."
1851    );
1852    if let Err(e) = store.commit_to_files() {
1853        warn!("Could not record the migration commitment: {e}");
1854        return false;
1855    }
1856    true
1857}
1858
1859/// The keys still only in the legacy store that this node is too close to give up.
1860async fn keys_this_node_must_not_give_up(
1861    store: &Arc<ChunkStore>,
1862    context: &MigrationContext,
1863) -> Vec<XorName> {
1864    let mut must_keep = Vec::new();
1865    for key in store.legacy_only_keys() {
1866        if !context.may_shed(&key).await {
1867            must_keep.push(key);
1868        }
1869    }
1870    must_keep
1871}
1872
1873/// Re-ask every network gate, after verification and immediately before the deletion.
1874///
1875/// Verification re-reads the whole store and can run for hours. A gate satisfied before it
1876/// started says nothing about the moment of deletion: peers leave, replicas are pruned
1877/// elsewhere, and a write whose file half failed adds a fresh legacy-only key that has
1878/// faced none of these checks. This is the last point at which the answer can still be
1879/// acted on, so it is the point at which it has to be true.
1880async fn every_gate_still_holds(
1881    store: &Arc<ChunkStore>,
1882    context: &MigrationContext,
1883    candidates: &std::collections::BTreeSet<XorName>,
1884) -> Option<RetireOutcome> {
1885    // A key that joined the legacy-only set since the snapshot was taken has been through
1886    // none of this. Stop now rather than asking the gates about a set that has already
1887    // moved; the next tick copies it and takes a fresh snapshot.
1888    let live: std::collections::BTreeSet<XorName> = store.legacy_only_keys().into_iter().collect();
1889    if live != *candidates {
1890        debug!(
1891            "Legacy environment not retired: the set changed while the gates were being \
1892             checked ({} keys then, {} now)",
1893            candidates.len(),
1894            live.len()
1895        );
1896        return Some(RetireOutcome::Waiting);
1897    }
1898    if !keys_this_node_must_not_give_up(store, context)
1899        .await
1900        .is_empty()
1901    {
1902        debug!("Legacy environment not retired: the shed rule changed during verification");
1903        return Some(RetireOutcome::Waiting);
1904    }
1905    if let Some(outcome) = shedding_is_still_safe(store, context, candidates).await {
1906        return Some(outcome);
1907    }
1908    // And the retention contract once more, for the same reason.
1909    if let Some(reason) = store.retirement_blocker(|k| context.still_answerable(k)) {
1910        debug!("Legacy environment not retired: {reason}");
1911        return Some(RetireOutcome::Waiting);
1912    }
1913    None
1914}
1915
1916/// The last two questions before anything is deleted, asked in this order because the
1917/// order is the safety argument: reduce the claim, let the group learn it, then give the
1918/// chunks up.
1919///
1920/// Returns `Some` with the reason to stop, or `None` when it is safe to proceed.
1921async fn shedding_is_still_safe(
1922    store: &Arc<ChunkStore>,
1923    context: &MigrationContext,
1924    shedding: &std::collections::BTreeSet<XorName>,
1925) -> Option<RetireOutcome> {
1926    // Nothing below is reached until the node has reduced its commitment (the phase
1927    // is `Committed`) and that reduction has been rebuilt and published. What remains
1928    // is to confirm the close group has actually *received* it, and that the chunks
1929    // being given up still exist elsewhere. Only then is anything deleted.
1930    if !shedding.is_empty() {
1931        // A rotation is not the same as neighbours knowing. Until they have the
1932        // smaller key set they keep auditing this node against the one it used to
1933        // hold, and a wave of audit failures is as damaging as losing the chunks.
1934        // Asked only when there is a commitment to deliver. A node whose file-backed set
1935        // is empty commits to nothing, so there is no hash for a neighbour to acknowledge
1936        // and this gate would never open, stranding its disk for good. Nothing is lost by
1937        // skipping it: the gate exists to stop neighbours auditing this node against a key
1938        // set it no longer holds, and a node claiming nothing cannot fail such an audit.
1939        // The possession check below, which proves every chunk being given up still exists
1940        // elsewhere, is the gate that protects the data, and it still runs.
1941        let commits_to_nothing = store
1942            .committable_keys()
1943            .await
1944            .is_ok_and(|keys| keys.is_empty());
1945        if commits_to_nothing {
1946            info!(
1947                "This node's file-backed set is empty, so it commits to nothing and has \
1948                 no reduced commitment for its close group to receive. Proceeding to the \
1949                 possession check on the {} chunk(s) it is giving up.",
1950                shedding.len()
1951            );
1952        } else if !context.neighbours_know_the_commitment().await {
1953            info!(
1954                "Holding: {} of this node's close group must receive its reduced \
1955                 commitment before it gives up {} chunk(s). {} have it so far.",
1956                context.commitment_recipients_needed(),
1957                shedding.len(),
1958                context
1959                    .commitment
1960                    .as_ref()
1961                    .map_or(0, |s| s.current_delivered_peer_count())
1962            );
1963            // Give the volume back while waiting on this. It is a network condition, not
1964            // a disk one, and it may never resolve: holding the lock through it would let
1965            // one node stop every other node on the machine from ever starting.
1966            return Some(RetireOutcome::NoWorkToSerialise);
1967        }
1968        // Asked again here, not only when the node committed. Hours pass in between,
1969        // the group moves, and a peer that held a copy then may not now. This is the
1970        // last moment at which the answer still matters.
1971        let ordered: Vec<XorName> = shedding.iter().copied().collect();
1972        let unconfirmed = unconfirmed_by_neighbours(store, context, &ordered).await;
1973        if !unconfirmed.is_empty() {
1974            let sample: Vec<String> = unconfirmed
1975                .iter()
1976                .take(REFUSAL_SAMPLE)
1977                .map(hex::encode)
1978                .collect();
1979            warn!(
1980                "{} of the {} chunk(s) this node is giving up can no longer be proven \
1981                 to exist elsewhere (for example {}). The legacy environment stays.",
1982                unconfirmed.len(),
1983                shedding.len(),
1984                sample.join(", ")
1985            );
1986            return Some(RetireOutcome::NoWorkToSerialise);
1987        }
1988    }
1989    None
1990}
1991
1992/// What one pass of the retirement gate concluded.
1993enum RetireOutcome {
1994    /// The legacy environment is gone. The driver is finished.
1995    Done,
1996    /// Exclusive disk work happened this tick: copying, or re-reading the store to verify
1997    /// it. Keep the volume, and count the time as time spent using it rather than time
1998    /// spent holding it.
1999    Working,
2000    /// Still working towards it, but waiting on a clock rather than on the disk. Keep the
2001    /// volume, because the node is about to need it, but let the hold cap run.
2002    Waiting,
2003    /// Blocked on something no amount of exclusive disk access will fix.
2004    NoWorkToSerialise,
2005}
2006
2007/// When this node last said out loud that its migration needs a person.
2008static LAST_OPERATOR_WARNING: parking_lot::Mutex<Option<Instant>> = parking_lot::Mutex::new(None);
2009
2010/// How often to repeat it. Often enough to be noticed, rarely enough not to drown the log.
2011const OPERATOR_WARNING_INTERVAL: Duration = Duration::from_secs(3600);
2012
2013/// Should the "this needs a person" warning be repeated now?
2014///
2015/// The condition it reports is checked on every tick and does not clear on its own, so
2016/// without this it would be a line every thirty seconds for as long as the node runs.
2017fn operator_should_hear_again() -> bool {
2018    let mut last = LAST_OPERATOR_WARNING.lock();
2019    let now = Instant::now();
2020    if last.is_some_and(|at| now.duration_since(at) < OPERATOR_WARNING_INTERVAL) {
2021        return false;
2022    }
2023    *last = Some(now);
2024    true
2025}
2026
2027/// The retention contract, asked before anything else in the tick.
2028///
2029/// `Some` with what the driver should do, or `None` when nothing is in the way.
2030fn blocked_before_the_gates(
2031    store: &Arc<ChunkStore>,
2032    context: &MigrationContext,
2033    config: &MigrationConfig,
2034) -> Option<RetireOutcome> {
2035    let reason = store.retirement_blocker(|k| context.still_answerable(k))?;
2036    // Three blockers no amount of exclusive disk access will clear: an environment this
2037    // node cannot read, one it cannot classify at all, and one it must not delete because
2038    // it is a link to somewhere else. Each needs a person, so give the volume back to the
2039    // nodes that can use it and say so where an operator will see it rather than at debug.
2040    if store.has_lost_its_legacy_handle()
2041        || store.legacy_cannot_be_classified()
2042        || store.legacy_is_a_link()
2043    {
2044        if operator_should_hear_again() {
2045            warn!(
2046                migration_event = "needs_an_operator",
2047                "The legacy chunk environment will not be retired automatically: {reason}"
2048            );
2049        }
2050        return Some(RetireOutcome::NoWorkToSerialise);
2051    }
2052    debug!("Legacy environment not retired yet: {reason}");
2053    Some(if config.retire_legacy {
2054        RetireOutcome::Waiting
2055    } else {
2056        // Retirement is switched off on this node, so it will never free its disk here
2057        // however long it waits.
2058        RetireOutcome::NoWorkToSerialise
2059    })
2060}
2061
2062/// One pass of the retirement gate.
2063async fn retire_tick(
2064    store: &Arc<ChunkStore>,
2065    context: &MigrationContext,
2066    config: &MigrationConfig,
2067    verified: &mut Option<(VerifyReport, Instant)>,
2068    shutdown: &CancellationToken,
2069) -> RetireOutcome {
2070    if let Some(outcome) = blocked_before_the_gates(store, context, config) {
2071        return outcome;
2072    }
2073
2074    // Re-check the shed rule against live routing immediately before the destructive
2075    // step, not once when the node committed hours ago. Two things put a key back into
2076    // the legacy-only set after that decision: a file that failed verification and is now
2077    // served from the legacy copy, and a write whose file half failed. Neither went
2078    // through the rank check, and both would be thrown away by the removal below.
2079    let must_keep = keys_this_node_must_not_give_up(store, context).await;
2080    if !must_keep.is_empty() {
2081        warn!(
2082            "{} chunk(s) are still only in the legacy environment and this node is too \
2083             close to them to give them up. Copying them before anything is removed.",
2084            must_keep.len()
2085        );
2086        match store
2087            .copy_batch(
2088                &must_keep,
2089                config.copier_slack_bytes(),
2090                config.copier_throttle_mib_per_sec,
2091                shutdown,
2092            )
2093            .await
2094        {
2095            Ok(report) if report.stopped_for_space => {
2096                warn!(
2097                    "Out of disk while copying {} chunk(s) this node must not give up. \
2098                     The legacy environment stays until there is room for them.",
2099                    must_keep.len()
2100                );
2101                *verified = None;
2102                return RetireOutcome::NoWorkToSerialise;
2103            }
2104            Ok(_) => {}
2105            Err(e) => {
2106                warn!("Could not copy the chunks this node must keep: {e}");
2107                *verified = None;
2108                return RetireOutcome::NoWorkToSerialise;
2109            }
2110        }
2111        // Anything copied changed the file store, so a previous verification no longer
2112        // covers it.
2113        *verified = None;
2114        return RetireOutcome::Working;
2115    }
2116
2117    // The real report from a recent pass, never a fabricated one. Reuse deliberately does
2118    // NOT refresh the window: re-arming it from a reused proof would let a node that
2119    // keeps deferring retirement run the verification exactly once and coast on it.
2120    let reusable = verified
2121        .filter(|(_, at)| at.elapsed() < VERIFICATION_REUSE_WINDOW)
2122        .map(|(proof, _)| proof);
2123    let proof = match reusable {
2124        Some(proof) => proof,
2125        None => match store
2126            .verify_before_retire(config.copier_throttle_mib_per_sec, shutdown)
2127            .await
2128        {
2129            Ok(proof) => {
2130                if proof.is_clean() {
2131                    *verified = Some((proof, Instant::now()));
2132                }
2133                proof
2134            }
2135            Err(e) => {
2136                // A pass that failed is not progress, however quickly it failed, and
2137                // treating it as work would let a node whose store cannot be read hold
2138                // the volume against every other node on the machine for good.
2139                warn!("Pre-retirement verification failed: {e}. Retrying on the next tick.");
2140                return RetireOutcome::NoWorkToSerialise;
2141            }
2142        },
2143    };
2144    if !proof.is_clean() {
2145        *verified = None;
2146        warn!(
2147            "Pre-retirement verification found {} chunk(s) that are damaged in the file \
2148             store and cannot be repaired from the legacy environment. The legacy \
2149             environment stays.",
2150            proof.unrepairable()
2151        );
2152        return RetireOutcome::NoWorkToSerialise;
2153    }
2154
2155    // Snapshotted BEFORE the gates, not after. Every gate below is asked about exactly
2156    // this set, and exactly this set is what the removal is permitted to destroy. Taken
2157    // afterwards, a key that joined between the last gate and the snapshot would be
2158    // counted as approved having passed nothing, which is the case the gates exist for.
2159    let approved: std::collections::BTreeSet<XorName> =
2160        store.legacy_only_keys().into_iter().collect();
2161
2162    if let Some(outcome) = every_gate_still_holds(store, context, &approved).await {
2163        return outcome;
2164    }
2165
2166    let kept = store.current_chunks().unwrap_or(0);
2167    let shed = store.migration_state().shed_key_count;
2168    match store
2169        .retire_legacy(
2170            &proof,
2171            &|k: &XorName| context.still_answerable(k),
2172            &approved,
2173        )
2174        .await
2175    {
2176        Ok(freed) => {
2177            log_migration_complete(kept, shed, freed);
2178            RetireOutcome::Done
2179        }
2180        Err(e) => {
2181            debug!("Legacy environment not retired yet: {e}");
2182            RetireOutcome::Waiting
2183        }
2184    }
2185}
2186
2187/// Convert a byte count to GiB for human-readable log messages.
2188#[allow(clippy::cast_precision_loss)] // display only
2189#[cfg_attr(not(feature = "logging"), allow(dead_code))]
2190fn bytes_to_gib(bytes: u64) -> f64 {
2191    bytes as f64 / (1024.0 * 1024.0 * 1024.0)
2192}
2193
2194#[cfg(test)]
2195#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2196mod tests {
2197    use super::*;
2198    use serial_test::serial;
2199    use tempfile::TempDir;
2200
2201    fn peer_id(byte: u8) -> PeerId {
2202        let mut bytes = [0u8; 32];
2203        if let Some(slot) = bytes.first_mut() {
2204            *slot = byte;
2205        }
2206        PeerId::from_bytes(bytes)
2207    }
2208
2209    /// The width shedding is measured against: the admission group, not the close group.
2210    const WIDTH: usize = storage_admission_width(7);
2211
2212    #[test]
2213    fn shedding_is_measured_against_the_width_the_pruner_protects() {
2214        // The pruner treats the admission group (close group plus its margin) as strictly
2215        // in-range and refuses to delete inside it. A one-off migration must not be more
2216        // willing to drop a chunk than the thing that runs every day.
2217        assert_eq!(WIDTH, storage_admission_width(7));
2218        assert!(
2219            storage_admission_width(7) > 7,
2220            "the admission group is wider than the close group"
2221        );
2222        // A rank the close group would have called sheddable is protected here.
2223        assert!(!rank_is_sheddable(GroupRank::Inside(5), WIDTH));
2224        assert!(!rank_is_sheddable(GroupRank::Inside(6), WIDTH));
2225    }
2226
2227    #[test]
2228    fn a_node_never_gives_up_a_chunk_it_is_among_the_closest_to() {
2229        // This node is one of the closest for these ranks. Giving one of them up is the
2230        // case where every short-of-space holder could drop the same chunk and take its
2231        // last replica, so it is refused outright.
2232        for rank in 0..WIDTH - SHEDDABLE_TAIL_RANKS {
2233            assert!(
2234                !rank_is_sheddable(GroupRank::Inside(rank), WIDTH),
2235                "rank {rank} must be protected"
2236            );
2237        }
2238        // The last two positions may be given up: a chunk has exactly one holder at each,
2239        // so it is only ever a candidate for two of its holders.
2240        for rank in WIDTH - SHEDDABLE_TAIL_RANKS..WIDTH {
2241            assert!(
2242                rank_is_sheddable(GroupRank::Inside(rank), WIDTH),
2243                "rank {rank} is in the tail and may be shed"
2244            );
2245        }
2246        // Out of range entirely: nothing to protect.
2247        assert!(rank_is_sheddable(GroupRank::Outside, WIDTH));
2248        // No routing to consult is never a licence.
2249        assert!(!rank_is_sheddable(GroupRank::Unknown, WIDTH));
2250    }
2251
2252    #[test]
2253    fn a_group_narrower_than_the_tail_protects_everything_in_it() {
2254        // A group with no tail has nothing to give up. Subtracting saturatingly would put
2255        // the threshold at zero and make every member sheddable, which is exactly
2256        // backwards for the narrowest groups.
2257        assert!(!rank_is_sheddable(GroupRank::Inside(0), 2));
2258        assert!(!rank_is_sheddable(GroupRank::Inside(0), 1));
2259        assert!(!rank_is_sheddable(GroupRank::Inside(1), 2));
2260        // Out of the group entirely is still out.
2261        assert!(rank_is_sheddable(GroupRank::Outside, 2));
2262        // And a group with a tail still has one.
2263        assert!(!rank_is_sheddable(GroupRank::Inside(0), 3));
2264        assert!(rank_is_sheddable(GroupRank::Inside(1), 3));
2265    }
2266
2267    #[test]
2268    fn the_marker_round_trips_and_a_corrupt_one_starts_over_conservatively() {
2269        let dir = TempDir::new().expect("temp dir");
2270        let mut state = MigrationState::new(MigrationPhase::Bridging);
2271        state.phase = MigrationPhase::Committed;
2272        state.shed_key_count = 12;
2273        state.committed_at_unix = Some(1_700_000_000);
2274        state.save(dir.path()).expect("save");
2275
2276        let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
2277        assert_eq!(loaded.phase, MigrationPhase::Committed);
2278        assert_eq!(loaded.shed_key_count, 12);
2279        assert_eq!(loaded.committed_at_unix, Some(1_700_000_000));
2280
2281        // An unreadable marker restarts the clocks rather than being fatal. Losing it
2282        // delays a migration and can never rush one.
2283        std::fs::write(state_path(dir.path()), b"not json").expect("corrupt");
2284        let recovered = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
2285        assert_eq!(recovered.phase, MigrationPhase::Bridging);
2286        assert_eq!(recovered.committed_at_unix, None);
2287    }
2288
2289    #[test]
2290    fn the_shed_hold_and_retirement_clocks_run_from_recorded_times() {
2291        let config = MigrationConfig {
2292            shed_hold_hours: 72,
2293            retire_delay_hours: MIN_RETIRE_DELAY_HOURS,
2294            ..MigrationConfig::default()
2295        };
2296
2297        let mut state = MigrationState::new(MigrationPhase::Bridging);
2298        assert!(!state.shed_hold_elapsed(&config), "just started");
2299        state.first_start_unix = now_unix().saturating_sub(73 * 3600);
2300        assert!(state.shed_hold_elapsed(&config));
2301
2302        assert!(
2303            !state.retire_delay_elapsed(&config),
2304            "never committed, so the clock has not started"
2305        );
2306        state.committed_at_unix = Some(now_unix().saturating_sub(3600));
2307        assert!(!state.retire_delay_elapsed(&config), "an hour is not four");
2308        state.committed_at_unix =
2309            Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
2310        assert!(state.retire_delay_elapsed(&config));
2311    }
2312
2313    #[test]
2314    fn only_one_node_on_a_volume_migrates_at_a_time() {
2315        let volume = TempDir::new().expect("temp dir");
2316        let node_a = volume.path().join("node-a");
2317        let node_b = volume.path().join("node-b");
2318        std::fs::create_dir_all(&node_a).expect("mkdir");
2319        std::fs::create_dir_all(&node_b).expect("mkdir");
2320
2321        let LockAttempt::Acquired(held) = VolumeLock::try_acquire(&node_a, None) else {
2322            panic!("the first node must take the lock");
2323        };
2324        assert!(
2325            matches!(VolumeLock::try_acquire(&node_b, None), LockAttempt::Busy),
2326            "a second node on the same volume must be told to wait, not that no lock exists"
2327        );
2328
2329        drop(held);
2330        assert!(
2331            matches!(
2332                VolumeLock::try_acquire(&node_b, None),
2333                LockAttempt::Acquired(_)
2334            ),
2335            "and take it once the first is done"
2336        );
2337    }
2338
2339    /// Seed a real LMDB chunk store, the way a node upgrading into this build has one.
2340    async fn seed_legacy(root: &std::path::Path, count: u32) -> Vec<XorName> {
2341        let lmdb = crate::storage::LmdbStorage::new(crate::storage::LmdbStorageConfig {
2342            root_dir: root.to_path_buf(),
2343            verify_on_read: true,
2344            max_map_size: 0,
2345            disk_reserve: 0,
2346        })
2347        .await
2348        .expect("open legacy");
2349        let mut keys = Vec::new();
2350        for i in 0..count {
2351            let content = format!("legacy-chunk-{i}").into_bytes();
2352            let addr = crate::client::compute_address(&content);
2353            lmdb.put(&addr, &content).await.expect("legacy put");
2354            keys.push(addr);
2355        }
2356        lmdb.wait_idle().await;
2357        drop(lmdb);
2358        keys
2359    }
2360
2361    /// The whole point, end to end: a node that starts with an LMDB chunk store and a
2362    /// disk to hold it finishes with the chunks in files and the LMDB gone.
2363    ///
2364    /// Driven by `run`, the same entry point node startup calls, rather than by poking the
2365    /// pieces. That matters: the wiring that calls it went missing once and every test
2366    /// passed, because they all built the store directly and a node with no legacy store
2367    /// starts no migration.
2368    #[tokio::test]
2369    async fn a_node_with_room_copies_everything_and_removes_the_legacy_store() {
2370        const CHUNKS: u32 = 24;
2371
2372        let tmp = TempDir::new().expect("temp dir");
2373        // Nested, so the volume lock this node takes lives in its own directory rather
2374        // than one shared with every other test running in parallel.
2375        let root = tmp.path().join("node");
2376        std::fs::create_dir_all(&root).expect("mkdir");
2377        let keys = seed_legacy(&root, CHUNKS).await;
2378
2379        let mut config = crate::storage::ChunkStoreConfig {
2380            root_dir: root.clone(),
2381            ..crate::storage::ChunkStoreConfig::test_default()
2382        };
2383        // Deliberately NOT setting `retire_legacy`. The shipped default has to be what
2384        // carries this all the way to a removed environment, or the release migrates every
2385        // node and reclaims nothing.
2386        config.migration.tick_secs = 1;
2387        // Scoped to this test's own directory. In production the lock is keyed by the
2388        // filesystem, so without this every test on this machine would serialise against
2389        // every other one that runs a migration.
2390        config.migration.lock_dir = Some(root.clone());
2391        config.migration.copier_throttle_mib_per_sec = 0;
2392        let store = Arc::new(
2393            crate::storage::ChunkStore::new(config)
2394                .await
2395                .expect("open store"),
2396        );
2397
2398        // Precondition: everything is in the legacy store and nothing is in files.
2399        assert!(store.has_legacy(), "the node must start with an LMDB store");
2400        assert_eq!(store.migration_phase(), MigrationPhase::Bridging);
2401        assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
2402        assert!(root.join("chunks.mdb").exists());
2403
2404        let shutdown = CancellationToken::new();
2405        let driver = tokio::spawn(run(
2406            Arc::clone(&store),
2407            MigrationContext {
2408                p2p: None,
2409                self_id: None,
2410                self_xor: None,
2411                commitment: None,
2412                replication: None,
2413                sync_state: None,
2414                audit_challenge_coordinator: None,
2415                peer_commitments: None,
2416                close_group_size: 7,
2417            },
2418            shutdown.clone(),
2419        ));
2420
2421        // The copier runs on its own and settles once nothing is left only in the legacy
2422        // store. This node has room, so it sheds nothing and needs no network at all.
2423        wait_for(
2424            &store,
2425            MigrationPhase::Committed,
2426            "the copier should finish",
2427        )
2428        .await;
2429        assert!(
2430            store.legacy_only_keys().is_empty(),
2431            "every chunk should have been copied"
2432        );
2433
2434        // Stand in for the commitment builder, which lives in the replication engine: the
2435        // retirement gate wants the reduced commitment published and its window elapsed.
2436        store.note_commitment_rebuilt();
2437        store.note_commitment_rebuilt();
2438        store.force_migration_state(|s| {
2439            s.committed_at_unix =
2440                Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
2441        });
2442
2443        wait_for(
2444            &store,
2445            MigrationPhase::FilesOnly,
2446            "retirement should complete",
2447        )
2448        .await;
2449        shutdown.cancel();
2450        let _ = tokio::time::timeout(Duration::from_secs(10), driver).await;
2451
2452        // The point of the whole exercise: the LMDB is gone from the filesystem.
2453        assert!(
2454            !root.join("chunks.mdb").exists(),
2455            "the legacy store must be removed, which is the only moment disk comes back"
2456        );
2457        assert!(!store.has_legacy());
2458
2459        // And nothing was lost: every chunk still reads, now out of a file.
2460        assert_eq!(store.current_chunks().expect("count"), u64::from(CHUNKS));
2461        for (i, key) in keys.iter().enumerate() {
2462            let expected = format!("legacy-chunk-{i}").into_bytes();
2463            assert_eq!(
2464                store.get(key).await.expect("get").expect("present"),
2465                expected,
2466                "chunk {i} did not survive the migration"
2467            );
2468        }
2469
2470        // In files, under the suffix shard its address names.
2471        let sample = keys.first().copied().expect("a key");
2472        let path = root
2473            .join(crate::storage::file_store::CHUNKS_DIR_NAME)
2474            .join(format!("{:02x}", sample.last().copied().unwrap_or(0)))
2475            .join(hex::encode(sample));
2476        assert!(path.exists(), "expected a chunk file at {}", path.display());
2477    }
2478
2479    /// The other half: a node that cannot fit its chunks and cannot prove anyone else
2480    /// holds them keeps both stores and deletes nothing.
2481    ///
2482    /// This is the case that must fail safe. The node is out of disk, so it would like to
2483    /// give chunks up, but with no view of the network it cannot show a single one exists
2484    /// elsewhere. Refusing costs it disk. Proceeding would cost the network data.
2485    #[tokio::test]
2486    async fn a_node_that_cannot_prove_its_chunks_are_safe_deletes_nothing() {
2487        const CHUNKS: u32 = 8;
2488
2489        let tmp = TempDir::new().expect("temp dir");
2490        let root = tmp.path().join("node");
2491        std::fs::create_dir_all(&root).expect("mkdir");
2492        let keys = seed_legacy(&root, CHUNKS).await;
2493
2494        let mut config = crate::storage::ChunkStoreConfig {
2495            root_dir: root.clone(),
2496            // Nothing will fit: the copier stops for space on its first chunk.
2497            disk_reserve: u64::MAX / 2,
2498            ..crate::storage::ChunkStoreConfig::test_default()
2499        };
2500        config.migration.retire_legacy = true;
2501        config.migration.tick_secs = 1;
2502        // Scoped to this test's own directory. In production the lock is keyed by the
2503        // filesystem, so without this every test on this machine would serialise against
2504        // every other one that runs a migration.
2505        config.migration.lock_dir = Some(root.clone());
2506        // Elapsed, so the hold is not what is doing the refusing here.
2507        config.migration.shed_hold_hours = 0;
2508        config.migration.wave_hours = 0;
2509        let store = Arc::new(
2510            crate::storage::ChunkStore::new(config)
2511                .await
2512                .expect("open store"),
2513        );
2514        assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
2515
2516        let shutdown = CancellationToken::new();
2517        let driver = tokio::spawn(run(
2518            Arc::clone(&store),
2519            MigrationContext {
2520                p2p: None,
2521                self_id: None,
2522                self_xor: None,
2523                commitment: None,
2524                replication: None,
2525                sync_state: None,
2526                audit_challenge_coordinator: None,
2527                peer_commitments: None,
2528                close_group_size: 7,
2529            },
2530            shutdown.clone(),
2531        ));
2532
2533        // Give it long enough to have tried, re-tried, and evaluated shedding.
2534        tokio::time::sleep(Duration::from_secs(5)).await;
2535        shutdown.cancel();
2536        let _ = tokio::time::timeout(Duration::from_secs(10), driver).await;
2537
2538        assert_eq!(
2539            store.migration_phase(),
2540            MigrationPhase::Bridging,
2541            "a node that cannot prove its chunks are held elsewhere must not commit"
2542        );
2543        assert!(
2544            root.join("chunks.mdb").exists(),
2545            "and must not remove the only copy of them"
2546        );
2547        assert_eq!(store.legacy_only_keys().len(), CHUNKS as usize);
2548        for (i, key) in keys.iter().enumerate() {
2549            assert_eq!(
2550                store.get(key).await.expect("get").expect("present"),
2551                format!("legacy-chunk-{i}").into_bytes(),
2552                "chunk {i} must still be served throughout"
2553            );
2554        }
2555    }
2556
2557    /// Poll until the store reaches `phase`, or fail with what it reached instead.
2558    ///
2559    /// The deadline is generous because it is measured on the wall clock while the driver
2560    /// it is waiting on runs on the runtime. On a saturated machine both stretch, and a
2561    /// deadline sized for the work rather than for the contention turns a slow build into
2562    /// a failing test. The work itself is two ticks.
2563    async fn wait_for(store: &Arc<crate::storage::ChunkStore>, phase: MigrationPhase, what: &str) {
2564        let deadline = std::time::Instant::now() + Duration::from_secs(180);
2565        while std::time::Instant::now() < deadline {
2566            if store.migration_phase() == phase {
2567                return;
2568            }
2569            tokio::time::sleep(Duration::from_millis(100)).await;
2570        }
2571        panic!(
2572            "{what}: still in {:?} after the deadline, expected {phase:?}",
2573            store.migration_phase()
2574        );
2575    }
2576
2577    /// A marker that cannot be used is replaced on disk, not just in memory.
2578    ///
2579    /// The shed hold counts from `first_start_unix`, and the whole reason this is written
2580    /// at startup rather than at the first phase change is that a marker written later
2581    /// would restart that clock on every reboot. A marker that is present but unusable used
2582    /// to defeat that: it was replaced in memory and left on disk, so every start read the
2583    /// same bad file and stamped a fresh clock. A node restarting more often than the hold
2584    /// would then never become eligible to shed and never finish migrating, which is the
2585    /// failure the doc comment on `load_or_create` names.
2586    #[test]
2587    fn an_unusable_marker_is_replaced_on_disk_so_the_hold_does_not_restart() {
2588        for (name, bad) in [
2589            ("truncated", br#"{"schema":1,"phase":"brid"#.to_vec()),
2590            ("not json at all", b"\x00\x01\x02".to_vec()),
2591            (
2592                "a newer schema",
2593                serde_json::json!({
2594                    "schema": 9_999,
2595                    "phase": "bridging",
2596                    "first_start_unix": 1,
2597                    "committed_at_unix": null,
2598                    "rebuilds_since_commit": 0,
2599                    "shed_key_count": 0,
2600                    "kept_key_count": 0,
2601                })
2602                .to_string()
2603                .into_bytes(),
2604            ),
2605            // The one most worth keeping, and the one a parse into today's struct cannot
2606            // read: a phase this build has no name for, and a field it does not know.
2607            (
2608                "a newer schema this build cannot parse at all",
2609                serde_json::json!({
2610                    "schema": 9_999,
2611                    "phase": "some_phase_from_the_future",
2612                    "first_start_unix": 1,
2613                    "something_this_build_never_heard_of": {"a": 1},
2614                })
2615                .to_string()
2616                .into_bytes(),
2617            ),
2618        ] {
2619            let dir = TempDir::new().expect("temp dir");
2620            std::fs::write(state_path(dir.path()), &bad).expect("plant the bad marker");
2621
2622            let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2623            let written = std::fs::read(state_path(dir.path())).expect("read it back");
2624            assert_ne!(written, bad, "{name}: the unusable marker was left on disk");
2625            if name.starts_with("a newer schema") {
2626                // Moved aside rather than destroyed: it was written on purpose by a build
2627                // that knew more than this one.
2628                let mut kept = state_path(dir.path()).into_os_string();
2629                kept.push(".schema-9999");
2630                let kept = PathBuf::from(kept);
2631                assert_eq!(
2632                    std::fs::read(&kept).expect("the newer marker must be kept"),
2633                    bad,
2634                    "the newer marker was written over rather than set aside"
2635                );
2636            }
2637
2638            // And the clock survives the next start, which is the point of all this.
2639            let second = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2640            assert_eq!(
2641                second.first_start_unix, first.first_start_unix,
2642                "{name}: the shed hold restarted on the next boot"
2643            );
2644        }
2645    }
2646
2647    /// A marker whose clock is impossible is corrected on disk too.
2648    ///
2649    /// `with_sane_clocks` fixes a future-dated marker for the process that read it. Left
2650    /// there, the same correction is made again on every start, from a new now each time,
2651    /// which is the same repeating reset by another route.
2652    #[test]
2653    fn a_future_dated_marker_is_corrected_on_disk_not_only_in_memory() {
2654        let dir = TempDir::new().expect("temp dir");
2655        let ahead = now_unix().saturating_add(60 * 60 * 24 * 365);
2656        let planted = serde_json::json!({
2657            "schema": 1,
2658            "phase": "bridging",
2659            "first_start_unix": ahead,
2660            "committed_at_unix": null,
2661            "rebuilds_since_commit": 0,
2662            "shed_key_count": 0,
2663            "kept_key_count": 0,
2664        })
2665        .to_string();
2666        std::fs::write(state_path(dir.path()), &planted).expect("plant it");
2667
2668        let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2669        assert!(
2670            first.first_start_unix < ahead,
2671            "the clock should have been brought back to something possible"
2672        );
2673
2674        let reread: MigrationState =
2675            serde_json::from_slice(&std::fs::read(state_path(dir.path())).expect("read"))
2676                .expect("the marker on disk must now parse");
2677        assert_eq!(
2678            reread.first_start_unix, first.first_start_unix,
2679            "the correction was made in memory and not written back"
2680        );
2681    }
2682
2683    /// A marker that is already right is not rewritten on every start.
2684    ///
2685    /// The counterpart to the two above: persisting on disagreement must not turn into
2686    /// persisting unconditionally, which would put a write on every node's start path for
2687    /// nothing.
2688    #[test]
2689    fn a_usable_marker_is_left_exactly_as_it_is() {
2690        let dir = TempDir::new().expect("temp dir");
2691        let first = MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2692
2693        // Written back out by hand in a shape this build would never produce: the same
2694        // facts, different spacing and key order. Comparing the bytes of a marker this
2695        // build wrote against the bytes after a second start proves nothing, because an
2696        // unconditional rewrite produces the same bytes and the test passes either way.
2697        // Something semantically equal but textually different is the only thing that can
2698        // tell "left alone" from "written again".
2699        let noncanonical = format!(
2700            "{{\"kept_key_count\":{},\"shed_key_count\":{},\"rebuilds_since_commit\":{},\
2701             \"committed_at_unix\":null,\"first_start_unix\":{},\"phase\":\"bridging\",\
2702             \"schema\":{}}}",
2703            first.kept_key_count,
2704            first.shed_key_count,
2705            first.rebuilds_since_commit,
2706            first.first_start_unix,
2707            first.schema
2708        );
2709        std::fs::write(state_path(dir.path()), &noncanonical).expect("write");
2710
2711        MigrationState::load_or_create(dir.path(), MigrationPhase::Bridging);
2712        assert_eq!(
2713            std::fs::read_to_string(state_path(dir.path())).expect("read"),
2714            noncanonical,
2715            "a marker that already said the right thing was rewritten for no reason"
2716        );
2717    }
2718
2719    /// Two nodes on one disk take the same lock, and the override is what makes that true
2720    /// where they do not share a `/tmp`.
2721    ///
2722    /// `lock_path_for` had no coverage at all, which is how it came to be right in a way
2723    /// that is false on our own fleet: every shipped test sets `lock_dir` and so never
2724    /// calls it. What the lock is for is one node copying at a time on a shared disk, so
2725    /// what has to be true is that two different node roots on one volume produce one path.
2726    ///
2727    /// Nothing here touches process-wide environment. An earlier version of this test set
2728    /// `TMPDIR` to stage the private-`/tmp` case, which moved every other test's temporary
2729    /// directory and then deleted it underneath them: sixty-three unrelated tests failed
2730    /// with LMDB errors that pointed nowhere near the cause.
2731    #[test]
2732    fn nodes_on_one_volume_agree_on_a_lock_path_when_they_are_told_where_it_is() {
2733        let volume = TempDir::new().expect("temp dir");
2734        let a = volume.path().join("node-0");
2735        let b = volume.path().join("node-1");
2736        std::fs::create_dir_all(&a).expect("mkdir");
2737        std::fs::create_dir_all(&b).expect("mkdir");
2738
2739        // With no override and one shared temporary directory, which is the case the
2740        // default is right for: two roots on one volume, one lock.
2741        assert_eq!(
2742            lock_path_with(&a, None),
2743            lock_path_with(&b, None),
2744            "two roots on one volume must share a lock when they share a /tmp"
2745        );
2746
2747        // Where they do not share one, the default gives each node a lock of its own and
2748        // every one of them takes it. That is the deployment hazard, and it is why the
2749        // override exists rather than something the code can detect.
2750        assert_ne!(
2751            lock_path_with(&a, Some("/tmp/private-to-node-0")),
2752            lock_path_with(&b, Some("/tmp/private-to-node-1")),
2753            "different lock directories must give different locks, or the override would \
2754             not be able to express anything"
2755        );
2756
2757        // And told where it lives, both land on it whatever their own root is.
2758        let told = volume.path().to_string_lossy().into_owned();
2759        let shared_a = lock_path_with(&a, Some(&told));
2760        let shared_b = lock_path_with(&b, Some(&told));
2761        assert_eq!(
2762            shared_a, shared_b,
2763            "nodes told where the lock lives must all use it"
2764        );
2765        assert!(shared_a.starts_with(volume.path()), "and use the one named");
2766        assert_eq!(
2767            lock_path_with(&a, Some("   ")),
2768            lock_path_with(&a, None),
2769            "an empty setting is not a location and must not be treated as one"
2770        );
2771
2772        // And the lock itself then does its job across the two roots.
2773        let LockAttempt::Acquired(held) = VolumeLock::try_acquire(&a, Some(volume.path())) else {
2774            panic!("the first node must take it");
2775        };
2776        assert!(
2777            matches!(
2778                VolumeLock::try_acquire(&b, Some(volume.path())),
2779                LockAttempt::Busy
2780            ),
2781            "the second must wait rather than copy alongside it"
2782        );
2783        drop(held);
2784        assert!(matches!(
2785            VolumeLock::try_acquire(&b, Some(volume.path())),
2786            LockAttempt::Acquired(_)
2787        ));
2788    }
2789
2790    /// A lock directory that cannot be written is reported, not silently ignored.
2791    ///
2792    /// The override is a deployment fact, so a typo in it must not read as "no lock needed
2793    /// here". `Unavailable` is the honest answer and it already warns; what this pins is
2794    /// that a bad override does not quietly fall back to a path that would appear to work.
2795    #[test]
2796    fn a_lock_directory_that_does_not_exist_is_unavailable_rather_than_ignored() {
2797        let dir = TempDir::new().expect("temp dir");
2798        let missing = dir.path().join("no-such-directory");
2799        assert!(matches!(
2800            VolumeLock::try_acquire(dir.path(), Some(&missing)),
2801            LockAttempt::Unavailable
2802        ));
2803    }
2804
2805    #[tokio::test]
2806    async fn the_driver_exits_immediately_when_there_is_nothing_to_migrate() {
2807        // The whole feature hangs off `run` being reachable from node startup. A port that
2808        // dropped that call once already, and nothing caught it, because a fresh node has
2809        // no legacy environment and every test built one directly. This asserts the entry
2810        // point is callable and terminates on its own for a node with nothing to do.
2811        let dir = TempDir::new().expect("temp dir");
2812        let store = Arc::new(
2813            crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
2814                root_dir: dir.path().to_path_buf(),
2815                ..crate::storage::ChunkStoreConfig::test_default()
2816            })
2817            .await
2818            .expect("open store"),
2819        );
2820        assert!(!store.has_legacy());
2821
2822        let context = MigrationContext {
2823            p2p: None,
2824            self_id: None,
2825            self_xor: None,
2826            commitment: None,
2827            replication: None,
2828            sync_state: None,
2829            audit_challenge_coordinator: None,
2830            peer_commitments: None,
2831            close_group_size: 7,
2832        };
2833        tokio::time::timeout(
2834            Duration::from_secs(5),
2835            run(store, context, CancellationToken::new()),
2836        )
2837        .await
2838        .expect("the driver must return rather than idle when there is nothing to migrate");
2839    }
2840
2841    #[tokio::test]
2842    async fn a_node_with_no_view_of_the_network_gives_up_nothing() {
2843        // Every field is `None`, which is what a devnet or a node whose routing is not up
2844        // yet looks like. No view of the network is no evidence, and the answer has to be
2845        // "keep everything" rather than "nobody is closer, so give it all away".
2846        let dir = TempDir::new().expect("temp dir");
2847        let store = Arc::new(
2848            crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
2849                root_dir: dir.path().to_path_buf(),
2850                ..crate::storage::ChunkStoreConfig::test_default()
2851            })
2852            .await
2853            .expect("open store"),
2854        );
2855        let context = MigrationContext {
2856            p2p: None,
2857            self_id: None,
2858            self_xor: None,
2859            commitment: None,
2860            replication: None,
2861            sync_state: None,
2862            audit_challenge_coordinator: None,
2863            peer_commitments: None,
2864            close_group_size: 7,
2865        };
2866
2867        let keys = vec![[1u8; 32], [2u8; 32], [3u8; 32]];
2868        let unconfirmed = unconfirmed_by_neighbours(&store, &context, &keys).await;
2869        assert_eq!(
2870            unconfirmed, keys,
2871            "with no routing state every key must count as unproven"
2872        );
2873        for key in &keys {
2874            assert!(
2875                !context.may_shed(key).await,
2876                "and none of them may be given up"
2877            );
2878        }
2879    }
2880
2881    #[test]
2882    fn the_possession_threshold_comes_from_the_whole_group_not_the_qualifying_subset() {
2883        use crate::replication::pruning::{prune_proofs_needed, target_peers_reported_present};
2884        use std::collections::{HashMap, HashSet};
2885
2886        // Seven holders. Deriving the bar from whichever peers happen to qualify is how
2887        // two last holders destroy a chunk between them: each sees only the other
2888        // publishing, so each needs exactly one proof, each gets it from the other, and
2889        // both delete. The bar must come from the group.
2890        let key = [7u8; 32];
2891        let group: Vec<PeerId> = (0..6u8).map(peer_id).collect();
2892        let only_one_qualifies: Vec<PeerId> = group.iter().take(1).copied().collect();
2893
2894        // That one peer does answer the challenge.
2895        let mut proofs: HashMap<XorName, HashSet<PeerId>> = HashMap::new();
2896        proofs.insert(key, only_one_qualifies.iter().copied().collect());
2897
2898        // The dangerous reading: bar taken from the qualifying subset, so one is enough.
2899        assert!(
2900            target_peers_reported_present(
2901                &key,
2902                &only_one_qualifies,
2903                &proofs,
2904                prune_proofs_needed(only_one_qualifies.len()),
2905            ),
2906            "this is the mistake being guarded against, shown here to be a real risk"
2907        );
2908
2909        // The correct reading: bar taken from the whole group, so one is nowhere near.
2910        assert!(
2911            !target_peers_reported_present(
2912                &key,
2913                &only_one_qualifies,
2914                &proofs,
2915                prune_proofs_needed(group.len()),
2916            ),
2917            "one proof must never satisfy a group of six"
2918        );
2919
2920        // And with the whole group answering, it passes.
2921        proofs.insert(key, group.iter().copied().collect());
2922        assert!(target_peers_reported_present(
2923            &key,
2924            &group,
2925            &proofs,
2926            prune_proofs_needed(group.len()),
2927        ));
2928    }
2929
2930    #[test]
2931    #[serial]
2932    fn shedding_reads_the_same_switch_the_auditors_read() {
2933        use crate::replication::config::{
2934            close_group_storage_penalty_suspended, set_close_group_storage_penalty_suspended,
2935        };
2936        // One switch, not two. There used to be a second constant of the same name with
2937        // its own environment override on this side of the decision, and nothing coupling
2938        // them: a node could have been willing to shed while every peer still applied the
2939        // full penalty, which is precisely what the release ordering exists to prevent.
2940        set_close_group_storage_penalty_suspended(true);
2941        assert!(close_group_storage_penalty_suspended());
2942        set_close_group_storage_penalty_suspended(false);
2943        assert!(!close_group_storage_penalty_suspended());
2944        set_close_group_storage_penalty_suspended(
2945            crate::replication::config::RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY,
2946        );
2947    }
2948
2949    #[test]
2950    fn a_close_group_is_split_into_enough_waves_to_bound_concurrent_migrations() {
2951        // Seven holders, two at a time, is four waves.
2952        assert_eq!(migration_wave_count(7), 4);
2953        assert_eq!(migration_wave_count(2), 1);
2954        assert_eq!(migration_wave_count(1), 1);
2955        // A degenerate width must still yield a usable wave count rather than dividing by
2956        // zero or collapsing to "everyone at once".
2957        assert_eq!(migration_wave_count(0), 1);
2958    }
2959
2960    #[test]
2961    fn wave_assignment_is_stable_per_node_and_spread_across_the_group() {
2962        use std::collections::HashMap;
2963        let waves = migration_wave_count(7);
2964
2965        // The same node always gets the same wave: a restart must not move a node into a
2966        // turn that has already passed.
2967        let peer = peer_id(7);
2968        assert_eq!(
2969            migration_wave_for(Some(&peer), 7),
2970            migration_wave_for(Some(&peer), 7)
2971        );
2972
2973        // And across many nodes every wave is used, so the group is genuinely staggered
2974        // rather than all landing together.
2975        let mut counts: HashMap<u64, usize> = HashMap::new();
2976        for b in 0..=255u8 {
2977            let w = migration_wave_for(Some(&peer_id(b)), 7);
2978            assert!(w < waves, "wave {w} outside 0..{waves}");
2979            *counts.entry(w).or_default() += 1;
2980        }
2981        assert_eq!(
2982            counts.len() as u64,
2983            waves,
2984            "every wave should be occupied, got {counts:?}"
2985        );
2986    }
2987
2988    #[test]
2989    fn waves_are_actually_staggered_under_the_shipped_defaults() {
2990        // The combination is what matters, not either setting alone. Measured from first
2991        // start, a 72 hour hold and 24 hour waves cancel out: waves would open at 0, 24,
2992        // 48 and 72 hours while nothing may shed until 72, so every wave is open the
2993        // moment the first one can act and the whole close group moves together. Measured
2994        // from the end of the hold, they stagger as intended.
2995        let config = MigrationConfig::default();
2996        assert_eq!(config.shed_hold_hours, 72);
2997        assert_eq!(config.wave_hours, 24);
2998
2999        let mut state = MigrationState::new(MigrationPhase::Bridging);
3000        let waves = migration_wave_count(7);
3001        assert_eq!(waves, 4);
3002
3003        // Nothing is open before the hold ends.
3004        state.first_start_unix = now_unix();
3005        for w in 0..waves {
3006            assert!(
3007                !wave_has_opened(&state, &config, w),
3008                "wave {w} opened too early"
3009            );
3010        }
3011
3012        // At the end of the hold, exactly the first wave is open.
3013        state.first_start_unix = now_unix().saturating_sub(72 * 3600 + 60);
3014        assert!(wave_has_opened(&state, &config, 0));
3015        for w in 1..waves {
3016            assert!(
3017                !wave_has_opened(&state, &config, w),
3018                "wave {w} must wait its turn, or the group migrates together"
3019            );
3020        }
3021
3022        // Each later wave opens one wave_hours after the one before it.
3023        for open in 1..waves {
3024            state.first_start_unix = now_unix().saturating_sub((72 + open * 24) * 3600 + 60);
3025            for w in 0..=open {
3026                assert!(wave_has_opened(&state, &config, w));
3027            }
3028            for w in open + 1..waves {
3029                assert!(!wave_has_opened(&state, &config, w));
3030            }
3031        }
3032    }
3033
3034    #[test]
3035    fn an_implausible_clock_restarts_the_holds_rather_than_voiding_them() {
3036        let dir = TempDir::new().expect("temp dir");
3037        let config = MigrationConfig::default();
3038
3039        // Zero is what a node with an unsynchronised clock writes at first boot, and it
3040        // would make every hold vacuous. So would a time in the future.
3041        let mut state = MigrationState::new(MigrationPhase::Committed);
3042        state.first_start_unix = 0;
3043        state.committed_at_unix = Some(0);
3044        state.save(dir.path()).expect("save");
3045
3046        let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
3047        assert!(
3048            !loaded.shed_hold_elapsed(&config),
3049            "the hold must not be void"
3050        );
3051        assert!(!loaded.retire_delay_elapsed(&config));
3052
3053        let mut future = MigrationState::new(MigrationPhase::Committed);
3054        future.first_start_unix = now_unix().saturating_add(10 * 365 * 24 * 3600);
3055        future.committed_at_unix = Some(future.first_start_unix);
3056        future.save(dir.path()).expect("save");
3057        let loaded = MigrationState::load_or_new(dir.path(), MigrationPhase::Bridging);
3058        assert!(!loaded.shed_hold_elapsed(&config));
3059        assert!(!loaded.retire_delay_elapsed(&config));
3060    }
3061
3062    #[test]
3063    fn copy_reports_accumulate_across_passes() {
3064        let mut total = CopyReport::default();
3065        total.merge(CopyReport {
3066            copied: 3,
3067            bytes: 300,
3068            ..CopyReport::default()
3069        });
3070        total.merge(CopyReport {
3071            copied: 2,
3072            bytes: 200,
3073            unusable: 1,
3074            stopped_for_space: true,
3075            ..CopyReport::default()
3076        });
3077        assert_eq!(total.copied, 5);
3078        assert_eq!(total.bytes, 500);
3079        assert_eq!(total.unusable, 1);
3080        assert!(total.stopped_for_space);
3081    }
3082    /// A peer that received the commitment and then left the group is not evidence.
3083    ///
3084    /// It is not going to audit this node, so counting it lets a node give chunks up
3085    /// while the neighbours who will audit it still hold it to the old, larger key set.
3086    #[test]
3087    fn a_departed_peer_that_knows_the_commitment_does_not_open_the_gate() {
3088        let received: HashSet<PeerId> = (0..6).map(peer_id).collect();
3089        let still_here: Vec<PeerId> = (0..3).map(peer_id).collect();
3090        let joined_since: Vec<PeerId> = (100..103).map(peer_id).collect();
3091        let current: Vec<PeerId> = still_here
3092            .iter()
3093            .chain(joined_since.iter())
3094            .copied()
3095            .collect();
3096
3097        // Six peers know it and the group is six wide, so a count that ignores who is
3098        // actually here would sail past the threshold.
3099        assert_eq!(received.len(), 6);
3100        assert_eq!(current.len(), 6);
3101        assert!(!enough_of_the_group_knows(&received, &current, 5));
3102
3103        // Only the three that are both here and informed count.
3104        assert!(enough_of_the_group_knows(&received, &current, 3));
3105        assert!(!enough_of_the_group_knows(&received, &current, 4));
3106    }
3107
3108    #[test]
3109    fn a_group_that_has_all_seen_the_commitment_opens_the_gate() {
3110        let group: Vec<PeerId> = (0..6).map(peer_id).collect();
3111        let received: HashSet<PeerId> = group.iter().copied().collect();
3112        assert!(enough_of_the_group_knows(&received, &group, 5));
3113    }
3114
3115    #[test]
3116    fn no_peer_ever_satisfies_a_zero_threshold() {
3117        let group: Vec<PeerId> = (0..6).map(peer_id).collect();
3118        let received: HashSet<PeerId> = group.iter().copied().collect();
3119        // A group this node cannot reason about must not be read as unanimous consent.
3120        assert!(!enough_of_the_group_knows(&received, &group, 0));
3121    }
3122
3123    /// The gate stays shut when routing cannot show a full close group at all.
3124    ///
3125    /// Without a routing view there is no way to tell an informed neighbour from a
3126    /// departed one, and an unanswerable question must not read as a yes.
3127    #[tokio::test]
3128    async fn without_a_routing_view_the_commitment_gate_stays_shut() {
3129        let context = MigrationContext {
3130            p2p: None,
3131            self_id: None,
3132            self_xor: None,
3133            commitment: None,
3134            replication: None,
3135            sync_state: None,
3136            audit_challenge_coordinator: None,
3137            peer_commitments: None,
3138            close_group_size: 7,
3139        };
3140        assert!(!context.neighbours_know_the_commitment().await);
3141    }
3142}