Skip to main content

ant_node/storage/
chunk_store.rs

1//! The node's chunk store: a file store, plus the legacy LMDB environment for as long
2//! as one still exists on disk.
3//!
4//! Every caller in the node talks to this type and sees **one** key set. That is the
5//! detail that keeps quoting, commitments, hints, audits and pruning coherent while a
6//! chunk moves from LMDB to a file: the backing changes, the logical key set does not.
7//!
8//! There is one deliberate asymmetry, and it is the whole safety argument of the
9//! migration. Serving reads the **union**, so the node answers for everything it ever
10//! committed to. The commitment builder reads only the **file-backed** set once the node
11//! has settled on what it will keep, so the node stops claiming keys it is about to give
12//! up. Between those two, a node is at worst over-honest: it serves more than it claims.
13
14use crate::ant_protocol::XorName;
15use crate::error::{Error, Result};
16use crate::logging::{debug, error, info, warn};
17use crate::storage::file_store::{FileStore, FileStoreConfig};
18use crate::storage::lmdb::{LmdbStorage, LmdbStorageConfig};
19use crate::storage::migration::{
20    CopyReport, MigrationConfig, MigrationPhase, MigrationState, REQUIRED_REBUILDS_BEFORE_RETIRE,
21};
22use crate::storage::StorageStats;
23use std::collections::{BTreeMap, BTreeSet};
24use std::io::Write;
25use std::path::{Path, PathBuf};
26use std::sync::Arc;
27use std::time::Duration;
28use tokio_util::sync::CancellationToken;
29
30/// Directory name of the legacy LMDB environment, under the node root.
31pub const LEGACY_ENV_DIR: &str = "chunks.mdb";
32
33/// Suffix for a legacy environment that has been retired but not yet deleted.
34pub const RETIRED_SUFFIX: &str = ".retired";
35
36/// Written inside a chunk environment directory once it has been retired.
37///
38/// The rename that moves the environment aside cannot be shown to be durable off Unix:
39/// there is no way to flush a directory through the standard library, and `MoveFileEx` is
40/// not documented as durable at return without a flag std does not use. So a power loss
41/// can bring the directory back under its old name with its contents already deleted, and
42/// a node that tried to open that would fail to start.
43///
44/// This file is what makes that unambiguous, and it is *inside* the directory rather than
45/// beside it so that it travels with it: a directory that reverts to its old name reverts
46/// carrying its own evidence. It is created with the same create-and-flush that publishes
47/// a chunk, which is documented as durable everywhere, and only after the rename has
48/// already succeeded. So a directory holding it has been retired, whatever it is called,
49/// and one that does not is a live environment and is opened normally.
50///
51/// Deliberately not a file beside the environment. A marker that can outlive the thing it
52/// describes has to be cancelled, cancellation can fail or be lost, and a stale one would
53/// authorise deleting an environment that had since taken a chunk.
54const RETIRED_MARKER: &str = "RETIRED";
55
56/// How many times the background reaper retries deleting a retired directory.
57///
58/// Generous, because giving up strands the disk until the next restart and the thread
59/// costs nothing while it sleeps. With the backoff below this keeps trying for about a
60/// day.
61const RETIRED_DELETE_ATTEMPTS: u32 = 60;
62
63/// Base wait between those attempts, multiplied by the attempt number up to the cap.
64const RETIRED_DELETE_BACKOFF: Duration = Duration::from_secs(10);
65
66/// The longest the reaper waits between attempts.
67const RETIRED_DELETE_BACKOFF_MAX: Duration = Duration::from_secs(30 * 60);
68
69/// How many retired directories may be waiting to be deleted before the node stops
70/// finding new names for them. Far more than a node should ever accumulate.
71const MAX_TOMBSTONES: u32 = 64;
72
73/// The legacy environment's data file. Its presence is what says a node still has one.
74const LEGACY_DATA_FILE: &str = "data.mdb";
75
76/// How many times retirement retries taking sole ownership of the legacy handle before
77/// giving up for this tick.
78const RETIRE_UNWRAP_ATTEMPTS: u32 = 20;
79
80/// How long to wait between those attempts.
81const RETIRE_UNWRAP_BACKOFF: Duration = Duration::from_millis(100);
82
83/// How many chunks the verification pass checks between progress lines.
84const VERIFY_LOG_EVERY: u64 = 2000;
85
86/// How many per-key critical sections the facade keeps.
87///
88/// Keyed on the address's LAST byte, for the same reason the shard directories are: a
89/// node's keys share their leading bytes, so lanes keyed on the first byte would all
90/// collapse into one.
91const KEY_LOCK_LANES: usize = 256;
92
93/// Configuration for [`ChunkStore`].
94#[derive(Debug, Clone)]
95pub struct ChunkStoreConfig {
96    /// Node root directory.
97    pub root_dir: PathBuf,
98    /// Verify `BLAKE3(content) == address` on read.
99    pub verify_on_read: bool,
100    /// Explicit LMDB map size cap in bytes, used only while a legacy environment exists.
101    ///
102    /// Dies with LMDB. Kept so an operator's existing `storage.db_size_gb` still means
103    /// what it meant during the bridge.
104    pub max_map_size: usize,
105    /// Minimum free disk space to preserve on the storage partition.
106    pub disk_reserve: u64,
107    /// Migration controls.
108    pub migration: MigrationConfig,
109}
110
111impl Default for ChunkStoreConfig {
112    fn default() -> Self {
113        Self {
114            root_dir: PathBuf::from(".ant/chunks"),
115            verify_on_read: true,
116            max_map_size: 0,
117            disk_reserve: crate::storage::DEFAULT_DISK_RESERVE,
118            migration: MigrationConfig::default(),
119        }
120    }
121}
122
123impl ChunkStoreConfig {
124    /// A test-friendly default with the disk reserve disabled, so unit tests do not
125    /// depend on the host having spare gigabytes.
126    #[cfg(any(test, feature = "test-utils"))]
127    #[must_use]
128    pub fn test_default() -> Self {
129        Self {
130            disk_reserve: 0,
131            ..Self::default()
132        }
133    }
134}
135
136/// The legacy environment and the keys only it still holds.
137#[derive(Clone)]
138struct Legacy {
139    /// The LMDB handle.
140    lmdb: Arc<LmdbStorage>,
141    /// Keys in the legacy environment that are **not** in the file store.
142    ///
143    /// Kept in memory so the union view costs nothing on the hot paths: `exists` and
144    /// `current_chunks` never touch LMDB, and `all_keys` merges two already-sorted
145    /// sequences. It is derived at open (LMDB keys minus file keys) and maintained by
146    /// every write, copy and delete.
147    only: Arc<parking_lot::RwLock<BTreeSet<XorName>>>,
148    /// Writes that have started and whose outcome is not yet known.
149    ///
150    /// A write into the legacy environment runs on a blocking thread that outlives the
151    /// future waiting for it, so a shutdown can leave the environment holding a chunk
152    /// while nothing ran to record it. A key in neither view is what retirement destroys,
153    /// so every write announces itself here first.
154    ///
155    /// Deliberately NOT part of what the node says it holds. This is a note to itself
156    /// that something is in flight, not a claim: `exists`, `all_keys`, the commitment, the
157    /// quote count and the pruner all ignore it. It vetoes retirement, and the driver
158    /// resolves each entry against what is actually on disk.
159    ///
160    /// How many writes were made without a rollback copy of the chunk in the environment.
161    ///
162    /// The rollback copy is best effort by design, and the ADR says so: a bridging node
163    /// whose environment has no reusable page keeps serving from files and simply has no
164    /// second copy to roll back to. What was missing was any way to ask how often that
165    /// happened. One `warn!` per chunk is not an answer to "how many nodes on this fleet
166    /// are actually keeping a rollback copy", which is the question the second release
167    /// turns on, and on a node with no free pages it is also a line per chunk forever.
168    ///
169    /// Writes, not distinct chunks: two attempts at one address count twice, and a later
170    /// attempt that succeeds does not count back down. Counted before the file half runs,
171    /// so a write that then fails outright is counted too. Keeping a set of addresses
172    /// instead would be exact and would also mean holding millions of them in memory to
173    /// answer a question that a rate answers. Read it as "this node is failing to keep
174    /// rollback copies, this often", not as a chunk count.
175    skipped_rollback_copies: Arc<std::sync::atomic::AtomicU64>,
176
177    /// Counted, not a set, for the reason the file store's `writing` map is counted.
178    /// Cancellation can release the facade's key lane while the blocking half survives, so
179    /// a second write for the same key can start behind the first. With one entry between
180    /// them, whichever returned first would clear it while the other was still queued, and
181    /// a delete arriving in that window would see no announcement, skip draining the
182    /// environment, and let the surviving write land afterwards and put the key back.
183    pending: Arc<parking_lot::RwLock<BTreeMap<XorName, usize>>>,
184}
185
186impl Legacy {
187    /// Note that a chunk went to files alone, and say whether to log it.
188    ///
189    /// Throttled by powers of ten. The condition is usually all-or-nothing, so the first
190    /// few lines say it started and the later ones say it is still going without becoming
191    /// the log.
192    fn note_skipped_rollback_copy(&self) -> Option<u64> {
193        let count = self
194            .skipped_rollback_copies
195            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
196            .saturating_add(1);
197        let round = matches!(
198            count,
199            10 | 100 | 1_000 | 10_000 | 100_000 | 1_000_000 | 10_000_000
200        );
201        (count <= 3 || round).then_some(count)
202    }
203
204    /// Announce a write into the environment, or note a second one for the same key.
205    fn announce(&self, address: &XorName) {
206        *self.pending.write().entry(*address).or_insert(0) += 1;
207    }
208
209    /// Retire one announcement, leaving any other for the same key still standing.
210    fn announced_write_finished(&self, address: &XorName) {
211        let mut pending = self.pending.write();
212        let Some(count) = pending.get_mut(address) else {
213            return;
214        };
215        *count = count.saturating_sub(1);
216        if *count == 0 {
217            pending.remove(address);
218        }
219    }
220}
221
222/// Content-addressed chunk storage.
223pub struct ChunkStore {
224    /// The file store. Always present, always the write target.
225    files: Arc<FileStore>,
226    /// The legacy environment, until it is retired.
227    legacy: parking_lot::RwLock<Option<Legacy>>,
228    /// Excludes retirement while any operation that touches the legacy environment runs.
229    ///
230    /// Reads, writes and deletes take it shared for their whole duration; retirement takes
231    /// it exclusively before it takes the environment away. Sole ownership of the handle
232    /// is not enough on its own: a read that has decided the file store cannot answer, and
233    /// has not yet taken a legacy handle, holds nothing and would be invisible to that
234    /// check. Nor would holding a handle throughout do instead, because on a busy node
235    /// there would always be one and retirement would never see the environment
236    /// unreferenced. Retirement also waits for the environment to go idle, which never
237    /// happens if new work can keep starting in it.
238    ///
239    /// A shared/exclusive lock states the actual requirement, and because it is fair, a
240    /// waiting retirement stops new work starting rather than starving behind it.
241    retirement: tokio::sync::RwLock<()>,
242    /// Where the legacy environment lives.
243    legacy_env_dir: PathBuf,
244    /// Store configuration.
245    config: ChunkStoreConfig,
246    /// The persisted migration marker.
247    state: parking_lot::RwLock<MigrationState>,
248    /// One lock per shard, held across a whole logical key transition.
249    ///
250    /// The file store has its own lane locks, but those only make a single file write
251    /// atomic. The races that matter here span two stores and an await point: the copier
252    /// reads a chunk out of LMDB, the pruner deletes that chunk from both stores, and
253    /// then the copier's write lands and resurrects it. One critical section per key,
254    /// held across put, delete and copy, is what closes that.
255    key_locks: Vec<tokio::sync::Mutex<()>>,
256}
257
258impl ChunkStore {
259    /// Open the store under `config.root_dir`.
260    ///
261    /// Opens the legacy environment only if one is already on disk. A fresh node never
262    /// creates one, so it never pays for a memory map it will not use.
263    ///
264    /// # Errors
265    ///
266    /// Returns [`Error::Storage`] if either store cannot be opened.
267    pub async fn new(config: ChunkStoreConfig) -> Result<Self> {
268        let files = Arc::new(
269            FileStore::new(FileStoreConfig {
270                root_dir: config.root_dir.clone(),
271                verify_on_read: config.verify_on_read,
272                disk_reserve: config.disk_reserve,
273            })
274            .await?,
275        );
276
277        // Before anything looks at the legacy environment: a directory carrying its own
278        // retirement mark is the remains of a removal a power loss interrupted, and is
279        // moved aside rather than opened.
280        let openable = finish_interrupted_retirement(&config.root_dir);
281        let legacy_env_dir = config.root_dir.join(LEGACY_ENV_DIR);
282        let legacy =
283            if openable == LiveEnvironment::WhateverIsOnDisk && legacy_present(&config.root_dir)? {
284                Some(Self::open_legacy(&config, &files).await?)
285            } else {
286                None
287            };
288
289        let phase = if legacy.is_some() {
290            MigrationPhase::Bridging
291        } else {
292            MigrationPhase::FilesOnly
293        };
294        let mut state = MigrationState::load_or_create(&config.root_dir, phase);
295        let legacy_only = Self::legacy_only_count(legacy.as_ref());
296
297        // The filesystem is the authority on whether a legacy environment exists; the
298        // marker only records decisions. Reconcile rather than trust.
299        if legacy.is_none() && state.phase != MigrationPhase::FilesOnly {
300            info!("No legacy chunk environment on disk; the migration is already complete");
301            state.phase = MigrationPhase::FilesOnly;
302            if let Err(e) = state.save(&config.root_dir) {
303                warn!("Could not persist the migration marker: {e}");
304            }
305        } else if legacy.is_some()
306            && state.phase == MigrationPhase::Committed
307            && files.current_chunks().unwrap_or(0) < state.kept_key_count
308        {
309            // The marker says this node already settled on what it would keep, but the
310            // file store holds less than it recorded keeping. Something outside the node
311            // changed the data directory, and trusting the marker here would skip the
312            // copier, the shed rules and their rank checks on the way to deleting the
313            // legacy environment. The filesystem wins.
314            warn!(
315                "The migration marker says this node kept {} chunk(s) but the file store \
316                 holds {}. Restarting the migration from the copying stage.",
317                state.kept_key_count,
318                files.current_chunks().unwrap_or(0)
319            );
320            state.phase = MigrationPhase::Bridging;
321            state.committed_at_unix = None;
322            state.rebuilds_since_commit = 0;
323            if let Err(e) = state.save(&config.root_dir) {
324                warn!("Could not persist the migration marker: {e}");
325            }
326        } else if state.phase == MigrationPhase::Committed && legacy_only > state.shed_key_count {
327            // Once committed, the copier only moves keys the rank check refuses to shed.
328            // A chunk that turns up in the legacy environment after that, and that this
329            // node never agreed to give up, is never copied and never proven to be held
330            // elsewhere, so nothing frees it from the environment and the environment is
331            // never retired. Free disk does not change that; only the phase does.
332            //
333            // The count, not emptiness, is the test. A node that legitimately shed keeps
334            // exactly the keys it is giving up in the legacy environment until they stop
335            // being answerable, and sending it back to the bridge on every restart would
336            // reset its retention clock each time.
337            warn!(
338                migration_event = "back_to_bridging",
339                legacy_only,
340                shed = state.shed_key_count,
341                "The migration marker says this node committed after agreeing to shed {} \
342                 chunk(s), but {legacy_only} are still only in the legacy environment. \
343                 Restarting the migration from the copying stage so they are copied.",
344                state.shed_key_count
345            );
346            state.phase = MigrationPhase::Bridging;
347            state.committed_at_unix = None;
348            state.rebuilds_since_commit = 0;
349            if let Err(e) = state.save(&config.root_dir) {
350                warn!("Could not persist the migration marker: {e}");
351            }
352        } else if legacy.is_some() && state.phase == MigrationPhase::FilesOnly {
353            warn!(
354                "The migration marker says this node is done but {} is still on disk. \
355                 Resuming the bridge.",
356                legacy_env_dir.display()
357            );
358            state.phase = MigrationPhase::Bridging;
359            if let Err(e) = state.save(&config.root_dir) {
360                warn!("Could not persist the migration marker: {e}");
361            }
362        }
363
364        let store = Self {
365            files,
366            legacy: parking_lot::RwLock::new(legacy),
367            retirement: tokio::sync::RwLock::new(()),
368            legacy_env_dir,
369            config,
370            state: parking_lot::RwLock::new(state),
371            key_locks: std::iter::repeat_with(|| tokio::sync::Mutex::new(()))
372                .take(KEY_LOCK_LANES)
373                .collect(),
374        };
375
376        let (file_keys, legacy_keys) = store.split_counts();
377        info!(
378            "Chunk store ready: {file_keys} chunks in files, {legacy_keys} still only in the \
379             legacy environment, phase {:?}",
380            store.migration_phase()
381        );
382        Ok(store)
383    }
384
385    /// Open the legacy environment and work out which keys only it holds.
386    async fn open_legacy(config: &ChunkStoreConfig, files: &FileStore) -> Result<Legacy> {
387        let (lmdb, legacy_keys) = Self::open_legacy_env(config).await?;
388        Ok(Legacy {
389            lmdb,
390            only: Arc::new(parking_lot::RwLock::new(Self::keys_only_in_legacy(
391                &legacy_keys,
392                files,
393            ))),
394            skipped_rollback_copies: Arc::new(std::sync::atomic::AtomicU64::new(0)),
395            pending: Arc::new(parking_lot::RwLock::new(BTreeMap::new())),
396        })
397    }
398
399    /// Open the legacy environment and read every key in it.
400    ///
401    /// Split from the diff against the file store because the two want different timing:
402    /// this is slow and safe to do at any moment, the diff has to be the last thing before
403    /// the handle is installed.
404    async fn open_legacy_env(
405        config: &ChunkStoreConfig,
406    ) -> Result<(Arc<LmdbStorage>, Vec<XorName>)> {
407        let lmdb = Arc::new(
408            LmdbStorage::new(LmdbStorageConfig {
409                root_dir: config.root_dir.clone(),
410                verify_on_read: config.verify_on_read,
411                max_map_size: config.max_map_size,
412                disk_reserve: config.disk_reserve,
413            })
414            .await?,
415        );
416        // From here it never grows. Two stores on one disk each measure the same free
417        // space and neither knows what the other is about to spend, so a chunk written to
418        // both can be admitted twice against one lot of headroom and the pair can cross
419        // the reserve together. Pinned, this one writes only from pages it already has,
420        // so the file store's accounting is the only claim on free disk.
421        //
422        // What it costs is that the rollback copy is made only when the environment has
423        // room of its own. That is the right way round: the copy exists to make a fleet
424        // rollback survivable, not to be the write that has to succeed, and an
425        // environment this migration exists to delete should not be taking new disk to
426        // hold a second copy of something the file store already has.
427        lmdb.pin_growth().await?;
428        let legacy_keys = lmdb.all_keys().await?;
429        Ok((lmdb, legacy_keys))
430    }
431
432    /// Which of `legacy_keys` the file store does not have.
433    ///
434    /// In memory, no I/O: the file store answers from its index. Cheap enough to redo
435    /// immediately before installing a handle, which is the point. A key that lost its
436    /// file while the environment was being read must be in this set, or nothing will
437    /// look for it again and retirement will destroy the copy that is left.
438    fn keys_only_in_legacy(legacy_keys: &[XorName], files: &FileStore) -> BTreeSet<XorName> {
439        legacy_keys
440            .iter()
441            .filter(|key| !files.is_indexed(key))
442            .copied()
443            .collect()
444    }
445
446    /// How many keys only the legacy environment holds; zero once it is gone.
447    fn legacy_only_count(legacy: Option<&Legacy>) -> u64 {
448        legacy.map_or(0, |l| l.only.read().len().try_into().unwrap_or(u64::MAX))
449    }
450
451    /// Take the critical section for one key.
452    async fn key_lock(&self, address: &XorName) -> Option<tokio::sync::MutexGuard<'_, ()>> {
453        let lane = address.last().copied().unwrap_or(0) as usize;
454        match self.key_locks.get(lane) {
455            Some(lock) => Some(lock.lock().await),
456            None => None,
457        }
458    }
459
460    /// A cheap clone of the legacy handle, or `None` once it is retired.
461    fn legacy(&self) -> Option<Legacy> {
462        self.legacy.read().clone()
463    }
464
465    /// `(chunks in files, chunks only in the legacy environment)`.
466    fn split_counts(&self) -> (u64, u64) {
467        // Legacy first, for the reason given on `exists`: a key mid-copy is then counted
468        // twice for an instant rather than not at all, and over-reporting what the node
469        // holds is the safe direction for every caller of `current_chunks`.
470        let legacy = self
471            .legacy()
472            .map_or(0, |l| l.only.read().len().try_into().unwrap_or(u64::MAX));
473        let files = self.files.current_chunks().unwrap_or(0);
474        (files, legacy)
475    }
476
477    /// Store a chunk.
478    ///
479    /// While a legacy environment exists and dual-writing is on, the chunk goes there
480    /// **first**. A chunk uploaded during the bridge to holders that all revert to a
481    /// pre-migration build would otherwise be gone from every one of them, and that is
482    /// real client data, not a replica.
483    ///
484    /// # Returns
485    ///
486    /// `true` if the chunk was newly stored, `false` if either store already had it.
487    ///
488    /// # Errors
489    ///
490    /// Returns [`Error::Storage`] if the content does not hash to `address`, the disk is
491    /// too full, or the write fails.
492    pub async fn put(&self, address: &XorName, content: &[u8]) -> Result<bool> {
493        // Shared, for the reason given on the field: retirement waits for the legacy
494        // environment to go idle, and a write that keeps starting new work in it while
495        // that wait runs makes the wait unbounded. It also stops a write inserting a key
496        // into the legacy-only set after the gates have approved the set that may go.
497        let _using_legacy = self.retirement.read().await;
498        let _lane = self.key_lock(address).await;
499        let legacy = self.legacy();
500        let already_in_legacy = legacy
501            .as_ref()
502            .is_some_and(|l| l.only.read().contains(address));
503
504        let mut dual_written = false;
505        if let Some(ref l) = legacy {
506            if self.config.migration.dual_write_legacy && !already_in_legacy {
507                // The legacy store's own verdict, not the file store's. It accounts for
508                // pages it can reuse internally, which is the right question for a write
509                // into it and the wrong one for the file about to be written. A full
510                // legacy store must not fail a put the file store can serve: the copy is
511                // there to make a fleet rollback survivable, and losing that for one
512                // chunk is much better than refusing the chunk.
513                if l.lmdb.capacity_verdict() == crate::storage::CapacityVerdict::Full {
514                    // Counted here as well as on the failure path below, and this is the
515                    // one that matters: a pinned environment with no reusable page answers
516                    // Full for every chunk, so on the node most affected this is the whole
517                    // of the skipping and the other path never runs at all.
518                    if let Some(count) = l.note_skipped_rollback_copy() {
519                        warn!(
520                            migration_event = "no_rollback_copy",
521                            skipped = count,
522                            "Legacy chunk environment is full; storing {} in files only. A \
523                             rollback to a pre-migration build would not have this chunk, \
524                             and {count} write(s) on this node have now gone without a \
525                             rollback copy.",
526                            hex::encode(address)
527                        );
528                    } else {
529                        debug!(
530                            "Legacy chunk environment is full; storing {} in files only.",
531                            hex::encode(address)
532                        );
533                    }
534                } else {
535                    // Announced BEFORE the write, not after it. The write runs on a
536                    // blocking thread that outlives this future: a shutdown that drops the
537                    // caller mid-way can leave the environment holding a chunk while
538                    // nothing here ever ran to record it, and a key in neither view is
539                    // what retirement destroys. In the in-flight note rather than the key
540                    // set, because until the write returns this node does not hold the
541                    // chunk and must not say it does.
542                    l.announce(address);
543                    // Best effort, and only best effort. The verdict above is optimistic
544                    // by design: LMDB can still refuse a write for fragmentation, pages
545                    // pinned by a long read, or a copy-on-write B-tree split. Propagating
546                    // that would let a store this node is in the middle of abandoning
547                    // reject paid chunks the file store has ample room for, for the whole
548                    // bridge period. The chunk's own validity is not at stake here; the
549                    // file store checks the content address itself.
550                    match l.lmdb.put(address, content).await {
551                        Ok(_) => dual_written = true,
552                        Err(e) => {
553                            if let Some(count) = l.note_skipped_rollback_copy() {
554                                warn!(
555                                    migration_event = "no_rollback_copy",
556                                    skipped = count,
557                                    "Could not also write {} to the legacy environment: \
558                                     {e}. Storing it in files only. A rollback to a \
559                                     pre-migration build would not have this chunk, and \
560                                     {count} write(s) on this node have now gone without a \
561                                     rollback copy.",
562                                    hex::encode(address)
563                                );
564                            }
565                        }
566                    }
567                }
568            }
569        }
570
571        let stored_in_files = match self.files.put(address, content).await {
572            Ok(stored) => stored,
573            Err(e) => {
574                // The bytes reached LMDB but not the file store. Record the key as
575                // legacy-only so the union still finds it and the copier retries later;
576                // without this the node would hold a chunk it could not serve.
577                //
578                // Only when the file store really does not have it. A write can fail
579                // because the file that is already there could not be read to check it,
580                // and calling that key legacy-only while the file index still names it
581                // puts it in both views, where it stays answerable and vetoes retirement
582                // for good.
583                // The file half failed and the legacy half did not, so the environment
584                // holds the only copy and the key really is legacy-only now. Promoted
585                // from the in-flight note to the key set, which is the one moment that
586                // promotion is warranted: both outcomes are known.
587                if let Some(ref l) = legacy {
588                    l.announced_write_finished(address);
589                    if dual_written && !self.files.is_indexed(address) {
590                        l.only.write().insert(*address);
591                    }
592                }
593                return Err(e);
594            }
595        };
596
597        // The file store has it, so it is not legacy-only, whether it was already there
598        // or this call put it there. The in-flight note goes at the same time: both
599        // writes have returned, so there is nothing left in flight to protect.
600        if let Some(ref l) = legacy {
601            l.only.write().remove(address);
602            l.announced_write_finished(address);
603        }
604        if already_in_legacy {
605            // Migrated for free: a hot key the copier no longer has to move.
606            return Ok(false);
607        }
608        Ok(stored_in_files)
609    }
610
611    /// Retrieve a chunk, verifying it against its address when configured to.
612    ///
613    /// # Errors
614    ///
615    /// Returns [`Error::Storage`] on an I/O failure, or when verification fails and no
616    /// intact copy is available.
617    pub async fn get(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
618        // Held for the whole read. A verifying read that finds rotted bytes throws the
619        // file away, and until this key is back in the legacy-only set there is a moment
620        // when it appears to live in neither store. Retirement waits behind this rather
621        // than deleting the copy the read is about to fall back on.
622        let _reading = self.retirement.read().await;
623        let fallback = self.legacy();
624        match self.files.get(address).await {
625            Ok(Some(content)) => Ok(Some(content)),
626            Ok(None) => {
627                // The file store missed. If the legacy store answers, the key has to go
628                // back into the union view: the file index has just dropped it, and a key
629                // in neither view is skipped by the verification pass and destroyed by
630                // retirement.
631                self.serve_from_legacy(address, fallback).await
632            }
633            Err(e) => {
634                // Whatever went wrong with the file, the legacy environment may still
635                // have the bytes, and while it is there it is the point of the bridge to
636                // use them. A verification failure means the file was thrown away; every
637                // other error (a full descriptor table, an I/O fault, an oversized file)
638                // leaves the file in place and unreadable. Both are unservable from the
639                // file store, and both are worth asking the other store about.
640                let verification_failed = format!("{e}").contains("verification failed");
641                warn!(
642                    "Chunk {} could not be served from the file store ({e}); looking for a \
643                     copy in the legacy environment",
644                    hex::encode(address)
645                );
646                let from_legacy = self.serve_from_legacy(address, fallback).await;
647                match from_legacy {
648                    Ok(Some(content)) => Ok(Some(content)),
649                    // Nothing anywhere. Report the original failure rather than a plain
650                    // miss, so the caller can tell the difference. The key is only
651                    // re-queued for copying when the file really went: an unreadable file
652                    // that is still there is not legacy-only, and calling it so is how a
653                    // key ends up claimed through one view and servable through neither.
654                    Ok(None) => Err(e),
655                    Err(legacy_error) => {
656                        if verification_failed {
657                            Err(e)
658                        } else {
659                            Err(legacy_error)
660                        }
661                    }
662                }
663            }
664        }
665    }
666
667    /// Serve a key the file store could not, from the legacy store, and put it back on
668    /// the copier's list.
669    ///
670    /// The whole sequence runs under the key's critical section, including the legacy
671    /// read. Reading first and locking afterwards would let a concurrent delete remove
672    /// both backings in between, and the key would then be re-inserted from bytes that no
673    /// longer exist anywhere: a phantom entry that `exists` reports and `get` never
674    /// satisfies.
675    async fn serve_from_legacy(
676        &self,
677        address: &XorName,
678        legacy: Option<Legacy>,
679    ) -> Result<Option<Vec<u8>>> {
680        // The handle the caller took before it read the file. Not re-fetched here: the
681        // point of taking it early is that it has been held continuously since before the
682        // file could be thrown away, so retirement cannot have run in between.
683        let Some(legacy) = legacy else {
684            return Ok(None);
685        };
686        let _lane = self.key_lock(address).await;
687        let Some(content) = legacy.lmdb.get(address).await? else {
688            return Ok(None);
689        };
690        // Only if the file really is gone: a concurrent write or repair may have put a
691        // good one back while this was waiting for the lock.
692        if !self.files.is_indexed(address) {
693            legacy.only.write().insert(*address);
694            debug!(
695                "Chunk {} served from the legacy environment and re-queued for copying",
696                hex::encode(address)
697            );
698        }
699        Ok(Some(content))
700    }
701
702    /// Retrieve raw chunk bytes without content-address verification.
703    ///
704    /// # Errors
705    ///
706    /// Returns [`Error::Storage`] on an I/O failure.
707    pub async fn get_raw(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
708        // For the reason given on `get`: retirement must not run in the gap between the
709        // file going missing and this key being put back in the union view.
710        let _reading = self.retirement.read().await;
711        let fallback = self.legacy();
712        let from_files = self.files.get_raw(address).await;
713        match from_files {
714            Ok(Some(content)) => return Ok(Some(content)),
715            Ok(None) => {}
716            // Same rule as `get`: while the legacy environment is there it may have the
717            // bytes, and this is the read that drives digest audits, possession checks
718            // and pruning. Answering "no digest" for a chunk the node can still produce
719            // is a failed audit for nothing.
720            Err(e) => {
721                let Some(legacy) = fallback else {
722                    return Err(e);
723                };
724                let _lane = self.key_lock(address).await;
725                return match legacy.lmdb.get_raw(address).await {
726                    Ok(Some(content)) => Ok(Some(content)),
727                    // Nothing anywhere: report the original failure, not a plain miss.
728                    Ok(None) | Err(_) => Err(e),
729                };
730            }
731        }
732        // Deliberately not gated on the legacy-only set. A chunk that was copied and then
733        // lost its file is not in that set, and the legacy environment is exactly where
734        // its bytes still are. An LMDB miss is cheap. Goes through the same path as
735        // `get`, so the key is restored to the union view rather than being served once
736        // and then quietly retired away.
737        let Some(legacy) = fallback else {
738            return Ok(None);
739        };
740        let _lane = self.key_lock(address).await;
741        let raw = legacy.lmdb.get_raw(address).await?;
742        let missing_locally = !self.files.is_indexed(address);
743        if raw.is_some() && missing_locally {
744            legacy.only.write().insert(*address);
745        }
746        Ok(raw)
747    }
748
749    /// Check whether a chunk is stored, in either backing.
750    ///
751    /// An in-memory lookup: no syscall, no I/O, in both phases.
752    ///
753    /// # Errors
754    ///
755    /// Never fails. The signature is kept because callers treat an error as "absent".
756    pub fn exists(&self, address: &XorName) -> Result<bool> {
757        // Legacy first, deliberately. The copier writes the file and only then drops the
758        // key from the legacy-only set, so a reader that checked files first could
759        // observe the gap between those two steps and report a chunk the node definitely
760        // holds as absent. In this order the same interleaving yields a harmless
761        // duplicate instead.
762        if self
763            .legacy()
764            .is_some_and(|l| l.only.read().contains(address))
765        {
766            return Ok(true);
767        }
768        self.files.exists(address)
769    }
770
771    /// Does this node already hold `address` with exactly these bytes, and if it holds a
772    /// damaged copy, replace it with these?
773    ///
774    /// The question a responder has to answer before turning away an offered copy. Plain
775    /// [`Self::exists`] answers from names alone, and a name can outlive the bytes under
776    /// it: off Unix a chunk is created under its final name before it is written, so a
777    /// crash leaves a short file that `exists` reports as a chunk, and bit rot leaves a
778    /// full-length one. Acknowledging a client on the strength of either throws away the
779    /// copy that would repair it, and nothing offers it again.
780    ///
781    /// So this reads. It is affordable because the only caller is the client-facing PUT
782    /// path, reached when a client offers a chunk this node already has, and because the
783    /// alternative is keeping a chunk this node cannot serve and being penalised for it at
784    /// the next audit.
785    ///
786    /// `content` must already hash to `address`; the caller checks that before this is
787    /// reached, and a repair from bytes that do not would be worse than the damage.
788    ///
789    /// # Errors
790    ///
791    /// Never fails. An unreadable chunk answers `false`, so the offered copy is stored
792    /// through the ordinary path rather than refused.
793    pub async fn holds_verified(&self, address: &XorName, content: &[u8]) -> bool {
794        // Held for the whole check, like every other operation that can reach the legacy
795        // environment.
796        let _using_legacy = self.retirement.read().await;
797        // And the key's own critical section, for the whole of it. Without it the pruner
798        // can delete both backings between the read and the answer, and the offered copy
799        // would be turned away for a chunk the node no longer has at all.
800        let _lane = self.key_lock(address).await;
801
802        if let Some(legacy) = self.legacy() {
803            if legacy.only.read().contains(address) {
804                // Held only in the legacy environment. Not taken on trust either: the
805                // bytes in there can be wrong too, and the copier drops such a key from
806                // the union when it finds out, which would leave no copy anywhere if this
807                // had turned the good one away.
808                if matches!(legacy.lmdb.get_raw(address).await, Ok(Some(bytes)) if bytes == content)
809                {
810                    return true;
811                }
812                warn!(
813                    "Chunk {} is in the legacy environment but its bytes are wrong; \
814                     storing the copy just offered instead",
815                    hex::encode(address)
816                );
817                if self.files.put(address, content).await.is_err() {
818                    return false;
819                }
820                legacy.only.write().remove(address);
821                return true;
822            }
823        }
824        if !self.files.is_indexed(address) {
825            return false;
826        }
827        // No cheap length pre-check. `metadata` failing is not the same as a length that
828        // does not match, and off Unix replacing a chunk truncates it in place, so acting
829        // on an unanswered question would empty a healthy sole copy. The read below
830        // distinguishes them.
831        match self.files.get_raw(address).await {
832            // Byte-for-byte what the caller has, and the caller checked those bytes
833            // against the address before getting here. Nothing is wrong with this file.
834            Ok(Some(stored)) if stored == content => {
835                self.files.note_bytes_proven_good(address);
836                true
837            }
838            Ok(_) => {
839                warn!(
840                    "Chunk {} is on disk but its contents are wrong; replacing it with the \
841                     copy just offered",
842                    hex::encode(address)
843                );
844                // Recorded before the repair is attempted, not after it succeeds. A
845                // repair can fail for capacity or I/O, and a chunk proven wrong that goes
846                // on looking healthy leaves a cached pre-retirement pass covering it,
847                // which deletes the legacy copy the repair would have come from.
848                self.files.note_known_wrong(address);
849                self.files.repair(address, content).await.is_ok()
850            }
851            // Unanswerable this time. Not claimed as held, so the offer goes through the
852            // ordinary path, which writes it rather than replacing anything.
853            Err(e) => {
854                warn!("Could not read {} to check it: {e}", hex::encode(address));
855                false
856            }
857        }
858    }
859
860    /// Delete a chunk from both backings.
861    ///
862    /// A logical delete has to reach the legacy environment too, or the union view would
863    /// resurrect the key on the next read. It frees no space there — only removing the
864    /// environment whole does that — but it keeps the two views honest.
865    ///
866    /// # Errors
867    ///
868    /// Returns [`Error::Storage`] if a file exists but cannot be removed.
869    pub async fn delete(&self, address: &XorName) -> Result<bool> {
870        // Shared, like every other operation that touches the legacy environment. Without
871        // it, retirement takes the exclusive guard and then waits for the environment to
872        // go idle while deletes keep starting new work in it, and the wait never ends.
873        let _using_legacy = self.retirement.read().await;
874        let _lane = self.key_lock(address).await;
875        // Behind whatever is already writing this key, and only this key. A write's
876        // blocking half outlives the future that started it, so one landing after this
877        // would put back a chunk the node had decided to prune.
878        self.files.wait_for_write(address).await;
879        // Legacy first, and only then the in-memory views. The other order removes the
880        // key from `only` and then, if the legacy delete fails, leaves bytes that live
881        // solely in the legacy store and are invisible to `exists`, `all_keys` and the
882        // pre-retirement verification, so retirement would take the only copy.
883        let from_legacy = match self.legacy() {
884            Some(legacy) => {
885                // A write for this key that nobody waited for may still be queued behind
886                // this delete. Letting it land afterwards would resurrect the key: the
887                // next reconciliation finds it in the environment and puts it back on the
888                // copier's list, undoing a prune the node decided on. Waited out here,
889                // holding the lane, so the delete is genuinely last.
890                //
891                // Both halves. A write has an environment half and a file half, either of
892                // which can be the one still running, and draining only the first leaves
893                // the second free to publish the file after this has deleted it.
894                //
895                // The environment half is found through the journal, which only dual
896                // writes keep. The file half is asked of the file store directly, because
897                // the copier and the repair path also spawn file writes and neither goes
898                // near that journal: using it as a proxy for "is anything writing this
899                // key" was a scope assumption, not a fact.
900                if legacy.pending.read().contains_key(address) {
901                    legacy.lmdb.wait_idle().await;
902                }
903                let deleted = legacy.lmdb.delete(address).await?;
904                let was_only = legacy.only.write().remove(address);
905                // Every announcement for this key, not one of them: the drain above waited
906                // out whatever was in flight and this delete is deliberately last.
907                legacy.pending.write().remove(address);
908                deleted || was_only
909            }
910            None => false,
911        };
912        let from_files = self.files.delete(address).await?;
913        Ok(from_files || from_legacy)
914    }
915
916    /// Every stored key, in ascending order, across both backings.
917    ///
918    /// The order is a correctness requirement: the commitment builder truncates the
919    /// responsible subset with `take(cap)` *before* the Merkle tree sorts it, so an
920    /// unstable order would make the node's published commitment depend on iteration
921    /// luck rather than on what it holds.
922    ///
923    /// # Errors
924    ///
925    /// Returns [`Error::Storage`] if the file index cannot be read.
926    pub async fn all_keys(&self) -> Result<Vec<XorName>> {
927        // Legacy first, for the reason given on `exists`. `merge_sorted` drops the
928        // duplicate that the overlap produces.
929        let legacy_only: Vec<XorName> = self
930            .legacy()
931            .map(|l| l.only.read().iter().copied().collect())
932            .unwrap_or_default();
933        let file_keys = self.files.all_keys().await?;
934        if legacy_only.is_empty() {
935            return Ok(file_keys);
936        }
937        Ok(merge_sorted(&file_keys, legacy_only.iter()))
938    }
939
940    /// The keys the commitment builder should commit to.
941    ///
942    /// While the node is still bridging this is the whole union, because it can still
943    /// serve all of it and dropping the claim early would collapse its commitment (and
944    /// with it its quoted price) for no reason. Once it has settled on what it will keep,
945    /// this narrows to the file-backed set, which is exactly the point at which the node
946    /// stops claiming keys it is about to give up.
947    ///
948    /// # Errors
949    ///
950    /// Returns [`Error::Storage`] if the file index cannot be read.
951    pub async fn committable_keys(&self) -> Result<Vec<XorName>> {
952        match self.migration_phase() {
953            MigrationPhase::Bridging => self.all_keys().await,
954            MigrationPhase::Committed | MigrationPhase::FilesOnly => self.files.all_keys().await,
955        }
956    }
957
958    /// Number of chunks currently stored, counted across both backings without
959    /// double-counting a chunk that is in each.
960    ///
961    /// # Errors
962    ///
963    /// Never fails.
964    pub fn current_chunks(&self) -> Result<u64> {
965        let (files, legacy) = self.split_counts();
966        Ok(files.saturating_add(legacy))
967    }
968
969    /// Operation statistics.
970    ///
971    /// The cumulative counters are the file store's; `current_chunks` is the union.
972    #[must_use]
973    pub fn stats(&self) -> StorageStats {
974        let mut stats = self.files.stats();
975        stats.current_chunks = self.current_chunks().unwrap_or(0);
976        stats
977    }
978
979    /// Compute a content address (BLAKE3 hash).
980    #[must_use]
981    pub fn compute_address(content: &[u8]) -> XorName {
982        crate::client::compute_address(content)
983    }
984
985    /// The node root directory.
986    #[must_use]
987    pub fn root_dir(&self) -> &Path {
988        &self.config.root_dir
989    }
990
991    /// Reject work early when the disk cannot take another chunk at all.
992    ///
993    /// # Errors
994    ///
995    /// Returns [`Error::Storage`] when free space is below the configured reserve.
996    pub fn check_capacity(&self) -> Result<()> {
997        self.files.check_capacity()
998    }
999
1000    /// Whether the store can take a write at all right now.
1001    ///
1002    /// Answered by the file store, which is where writes land. The legacy environment's
1003    /// own verdict is deliberately not consulted: it accounts for pages it can reuse
1004    /// internally, and a reusable page in a store this node is moving *off* says nothing
1005    /// about whether the file it is about to write will fit.
1006    ///
1007    /// Three-way, not two. The verification cycle treats `Full` as a standing condition
1008    /// worth minutes of backoff, so folding a failed free-space query into it would latch
1009    /// a transient filesystem hiccup into a stall on a node that is not full at all.
1010    #[must_use]
1011    pub(crate) fn capacity_verdict(&self) -> crate::storage::CapacityVerdict {
1012        self.files.capacity_verdict()
1013    }
1014
1015    /// Reject work early when the disk cannot take `bytes` more.
1016    ///
1017    /// Free bytes alone stopped being a sufficient answer once chunks became files.
1018    ///
1019    /// # Errors
1020    ///
1021    /// Returns [`Error::Storage`] when the write would not fit above the reserve.
1022    pub fn check_capacity_for(&self, bytes: u64) -> Result<()> {
1023        self.files.check_capacity_for(bytes)
1024    }
1025
1026    /// Wait until every blocking task in either backing has finished.
1027    pub async fn wait_idle(&self) {
1028        self.files.wait_idle().await;
1029        if let Some(legacy) = self.legacy() {
1030            legacy.lmdb.wait_idle().await;
1031        }
1032    }
1033
1034    // ── Migration ───────────────────────────────────────────────────────────
1035
1036    /// Where the node is in the migration.
1037    #[must_use]
1038    pub fn migration_phase(&self) -> MigrationPhase {
1039        self.state.read().phase
1040    }
1041
1042    /// A snapshot of the persisted migration marker.
1043    #[must_use]
1044    pub fn migration_state(&self) -> MigrationState {
1045        self.state.read().clone()
1046    }
1047
1048    /// The migration settings this store was built with.
1049    #[must_use]
1050    pub fn migration_config(&self) -> &MigrationConfig {
1051        &self.config.migration
1052    }
1053
1054    /// Whether a legacy environment is still open.
1055    #[must_use]
1056    pub fn has_legacy(&self) -> bool {
1057        self.legacy.read().is_some()
1058    }
1059
1060    /// The keys the legacy environment still holds alone, ascending.
1061    #[must_use]
1062    pub fn legacy_only_keys(&self) -> Vec<XorName> {
1063        self.legacy()
1064            .map(|l| l.only.read().iter().copied().collect())
1065            .unwrap_or_default()
1066    }
1067
1068    /// Bytes the legacy environment occupies, as the filesystem sees it.
1069    #[must_use]
1070    pub fn legacy_bytes(&self) -> u64 {
1071        std::fs::metadata(self.legacy_env_dir.join(LEGACY_DATA_FILE)).map_or(0, |m| m.len())
1072    }
1073
1074    /// Test-only handle to the file store's put gate.
1075    #[cfg(any(test, feature = "test-utils"))]
1076    #[must_use]
1077    pub fn test_put_gate(&self) -> Arc<parking_lot::RwLock<()>> {
1078        self.files.test_put_gate()
1079    }
1080
1081    /// Test-only: adjust the persisted migration marker directly.
1082    ///
1083    /// Real transitions go through [`Self::commit_to_files`] and
1084    /// [`Self::note_commitment_rebuilt`]; this exists so a test can put a store into a
1085    /// state that would otherwise take hours of wall clock to reach.
1086    #[cfg(any(test, feature = "test-utils"))]
1087    pub fn force_migration_state<F: FnOnce(&mut MigrationState)>(&self, f: F) {
1088        f(&mut self.state.write());
1089    }
1090
1091    /// Copy up to `keys.len()` chunks out of the legacy environment into files.
1092    ///
1093    /// Stops as soon as free space would fall below `slack` above the configured
1094    /// reserve, so a migration never fills the disk it is trying to free.
1095    ///
1096    /// # Errors
1097    ///
1098    /// Returns [`Error::Storage`] only for failures that are not per-key: a per-key
1099    /// problem is counted in the report and the pass continues.
1100    pub async fn copy_batch(
1101        &self,
1102        keys: &[XorName],
1103        slack: u64,
1104        throttle_mib_per_sec: u64,
1105        shutdown: &CancellationToken,
1106    ) -> Result<CopyReport> {
1107        let mut report = CopyReport::default();
1108        let Some(legacy) = self.legacy() else {
1109            return Ok(report);
1110        };
1111
1112        for key in keys {
1113            // Checked per chunk, not per batch. Everything here is idempotent and
1114            // re-derived at the next start, so stopping between two chunks costs nothing
1115            // and stops shutdown waiting out a whole pass.
1116            if shutdown.is_cancelled() {
1117                break;
1118            }
1119            let lane = self.key_lock(key).await;
1120            // Re-checked inside the critical section. A prune that landed while this
1121            // pass was running has already taken the key out of the legacy-only set, and
1122            // copying it now would resurrect a chunk the node deliberately deleted.
1123            if !legacy.only.read().contains(key) {
1124                continue;
1125            }
1126            // Physically, again: a chunk the store holds and cannot read is not one to
1127            // copy over the top of, and it is not legacy-only either.
1128            if self.files.is_indexed(key) {
1129                legacy.only.write().remove(key);
1130                continue;
1131            }
1132            // Reserve room for a full chunk plus the slack floor before reading, so the
1133            // copier stops with headroom rather than on a failed write.
1134            if self.files.check_capacity_for(slack).is_err() {
1135                report.stopped_for_space = true;
1136                break;
1137            }
1138
1139            let Some(bytes) = legacy.lmdb.get_raw(key).await? else {
1140                report.vanished += 1;
1141                legacy.only.write().remove(key);
1142                continue;
1143            };
1144            let len = bytes.len() as u64;
1145
1146            match self.files.put(key, &bytes).await {
1147                Ok(_) => {
1148                    legacy.only.write().remove(key);
1149                    report.copied += 1;
1150                    report.bytes += len;
1151                }
1152                Err(e) => {
1153                    let message = format!("{e}");
1154                    // Bigger than this build will ever serve. The legacy store took it
1155                    // through an API with no size bound; the file store will not, and no
1156                    // amount of retrying changes that. Counted as unusable and removed,
1157                    // like a record whose bytes do not match, or one such record would
1158                    // stop this node and every node sharing its disk from ever reclaiming
1159                    // space.
1160                    if message.contains("byte maximum") {
1161                        warn!(
1162                            "Chunk {} in the legacy environment is larger than this build \
1163                             will store; removing it. It cannot be served either way.",
1164                            hex::encode(key)
1165                        );
1166                        match legacy.lmdb.delete(key).await {
1167                            Ok(_) => {
1168                                legacy.only.write().remove(key);
1169                                report.unusable += 1;
1170                            }
1171                            Err(e) => warn!(
1172                                "Oversized chunk {} could not be removed from the legacy \
1173                                 environment: {e}. The environment stays.",
1174                                hex::encode(key)
1175                            ),
1176                        }
1177                        continue;
1178                    }
1179                    if message.contains("Content address mismatch") {
1180                        // The legacy bytes do not hash to their own key, so this chunk
1181                        // cannot be reproduced and was never servable. Stop advertising
1182                        // it rather than carrying a key we cannot answer for.
1183                        //
1184                        // Deleted from the environment too, and only dropped from the key
1185                        // set once that has worked. Leaving the record behind puts the
1186                        // key in neither view, which the pre-retirement pass reads as a
1187                        // chunk to protect and puts straight back — and the next copier
1188                        // pass drops it again. One malformed record would keep a node,
1189                        // and every node sharing its disk, from ever reclaiming space.
1190                        warn!(
1191                            "Chunk {} in the legacy environment does not match its address; \
1192                             removing it so replication can repair it",
1193                            hex::encode(key)
1194                        );
1195                        match legacy.lmdb.delete(key).await {
1196                            Ok(_) => {
1197                                legacy.only.write().remove(key);
1198                                report.unusable += 1;
1199                            }
1200                            Err(e) => warn!(
1201                                "Chunk {} does not match its address and could not be \
1202                                 removed from the legacy environment: {e}. It stays on the \
1203                                 list and the environment stays.",
1204                                hex::encode(key)
1205                            ),
1206                        }
1207                        continue;
1208                    }
1209                    if message.contains("Insufficient disk space") {
1210                        report.stopped_for_space = true;
1211                        break;
1212                    }
1213                    return Err(e);
1214                }
1215            }
1216
1217            // Outside the critical section on purpose: at 32 MiB/s a 4 MiB chunk sleeps
1218            // for over a tenth of a second, and a shard lane held for that would stall
1219            // every write sharing its last address byte for the whole pass.
1220            drop(lane);
1221            if let Some(delay) = throttle_delay(len, throttle_mib_per_sec) {
1222                tokio::time::sleep(delay).await;
1223            }
1224        }
1225        Ok(report)
1226    }
1227
1228    /// Settle on the file-backed set: from now on the node commits only to what it will
1229    /// keep, while still serving everything it ever committed to.
1230    ///
1231    /// # Errors
1232    ///
1233    /// Returns [`Error::Storage`] if the marker cannot be persisted.
1234    pub fn commit_to_files(&self) -> Result<()> {
1235        let shed = self
1236            .legacy()
1237            .map_or(0, |l| l.only.read().len().try_into().unwrap_or(u64::MAX));
1238        let kept = self.files.current_chunks().unwrap_or(0);
1239        // Written to disk before it is published in memory. The other order leaves this
1240        // process acting as `Committed` (and so committing only to file-backed keys)
1241        // while the marker still says `Bridging`, so a restart would silently undo it.
1242        let candidate = {
1243            let state = self.state.read();
1244            if state.phase != MigrationPhase::Bridging {
1245                return Ok(());
1246            }
1247            MigrationState {
1248                phase: MigrationPhase::Committed,
1249                committed_at_unix: None,
1250                rebuilds_since_commit: 0,
1251                shed_key_count: shed,
1252                kept_key_count: kept,
1253                ..state.clone()
1254            }
1255        };
1256        candidate.save(&self.config.root_dir)?;
1257        *self.state.write() = candidate;
1258        if shed == 0 {
1259            info!("Committed to the file-backed key set; nothing has to be shed");
1260        } else {
1261            info!(
1262                "Committed to the file-backed key set; {shed} chunk(s) will be shed and \
1263                 refetched once the legacy environment is gone and there is room"
1264            );
1265        }
1266        Ok(())
1267    }
1268
1269    /// Record that the commitment builder has read and published the committable set.
1270    ///
1271    /// The retirement gate counts these: one proves the builder saw the new set, two
1272    /// prove it survived a rotation, which is what makes the answerability window
1273    /// meaningful rather than notional.
1274    pub fn note_commitment_rebuilt(&self) {
1275        let should_save = {
1276            let mut state = self.state.write();
1277            if state.phase != MigrationPhase::Committed {
1278                return;
1279            }
1280            if state.committed_at_unix.is_none() {
1281                state.committed_at_unix = Some(crate::storage::migration::now_unix());
1282            }
1283            state.rebuilds_since_commit = state.rebuilds_since_commit.saturating_add(1);
1284            state.rebuilds_since_commit <= REQUIRED_REBUILDS_BEFORE_RETIRE
1285        };
1286        if should_save {
1287            let snapshot = self.state.read().clone();
1288            if let Err(e) = snapshot.save(&self.config.root_dir) {
1289                warn!("Could not persist the migration marker: {e}");
1290            }
1291        }
1292    }
1293
1294    /// Whether every gate on deleting the legacy environment is satisfied.
1295    ///
1296    /// `still_answerable` is asked of each key the node is about to give up: the pruner's
1297    /// existing retention contract, reused verbatim. A key still covered by a retained
1298    /// commitment slot vetoes the delete, because the node could still be challenged on it.
1299    pub fn retirement_blocker<F>(&self, still_answerable: F) -> Option<String>
1300    where
1301        F: Fn(&XorName) -> bool,
1302    {
1303        // Before anything else, and whether or not there is a handle. An environment this
1304        // node cannot classify must not be retired, and asking only on the no-handle path
1305        // meant the ordinary path never asked: a node holding its store open went through
1306        // every gate, renamed the directory aside and deleted it.
1307        if self.legacy_cannot_be_classified() {
1308            return Some(format!(
1309                "{} cannot be read well enough to say whether it was already retired. \
1310                 Nothing will be deleted until it can. Check that the directory and \
1311                 anything inside it can be read.",
1312                self.legacy_env_dir.display()
1313            ));
1314        }
1315        if !self.has_legacy() {
1316            // No handle is not the same as no environment. A rename that failed and then
1317            // could not be reopened leaves exactly that: the directory is still on disk
1318            // and this node can no longer read it. Answering "nothing blocks retirement"
1319            // would have the driver log the migration complete over a store that is still
1320            // there and still holding chunks nothing else can serve.
1321            let mark = retirement_mark(&self.legacy_env_dir);
1322            if legacy_present(&self.config.root_dir).unwrap_or(true) && !mark.permits_removal() {
1323                // Two different situations wearing one message would send an operator to
1324                // the wrong place. One is a store this node cannot open; the other is a
1325                // store nothing can even classify, which usually means a permission or a
1326                // mount, and which the node deliberately will not act on either way.
1327                if mark == RetirementMark::Unknown {
1328                    return Some(format!(
1329                        "{} is still on disk and this node cannot tell whether it was \
1330                         retired, so it will neither open it nor remove it. Check that the \
1331                         directory and anything inside it can be read.",
1332                        self.legacy_env_dir.display()
1333                    ));
1334                }
1335                return Some(format!(
1336                    "{} is still on disk but this node has no handle to it. It cannot be \
1337                     read, verified or removed until the node is restarted.",
1338                    self.legacy_env_dir.display()
1339                ));
1340            }
1341            return None;
1342        }
1343        if !self.config.migration.retire_legacy {
1344            return Some(
1345                "retirement is disabled in this release (storage.migration.retire_legacy)".into(),
1346            );
1347        }
1348        // A linked environment is never retired automatically. Retirement renames the
1349        // path and then deletes what is behind it, and behind a link is a directory
1350        // somewhere else that this node does not own. Copying still happens; only the
1351        // removal is refused, so the node ends up serving from files with its old store
1352        // intact and its operator told what to do about it.
1353        if is_a_link(&self.legacy_env_dir) {
1354            return Some(format!(
1355                "{} is a link rather than a directory. The chunks are being copied out of \
1356                 it, but it will not be deleted: what it points at is not this node's to \
1357                 remove. Once the migration has settled, delete it by hand.",
1358                self.legacy_env_dir.display()
1359            ));
1360        }
1361        let state = self.state.read().clone();
1362        if state.phase != MigrationPhase::Committed {
1363            return Some(format!("phase is {:?}, not Committed", state.phase));
1364        }
1365        if state.rebuilds_since_commit < REQUIRED_REBUILDS_BEFORE_RETIRE {
1366            return Some(format!(
1367                "only {} of {REQUIRED_REBUILDS_BEFORE_RETIRE} commitment rebuilds observed",
1368                state.rebuilds_since_commit
1369            ));
1370        }
1371        if !state.retire_delay_elapsed(&self.config.migration) {
1372            return Some(format!(
1373                "the {}h retirement delay has not elapsed",
1374                self.config.migration.effective_retire_delay_hours()
1375            ));
1376        }
1377        if let Some(key) = self
1378            .legacy_only_keys()
1379            .into_iter()
1380            .find(|k| still_answerable(k))
1381        {
1382            return Some(format!(
1383                "chunk {} is still answerable under a retained commitment",
1384                hex::encode(key)
1385            ));
1386        }
1387        None
1388    }
1389
1390    /// Re-hash every chunk that both stores hold, repairing the file from the legacy
1391    /// copy when they disagree.
1392    ///
1393    /// A filename is not proof the bytes behind it are good. The startup scan reads
1394    /// names only, so a file that was truncated or that rotted while the node was down is
1395    /// indexed, counted as copied, committed to, and would have its intact legacy copy
1396    /// deleted underneath it. The first verified read would then find the corruption with
1397    /// nothing left to repair from. This pass is what turns "a file with that name
1398    /// exists" into "those bytes are that chunk", and it is why it runs before
1399    /// retirement rather than after.
1400    ///
1401    /// # Errors
1402    ///
1403    /// Returns [`Error::Storage`] if the legacy key set cannot be read.
1404    pub async fn verify_before_retire(
1405        &self,
1406        throttle_mib_per_sec: u64,
1407        shutdown: &CancellationToken,
1408    ) -> Result<VerifyReport> {
1409        let mut report = VerifyReport::default();
1410        // Taken BEFORE anything is read. Stamping it at the end would absorb exactly the
1411        // failures this exists to catch: a chunk verified early in the pass that stops
1412        // being readable before the pass finishes would leave the report carrying the
1413        // already-incremented count, and both later checks would see it match.
1414        let health_at_start = self.files.health_generation();
1415        let Some(legacy) = self.legacy() else {
1416            report.ran = true;
1417            report.health = health_at_start;
1418            return Ok(report);
1419        };
1420        report.ran = true;
1421
1422        // Names before bytes. A chunk whose contents are durable but whose directory entry
1423        // is not is still lost to a power loss, and the legacy copy is about to be deleted
1424        // on the strength of this proof. Any failure here is a proof this pass did not
1425        // produce.
1426        if let Err(e) = self.files.flush_namespace() {
1427            report.unrepairable = report.unrepairable.saturating_add(1);
1428            warn!(
1429                "Could not make the file store's directory entries durable: {e}. The legacy \
1430                 environment stays until they are."
1431            );
1432            return Ok(report);
1433        }
1434
1435        let legacy_keys = legacy.lmdb.all_keys().await?;
1436        let total = legacy_keys.len();
1437        info!("Verifying {total} chunk(s) before removing the legacy environment");
1438        let mut since_log = 0u64;
1439        for key in legacy_keys {
1440            // This pass is a full read of the store and can run for hours. A shutdown
1441            // must not wait it out, and an incomplete pass is simply not a clean proof.
1442            if shutdown.is_cancelled() {
1443                report.unrepairable = report.unrepairable.saturating_add(1);
1444                debug!("Pre-retirement verification stopped for shutdown");
1445                return Ok(report);
1446            }
1447            // Under the key's critical section, so the two questions below are asked of
1448            // one moment. Without it a write can publish the file and take the key out of
1449            // the legacy-only set in between, and this pass would put it straight back.
1450            let classified = {
1451                let _lane = self.key_lock(&key).await;
1452                // The physical question. A chunk the store holds but cannot currently
1453                // read is still one it holds, and calling it absent here would put the
1454                // key in the legacy-only set, where the union view advertises it again.
1455                let in_files = self.files.is_indexed(&key);
1456                let legacy_only = legacy.only.read().contains(&key);
1457                if in_files && legacy_only {
1458                    // In both views at once, which nothing else clears once the copier
1459                    // has stopped running. The file store has it, so the legacy-only set
1460                    // is the one that is wrong: an answerable key in that set vetoes
1461                    // retirement for as long as the process lives.
1462                    debug!(
1463                        "Chunk {} was in both views; the file store has it, so it is no \
1464                         longer legacy-only",
1465                        hex::encode(key)
1466                    );
1467                    legacy.only.write().remove(&key);
1468                }
1469                (in_files, legacy_only)
1470            };
1471            if !classified.0 {
1472                // Known to be legacy-only, which is what a key this node is giving up
1473                // looks like. Whether it may go is the gates' decision, not this pass's.
1474                if classified.1 {
1475                    continue;
1476                }
1477                // In neither view. However that came about — a publish that failed, a
1478                // file quarantined for corruption, a name this store stopped advertising —
1479                // the environment holds the only copy, and nothing is looking after it:
1480                // the gates only ever see the legacy-only set. Put it back there and
1481                // refuse the proof this pass. What neither view protects is exactly what
1482                // retirement destroys.
1483                warn!(
1484                    "Chunk {} is in the legacy environment, is not in the file store, and \
1485                     was in neither view; re-queued for copying and the legacy environment \
1486                     stays",
1487                    hex::encode(key)
1488                );
1489                legacy.only.write().insert(key);
1490                report.unrepairable = report.unrepairable.saturating_add(1);
1491                continue;
1492            }
1493            since_log += 1;
1494            if since_log >= VERIFY_LOG_EVERY {
1495                since_log = 0;
1496                info!(
1497                    "Pre-retirement verification: {} of at most {total} chunk(s) checked",
1498                    report.checked
1499                );
1500            }
1501            let outcome = self.verify_one(&legacy, &key).await;
1502            report.checked += 1;
1503            report.bytes += outcome.bytes;
1504            match outcome.verdict {
1505                VerifyVerdict::Intact => {}
1506                VerifyVerdict::Repaired => report.repaired += 1,
1507                VerifyVerdict::Vanished => {
1508                    // The file went away while this pass was running, so the key is no
1509                    // longer file-backed. Put it back on the copier's list rather than
1510                    // republishing it here, where it could resurrect something the
1511                    // pruner deleted a moment ago.
1512                    legacy.only.write().insert(key);
1513                    report.unrepairable += 1;
1514                }
1515                VerifyVerdict::Unrepairable => report.unrepairable += 1,
1516            }
1517            if let Some(delay) = throttle_delay(outcome.bytes, throttle_mib_per_sec) {
1518                tokio::time::sleep(delay).await;
1519            }
1520        }
1521
1522        if report.unrepairable == 0 {
1523            info!(
1524                "Pre-retirement verification passed: {} chunk(s) checked, {} repaired",
1525                report.checked, report.repaired
1526            );
1527        }
1528        // The count this pass started from, and a refusal if the store moved while it
1529        // ran. Retirement compares the same value again immediately before deleting
1530        // anything, so one number covers both windows: during the pass, and after it.
1531        report.health = health_at_start;
1532        if self.files.health_generation() != health_at_start {
1533            warn!(
1534                "A chunk stopped being servable while the pre-retirement pass was running, \
1535                 so this pass does not describe the store. Another runs on the next tick."
1536            );
1537            report.unrepairable = report.unrepairable.saturating_add(1);
1538        }
1539        Ok(report)
1540    }
1541
1542    /// Check one chunk that both stores hold, repairing the file if it is wrong.
1543    async fn verify_one(&self, legacy: &Legacy, key: &XorName) -> VerifyOutcome {
1544        // The throttle sleep is deliberately outside this critical section: at 32 MiB/s a
1545        // 4 MiB chunk sleeps for over a tenth of a second, and holding a shard lane for
1546        // that would stall every write to a sixteenth of the address space for hours.
1547        let _lane = self.key_lock(key).await;
1548
1549        let bytes = match self.files.get_raw(key).await {
1550            Ok(bytes) => bytes,
1551            // Not the same as gone. `Vanished` puts the key back on the copier's list,
1552            // and doing that for a file that is still there and still indexed leaves the
1553            // key in both views at once: the file index keeps it in every commitment, so
1554            // it stays answerable, and an answerable legacy-only key vetoes retirement for
1555            // as long as the process lives. Refuse this pass instead.
1556            Err(e) => {
1557                warn!(
1558                    "Chunk {} could not be read while verifying: {e}. The legacy \
1559                     environment stays.",
1560                    hex::encode(key)
1561                );
1562                return VerifyOutcome {
1563                    bytes: 0,
1564                    verdict: VerifyVerdict::Unrepairable,
1565                };
1566            }
1567        };
1568        let len = bytes.as_ref().map_or(0, Vec::len) as u64;
1569        let Some(bytes) = bytes else {
1570            return VerifyOutcome {
1571                bytes: 0,
1572                verdict: VerifyVerdict::Vanished,
1573            };
1574        };
1575        if crate::client::compute_address(&bytes) == *key {
1576            // The pass hashed these bytes and they are right, so whatever this store
1577            // thought was wrong with them is not. It reads raw, which does not settle
1578            // that on its own, and leaving the mark would retire the environment while a
1579            // healthy chunk stayed unadvertised until some later verified read.
1580            self.files.note_bytes_proven_good(key);
1581            return VerifyOutcome {
1582                bytes: len,
1583                verdict: VerifyVerdict::Intact,
1584            };
1585        }
1586
1587        warn!(
1588            "Chunk {} is in the file store but does not match its address; rewriting it \
1589             from the legacy environment before that environment is removed",
1590            hex::encode(key)
1591        );
1592        // Replace in place. Deleting first and writing after would leave a window whose
1593        // only surviving copy is the one this whole pass exists to make safe to delete.
1594        let verdict = match legacy.lmdb.get_raw(key).await {
1595            Ok(Some(good)) if self.files.repair(key, &good).await.is_ok() => {
1596                VerifyVerdict::Repaired
1597            }
1598            _ => {
1599                warn!(
1600                    "Chunk {} could not be rewritten from the legacy environment. \
1601                     Retirement stays blocked so its bytes are not thrown away.",
1602                    hex::encode(key)
1603                );
1604                VerifyVerdict::Unrepairable
1605            }
1606        };
1607        VerifyOutcome {
1608            bytes: len,
1609            verdict,
1610        }
1611    }
1612
1613    /// Is this verification still worth acting on?
1614    ///
1615    /// # Errors
1616    ///
1617    /// Returns [`Error::Storage`] naming what has changed since the pass ran.
1618    fn proof_is_usable(&self, proof: &VerifyReport) -> Result<()> {
1619        if !proof.is_clean() {
1620            return Err(Error::Storage(format!(
1621                "Refusing to remove the legacy environment: verification reported {} \
1622                 unrepairable chunk(s) (ran: {})",
1623                proof.unrepairable, proof.ran
1624            )));
1625        }
1626        if !proof.still_describes(&self.files) {
1627            return Err(Error::Storage(
1628                "Refusing to remove the legacy environment: a chunk stopped being \
1629                 servable since it was verified, so that verification no longer describes \
1630                 the file store. A fresh pass runs on the next tick."
1631                    .into(),
1632            ));
1633        }
1634        if self.has_pending_writes() {
1635            return Err(Error::Storage(
1636                "Refusing to remove the legacy environment: a write announced itself and \
1637                 has not reported back, so what the environment holds is not yet settled."
1638                    .into(),
1639            ));
1640        }
1641        Ok(())
1642    }
1643
1644    /// Close the legacy environment and remove it, returning the bytes freed.
1645    ///
1646    /// This is the only destructive step in the migration and the only one that cannot
1647    /// be undone. It is also the only moment the disk comes back.
1648    ///
1649    /// Takes a [`VerifyReport`] rather than a flag so the verification pass cannot be
1650    /// skipped: there is no way to call this without having produced one.
1651    ///
1652    /// # Errors
1653    ///
1654    /// Returns [`Error::Storage`] if verification did not pass or no longer describes the
1655    /// store, if a write has not reported back, if the handle is still shared (the caller
1656    /// should retry on the next tick), or if the directory cannot be removed.
1657    pub async fn retire_legacy<F>(
1658        &self,
1659        proof: &VerifyReport,
1660        still_answerable: &F,
1661        approved_to_shed: &BTreeSet<XorName>,
1662    ) -> Result<u64>
1663    where
1664        F: Fn(&XorName) -> bool + Send + Sync,
1665    {
1666        self.proof_is_usable(proof)?;
1667        // Rechecked here, not only by the caller. Everything between the caller's check
1668        // and this point is a window: the verification pass alone can run for hours, and
1669        // a write whose file half failed inserts a new legacy-only key in the meantime.
1670        if let Some(reason) = self.retirement_blocker(still_answerable) {
1671            return Err(Error::Storage(format!(
1672                "Refusing to remove the legacy environment: {reason}"
1673            )));
1674        }
1675        // Exclusive from here until the handle is out. Every read, write and delete holds
1676        // this shared, so taking it means none is in progress and none can start: no
1677        // reader is mid-way between discarding a corrupt file and reaching the copy that
1678        // would replace it, and nothing new can start work in an environment that is about
1679        // to go idle.
1680        //
1681        // Released as soon as the handle has been taken and the directory renamed away,
1682        // which is the point after which nothing can reach the environment anyway. The
1683        // deletion that follows can take a long time on a large store, and holding every
1684        // chunk request on the node behind it would turn retirement into an outage.
1685        //
1686        let retiring = self.retirement.write().await;
1687        // Asked again with the guard held, which is the only moment the answer cannot
1688        // change underneath it. The check above can be overtaken by a read that fails
1689        // between there and here.
1690        if !proof.still_describes(&self.files) {
1691            drop(retiring);
1692            return Err(Error::Storage(
1693                "Refusing to remove the legacy environment: a chunk stopped being \
1694                 servable while retirement was starting. A fresh pass runs on the next \
1695                 tick."
1696                    .into(),
1697            ));
1698        }
1699        let Some(legacy) = self.legacy() else {
1700            return Ok(0);
1701        };
1702        let freed = self.legacy_bytes();
1703        // Let go of our own clone straight away, so the only strong reference that should
1704        // remain is the one the store itself holds.
1705        drop(legacy);
1706
1707        for attempt in 0..RETIRE_UNWRAP_ATTEMPTS {
1708            // Drained on every attempt, not once up front: `LmdbStorage`'s blocking
1709            // closures capture a cloned `Env` rather than the `Arc`, so the strong count
1710            // alone would not notice a read that is still mapped. The tracker does, and
1711            // it reopens itself, so a read that started since the last drain needs
1712            // another one.
1713            if let Some(l) = self.legacy() {
1714                l.lmdb.wait_idle().await;
1715                drop(l);
1716            }
1717            // Taking the handle out and proving sole ownership happen in the same
1718            // critical section. Deliberately not two steps: taking it first and putting
1719            // it back on failure would leave a window in which reads see no legacy store
1720            // and report a chunk that lives only there as missing.
1721            let taken = {
1722                let mut guard = self.legacy.write();
1723                match guard.as_ref() {
1724                    // A strong count of one means nobody else holds a handle, so nobody
1725                    // can be reading the legacy store *or* mutating its key set. That is
1726                    // what makes the final check below atomic with the removal: this is
1727                    // the only moment at which the answer cannot change underneath us.
1728                    Some(l) if Arc::strong_count(&l.lmdb) == 1 => {
1729                        // Asked here, in the same critical section as the checks below
1730                        // and immediately before the handle is taken. Asking earlier is
1731                        // not enough: a write can announce itself under the shared guard,
1732                        // be cancelled so the guard is released, and leave its blocking
1733                        // half running past the drain above. Its note is the only thing
1734                        // that says so, and dropping the journal with the environment
1735                        // would take the evidence with it.
1736                        if !l.pending.read().is_empty() {
1737                            return Err(Error::Storage(
1738                                "Refusing to remove the legacy environment: a write \
1739                                 announced itself and has not reported back, so what the \
1740                                 environment holds is not yet settled."
1741                                    .into(),
1742                            ));
1743                        }
1744                        let only = l.only.read();
1745                        // A count of one proves nobody else holds a handle, so nobody can
1746                        // be mutating this set. That is what makes the two checks below
1747                        // authoritative rather than a snapshot that has already moved.
1748                        if let Some(key) = only.iter().find(|k| still_answerable(k)) {
1749                            return Err(Error::Storage(format!(
1750                                "Refusing to remove the legacy environment: chunk {} became \
1751                                 answerable again while retirement was in progress",
1752                                hex::encode(key)
1753                            )));
1754                        }
1755                        // Only the keys the caller cleared may go. A write whose file half
1756                        // failed adds a legacy-only key that is in no commitment, so the
1757                        // answerability check above cannot see it, and it would otherwise
1758                        // be destroyed without ever facing the rank, delivery or
1759                        // possession gates.
1760                        if let Some(key) = only.iter().find(|k| !approved_to_shed.contains(*k)) {
1761                            return Err(Error::Storage(format!(
1762                                "Refusing to remove the legacy environment: chunk {} entered \
1763                                 the legacy-only set after the gates were cleared and has \
1764                                 passed none of them",
1765                                hex::encode(key)
1766                            )));
1767                        }
1768                        drop(only);
1769                        guard.take()
1770                    }
1771                    Some(_) => None,
1772                    None => return Ok(0),
1773                }
1774            };
1775            if let Some(Legacy {
1776                lmdb,
1777                only,
1778                pending,
1779                skipped_rollback_copies,
1780            }) = taken
1781            {
1782                drop(only);
1783                drop(pending);
1784                drop(skipped_rollback_copies);
1785                drop(lmdb);
1786                return self.remove_legacy_dir(freed, retiring).await;
1787            }
1788            if attempt + 1 < RETIRE_UNWRAP_ATTEMPTS {
1789                tokio::time::sleep(RETIRE_UNWRAP_BACKOFF).await;
1790            }
1791        }
1792
1793        // Nothing was taken and nothing will be this tick, so let the node get on with
1794        // serving rather than leaving this held until the function returns.
1795        drop(retiring);
1796        Err(Error::Storage(
1797            "Legacy environment is still being read; retirement deferred to the next tick".into(),
1798        ))
1799    }
1800
1801    /// Remove the legacy directory and record that the migration is over.
1802    ///
1803    /// The handle is already closed by the time this runs, so the node is file-only
1804    /// either way. If the removal fails the phase still moves on, because there is no
1805    /// going back to a half-removed environment, and the operator is told exactly which
1806    /// directory to delete by hand to get the space back.
1807    async fn remove_legacy_dir(
1808        &self,
1809        freed: u64,
1810        retiring: tokio::sync::RwLockWriteGuard<'_, ()>,
1811    ) -> Result<u64> {
1812        // Renamed aside first, because `remove_dir_all` is not atomic: a failure partway
1813        // through leaves a directory that can no longer be opened as an environment, and
1814        // recording the migration as finished on top of that would have the node claim
1815        // completion over a half-deleted store. A rename either happens or does not.
1816        let tombstone = free_tombstone_path(&self.config.root_dir);
1817
1818        if let Err(e) = std::fs::rename(&self.legacy_env_dir, &tombstone) {
1819            // Nothing was deleted, but the handle is already closed, so this node has
1820            // stopped being able to serve anything that lives only in there. Put it back
1821            // rather than carrying on with chunks it holds and cannot read, and rather
1822            // than letting the next tick see no handle and call that success.
1823            let restored = self.reopen_legacy().await;
1824            return Err(Error::Storage(format!(
1825                "Could not move the legacy environment {} aside: {e}. Nothing was deleted{}",
1826                self.legacy_env_dir.display(),
1827                if restored {
1828                    " and it has been reopened, so the node keeps serving from both stores."
1829                } else {
1830                    ". IT COULD NOT BE REOPENED: this node cannot serve chunks that live                      only there until it is restarted."
1831                }
1832            )));
1833        }
1834        // The rename has to reach the directory itself, not just the page cache, and this
1835        // one is not best effort. The tombstone is deleted a few lines below. If the
1836        // rename has not reached the disk when that happens, a power loss brings the
1837        // environment back under its old name with its contents already removed, and the
1838        // next start finds a corrupt environment it cannot open. Stopping here instead
1839        // leaves the tombstone in place, which the next start sweeps.
1840        // Marked from the inside, now that the rename has succeeded and before anything
1841        // is deleted. This is what a directory that reverts to its old name carries with
1842        // it, and it is the only thing a later start treats as permission to delete.
1843        if let Err(e) = mark_directory_retired(&tombstone) {
1844            // Nothing has been deleted and the directory is intact, so put it back rather
1845            // than recording the migration as finished over a store that is still there.
1846            // Recording finished would be worse than it sounds: the next tick restores the
1847            // unmarked directory to its own name, and a node that has already called
1848            // itself file-only would then exit with a live environment on disk and no
1849            // handle to it.
1850            // Only when the mark is provably gone. A mark left inside would have the
1851            // next cleanup pass reap a live, open environment.
1852            let restored =
1853                e.mark_definitely_gone && std::fs::rename(&tombstone, &self.legacy_env_dir).is_ok();
1854            let reopened = restored && self.reopen_legacy().await;
1855            return Err(Error::Storage(format!(
1856                "Moved the legacy environment to {} but could not mark it retired: {e}. \
1857                 Nothing was deleted{}",
1858                tombstone.display(),
1859                if reopened {
1860                    ", and it has been put back, so the node keeps serving from both \
1861                     stores and retirement is tried again."
1862                } else if e.mark_definitely_gone {
1863                    ". IT COULD NOT BE PUT BACK: this node cannot serve chunks that live \
1864                     only there until it is restarted."
1865                } else {
1866                    ". It has been left where nothing will open it, because a partial \
1867                     retirement mark may still be inside it. Its chunks are in the file \
1868                     store; move it back by hand only after removing that mark."
1869                }
1870            )));
1871        }
1872
1873        // Test-only: renamed aside and marked, nothing deleted yet. A process killed here
1874        // is what the recovery on the next start exists for.
1875        #[cfg(any(test, feature = "test-utils"))]
1876        crate::storage::file_store::halt_here_if_asked(
1877            crate::storage::file_store::HALT_AFTER_RETIRE_MARK,
1878            &tombstone,
1879        );
1880
1881        if let Err(e) = crate::storage::file_store::fsync_path(&self.config.root_dir) {
1882            warn!(
1883                "The legacy environment was moved aside but {} could not be flushed: {e}. \
1884                 Leaving {} in place rather than deleting a directory whose new name may \
1885                 not have reached the disk. The next start finishes this.",
1886                self.config.root_dir.display(),
1887                tombstone.display()
1888            );
1889            self.finish_migration();
1890            return Ok(0);
1891        }
1892        self.finish_migration();
1893
1894        // From here nothing can reach the environment: its handle is gone and its
1895        // directory is under a name no code looks for. Let the node serve again rather
1896        // than holding every chunk request behind a deletion that can run for minutes.
1897        drop(retiring);
1898
1899        // Only now, and best effort: the bytes come back when this completes, and if it
1900        // does not the next start sweeps the tombstone.
1901        //
1902        // On a detached OS thread, and not awaited. This is a synchronous recursive delete
1903        // of a directory that can hold hundreds of gigabytes and cannot be interrupted
1904        // once it starts. Inside the migration task it would sit through shutdown's grace
1905        // and past it, because an abort is not observed until the call returns; on the
1906        // runtime's blocking pool a normal runtime shutdown would wait for it anyway. A
1907        // plain thread is the only one the process can genuinely walk away from, and the
1908        // directory carries its own retirement mark, so whatever is left is finished by
1909        // the next start.
1910        delete_retired_directory(tombstone);
1911        Ok(freed)
1912    }
1913
1914    /// Try again to open a legacy environment this node has lost its handle to.
1915    ///
1916    /// A rename that failed and then could not be reopened leaves the directory on disk
1917    /// with no way to read it, and every chunk that lives only there unserved. Saying so
1918    /// once and waiting for a restart is not enough: the reason is usually transient, and
1919    /// a node that is otherwise healthy should not stay half-blind until somebody notices.
1920    ///
1921    /// Returns whether it came back. Does nothing when there is a handle already, or when
1922    /// there is nothing on disk to open.
1923    pub async fn recover_lost_legacy_handle(&self) -> bool {
1924        if self.has_legacy() || !retirement_mark(&self.legacy_env_dir).permits_opening() {
1925            return false;
1926        }
1927        if !legacy_present(&self.config.root_dir).unwrap_or(false) {
1928            return false;
1929        }
1930        // Opened WITHOUT the exclusive guard. Opening scans every key in the environment,
1931        // which on a large store is minutes, and every read and write on the node would
1932        // wait behind it. Nothing else can be installing a handle: retirement does nothing
1933        // while there is none, and this runs from the one migration task.
1934        let (lmdb, legacy_keys) = match Self::open_legacy_env(&self.config).await {
1935            Ok(opened) => opened,
1936            Err(e) => {
1937                warn!(
1938                    "Could not reopen {}: {e}. The chunks that live only there stay \
1939                     unreadable until this succeeds.",
1940                    self.legacy_env_dir.display()
1941                );
1942                return false;
1943            }
1944        };
1945        // Exclusive only to install it, which is instant.
1946        let _recovering = self.retirement.write().await;
1947        if self.has_legacy() {
1948            return false;
1949        }
1950        // The diff happens HERE, not when the environment was read. Reading it takes
1951        // minutes on a large store, and a verifying read in that time can find a file
1952        // rotted and throw it away. With no handle installed there was nothing to put the
1953        // key back into, so a set computed beforehand would be missing it, every gate
1954        // would skip it, and retirement would destroy the intact copy in the environment.
1955        // Under this guard no read, write or delete is in flight, so the file store's
1956        // answer cannot move while it is being asked.
1957        let only = Self::keys_only_in_legacy(&legacy_keys, &self.files);
1958        *self.legacy.write() = Some(Legacy {
1959            lmdb,
1960            only: Arc::new(parking_lot::RwLock::new(only)),
1961            skipped_rollback_copies: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1962            pending: Arc::new(parking_lot::RwLock::new(BTreeMap::new())),
1963        });
1964        // A node that recorded itself file-only and then got an environment back has to
1965        // go through the migration again from the start: the phase decides what the
1966        // driver does, and file-only does no copying, so leaving it there would give the
1967        // node a handle it never uses. Conservative on purpose; the copier finds most of
1968        // the work already done.
1969        if self.migration_phase() == MigrationPhase::FilesOnly {
1970            warn!(
1971                "Recovered a legacy chunk environment after recording this node as \
1972                 file-only. Starting the migration again from the copying stage."
1973            );
1974            let mut state = self.state.write();
1975            state.phase = MigrationPhase::Bridging;
1976            state.committed_at_unix = None;
1977            state.rebuilds_since_commit = 0;
1978            let snapshot = state.clone();
1979            drop(state);
1980            if let Err(e) = snapshot.save(&self.config.root_dir) {
1981                warn!("Could not persist the migration marker: {e}");
1982            }
1983        }
1984        warn!(
1985            "Reopened {} after losing its handle",
1986            self.legacy_env_dir.display()
1987        );
1988        true
1989    }
1990
1991    /// Is there a retired directory still waiting to be deleted?
1992    ///
1993    /// Separate from having a legacy environment: a node whose removal was interrupted has
1994    /// no handle and nothing to migrate, but its disk has not come back. Something has to
1995    /// keep trying during this uptime rather than leaving it until the next restart.
1996    #[must_use]
1997    pub fn has_cleanup_pending(&self) -> bool {
1998        !retired_tombstones(&self.config.root_dir).is_empty()
1999            || !retirement_mark(&self.legacy_env_dir).permits_opening()
2000    }
2001
2002    /// Try again to finish a removal a previous attempt left behind.
2003    ///
2004    /// Safe to call at any time: it only ever moves or deletes a directory that carries
2005    /// its own retirement mark.
2006    pub fn retry_cleanup(&self) {
2007        // Never while this node has the environment open. Cleanup decides what to do from
2008        // the directory's own mark, and a mark that outlived a failed retirement would
2009        // have it rename a live, mapped environment out from under the handle.
2010        if self.has_legacy() {
2011            sweep_retired_legacy(&self.config.root_dir);
2012            return;
2013        }
2014        finish_interrupted_retirement(&self.config.root_dir);
2015    }
2016
2017    /// Resolve writes whose outcome was never recorded.
2018    ///
2019    /// A write announces itself before it starts and clears the note when both halves
2020    /// have returned. A note still there afterwards belongs to a write nobody waited for,
2021    /// and only the disk can say what became of it: the file store has the chunk, or the
2022    /// environment does and nothing else, or neither and there was never anything to
2023    /// protect.
2024    pub async fn reconcile_pending_writes(&self) {
2025        if !self.has_pending_writes() {
2026            return;
2027        }
2028        // Exclusively, and before the snapshot. Draining is not a barrier on its own:
2029        // writes hold this shared, and a new one for the same key could announce itself,
2030        // be cancelled, and leave its blocking half running while this decided the older
2031        // one's fate and removed the single entry they share. Held here, nothing new can
2032        // start, so what the disk says once the drain returns is final.
2033        //
2034        // Only reached when something is waiting, which after a clean run is never, so
2035        // this is not a stall on the ordinary path.
2036        let _settling = self.retirement.write().await;
2037        let Some(legacy) = self.legacy() else {
2038            return;
2039        };
2040        let waiting: Vec<XorName> = legacy.pending.read().keys().copied().collect();
2041        if waiting.is_empty() {
2042            return;
2043        }
2044        legacy.lmdb.wait_idle().await;
2045        self.files.wait_idle().await;
2046        for key in waiting {
2047            let _lane = self.key_lock(&key).await;
2048            if self.files.is_indexed(&key) {
2049                legacy.only.write().remove(&key);
2050                legacy.pending.write().remove(&key);
2051                continue;
2052            }
2053            match legacy.lmdb.get_raw(&key).await {
2054                Ok(Some(_)) => {
2055                    debug!(
2056                        "Chunk {} was written to the legacy environment by a call that \
2057                         never returned; recording it so the copier picks it up",
2058                        hex::encode(key)
2059                    );
2060                    legacy.only.write().insert(key);
2061                    legacy.pending.write().remove(&key);
2062                }
2063                // Nothing behind it: there was never anything to protect.
2064                Ok(None) => {
2065                    legacy.pending.write().remove(&key);
2066                }
2067                // NOT the same as nothing behind it. Dropping the note on a read that
2068                // failed would leave a committed write with no protection at all, which
2069                // is the case this journal exists for. Keep it and ask again next tick;
2070                // retirement stays vetoed meanwhile.
2071                Err(e) => warn!(
2072                    "Could not tell what became of the write for {}: {e}. Asking again on \
2073                     the next tick.",
2074                    hex::encode(key)
2075                ),
2076            }
2077        }
2078    }
2079
2080    /// Are there writes in flight whose outcome nothing has recorded?
2081    #[must_use]
2082    pub fn has_pending_writes(&self) -> bool {
2083        self.legacy().is_some_and(|l| !l.pending.read().is_empty())
2084    }
2085
2086    /// Is there anything at the legacy environment's path at all?
2087    ///
2088    /// Asked without a handle, and answered conservatively: a path this node cannot even
2089    /// look at counts as present. The migration is not finished while something is there,
2090    /// whether or not this node can currently read it.
2091    #[must_use]
2092    pub fn legacy_dir_is_on_disk(&self) -> bool {
2093        // `symlink_metadata`, not `try_exists`, which follows links. An operator's link to
2094        // storage that is not mounted right now reads as nothing at all through the
2095        // second, and the node would call its migration finished and go file-only, blind
2096        // to every chunk that lives only there until somebody restarts it.
2097        match std::fs::symlink_metadata(&self.legacy_env_dir) {
2098            Ok(_) => true,
2099            // Only "it is not there" means it is not there. A permission change or a
2100            // transient fault is an unanswered question, and answering it with "nothing
2101            // here" is how the driver declares the migration finished over a store it has
2102            // merely lost sight of.
2103            Err(e) => e.kind() != std::io::ErrorKind::NotFound,
2104        }
2105    }
2106
2107    /// Is the legacy environment a link this node must not delete?
2108    ///
2109    /// Copying out of it works; only the removal is refused. Callers use this to stop
2110    /// waiting for a retirement that is never going to happen.
2111    #[must_use]
2112    pub fn legacy_is_a_link(&self) -> bool {
2113        self.has_legacy() && is_a_link(&self.legacy_env_dir)
2114    }
2115
2116    /// How many writes this node made without a rollback copy, cumulatively.
2117    ///
2118    /// Zero on a node that is not bridging, and zero on a bridging node whose environment
2119    /// has room. A number that is climbing says this node would lose those chunks on a
2120    /// rollback to a pre-migration build, which is a fleet question the second release
2121    /// turns on and which a per-chunk log line cannot answer.
2122    ///
2123    /// Attempts rather than distinct chunks, for the reason given on the field: it is a
2124    /// rate, not an inventory.
2125    #[must_use]
2126    pub fn writes_without_a_rollback_copy(&self) -> u64 {
2127        self.legacy().map_or(0, |l| {
2128            l.skipped_rollback_copies
2129                .load(std::sync::atomic::Ordering::Relaxed)
2130        })
2131    }
2132
2133    /// Is there an environment on disk this node cannot classify at all?
2134    ///
2135    /// Neither removable nor openable, which is not a state waiting will clear: something
2136    /// about the path has to change first, and until it does the node will refuse to touch
2137    /// it in either direction. The driver treats this the way it treats a lost handle or a
2138    /// link, by standing down from the shared volume and saying so where an operator looks,
2139    /// because holding a disk exclusively to wait for a person is a disk nobody else can
2140    /// use.
2141    #[must_use]
2142    pub fn legacy_cannot_be_classified(&self) -> bool {
2143        retirement_mark(&self.legacy_env_dir) == RetirementMark::Unknown
2144    }
2145
2146    /// Is there an environment on disk this node can no longer read?
2147    #[must_use]
2148    pub fn has_lost_its_legacy_handle(&self) -> bool {
2149        !self.has_legacy()
2150            && retirement_mark(&self.legacy_env_dir).permits_opening()
2151            // Conservative in the same direction as the retirement blocker, which reads the
2152            // same failure as "there is one". A question that cannot be answered is not an
2153            // answer of no, and answering no here left the node holding the shared volume
2154            // for the six-hour cap over work no amount of disk will finish.
2155            && legacy_present(&self.config.root_dir).unwrap_or(true)
2156    }
2157
2158    /// Reopen the legacy store after a failed retirement, so the node keeps serving.
2159    ///
2160    /// Returns whether it came back. The handle is closed before the rename is attempted,
2161    /// so a rename that fails leaves the node holding chunks it can no longer read; that
2162    /// is worth undoing rather than living with until the next restart.
2163    async fn reopen_legacy(&self) -> bool {
2164        if !legacy_present(&self.config.root_dir).unwrap_or(false) {
2165            return false;
2166        }
2167        match Self::open_legacy(&self.config, &self.files).await {
2168            Ok(legacy) => {
2169                *self.legacy.write() = Some(legacy);
2170                warn!("Reopened the legacy chunk environment after a failed retirement");
2171                true
2172            }
2173            Err(e) => {
2174                error!("Could not reopen the legacy chunk environment: {e}");
2175                false
2176            }
2177        }
2178    }
2179
2180    /// Record that this node serves from files alone from here on.
2181    fn finish_migration(&self) {
2182        self.files.invalidate_capacity_cache();
2183        {
2184            let mut state = self.state.write();
2185            state.phase = MigrationPhase::FilesOnly;
2186        }
2187        let snapshot = self.state.read().clone();
2188        if let Err(e) = snapshot.save(&self.config.root_dir) {
2189            warn!("Could not persist the migration marker: {e}");
2190        }
2191    }
2192}
2193
2194/// What checking one chunk concluded.
2195enum VerifyVerdict {
2196    /// The file matches its name.
2197    Intact,
2198    /// The file was wrong and was rewritten from the legacy copy.
2199    Repaired,
2200    /// The file was wrong and could not be rewritten.
2201    Unrepairable,
2202    /// The file disappeared while the pass was running.
2203    Vanished,
2204}
2205
2206/// One chunk's verification result.
2207struct VerifyOutcome {
2208    /// Bytes read, for the throttle.
2209    bytes: u64,
2210    /// What was concluded.
2211    verdict: VerifyVerdict,
2212}
2213
2214/// What the pre-retirement verification pass found.
2215///
2216/// Every field is private, and the only way to obtain one is
2217/// [`ChunkStore::verify_before_retire`]. That is deliberate: it is the sole evidence
2218/// [`ChunkStore::retire_legacy`] accepts that the file store really holds what it claims,
2219/// and a report anyone could construct would be no evidence at all.
2220#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2221pub struct VerifyReport {
2222    /// Whether the pass actually ran.
2223    ran: bool,
2224    /// Chunks re-hashed.
2225    checked: u64,
2226    /// Bytes read.
2227    bytes: u64,
2228    /// Chunks whose file was wrong and was rewritten from the legacy copy.
2229    repaired: u64,
2230    /// Chunks whose file was wrong and could not be repaired.
2231    unrepairable: u64,
2232    /// What the file store's health looked like when this pass finished.
2233    ///
2234    /// A clean report is reused for a while rather than re-read on every tick, and a lot
2235    /// can happen in that window: a kept file can start failing to read while ordinary
2236    /// requests are served from the legacy copy, and the node would then delete the
2237    /// legacy copy on the strength of a pass that no longer describes the store. This is
2238    /// how retirement tells, immediately before it deletes anything.
2239    health: u64,
2240}
2241
2242impl VerifyReport {
2243    /// Whether this report clears the way for retirement.
2244    #[must_use]
2245    pub fn is_clean(&self) -> bool {
2246        self.ran && self.unrepairable == 0
2247    }
2248
2249    /// Does this report still describe the store?
2250    #[must_use]
2251    fn still_describes(&self, files: &FileStore) -> bool {
2252        self.health == files.health_generation()
2253    }
2254
2255    /// Chunks re-hashed.
2256    #[must_use]
2257    pub fn checked(&self) -> u64 {
2258        self.checked
2259    }
2260
2261    /// Chunks rewritten from the legacy copy.
2262    #[must_use]
2263    pub fn repaired(&self) -> u64 {
2264        self.repaired
2265    }
2266
2267    /// Chunks that could not be made good.
2268    #[must_use]
2269    pub fn unrepairable(&self) -> u64 {
2270        self.unrepairable
2271    }
2272}
2273
2274/// Mark a retired environment directory as retired, from the inside, durably.
2275///
2276/// Called only after the directory has already been renamed aside, so it can never land
2277/// inside a live environment. See [`RETIRED_MARKER`] for why it goes inside.
2278///
2279/// # Errors
2280///
2281/// Returns [`Error::Storage`] if it cannot be created or flushed.
2282fn mark_directory_retired(dir: &Path) -> std::result::Result<(), MarkFailure> {
2283    match write_retirement_mark(dir) {
2284        Ok(()) => Ok(()),
2285        Err(e) if e.pre_existing => {
2286            // Nothing here was created by this attempt, so there is nothing to take back.
2287            // Removing a mark that was already there because re-flushing it failed is how
2288            // a correctly retired directory comes to look unmarked, and an unmarked
2289            // directory is restored as a live environment.
2290            Err(MarkFailure {
2291                pre_existing: true,
2292                ..e
2293            })
2294        }
2295        Err(e) => {
2296            // A half-written mark is worse than none: the caller puts the directory back
2297            // under the live name and reopens it, and a mark left inside would have the
2298            // next cleanup pass reap a live, open environment. If it cannot be taken away,
2299            // say so, and the caller keeps the directory where nothing will open it.
2300            let path = dir.join(RETIRED_MARKER);
2301            match std::fs::remove_file(&path) {
2302                Ok(()) => {}
2303                Err(gone) if gone.kind() == std::io::ErrorKind::NotFound => {}
2304                Err(stuck) => {
2305                    return Err(MarkFailure {
2306                        reason: format!(
2307                            "{e}. The partial mark at {} could not be removed either \
2308                             ({stuck})",
2309                            path.display()
2310                        ),
2311                        mark_definitely_gone: false,
2312                        pre_existing: false,
2313                    })
2314                }
2315            }
2316            if let Err(flush) = crate::storage::file_store::fsync_path(dir) {
2317                return Err(MarkFailure {
2318                    reason: format!(
2319                        "{e}. Removing the partial mark at {} could not be flushed \
2320                         ({flush})",
2321                        path.display()
2322                    ),
2323                    mark_definitely_gone: false,
2324                    pre_existing: false,
2325                });
2326            }
2327            Err(MarkFailure {
2328                reason: format!("{e}"),
2329                mark_definitely_gone: true,
2330                pre_existing: false,
2331            })
2332        }
2333    }
2334}
2335
2336/// Why a directory could not be marked retired, and whether it is safe to reopen.
2337#[derive(Debug)]
2338struct MarkFailure {
2339    /// What went wrong, for the operator.
2340    reason: String,
2341    /// Is the directory provably free of a partial mark?
2342    ///
2343    /// Only then may the caller put it back under the live name. A mark left inside would
2344    /// have the next cleanup pass reap a live, open environment.
2345    mark_definitely_gone: bool,
2346    /// Was the mark already there before this attempt?
2347    ///
2348    /// Then this attempt created nothing and must take nothing away. Removing a mark that
2349    /// was already there because re-flushing it failed is how a correctly retired
2350    /// directory comes to look unmarked, and an unmarked directory is restored as a live
2351    /// environment.
2352    pre_existing: bool,
2353}
2354
2355impl std::fmt::Display for MarkFailure {
2356    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2357        write!(f, "{}", self.reason)
2358    }
2359}
2360
2361/// Create the mark. See [`mark_directory_retired`], which owns the failure handling.
2362fn write_retirement_mark(dir: &Path) -> std::result::Result<(), MarkFailure> {
2363    let path = dir.join(RETIRED_MARKER);
2364    let mut file = match std::fs::OpenOptions::new()
2365        .write(true)
2366        .create_new(true)
2367        .open(&path)
2368    {
2369        Ok(f) => f,
2370        // Already there, from an attempt that got this far and no further. Flushed
2371        // again rather than taken on trust: the attempt that wrote it may have been the
2372        // one that could not flush it.
2373        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2374            // Something is already at that name. That it could not be created is not the
2375            // same as its being a mark this node can read, and everything downstream
2376            // deletes an environment on the strength of it. The rest of this file insists
2377            // the name is not the evidence; this is the one place that was taking it.
2378            if retirement_mark(dir) != RetirementMark::Present {
2379                return Err(MarkFailure {
2380                    reason: format!(
2381                        "{} already exists but cannot be read as a retirement mark, so it \
2382                         is not one this node will delete on. Check what is at that path.",
2383                        path.display()
2384                    ),
2385                    mark_definitely_gone: false,
2386                    pre_existing: true,
2387                });
2388            }
2389            return crate::storage::file_store::fsync_path(dir).map_err(|flush| MarkFailure {
2390                reason: format!(
2391                    "{} is already there but could not be flushed: {flush}",
2392                    path.display()
2393                ),
2394                mark_definitely_gone: false,
2395                pre_existing: true,
2396            });
2397        }
2398        Err(e) => {
2399            return Err(MarkFailure {
2400                reason: format!("Could not mark {} as retired: {e}", path.display()),
2401                mark_definitely_gone: true,
2402                pre_existing: false,
2403            })
2404        }
2405    };
2406    // For whoever reads the directory. To the node, presence is the whole signal.
2407    if let Err(e) = file.write_all(
2408        b"This chunk environment was verified as fully copied into the file store and \n\
2409retired. It is being deleted; if it is still here, that was interrupted and the next \n\
2410node start finishes it. Nothing needs it.\n",
2411    ) {
2412        drop(file);
2413        return Err(MarkFailure {
2414            reason: format!("Could not write {}: {e}", path.display()),
2415            mark_definitely_gone: false,
2416            pre_existing: false,
2417        });
2418    }
2419    file.sync_all().map_err(|e| MarkFailure {
2420        reason: format!(
2421            "Could not flush {}: {e}. Not deleting on the strength of a mark that may not \
2422             survive a power loss.",
2423            path.display()
2424        ),
2425        mark_definitely_gone: false,
2426        pre_existing: false,
2427    })?;
2428    // And the directory that now contains it. Flushing the file makes its contents
2429    // durable; the entry naming it is in the directory, and on Unix that needs its own
2430    // flush. Without this the mark can be missing after a crash from a directory that
2431    // was in fact retired, which is the whole question this file answers.
2432    crate::storage::file_store::fsync_path(dir).map_err(|e| MarkFailure {
2433        reason: format!(
2434            "Marked {} retired but could not flush {}: {e}. Not deleting on the strength \
2435             of a mark that may not survive a power loss.",
2436            path.display(),
2437            dir.display()
2438        ),
2439        mark_definitely_gone: false,
2440        pre_existing: false,
2441    })
2442}
2443
2444/// Delete a retired directory in the background, without anything waiting for it.
2445///
2446/// The caller is finished with it either way: the environment is closed, the directory is
2447/// under a name nothing looks for, and it carries its own mark, so an interrupted deletion
2448/// is finished by the next start. What matters is that neither shutdown nor startup ever
2449/// blocks on a recursive delete that can run for minutes.
2450fn delete_retired_directory(dir: PathBuf) {
2451    // One at a time per directory. The driver asks for cleanup on every tick while
2452    // anything is pending, and starting a fresh thread each time would leave hundreds of
2453    // them asleep on the same path, all retrying the same failure.
2454    if !REAPING.lock().insert(dir.clone()) {
2455        return;
2456    }
2457    let named = dir.clone();
2458    let started = std::thread::Builder::new()
2459        .name("chunk-store-retire".into())
2460        .spawn(move || {
2461            let _done = ReapingGuard(dir.clone());
2462            for attempt in 1..=RETIRED_DELETE_ATTEMPTS {
2463                match remove_marked_directory(&dir) {
2464                    Ok(()) => {
2465                        info!(
2466                            migration_event = "space_returned",
2467                            "Removed the retired chunk environment {} and returned its \
2468                             space",
2469                            dir.display()
2470                        );
2471                        return;
2472                    }
2473                    // Worth another go: on Windows a scanner or an antivirus can hold a
2474                    // handle inside it for a moment, and a partial delete leaves less to
2475                    // do next time.
2476                    Err(e) if attempt < RETIRED_DELETE_ATTEMPTS => {
2477                        debug!(
2478                            "Could not delete {} (attempt {attempt}): {e}. Trying again.",
2479                            dir.display()
2480                        );
2481                        std::thread::sleep(
2482                            (RETIRED_DELETE_BACKOFF * attempt).min(RETIRED_DELETE_BACKOFF_MAX),
2483                        );
2484                    }
2485                    Err(e) => warn!(
2486                        "The chunk environment has been retired but {} could not be \
2487                         deleted: {e}. Its space is not returned until it is, and the node \
2488                         needs nothing from it. The next start tries again.",
2489                        dir.display()
2490                    ),
2491                }
2492            }
2493        });
2494    if let Err(e) = started {
2495        REAPING.lock().remove(&named);
2496        warn!(
2497            "Could not start the thread to delete the retired chunk environment {}: {e}. \
2498             The next start sweeps it.",
2499            named.display()
2500        );
2501    }
2502}
2503
2504/// Directories a reaper thread is already working on.
2505static REAPING: parking_lot::Mutex<BTreeSet<PathBuf>> = parking_lot::Mutex::new(BTreeSet::new());
2506
2507/// Releases a directory from [`REAPING`] however its thread ends.
2508struct ReapingGuard(PathBuf);
2509
2510impl Drop for ReapingGuard {
2511    fn drop(&mut self) {
2512        REAPING.lock().remove(&self.0);
2513    }
2514}
2515
2516/// Delete a retired directory, taking its mark away last of all.
2517///
2518/// `remove_dir_all` walks in whatever order the filesystem hands back, so it can unlink
2519/// the mark and then fail on the next entry, which is exactly what a Windows sharing
2520/// violation on the data file produces. What is left is a genuinely retired, partly
2521/// deleted directory carrying no evidence that it was retired, and the next start would
2522/// read that as an intact environment and restore it.
2523///
2524/// Emptying it first and removing the mark last means the mark is only ever absent from a
2525/// directory that has nothing else left in it.
2526///
2527/// # Errors
2528///
2529/// Returns the underlying I/O error. The directory is left with its mark intact on every
2530/// failure that happens before the mark is reached.
2531fn remove_marked_directory(dir: &Path) -> std::io::Result<()> {
2532    // Never through a link. An operator who points the chunk environment at another
2533    // volume leaves a symlink here, and walking it would delete the contents of a
2534    // directory that is not this node's to delete. Retirement refuses such a root before
2535    // it gets this far; this is the second line, because the check and the walk are not
2536    // one operation.
2537    if std::fs::symlink_metadata(dir)?.file_type().is_symlink() {
2538        return Err(std::io::Error::other(format!(
2539            "{} is a link, not a directory. Refusing to delete through it.",
2540            dir.display()
2541        )));
2542    }
2543    for entry in std::fs::read_dir(dir)? {
2544        let entry = entry?;
2545        if entry.file_name() == RETIRED_MARKER {
2546            continue;
2547        }
2548        let path = entry.path();
2549        if entry.file_type()?.is_dir() {
2550            std::fs::remove_dir_all(&path)?;
2551        } else {
2552            std::fs::remove_file(&path)?;
2553        }
2554    }
2555    match std::fs::remove_file(dir.join(RETIRED_MARKER)) {
2556        Ok(()) => {}
2557        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2558        Err(e) => return Err(e),
2559    }
2560    match std::fs::remove_dir(dir) {
2561        Ok(()) => Ok(()),
2562        Err(e) => {
2563            // The mark is gone and the directory is not, which is the one state the whole
2564            // scheme says cannot happen: a start that found it would read an unmarked
2565            // directory as an intact environment. Put the mark back before giving up.
2566            if let Err(remark) = mark_directory_retired(dir) {
2567                error!(
2568                    "Could not remove {} ({e}) and could not restore its retirement mark \
2569                     ({remark}). It is empty and nothing needs it; delete it by hand.",
2570                    dir.display()
2571                );
2572            }
2573            Err(e)
2574        }
2575    }
2576}
2577
2578/// What a directory's own contents say about whether it was retired.
2579///
2580/// Three answers, not two. Reading the mark can fail for reasons that are neither yes nor
2581/// no: a permission change, a descriptor limit, a filesystem that has gone away underneath
2582/// the node. Folding that into "no" is the failure mode the rest of this file exists to
2583/// avoid, and it fails in the worst direction: a retired environment that reads as unmarked
2584/// is put back under the live name and reopened, and its keys re-enter a commitment they
2585/// have already left.
2586///
2587/// So an unreadable answer is its own answer, and the two questions callers actually ask
2588/// are asked separately. Neither of them treats "cannot tell" as permission.
2589#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2590enum RetirementMark {
2591    /// The directory carries its mark. It is the remains of a removal.
2592    Present,
2593    /// The directory carries no mark, and that is known rather than assumed.
2594    Absent,
2595    /// Whether it carries one could not be determined.
2596    Unknown,
2597}
2598
2599impl RetirementMark {
2600    /// May this directory be deleted, or treated as already gone?
2601    ///
2602    /// Only a mark actually read says yes. Deleting on a guess destroys chunks.
2603    const fn permits_removal(self) -> bool {
2604        matches!(self, Self::Present)
2605    }
2606
2607    /// May this directory be opened and served from?
2608    ///
2609    /// Only a mark known to be absent says yes. Opening a retired environment puts keys
2610    /// back into a commitment they have already left.
2611    const fn permits_opening(self) -> bool {
2612        matches!(self, Self::Absent)
2613    }
2614}
2615
2616/// Has this directory been retired?
2617///
2618/// A link is never treated as retired, whatever it points at: the mark would have been
2619/// written through it into somebody else's directory, and acting on it would delete
2620/// somebody else's data. A path whose kind cannot be determined is not a link either way,
2621/// and is reported as unknown rather than as a link, so that neither question gets a yes.
2622fn retirement_mark(dir: &Path) -> RetirementMark {
2623    match std::fs::symlink_metadata(dir) {
2624        Ok(meta) if meta.file_type().is_symlink() => return RetirementMark::Absent,
2625        Ok(_) => {}
2626        // Nothing here at all, which is the ordinary case on a node that has already
2627        // finished or never had a legacy store. There is no mark because there is nothing
2628        // to carry one, and that is known rather than undetermined.
2629        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return RetirementMark::Absent,
2630        Err(e) => {
2631            // Debug, not warn: this is asked on every tick, so a warn here would be a
2632            // wall of the same line. The operator-facing version is the retirement
2633            // blocker, which says what it means for the node.
2634            debug!(
2635                "Could not tell what {} is ({e}); treating it as neither removable nor \
2636                 openable until it can be read",
2637                dir.display()
2638            );
2639            return RetirementMark::Unknown;
2640        }
2641    }
2642    match dir.join(RETIRED_MARKER).try_exists() {
2643        Ok(true) => RetirementMark::Present,
2644        Ok(false) => RetirementMark::Absent,
2645        Err(e) => {
2646            debug!(
2647                "Could not read the retirement mark in {} ({e}); treating it as neither \
2648                 removable nor openable until it can be read",
2649                dir.display()
2650            );
2651            RetirementMark::Unknown
2652        }
2653    }
2654}
2655
2656/// Is this path a symbolic link, or something whose kind cannot be determined?
2657///
2658/// Unknown counts as yes. Every caller is deciding whether it is safe to delete through
2659/// the path, and a question that cannot be answered is not a yes to that.
2660fn is_a_link(path: &Path) -> bool {
2661    std::fs::symlink_metadata(path).map_or(true, |m| m.file_type().is_symlink())
2662}
2663
2664/// Finish a removal a previous run did not, before anything tries to open the environment.
2665///
2666/// The only thing that counts as evidence is the directory's own mark. An open that fails
2667/// is not: `open_legacy` queries free space, maps the file, takes a write transaction and
2668/// scans every key, so a full disk, a permission change, a mapping limit or a transient
2669/// I/O fault all look identical to corruption, and deleting on any of those would destroy
2670/// a perfectly good environment.
2671fn finish_interrupted_retirement(root_dir: &Path) -> LiveEnvironment {
2672    let env = root_dir.join(LEGACY_ENV_DIR);
2673    // Three answers, three branches. Asking only whether it may be removed and letting
2674    // everything else fall through would put "cannot tell" back on the opening path, which
2675    // is the whole failure this is three states to avoid: the mark check can fail for a
2676    // moment and succeed the next, and the open in between would resurrect a store that
2677    // really had been retired.
2678    //
2679    // Asked of the mark alone, with no separate "is it there" first. A `try_exists` that
2680    // could not answer would have folded straight back into "nothing here" and skipped both
2681    // branches below, which is the same fold one level up. The mark already tells the three
2682    // apart: a path that is not there carries no mark and says so, and a path that cannot be
2683    // reached at all says it cannot be reached.
2684    // Asked once. Asking twice is asking two different questions: the answer can change
2685    // between them, and a second answer of "cannot tell" after a first of "retired" fell
2686    // through to opening the very directory the first answer said not to open.
2687    let mark = retirement_mark(&env);
2688    if mark == RetirementMark::Unknown {
2689        error!(
2690            "{} is under the live name and this node cannot tell whether it was retired. \
2691             It will NOT be opened and it will NOT be removed. The node serves from files \
2692             alone. Check that the directory and anything inside it can be read.",
2693            env.display()
2694        );
2695        return LiveEnvironment::None;
2696    }
2697    if mark.permits_removal() {
2698        // Its own contents say it was retired, so whatever name it is wearing now, it is
2699        // the remains of a removal that a power loss undid the rename of.
2700        warn!(
2701            "{} carries its own retirement mark, so it is what an interrupted removal left \
2702             behind rather than a live environment. Finishing that removal.",
2703            env.display()
2704        );
2705        // Renamed rather than deleted here, so the node can get on with starting: the
2706        // deletion itself is detached below and can take minutes on a large store. Under a
2707        // name nothing else is using, so a tombstone whose deletion is still running does
2708        // not force a synchronous delete first.
2709        let tombstone = free_tombstone_path(root_dir);
2710        if let Err(e) = std::fs::rename(&env, &tombstone) {
2711            error!(
2712                "{} carries its own retirement mark but could not be moved aside: {e}. It \
2713                 will NOT be opened: it says it has been retired, so it may be partly \
2714                 deleted, and its chunks are in the file store. The node serves from files \
2715                 alone and the next start tries again.",
2716                env.display()
2717            );
2718            sweep_retired_legacy(root_dir);
2719            return LiveEnvironment::None;
2720        }
2721    }
2722    sweep_retired_legacy(root_dir);
2723    LiveEnvironment::WhateverIsOnDisk
2724}
2725
2726/// Whether the ordinary open may look at what is under the live environment name.
2727#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2728enum LiveEnvironment {
2729    /// Nothing is claiming it should not be opened.
2730    WhateverIsOnDisk,
2731    /// A directory under the live name says it has been retired, and could not be moved
2732    /// out of the way. It must not be opened: a retired directory may be partly deleted,
2733    /// and opening it would put its keys back into a commitment they have left.
2734    None,
2735}
2736
2737fn sweep_retired_legacy(root_dir: &Path) {
2738    let tombstones = retired_tombstones(root_dir);
2739    if tombstones.is_empty() {
2740        return;
2741    }
2742    // Flushed first, and only best effort is not good enough here for the same reason it
2743    // was not good enough when the rename was made: deleting the contents of a directory
2744    // whose new name may not have reached the disk is what turns a power loss into a
2745    // resurrected, half-empty environment. If it cannot be flushed, leave them for a later
2746    // start. It costs disk, not data.
2747    if let Err(e) = crate::storage::file_store::fsync_path(root_dir) {
2748        warn!(
2749            "Leaving {} retired chunk environment(s) in place: {} could not be flushed \
2750             ({e}), so the rename that put them there may not be on disk yet.",
2751            tombstones.len(),
2752            root_dir.display()
2753        );
2754        return;
2755    }
2756    for tombstone in tombstones {
2757        // The name is not the evidence. Only the directory's own mark is: a crash between
2758        // the rename and the mark leaves an intact environment sitting under the retired
2759        // name, and deleting that because of what it is called would destroy every chunk
2760        // in it.
2761        let mark = retirement_mark(&tombstone);
2762        if mark == RetirementMark::Unknown {
2763            // Neither restored nor deleted. Restoring would put a directory that may be
2764            // half-deleted back under the live name for the next start to open, and
2765            // deleting would destroy an intact one. It costs disk until somebody looks,
2766            // which is the right price for not knowing.
2767            warn!(
2768                "{} cannot be classified: this node cannot tell whether it carries a \
2769                 retirement mark, so it will be neither restored nor deleted. Check that \
2770                 the directory and anything inside it can be read.",
2771                tombstone.display()
2772            );
2773            continue;
2774        }
2775        if mark.permits_removal() {
2776            // The mark is re-established before anything is deleted on the strength of
2777            // it. A retirement that failed part-way can leave one that was never flushed,
2778            // and this is the pass that would otherwise act on it thirty seconds after
2779            // the failure that said it would be left alone.
2780            if let Err(e) = mark_directory_retired(&tombstone) {
2781                warn!(
2782                    "{} says it was retired but that could not be confirmed ({e}). \
2783                     Leaving it.",
2784                    tombstone.display()
2785                );
2786                continue;
2787            }
2788            // Detached, so a node starting beside a large leftover directory serves
2789            // immediately rather than waiting out a recursive delete before it opens its
2790            // store.
2791            delete_retired_directory(tombstone);
2792            continue;
2793        }
2794        restore_unmarked_environment(root_dir, &tombstone);
2795    }
2796}
2797
2798/// Put an intact environment back under its own name.
2799///
2800/// An environment under the retired name with no mark inside it was renamed and then
2801/// interrupted before it could be marked. Nothing was deleted, so it is whole, and the
2802/// answer is to give it its name back and let the migration run again from the beginning:
2803/// every gate is re-derived, and a second retirement costs a pass, not data.
2804fn restore_unmarked_environment(root_dir: &Path, tombstone: &Path) {
2805    // An empty one is what a deletion that removed the contents and the mark and then
2806    // could not remove the directory leaves. There is nothing in it to restore, and
2807    // putting it back under the live name would strand an empty path the node then tries
2808    // to open.
2809    if std::fs::read_dir(tombstone).is_ok_and(|mut entries| entries.next().is_none()) {
2810        if let Err(e) = std::fs::remove_dir(tombstone) {
2811            warn!("Could not remove the empty {}: {e}", tombstone.display());
2812        }
2813        return;
2814    }
2815    let env = root_dir.join(LEGACY_ENV_DIR);
2816    if env.try_exists().unwrap_or(true) {
2817        // Both names are taken, so which one the node should serve is not this code's
2818        // decision to make.
2819        error!(
2820            "{} and {} both exist, and {} carries no retirement mark, so it may hold \
2821             chunks. Neither has been touched. Move or remove one by hand: the node is \
2822             using {}.",
2823            env.display(),
2824            tombstone.display(),
2825            tombstone.display(),
2826            env.display()
2827        );
2828        return;
2829    }
2830    match std::fs::rename(tombstone, &env) {
2831        Ok(()) => {
2832            let _ = crate::storage::file_store::fsync_path(root_dir);
2833            warn!(
2834                "{} was moved aside for retirement but never marked retired, so it is \
2835                 intact. It has been restored to {} and the migration starts again.",
2836                tombstone.display(),
2837                env.display()
2838            );
2839        }
2840        Err(e) => error!(
2841            "{} carries no retirement mark, so it may hold chunks, but it could not be \
2842             restored to {}: {e}. It has not been deleted.",
2843            tombstone.display(),
2844            env.display()
2845        ),
2846    }
2847}
2848
2849/// Every retired environment directory under `root_dir`.
2850///
2851/// More than one can be there: a node that retires, is restarted before the deletion
2852/// finishes, and somehow acquires another environment would leave the first behind. Each
2853/// is named so it cannot collide with the next.
2854fn retired_tombstones(root_dir: &Path) -> Vec<PathBuf> {
2855    let prefix = format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}");
2856    let entries = match std::fs::read_dir(root_dir) {
2857        Ok(entries) => entries,
2858        Err(e) => {
2859            // Cannot tell. Not the same as nothing here, and the caller uses this to
2860            // decide whether cleanup is finished, so answer with the one that keeps it
2861            // looking rather than the one that declares victory.
2862            warn!(
2863                "Could not list {} to look for retired chunk environments: {e}",
2864                root_dir.display()
2865            );
2866            return vec![root_dir.join(&prefix)];
2867        }
2868    };
2869    let mut found = Vec::new();
2870    for entry in entries {
2871        match entry {
2872            Ok(entry) => {
2873                if entry
2874                    .file_name()
2875                    .to_str()
2876                    .is_some_and(|n| n.starts_with(&prefix))
2877                {
2878                    found.push(entry.path());
2879                }
2880            }
2881            // One unreadable entry is not evidence there is nothing here, and the caller
2882            // uses this to decide whether cleanup is finished. Answer with the one that
2883            // keeps it looking.
2884            Err(e) => {
2885                warn!(
2886                    "Could not read an entry of {} while looking for retired chunk \
2887                     environments: {e}",
2888                    root_dir.display()
2889                );
2890                found.push(root_dir.join(&prefix));
2891            }
2892        }
2893    }
2894    found
2895}
2896
2897/// A directory name to retire the environment under that nothing else is using.
2898///
2899/// A fixed name would collide with a tombstone whose deletion is still running, and
2900/// clearing that one first would put a synchronous recursive delete back on the path this
2901/// is trying to keep clear.
2902fn free_tombstone_path(root_dir: &Path) -> PathBuf {
2903    let base = root_dir.join(format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}"));
2904    if !base.try_exists().unwrap_or(true) {
2905        return base;
2906    }
2907    for n in 1..=MAX_TOMBSTONES {
2908        let candidate = root_dir.join(format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}.{n}"));
2909        if !candidate.try_exists().unwrap_or(true) {
2910            return candidate;
2911        }
2912    }
2913    // Every name taken, which means many retirements have been interrupted without their
2914    // deletions finishing. Reuse the base: the rename fails, retirement defers, and the
2915    // operator sees a directory full of them.
2916    base
2917}
2918
2919/// Whether a legacy environment is on disk under `root_dir`.
2920///
2921/// # Errors
2922///
2923/// Returns [`Error::Storage`] if the answer cannot be determined. `Path::exists` would
2924/// turn a permission problem into "absent", and a node that starts in file-only mode
2925/// beside a `chunks.mdb` holding every chunk it has stops serving all of them.
2926pub fn legacy_present(root_dir: &Path) -> Result<bool> {
2927    let path = root_dir.join(LEGACY_ENV_DIR).join(LEGACY_DATA_FILE);
2928    path.try_exists().map_err(|e| {
2929        Error::Storage(format!(
2930            "Cannot tell whether the legacy chunk environment {} exists: {e}. Refusing to \
2931             start rather than ignore it.",
2932            path.display()
2933        ))
2934    })
2935}
2936
2937/// How long to sleep after copying `bytes` to hold the copier to a rate ceiling.
2938fn throttle_delay(bytes: u64, mib_per_sec: u64) -> Option<Duration> {
2939    if mib_per_sec == 0 {
2940        return None;
2941    }
2942    let per_sec = mib_per_sec.saturating_mul(1024 * 1024);
2943    if per_sec == 0 {
2944        return None;
2945    }
2946    let micros = bytes.saturating_mul(1_000_000) / per_sec;
2947    if micros == 0 {
2948        None
2949    } else {
2950        Some(Duration::from_micros(micros))
2951    }
2952}
2953
2954/// Merge two ascending key sequences into one, dropping duplicates.
2955fn merge_sorted<'a, I>(sorted: &[XorName], other: I) -> Vec<XorName>
2956where
2957    I: Iterator<Item = &'a XorName>,
2958{
2959    let other: Vec<XorName> = other.copied().collect();
2960    let mut out = Vec::with_capacity(sorted.len() + other.len());
2961    let mut a = sorted.iter().copied().peekable();
2962    let mut b = other.into_iter().peekable();
2963    loop {
2964        match (a.peek(), b.peek()) {
2965            (Some(x), Some(y)) => match x.cmp(y) {
2966                std::cmp::Ordering::Less => out.extend(a.next()),
2967                std::cmp::Ordering::Greater => out.extend(b.next()),
2968                std::cmp::Ordering::Equal => {
2969                    out.extend(a.next());
2970                    let _ = b.next();
2971                }
2972            },
2973            (Some(_), None) => out.extend(a.next()),
2974            (None, Some(_)) => out.extend(b.next()),
2975            (None, None) => break,
2976        }
2977    }
2978    out
2979}
2980
2981#[cfg(test)]
2982#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2983mod tests {
2984    use super::*;
2985    use crate::storage::migration::{now_unix, rank_closest_first, MIN_RETIRE_DELAY_HOURS};
2986    use tempfile::TempDir;
2987
2988    /// Everything currently legacy-only, as the set a test has "approved" for shedding.
2989    fn approved_shed(store: &ChunkStore) -> BTreeSet<XorName> {
2990        store.legacy_only_keys().into_iter().collect()
2991    }
2992
2993    /// A token that is never cancelled, for tests that are not exercising shutdown.
2994    fn never_cancelled() -> CancellationToken {
2995        CancellationToken::new()
2996    }
2997
2998    /// Put a store through every gate a real node passes before it may retire.
2999    ///
3000    /// Deliberately not a shortcut around them: `retire_legacy` rechecks the whole set
3001    /// itself, so a test that skipped them would exercise a path production never takes.
3002    fn open_the_retirement_gate(store: &ChunkStore) {
3003        store.commit_to_files().expect("commit");
3004        store.note_commitment_rebuilt();
3005        store.note_commitment_rebuilt();
3006        store.force_migration_state(|s| {
3007            s.committed_at_unix =
3008                Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
3009        });
3010    }
3011
3012    /// Content plus the address it hashes to.
3013    fn addressed(seed: &str) -> (XorName, Vec<u8>) {
3014        let content = format!("chunk-content-{seed}").into_bytes();
3015        (crate::client::compute_address(&content), content)
3016    }
3017
3018    fn test_config(dir: &TempDir) -> ChunkStoreConfig {
3019        ChunkStoreConfig {
3020            root_dir: dir.path().to_path_buf(),
3021            ..ChunkStoreConfig::test_default()
3022        }
3023    }
3024
3025    async fn open(dir: &TempDir) -> ChunkStore {
3026        ChunkStore::new(test_config(dir)).await.expect("open store")
3027    }
3028
3029    /// Populate a legacy LMDB environment the way an existing node would have one, then
3030    /// close it so the facade can adopt it.
3031    async fn seed_legacy(dir: &TempDir, seeds: &[&str]) -> Vec<XorName> {
3032        let lmdb = LmdbStorage::new(LmdbStorageConfig {
3033            root_dir: dir.path().to_path_buf(),
3034            verify_on_read: true,
3035            max_map_size: 0,
3036            disk_reserve: 0,
3037        })
3038        .await
3039        .expect("open legacy");
3040        let mut keys = Vec::new();
3041        for seed in seeds {
3042            let (addr, content) = addressed(seed);
3043            lmdb.put(&addr, &content).await.expect("legacy put");
3044            keys.push(addr);
3045        }
3046        lmdb.wait_idle().await;
3047        drop(lmdb);
3048        keys
3049    }
3050
3051    #[tokio::test]
3052    async fn a_fresh_node_never_creates_a_legacy_environment() {
3053        let dir = TempDir::new().expect("temp dir");
3054        let store = open(&dir).await;
3055
3056        assert!(!store.has_legacy());
3057        assert_eq!(store.migration_phase(), MigrationPhase::FilesOnly);
3058        assert!(!dir.path().join(LEGACY_ENV_DIR).exists());
3059
3060        let (addr, content) = addressed("fresh");
3061        assert!(store.put(&addr, &content).await.expect("put"));
3062        assert_eq!(
3063            store.get(&addr).await.expect("get").expect("present"),
3064            content
3065        );
3066    }
3067
3068    #[tokio::test]
3069    async fn an_existing_legacy_store_is_adopted_and_served() {
3070        let dir = TempDir::new().expect("temp dir");
3071        let keys = seed_legacy(&dir, &["a", "b", "c"]).await;
3072        let store = open(&dir).await;
3073
3074        assert!(store.has_legacy());
3075        assert_eq!(store.migration_phase(), MigrationPhase::Bridging);
3076        assert_eq!(store.current_chunks().expect("count"), 3);
3077        for key in &keys {
3078            assert!(store.exists(key).expect("exists"), "union must see it");
3079            assert!(store.get(key).await.expect("get").is_some());
3080        }
3081    }
3082
3083    #[tokio::test]
3084    async fn the_union_key_set_is_sorted_and_free_of_duplicates() {
3085        let dir = TempDir::new().expect("temp dir");
3086        let mut expected = seed_legacy(&dir, &["u1", "u2", "u3", "u4"]).await;
3087        let store = open(&dir).await;
3088
3089        // One chunk written now lives in both backings, and must be counted once.
3090        let (addr, content) = addressed("u2");
3091        assert!(expected.contains(&addr));
3092        assert!(!store.put(&addr, &content).await.expect("put"));
3093
3094        let (fresh, fresh_content) = addressed("u5");
3095        store.put(&fresh, &fresh_content).await.expect("put");
3096        expected.push(fresh);
3097        expected.sort_unstable();
3098
3099        let keys = store.all_keys().await.expect("all_keys");
3100        assert_eq!(keys, expected);
3101        assert_eq!(store.current_chunks().expect("count"), 5);
3102    }
3103
3104    /// The legacy environment takes no new disk during the bridge.
3105    ///
3106    /// Both stores sit on one disk, each measures the same free space, and neither knows
3107    /// what the other is about to spend. A chunk written to both could be admitted twice
3108    /// against one lot of headroom, and enough of them could cross the reserve together
3109    /// and fill the volume this migration exists to free.
3110    ///
3111    /// So the environment is pinned to what it already occupies. It still takes the
3112    /// rollback copy when it has room of its own, which on a real node it usually does:
3113    /// this migration exists because deleting millions of chunks left the free list full
3114    /// and returned nothing to the filesystem. What it will not do is grow.
3115    #[tokio::test]
3116    async fn the_legacy_environment_takes_no_new_disk_during_the_bridge() {
3117        let dir = TempDir::new().expect("temp dir");
3118        seed_legacy(&dir, &["seed"]).await;
3119        let store = open(&dir).await;
3120
3121        let data_file = dir.path().join(LEGACY_ENV_DIR).join(LEGACY_DATA_FILE);
3122        let before = std::fs::metadata(&data_file).expect("meta").len();
3123
3124        for seed in ["dual-1", "dual-2", "dual-3", "dual-4"] {
3125            let (addr, content) = addressed(seed);
3126            assert!(store.put(&addr, &content).await.expect("put"));
3127            assert!(
3128                store.exists(&addr).expect("exists"),
3129                "the file store is the one that has to have it"
3130            );
3131        }
3132        store.wait_idle().await;
3133
3134        let after = std::fs::metadata(&data_file).expect("meta").len();
3135        assert_eq!(
3136            after, before,
3137            "the environment must not claim disk the file store is also counting on"
3138        );
3139    }
3140
3141    #[tokio::test]
3142    async fn the_copier_moves_keys_into_files_and_is_resumable() {
3143        let dir = TempDir::new().expect("temp dir");
3144        let keys = seed_legacy(&dir, &["c1", "c2", "c3", "c4", "c5"]).await;
3145        let store = open(&dir).await;
3146        assert_eq!(store.legacy_only_keys().len(), 5);
3147
3148        let first = store
3149            .copy_batch(&keys[..2], 0, 0, &never_cancelled())
3150            .await
3151            .expect("copy first batch");
3152        assert_eq!(first.copied, 2);
3153        assert_eq!(store.legacy_only_keys().len(), 3);
3154        store.wait_idle().await;
3155        drop(store);
3156
3157        // A restart re-derives what is left from the filesystem: no progress file to
3158        // corrupt, and no work repeated.
3159        let store = open(&dir).await;
3160        assert_eq!(store.legacy_only_keys().len(), 3);
3161        let rest = store
3162            .copy_batch(&keys, 0, 0, &never_cancelled())
3163            .await
3164            .expect("copy rest");
3165        assert_eq!(rest.copied, 3);
3166        assert!(store.legacy_only_keys().is_empty());
3167        assert_eq!(store.current_chunks().expect("count"), 5);
3168    }
3169
3170    #[tokio::test]
3171    async fn a_delete_reaches_both_stores() {
3172        let dir = TempDir::new().expect("temp dir");
3173        let keys = seed_legacy(&dir, &["d1", "d2"]).await;
3174        let store = open(&dir).await;
3175
3176        let target = keys.first().copied().expect("a key");
3177        assert!(store.delete(&target).await.expect("delete"));
3178        assert!(!store.exists(&target).expect("exists"));
3179        assert!(store.get(&target).await.expect("get").is_none());
3180        assert_eq!(store.current_chunks().expect("count"), 1);
3181
3182        // And it stays gone across a restart, which is what proves it left the legacy
3183        // environment too rather than only the union view.
3184        store.wait_idle().await;
3185        drop(store);
3186        let store = open(&dir).await;
3187        assert!(!store.exists(&target).expect("exists"));
3188    }
3189
3190    #[tokio::test]
3191    async fn the_copier_does_not_resurrect_a_deleted_chunk() {
3192        let dir = TempDir::new().expect("temp dir");
3193        let keys = seed_legacy(&dir, &["r1", "r2"]).await;
3194        let store = open(&dir).await;
3195
3196        let target = keys.first().copied().expect("a key");
3197        store.delete(&target).await.expect("delete");
3198
3199        let report = store
3200            .copy_batch(&keys, 0, 0, &never_cancelled())
3201            .await
3202            .expect("copy");
3203        assert_eq!(report.copied, 1, "only the surviving chunk may be copied");
3204        assert!(!store.exists(&target).expect("exists"));
3205    }
3206
3207    /// A store left partway through by the release that shipped is picked up, not restarted.
3208    ///
3209    /// This release lands on nodes that are already migrating under the one before it, so what
3210    /// matters is not what it does to a fresh store but what it does to a half-finished one.
3211    /// It must re-read that state and change nothing: the phase, the first-start time the
3212    /// waves are measured from, what the node committed to giving up, and the keys still only
3213    /// in the legacy store all have to survive, or a node restarts a clock it had nearly run
3214    /// down, or re-copies what it already copied.
3215    ///
3216    /// Nothing in this release writes migration state, and this is what says so.
3217    #[tokio::test]
3218    async fn a_store_left_midway_by_the_previous_release_keeps_its_place() {
3219        let dir = TempDir::new().expect("temp dir");
3220        let keys = seed_legacy(&dir, &["k1", "k2", "k3"]).await;
3221
3222        let started_at = {
3223            let store = open(&dir).await;
3224            // Partway: one copied, two still only in the legacy store, which is where a node
3225            // that ran out of disk under the previous release sits.
3226            store
3227                .copy_batch(&keys[..1], 0, 0, &never_cancelled())
3228                .await
3229                .expect("copy");
3230            store.commit_to_files().expect("commit");
3231            assert_eq!(store.migration_phase(), MigrationPhase::Committed);
3232            assert_eq!(store.legacy_only_keys().len(), 2);
3233            store.migration_state().first_start_unix
3234        };
3235
3236        // The upgrade: a new process opening the same directory.
3237        let store = open(&dir).await;
3238        assert_eq!(
3239            store.migration_phase(),
3240            MigrationPhase::Committed,
3241            "an upgrade must not put a committed node back to bridging"
3242        );
3243        assert_eq!(
3244            store.migration_state().first_start_unix,
3245            started_at,
3246            "the waves are measured from this, so restarting it restarts the schedule"
3247        );
3248        assert_eq!(
3249            store.migration_state().shed_key_count,
3250            2,
3251            "what the node committed to giving up must survive the upgrade"
3252        );
3253        assert_eq!(
3254            store.legacy_only_keys().len(),
3255            2,
3256            "the keys still to copy must not be recounted from scratch"
3257        );
3258
3259        // And everything is still servable, out of whichever store holds it.
3260        for key in &keys {
3261            assert!(
3262                store.get(key).await.expect("get").is_some(),
3263                "a chunk stopped being servable across the upgrade"
3264            );
3265        }
3266    }
3267
3268    #[tokio::test]
3269    async fn committing_narrows_the_commitment_but_not_what_is_served() {
3270        let dir = TempDir::new().expect("temp dir");
3271        let keys = seed_legacy(&dir, &["k1", "k2", "k3"]).await;
3272        let store = open(&dir).await;
3273
3274        // Copy one, leave two behind as if the disk had run out.
3275        store
3276            .copy_batch(&keys[..1], 0, 0, &never_cancelled())
3277            .await
3278            .expect("copy");
3279
3280        // While bridging, the node still claims everything it can serve.
3281        assert_eq!(
3282            store.committable_keys().await.expect("committable").len(),
3283            3
3284        );
3285
3286        store.commit_to_files().expect("commit");
3287        assert_eq!(store.migration_phase(), MigrationPhase::Committed);
3288        assert_eq!(store.migration_state().shed_key_count, 2);
3289
3290        // It now claims only what it will keep...
3291        assert_eq!(
3292            store.committable_keys().await.expect("committable").len(),
3293            1
3294        );
3295        // ...while still serving everything it ever claimed.
3296        assert_eq!(store.all_keys().await.expect("all_keys").len(), 3);
3297        for key in &keys {
3298            assert!(store.get(key).await.expect("get").is_some());
3299        }
3300    }
3301
3302    #[tokio::test]
3303    async fn retirement_is_refused_until_every_gate_is_satisfied() {
3304        let dir = TempDir::new().expect("temp dir");
3305        let keys = seed_legacy(&dir, &["g1", "g2"]).await;
3306        let mut config = test_config(&dir);
3307        config.migration.retire_legacy = true;
3308        let store = ChunkStore::new(config).await.expect("open");
3309
3310        // Still bridging.
3311        assert!(store
3312            .retirement_blocker(|_| false)
3313            .expect("blocked")
3314            .contains("Bridging"));
3315
3316        store
3317            .copy_batch(&keys, 0, 0, &never_cancelled())
3318            .await
3319            .expect("copy");
3320        store.commit_to_files().expect("commit");
3321
3322        // No commitment rebuild observed yet.
3323        assert!(store
3324            .retirement_blocker(|_| false)
3325            .expect("blocked")
3326            .contains("commitment rebuilds"));
3327
3328        store.note_commitment_rebuilt();
3329        store.note_commitment_rebuilt();
3330
3331        // The retention delay has not elapsed.
3332        assert!(store
3333            .retirement_blocker(|_| false)
3334            .expect("blocked")
3335            .contains("retirement delay"));
3336
3337        store.force_migration_state(|s| {
3338            s.committed_at_unix =
3339                Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
3340        });
3341        assert!(store.retirement_blocker(|_| false).is_none());
3342    }
3343
3344    #[tokio::test]
3345    async fn a_chunk_still_answerable_vetoes_retirement() {
3346        let dir = TempDir::new().expect("temp dir");
3347        seed_legacy(&dir, &["h1", "h2"]).await;
3348        let mut config = test_config(&dir);
3349        config.migration.retire_legacy = true;
3350        let store = ChunkStore::new(config).await.expect("open");
3351
3352        // Shed both, as a node short of disk would.
3353        store.commit_to_files().expect("commit");
3354        store.note_commitment_rebuilt();
3355        store.note_commitment_rebuilt();
3356        store.force_migration_state(|s| {
3357            s.committed_at_unix =
3358                Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
3359        });
3360
3361        // The pruner's existing retention contract, reused verbatim: a key the node
3362        // could still be challenged on keeps its last local copy.
3363        assert!(store
3364            .retirement_blocker(|_| true)
3365            .expect("blocked")
3366            .contains("still answerable"));
3367        assert!(store.retirement_blocker(|_| false).is_none());
3368    }
3369
3370    /// The stock configuration retires, with no environment variable and no operator step.
3371    ///
3372    /// This is the property the whole release rests on. Deleting `chunks.mdb` is the only
3373    /// step that returns disk: LMDB never gives freed pages back, which is why the fleet
3374    /// deleted millions of chunks and recovered nothing. A build that shipped with this
3375    /// off would migrate every node and reclaim not one byte.
3376    #[tokio::test]
3377    async fn the_shipped_configuration_retires_without_an_operator_setting_anything() {
3378        // Asked of the configuration a node actually builds, not of the constant behind
3379        // it, so neither the constant nor a serde default nor the `Default` impl can turn
3380        // retirement off without this failing.
3381        assert!(
3382            crate::storage::MigrationConfig::default().retire_legacy,
3383            "this release must delete the legacy environment, or it frees no disk"
3384        );
3385
3386        let dir = TempDir::new().expect("temp dir");
3387        let keys = seed_legacy(&dir, &["shipped"]).await;
3388        let store = open(&dir).await;
3389        store
3390            .copy_batch(&keys, 0, 0, &never_cancelled())
3391            .await
3392            .expect("copy");
3393        open_the_retirement_gate(&store);
3394        assert!(
3395            store.retirement_blocker(|_| false).is_none(),
3396            "with every gate met, the shipped configuration must not refuse to retire"
3397        );
3398    }
3399
3400    /// Retirement waits for a read that is already running.
3401    ///
3402    /// The window this closes: a verifying read finds rotted bytes, throws the file away,
3403    /// and has not yet reached the legacy copy that would replace it. If retirement ran in
3404    /// that gap it would delete the only remaining copy. Holding the barrier shared for
3405    /// the whole read, and exclusively for the removal, is what makes that impossible.
3406    #[tokio::test]
3407    async fn retirement_waits_for_a_read_that_is_already_running() {
3408        let dir = TempDir::new().expect("temp dir");
3409        let keys = seed_legacy(&dir, &["held"]).await;
3410        let store = Arc::new(open(&dir).await);
3411        store
3412            .copy_batch(&keys, 0, 0, &never_cancelled())
3413            .await
3414            .expect("copy");
3415        open_the_retirement_gate(&store);
3416        let proof = store
3417            .verify_before_retire(0, &never_cancelled())
3418            .await
3419            .expect("verify");
3420
3421        // Stand in for a read that has started and not finished.
3422        let reading = store.retirement.read().await;
3423
3424        let retiring = {
3425            let store = Arc::clone(&store);
3426            let approved = approved_shed(&store);
3427            tokio::spawn(async move {
3428                store
3429                    .retire_legacy(&proof, &|_: &XorName| false, &approved)
3430                    .await
3431            })
3432        };
3433
3434        // It must not have got anywhere. Given a generous window rather than a tight one,
3435        // so this fails on the behaviour rather than on scheduling luck.
3436        tokio::time::sleep(Duration::from_millis(200)).await;
3437        assert!(
3438            !retiring.is_finished(),
3439            "retirement removed the legacy environment while a read was still running"
3440        );
3441        assert!(
3442            store.has_legacy(),
3443            "the legacy environment went while a read was still running"
3444        );
3445
3446        drop(reading);
3447        let freed = retiring.await.expect("join").expect("retire");
3448        assert!(freed > 0, "retirement should have freed the environment");
3449        assert!(!store.has_legacy());
3450    }
3451
3452    /// A good copy is never turned away because a damaged one wears its name.
3453    ///
3454    /// Two shapes of damage, because they are caught differently: a short file, which is
3455    /// what an interrupted create leaves on a platform that writes under the final name,
3456    /// and a full-length file with wrong bytes, which is what rot leaves. Answering
3457    /// "already have it" to either discards the copy that would fix it, and nothing offers
3458    /// it again.
3459    #[tokio::test]
3460    async fn a_damaged_chunk_is_repaired_from_the_copy_being_offered() {
3461        let dir = TempDir::new().expect("temp dir");
3462        let store = open(&dir).await;
3463        let (addr, content) = addressed("repairable-by-offer");
3464        store.put(&addr, &content).await.expect("put");
3465
3466        // Intact: the offer is correctly refused.
3467        assert!(store.holds_verified(&addr, &content).await);
3468
3469        // Truncated.
3470        let path = dir
3471            .path()
3472            .join("chunks")
3473            .join(format!("{:02x}", addr.last().copied().unwrap_or(0)))
3474            .join(hex::encode(addr));
3475        std::fs::write(&path, &content[..content.len() / 2]).expect("truncate");
3476        assert!(
3477            store.holds_verified(&addr, &content).await,
3478            "a short file must be replaced from the offered copy, not left in place"
3479        );
3480        assert_eq!(
3481            store.get(&addr).await.expect("get").expect("present"),
3482            content
3483        );
3484
3485        // Same length, wrong bytes.
3486        let rotted = vec![b'x'; content.len()];
3487        assert_ne!(rotted, content);
3488        std::fs::write(&path, &rotted).expect("rot");
3489        assert!(
3490            store.holds_verified(&addr, &content).await,
3491            "a rotted file must be replaced from the offered copy"
3492        );
3493        assert_eq!(
3494            store.get(&addr).await.expect("get").expect("present"),
3495            content
3496        );
3497    }
3498
3499    /// A chunk held only in the legacy environment is checked, not assumed good.
3500    ///
3501    /// The bytes in there can be wrong too, and when the copier finds that out it drops
3502    /// the key from the union view. Having turned the good copy away on the strength of
3503    /// the key being present, the node would then hold nothing at all.
3504    #[tokio::test]
3505    async fn a_legacy_only_chunk_with_wrong_bytes_is_replaced_by_the_offer() {
3506        let dir = TempDir::new().expect("temp dir");
3507        let keys = seed_legacy(&dir, &["legacy-side"]).await;
3508        let key = *keys.first().expect("one key");
3509        let content = format!("chunk-content-{}", "legacy-side").into_bytes();
3510        let store = open(&dir).await;
3511        assert!(store.legacy_only_keys().contains(&key));
3512
3513        // Intact: the offer is correctly refused.
3514        assert!(store.holds_verified(&key, &content).await);
3515
3516        // Wreck the legacy copy underneath, leaving the key in the union view.
3517        let legacy = store.legacy().expect("legacy");
3518        legacy.lmdb.delete(&key).await.expect("delete");
3519        assert!(
3520            store.holds_verified(&key, &content).await,
3521            "with no readable legacy copy the offered bytes must be taken, not refused"
3522        );
3523        assert_eq!(
3524            store.get(&key).await.expect("get").expect("present"),
3525            content
3526        );
3527        assert!(
3528            !store.legacy_only_keys().contains(&key),
3529            "and the key must leave the legacy-only set now that a file holds it"
3530        );
3531    }
3532
3533    /// A chunk this node does not have is not claimed as held.
3534    #[tokio::test]
3535    async fn a_chunk_this_node_does_not_have_is_not_claimed() {
3536        let dir = TempDir::new().expect("temp dir");
3537        let store = open(&dir).await;
3538        let (addr, content) = addressed("never-stored");
3539        assert!(!store.holds_verified(&addr, &content).await);
3540    }
3541
3542    /// An environment is never deleted because it failed to open.
3543    ///
3544    /// Opening is not a corruption test. It queries free space, maps the file, takes a
3545    /// write transaction and scans every key, so a full disk, a permission change or a
3546    /// transient fault all look identical to corruption. The only thing that counts is the
3547    /// directory's own mark.
3548    #[tokio::test]
3549    async fn an_unmarked_environment_is_kept_however_badly_it_reads() {
3550        let dir = TempDir::new().expect("temp dir");
3551        seed_legacy(&dir, &["unmarked"]).await;
3552        let env = dir.path().join(LEGACY_ENV_DIR);
3553        assert_eq!(retirement_mark(&env), RetirementMark::Absent);
3554
3555        finish_interrupted_retirement(dir.path());
3556        assert!(
3557            env.exists(),
3558            "an environment carrying no retirement mark must never be removed"
3559        );
3560    }
3561
3562    /// A directory carrying its own retirement mark is finished off, whatever it is named.
3563    ///
3564    /// This is the case the mark exists for. Off Unix the rename that moves the
3565    /// environment aside cannot be shown to be durable, so a power loss can bring it back
3566    /// under its old name with its contents already deleted. Without the mark the node
3567    /// would refuse to start on it forever; with it, the directory says what it is.
3568    #[tokio::test]
3569    async fn a_directory_that_says_it_was_retired_is_removed_under_any_name() {
3570        let dir = TempDir::new().expect("temp dir");
3571        let keys = seed_legacy(&dir, &["reverted"]).await;
3572        {
3573            let store = open(&dir).await;
3574            store
3575                .copy_batch(&keys, 0, 0, &never_cancelled())
3576                .await
3577                .expect("copy");
3578        }
3579        // What a reverted rename leaves: the old name, the retirement mark inside it.
3580        let env = dir.path().join(LEGACY_ENV_DIR);
3581        mark_directory_retired(&env).expect("mark");
3582
3583        let store = open(&dir).await;
3584        assert!(
3585            !store.has_legacy(),
3586            "the remains of an interrupted removal must not be adopted"
3587        );
3588        assert!(!env.exists(), "and the next start must finish the removal");
3589        // Every chunk is still served, from the file store.
3590        for key in &keys {
3591            assert!(store.get(key).await.expect("get").is_some());
3592        }
3593    }
3594
3595    /// The mark goes inside the directory, so a rename cannot separate them.
3596    ///
3597    /// A mark beside the environment would have to be cancelled when a retirement is
3598    /// abandoned, cancellation can fail or be lost, and a stale one would then authorise
3599    /// deleting an environment that had since taken a chunk.
3600    #[test]
3601    fn the_retirement_mark_travels_with_the_directory() {
3602        let dir = TempDir::new().expect("temp dir");
3603        let original = dir.path().join("chunks.mdb");
3604        std::fs::create_dir_all(&original).expect("mkdir");
3605        mark_directory_retired(&original).expect("mark");
3606        assert_eq!(retirement_mark(&original), RetirementMark::Present);
3607
3608        let renamed = dir.path().join("chunks.mdb.retired");
3609        std::fs::rename(&original, &renamed).expect("rename");
3610        assert!(
3611            retirement_mark(&renamed) == RetirementMark::Present,
3612            "the mark must survive the rename it exists to outlive"
3613        );
3614        // And back again, which is what a power loss undoing the rename looks like.
3615        std::fs::rename(&renamed, &original).expect("rename back");
3616        assert_eq!(retirement_mark(&original), RetirementMark::Present);
3617    }
3618
3619    /// Losing the handle to an environment that is still there is not completion.
3620    ///
3621    /// A rename that failed and then could not be reopened leaves the directory on disk
3622    /// with no way to read it. Treating the missing handle as "nothing left to migrate"
3623    /// would have the driver log the migration finished over a store still holding chunks
3624    /// nothing else can serve.
3625    #[tokio::test]
3626    async fn a_lost_handle_beside_a_live_environment_blocks_retirement() {
3627        let dir = TempDir::new().expect("temp dir");
3628        seed_legacy(&dir, &["orphaned"]).await;
3629        let store = open(&dir).await;
3630        assert!(store.has_legacy());
3631
3632        // Stand in for a failed rename followed by a failed reopen.
3633        *store.legacy.write() = None;
3634        assert!(!store.has_legacy());
3635        assert!(dir.path().join(LEGACY_ENV_DIR).exists());
3636
3637        let blocker = store
3638            .retirement_blocker(|_| false)
3639            .expect("a live environment with no handle must block");
3640        assert!(
3641            blocker.contains("no handle"),
3642            "the reason must name the actual problem, got: {blocker}"
3643        );
3644    }
3645
3646    /// A node that still holds its store open is gated too.
3647    ///
3648    /// The classification used to be asked only when there was no handle, which meant the
3649    /// ordinary path never asked it: a node holding its environment open went through every
3650    /// gate, renamed the directory aside and deleted it, whatever the mark said or failed to
3651    /// say. Retirement deletes the last other copy of these chunks, so it is not a question
3652    /// to skip because a different question already had an answer.
3653    #[cfg(unix)]
3654    #[tokio::test]
3655    async fn an_environment_that_cannot_be_classified_blocks_retirement_even_with_a_handle() {
3656        let dir = TempDir::new().expect("temp dir");
3657        seed_legacy(&dir, &["still-open"]).await;
3658        let store = open(&dir).await;
3659        assert!(
3660            store.has_legacy(),
3661            "this one keeps its handle, deliberately"
3662        );
3663        // Whatever else is in the way at this point, it is not this. Compared rather than
3664        // required to be nothing, because the other gates have their own tests and their
3665        // own reasons to be unmet here.
3666        let before = store.retirement_blocker(|_| false).unwrap_or_default();
3667        assert!(
3668            !before.contains("already retired"),
3669            "a readable environment must not be blocked for being unclassifiable: {before}"
3670        );
3671
3672        make_the_mark_unreadable(&dir.path().join(LEGACY_ENV_DIR));
3673
3674        let blocker = store
3675            .retirement_blocker(|_| false)
3676            .expect("an environment that cannot be classified must block retirement");
3677        assert!(
3678            blocker.contains("already retired"),
3679            "the reason must name the actual problem, got: {blocker}"
3680        );
3681        assert!(
3682            store.legacy_cannot_be_classified(),
3683            "and the driver must see it as work only a person can finish, so that it \
3684             gives the shared volume back"
3685        );
3686    }
3687
3688    /// A directory under the retired name with no mark inside it is an intact store.
3689    ///
3690    /// It got that name from a rename, and the rename happens after every gate; the mark
3691    /// is written straight afterwards. A crash in between leaves a whole environment
3692    /// wearing a name that says otherwise, and deleting it because of what it is called
3693    /// would destroy every chunk in it. It is put back instead.
3694    #[tokio::test]
3695    async fn an_unmarked_retired_directory_is_restored_rather_than_deleted() {
3696        let dir = TempDir::new().expect("temp dir");
3697        let keys = seed_legacy(&dir, &["not-really-retired"]).await;
3698        let env = dir.path().join(LEGACY_ENV_DIR);
3699        let tombstone = dir.path().join(format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}"));
3700        std::fs::rename(&env, &tombstone).expect("rename");
3701        assert_eq!(retirement_mark(&tombstone), RetirementMark::Absent);
3702
3703        let store = open(&dir).await;
3704        assert!(
3705            store.has_legacy(),
3706            "an unmarked environment must be restored and served, not deleted"
3707        );
3708        assert!(env.exists(), "it must be back under its own name");
3709        for key in &keys {
3710            assert!(store.get(key).await.expect("get").is_some());
3711        }
3712    }
3713
3714    /// A mark already at that name is not a mark until it can be read.
3715    ///
3716    /// The one place in this file that was taking the name as the evidence, which is the
3717    /// thing every other part of it refuses to do. Retirement writes the mark with
3718    /// `create_new`, and a failure saying something is already there was accepted as "the
3719    /// mark is present" and the environment deleted on the strength of it. What is at that
3720    /// name might be anything.
3721    ///
3722    /// It matters most for a node that already has its store open. That path never
3723    /// consulted the mark at all until this round, so an unreadable one would have gone
3724    /// through every gate and been deleted.
3725    #[cfg(unix)]
3726    #[test]
3727    fn a_mark_already_at_that_name_is_not_accepted_until_it_can_be_read() {
3728        let dir = TempDir::new().expect("temp dir");
3729        let env = dir.path().join(LEGACY_ENV_DIR);
3730        std::fs::create_dir_all(&env).expect("mkdir");
3731        make_the_mark_unreadable(&env);
3732
3733        let refused = mark_directory_retired(&env).expect_err("an unreadable mark is not a mark");
3734        assert!(
3735            !refused.mark_definitely_gone,
3736            "something is at that name, so the caller must not treat it as absent and put \
3737             the directory back under a name that will be opened"
3738        );
3739        assert_eq!(retirement_mark(&env), RetirementMark::Unknown);
3740
3741        // And a real one is still accepted, so the refusal above is about being unable to
3742        // read it rather than about there being something there at all.
3743        std::fs::remove_file(env.join(RETIRED_MARKER)).expect("clear the link");
3744        mark_directory_retired(&env).expect("a first mark");
3745        mark_directory_retired(&env).expect("and the same mark again, which is readable");
3746        assert_eq!(retirement_mark(&env), RetirementMark::Present);
3747    }
3748
3749    /// A directory nothing can classify is neither restored nor deleted.
3750    ///
3751    /// The half of the three-state answer that a first attempt at this got wrong. Asking
3752    /// only "may it be removed" and letting everything else fall through puts "cannot tell"
3753    /// straight back on the restoring path, which is the resurrection this exists to
3754    /// prevent: the mark check can fail for a moment and succeed the next, and the restore
3755    /// in between brings back a store that really had been retired.
3756    ///
3757    /// Unix only: the state is staged with a symbolic link, which Windows does not offer
3758    /// on the same terms.
3759    #[cfg(unix)]
3760    #[tokio::test]
3761    async fn a_tombstone_that_cannot_be_classified_is_left_where_it_is() {
3762        let dir = TempDir::new().expect("temp dir");
3763        seed_legacy(&dir, &["unclassifiable"]).await;
3764        let env = dir.path().join(LEGACY_ENV_DIR);
3765        let tombstone = dir.path().join(format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}"));
3766        std::fs::rename(&env, &tombstone).expect("rename");
3767        make_the_mark_unreadable(&tombstone);
3768        assert_eq!(retirement_mark(&tombstone), RetirementMark::Unknown);
3769
3770        sweep_retired_legacy(dir.path());
3771        let still_there = tombstone.exists();
3772        let restored = env.exists();
3773
3774        assert!(
3775            still_there,
3776            "a directory that cannot be classified must not be deleted: it may be intact"
3777        );
3778        assert!(
3779            !restored,
3780            "a directory that cannot be classified must not be put back under the live \
3781             name: it may be half deleted"
3782        );
3783    }
3784
3785    /// The same directory under the live name is not opened either.
3786    ///
3787    /// Opening it would put keys back into a commitment they may already have left, and
3788    /// this node cannot tell whether they have. Serving from files alone is the answer that
3789    /// is right either way.
3790    #[cfg(unix)]
3791    #[test]
3792    fn a_live_environment_that_cannot_be_classified_is_not_opened() {
3793        let dir = TempDir::new().expect("temp dir");
3794        let env = dir.path().join(LEGACY_ENV_DIR);
3795        std::fs::create_dir_all(&env).expect("mkdir");
3796        std::fs::write(env.join("data.mdb"), b"not really an environment").expect("seed");
3797        assert_eq!(
3798            finish_interrupted_retirement(dir.path()),
3799            LiveEnvironment::WhateverIsOnDisk,
3800            "a readable directory with no mark is ordinary and may be opened"
3801        );
3802
3803        make_the_mark_unreadable(&env);
3804        assert_eq!(retirement_mark(&env), RetirementMark::Unknown);
3805
3806        let verdict = finish_interrupted_retirement(dir.path());
3807        let still_there = env.exists();
3808
3809        assert_eq!(
3810            verdict,
3811            LiveEnvironment::None,
3812            "a directory that cannot be classified must not be opened"
3813        );
3814        assert!(
3815            still_there,
3816            "and it must not be deleted either: it may be a live environment"
3817        );
3818    }
3819
3820    /// Make the retirement mark in `dir` unreadable without touching the directory itself.
3821    ///
3822    /// A symbolic link pointing at itself. Looking for the mark follows it, gets
3823    /// `FilesystemLoop` back, and the answer is neither "there" nor "not there", which is
3824    /// the state under test.
3825    ///
3826    /// Taking the directory's permissions away instead was the first attempt and staged too
3827    /// much: at mode 000 the operating system refuses the rename as well, so the code being
3828    /// tested was never reached and the test passed with its own protection removed. Root
3829    /// can also read a mode-000 directory, which would have made it fail on any CI that
3830    /// runs as root. A link loop is neither: everything else about the directory keeps
3831    /// working, for every user.
3832    #[cfg(unix)]
3833    fn make_the_mark_unreadable(dir: &Path) {
3834        let link = dir.join(RETIRED_MARKER);
3835        let _ = std::fs::remove_file(&link);
3836        std::os::unix::fs::symlink(&link, &link).expect("a link to itself");
3837    }
3838
3839    /// Both names taken is not a decision this code makes.
3840    #[tokio::test]
3841    async fn an_unmarked_retired_directory_beside_a_live_one_is_left_alone() {
3842        let dir = TempDir::new().expect("temp dir");
3843        seed_legacy(&dir, &["live"]).await;
3844        let tombstone = dir.path().join(format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}"));
3845        std::fs::create_dir_all(&tombstone).expect("mkdir");
3846        std::fs::write(tombstone.join("data.mdb"), b"something").expect("write");
3847
3848        let store = open(&dir).await;
3849        assert!(store.has_legacy());
3850        assert!(
3851            tombstone.exists(),
3852            "an unmarked directory must never be deleted, even beside a live one"
3853        );
3854        assert!(dir.path().join(LEGACY_ENV_DIR).exists());
3855    }
3856
3857    /// The mark is the last thing a deletion takes away.
3858    ///
3859    /// A recursive delete walks in whatever order the filesystem gives, so it can unlink
3860    /// the mark and then fail on the next entry, which is what a sharing violation on the
3861    /// data file looks like. That leaves a genuinely retired, partly deleted directory
3862    /// carrying no evidence of it, and the next start would read that as intact and
3863    /// restore it.
3864    /// Unix only: the failure is provoked with directory permissions, which is not how
3865    /// the same thing happens on Windows. The behaviour under test is platform-neutral.
3866    #[cfg(unix)]
3867    #[test]
3868    fn a_failed_deletion_leaves_the_mark_in_place() {
3869        use std::os::unix::fs::PermissionsExt;
3870
3871        let dir = TempDir::new().expect("temp dir");
3872        let retired = dir.path().join("chunks.mdb.retired");
3873        std::fs::create_dir_all(&retired).expect("mkdir");
3874        std::fs::write(retired.join(LEGACY_DATA_FILE), b"payload").expect("write");
3875        mark_directory_retired(&retired).expect("mark");
3876
3877        // An entry that cannot be removed, standing in for whatever the filesystem
3878        // refuses on the day.
3879        std::fs::create_dir_all(retired.join("stuck")).expect("mkdir");
3880        let mut perms = std::fs::metadata(&retired).expect("meta").permissions();
3881        perms.set_mode(0o500);
3882        std::fs::set_permissions(&retired, perms.clone()).expect("chmod");
3883
3884        let failed = remove_marked_directory(&retired).is_err();
3885
3886        perms.set_mode(0o700);
3887        std::fs::set_permissions(&retired, perms).expect("chmod back");
3888
3889        assert!(failed, "the deletion was supposed to fail");
3890        assert!(
3891            retirement_mark(&retired) == RetirementMark::Present,
3892            "a deletion that failed must leave the mark, or the directory stops saying \
3893             what it is"
3894        );
3895    }
3896
3897    /// A mark that cannot be read is not permission to do anything.
3898    ///
3899    /// The reason this is three states and not two. Reading the mark can fail for reasons
3900    /// that are neither yes nor no, and the old answer for those was "no mark", which is
3901    /// the worst of the three: a retired environment reads as live, goes back under its own
3902    /// name, and its keys re-enter a commitment they have already left. Deleting on an
3903    /// unreadable answer would be just as wrong in the other direction.
3904    ///
3905    /// Unix only: the state is staged with a symbolic link, which Windows does not offer
3906    /// on the same terms.
3907    #[cfg(unix)]
3908    #[test]
3909    fn a_mark_that_cannot_be_read_permits_nothing() {
3910        let dir = TempDir::new().expect("temp dir");
3911        let env = dir.path().join(LEGACY_ENV_DIR);
3912
3913        // Nothing there is not the same as cannot tell, and it is the ordinary case: every
3914        // node that never had a legacy store, and every node that has finished with one,
3915        // asks this question on every tick. Answering "cannot tell" for those would have a
3916        // fresh node run a migration driver forever over a store it does not have.
3917        assert_eq!(
3918            retirement_mark(&env),
3919            RetirementMark::Absent,
3920            "a directory that is not there carries no mark, and that is known"
3921        );
3922        assert!(retirement_mark(&env).permits_opening());
3923
3924        std::fs::create_dir_all(&env).expect("mkdir");
3925        std::fs::write(env.join(RETIRED_MARKER), b"retired").expect("mark");
3926        assert_eq!(retirement_mark(&env), RetirementMark::Present);
3927
3928        // Looking for the mark now goes round in a circle, so the answer is neither there
3929        // nor not there.
3930        make_the_mark_unreadable(&env);
3931        let unreadable = retirement_mark(&env);
3932
3933        assert_eq!(
3934            unreadable,
3935            RetirementMark::Unknown,
3936            "a mark that cannot be read must not report as absent"
3937        );
3938        assert!(
3939            !unreadable.permits_removal(),
3940            "an unreadable mark must not authorise deleting the environment"
3941        );
3942        assert!(
3943            !unreadable.permits_opening(),
3944            "an unreadable mark must not authorise reopening the environment"
3945        );
3946    }
3947
3948    /// A directory under the live name that says it was retired is never opened.
3949    ///
3950    /// It may be partly deleted, and opening it would put keys back into a commitment
3951    /// they have already left. Its chunks are in the file store, which is what the mark
3952    /// records, so serving from files alone is correct.
3953    #[tokio::test]
3954    async fn a_marked_directory_under_the_live_name_is_not_served_from() {
3955        let dir = TempDir::new().expect("temp dir");
3956        let keys = seed_legacy(&dir, &["marked-live"]).await;
3957        {
3958            let store = open(&dir).await;
3959            store
3960                .copy_batch(&keys, 0, 0, &never_cancelled())
3961                .await
3962                .expect("copy");
3963        }
3964        let env = dir.path().join(LEGACY_ENV_DIR);
3965        mark_directory_retired(&env).expect("mark");
3966
3967        // Every name it could be moved to is taken by something that is not empty, so the
3968        // rename fails and the marked directory stays under the live name. That is the
3969        // case this is about: it must be left alone rather than opened.
3970        for n in 0..=MAX_TOMBSTONES {
3971            let taken = if n == 0 {
3972                dir.path().join(format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}"))
3973            } else {
3974                dir.path()
3975                    .join(format!("{LEGACY_ENV_DIR}{RETIRED_SUFFIX}.{n}"))
3976            };
3977            std::fs::create_dir_all(&taken).expect("mkdir");
3978            std::fs::write(taken.join("occupied"), b"x").expect("write");
3979        }
3980
3981        let store = open(&dir).await;
3982        assert!(
3983            env.exists(),
3984            "the rename was supposed to fail, leaving the marked directory in place"
3985        );
3986        assert!(
3987            !store.has_legacy(),
3988            "a directory that says it was retired must never be opened as live"
3989        );
3990        for key in &keys {
3991            assert!(store.get(key).await.expect("get").is_some());
3992        }
3993    }
3994
3995    /// A linked environment is copied out of but never deleted.
3996    ///
3997    /// An operator who points the chunk store at another volume leaves a link here.
3998    /// Retirement renames the path and then deletes what is behind it, and behind a link
3999    /// is a directory somewhere else that this node does not own.
4000    #[cfg(unix)]
4001    #[tokio::test]
4002    async fn a_linked_environment_is_never_retired() {
4003        let outside = TempDir::new().expect("temp dir");
4004        let dir = TempDir::new().expect("temp dir");
4005        // A real environment that lives in `outside`; the node root only links to it.
4006        seed_legacy(&outside, &["someone-elses"]).await;
4007        let real = outside.path().join(LEGACY_ENV_DIR);
4008        let bystander = outside.path().join("unrelated");
4009        std::fs::create_dir_all(&bystander).expect("mkdir");
4010        std::os::unix::fs::symlink(&real, dir.path().join(LEGACY_ENV_DIR)).expect("symlink");
4011
4012        let store = open(&dir).await;
4013        let blocker = store
4014            .retirement_blocker(|_| false)
4015            .expect("a linked environment must block retirement");
4016        assert!(
4017            blocker.contains("link"),
4018            "the reason must name the actual problem, got: {blocker}"
4019        );
4020
4021        // And nothing walks through it, whatever it is marked with.
4022        std::fs::write(real.join(RETIRED_MARKER), b"x").expect("mark through the link");
4023        assert!(
4024            retirement_mark(&dir.path().join(LEGACY_ENV_DIR)) != RetirementMark::Present,
4025            "a link must never be treated as a retired directory"
4026        );
4027        assert!(
4028            remove_marked_directory(&dir.path().join(LEGACY_ENV_DIR)).is_err(),
4029            "deleting through a link must be refused"
4030        );
4031        assert!(
4032            real.join(LEGACY_DATA_FILE).exists(),
4033            "and must delete nothing"
4034        );
4035        assert!(bystander.exists());
4036    }
4037
4038    /// A deletion that cannot remove the directory itself puts the mark back.
4039    ///
4040    /// An unmarked directory that still exists is the one state the scheme says cannot
4041    /// happen: the next start would read it as an intact environment.
4042    ///
4043    /// Unix only: the failure is provoked with directory permissions, which is not how
4044    /// the same thing happens on Windows. The behaviour under test is platform-neutral.
4045    #[cfg(unix)]
4046    #[test]
4047    fn a_directory_that_cannot_be_removed_keeps_saying_it_was_retired() {
4048        use std::os::unix::fs::PermissionsExt;
4049
4050        let dir = TempDir::new().expect("temp dir");
4051        let retired = dir.path().join("chunks.mdb.retired");
4052        std::fs::create_dir_all(&retired).expect("mkdir");
4053        std::fs::write(retired.join(LEGACY_DATA_FILE), b"payload").expect("write");
4054        mark_directory_retired(&retired).expect("mark");
4055
4056        // The parent read-only, so the directory cannot be unlinked from it while its own
4057        // contents still can be. That is the shape that leaves an emptied, unmarked
4058        // directory behind.
4059        let mut perms = std::fs::metadata(dir.path()).expect("meta").permissions();
4060        perms.set_mode(0o500);
4061        std::fs::set_permissions(dir.path(), perms).expect("chmod");
4062
4063        let failed = remove_marked_directory(&retired).is_err();
4064
4065        let mut perms = std::fs::metadata(dir.path()).expect("meta").permissions();
4066        perms.set_mode(0o700);
4067        std::fs::set_permissions(dir.path(), perms).expect("chmod back");
4068
4069        assert!(failed, "the removal was supposed to fail");
4070        assert!(retired.exists(), "and to leave the directory behind");
4071        assert!(
4072            retirement_mark(&retired) == RetirementMark::Present,
4073            "a directory that outlived its deletion must still say what it is"
4074        );
4075    }
4076
4077    /// A key the environment holds that is in neither view stops retirement.
4078    ///
4079    /// The gates only ever see the legacy-only set, so a key that has fallen out of both
4080    /// the file index and that set has been through nothing and is protected by nothing.
4081    /// It is the environment's only copy, and retirement would take it.
4082    #[tokio::test]
4083    async fn a_legacy_key_in_neither_view_refuses_the_proof_and_is_re_queued() {
4084        let dir = TempDir::new().expect("temp dir");
4085        let keys = seed_legacy(&dir, &["orphan"]).await;
4086        let key = *keys.first().expect("one key");
4087        let store = open(&dir).await;
4088        store
4089            .copy_batch(&keys, 0, 0, &never_cancelled())
4090            .await
4091            .expect("copy");
4092        assert!(!store.legacy_only_keys().contains(&key));
4093
4094        // Stand in for whatever takes the file out from under the index: a quarantine, a
4095        // publish that failed, an operator. The key is now in neither view.
4096        let path = dir
4097            .path()
4098            .join("chunks")
4099            .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
4100            .join(hex::encode(key));
4101        std::fs::remove_file(&path).expect("remove the file");
4102        store.files.forget_for_test(&key);
4103        assert!(!store.files.exists(&key).unwrap_or(false));
4104        assert!(!store.legacy_only_keys().contains(&key));
4105
4106        let proof = store
4107            .verify_before_retire(0, &never_cancelled())
4108            .await
4109            .expect("verify");
4110        assert!(
4111            !proof.is_clean(),
4112            "a key protected by neither view must refuse the proof"
4113        );
4114        assert!(
4115            store.legacy_only_keys().contains(&key),
4116            "and must be put back where the gates can see it"
4117        );
4118    }
4119
4120    /// A verification that no longer describes the store does not authorise a deletion.
4121    ///
4122    /// The pass reads every chunk and its result is reused for a while rather than re-read
4123    /// on every tick. Retirement is often deferred in that window by a gate that has
4124    /// nothing to do with the files. If a kept chunk stops being readable meanwhile,
4125    /// ordinary requests are still served from the legacy copy, and deleting that copy on
4126    /// the strength of the older pass leaves the node holding only the unreadable one.
4127    #[cfg(unix)]
4128    #[tokio::test]
4129    async fn a_verification_overtaken_by_a_failing_file_does_not_authorise_retirement() {
4130        use std::os::unix::fs::PermissionsExt;
4131
4132        let dir = TempDir::new().expect("temp dir");
4133        let keys = seed_legacy(&dir, &["kept-then-unreadable"]).await;
4134        let key = *keys.first().expect("one key");
4135        let mut config = test_config(&dir);
4136        config.migration.retire_legacy = true;
4137        let store = ChunkStore::new(config).await.expect("open");
4138        store
4139            .copy_batch(&keys, 0, 0, &never_cancelled())
4140            .await
4141            .expect("copy");
4142        open_the_retirement_gate(&store);
4143
4144        let proof = store
4145            .verify_before_retire(0, &never_cancelled())
4146            .await
4147            .expect("verify");
4148        assert!(proof.is_clean());
4149
4150        // The window: the file stops being readable after the pass and before the
4151        // deletion it authorised.
4152        let path = dir
4153            .path()
4154            .join("chunks")
4155            .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
4156            .join(hex::encode(key));
4157        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
4158        perms.set_mode(0o000);
4159        std::fs::set_permissions(&path, perms).expect("chmod");
4160        assert!(
4161            store.get(&key).await.is_ok(),
4162            "the legacy copy still serves it, which is what hides the problem"
4163        );
4164
4165        let err = store
4166            .retire_legacy(&proof, &|_: &XorName| false, &approved_shed(&store))
4167            .await
4168            .expect_err("a verification the store has outrun must not authorise a delete");
4169        assert!(format!("{err}").contains("no longer describes"), "{err}");
4170        assert!(
4171            store.has_legacy(),
4172            "and the legacy environment must survive"
4173        );
4174
4175        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
4176        perms.set_mode(0o600);
4177        std::fs::set_permissions(&path, perms).expect("chmod back");
4178    }
4179
4180    /// A write with no rollback copy is counted, on the path that actually skips.
4181    ///
4182    /// The environment is pinned to its current size for the whole bridge, so one with no
4183    /// reusable page answers `Full` to every write and the node stores in files alone. That
4184    /// is accepted, and the ADR says so. What was missing was any way to ask how often it
4185    /// happens: the second release turns on knowing how many nodes are really keeping a
4186    /// rollback copy, and a log line per chunk does not answer it.
4187    ///
4188    /// The first version of this counter missed exactly this path and counted only the
4189    /// other one, the write that is attempted and refused. On the node most affected the
4190    /// other path never runs, so the counter stayed at zero on precisely the nodes it was
4191    /// added for.
4192    #[tokio::test]
4193    async fn a_write_with_no_rollback_copy_is_counted() {
4194        let dir = TempDir::new().expect("temp dir");
4195        seed_legacy(&dir, &["settled"]).await;
4196        let store = open(&dir).await;
4197        assert_eq!(
4198            store.writes_without_a_rollback_copy(),
4199            0,
4200            "nothing has been skipped yet"
4201        );
4202
4203        let legacy = store.legacy().expect("legacy");
4204        let before = legacy
4205            .skipped_rollback_copies
4206            .load(std::sync::atomic::Ordering::Relaxed);
4207
4208        // Whichever way the environment refuses, the count moves. Driven through the
4209        // counter itself rather than by filling a real environment, because what is under
4210        // test is that the skip is recorded, and staging a genuinely unwritable LMDB from
4211        // here would be testing LMDB.
4212        for _ in 0..12 {
4213            let _ = legacy.note_skipped_rollback_copy();
4214        }
4215        assert_eq!(
4216            store.writes_without_a_rollback_copy(),
4217            before + 12,
4218            "skipped writes must be visible to whoever asks the node"
4219        );
4220
4221        // And the log is throttled, or a node with no free pages writes one line per chunk
4222        // for the rest of its life.
4223        let said: Vec<u64> = (0..1_000)
4224            .filter_map(|_| legacy.note_skipped_rollback_copy())
4225            .collect();
4226        assert!(
4227            said.len() < 10,
4228            "the warning fired {} times in a thousand writes",
4229            said.len()
4230        );
4231    }
4232
4233    /// Two writes for one key need two notes, not one shared between them.
4234    ///
4235    /// The journal used to be a set, so a second write for the same key announced nothing
4236    /// and the first to return cleared the entry for both. A delete arriving in that window
4237    /// sees no announcement, skips draining the environment, and the surviving write lands
4238    /// afterwards and puts the key back, undoing a prune the node had decided on. The key
4239    /// then sits in the environment and in neither view, which is the state retirement is
4240    /// built to refuse: no data is lost, but a prune and a retirement cycle are.
4241    ///
4242    /// The file store's own in-flight map is counted for exactly this reason. This is the
4243    /// same reasoning applied to the half that did not have it.
4244    #[tokio::test]
4245    async fn two_writes_for_one_key_are_two_notes_and_the_first_to_return_clears_neither() {
4246        let dir = TempDir::new().expect("temp dir");
4247        seed_legacy(&dir, &["settled"]).await;
4248        let store = open(&dir).await;
4249        let legacy = store.legacy().expect("legacy");
4250        let (addr, _) = addressed("two-writes");
4251
4252        legacy.announce(&addr);
4253        legacy.announce(&addr);
4254        assert!(store.has_pending_writes());
4255
4256        // The first write returns. The second is still out there, so the note has to stand.
4257        legacy.announced_write_finished(&addr);
4258        assert!(
4259            store.has_pending_writes(),
4260            "the first write to return cleared a note the second one was still relying on"
4261        );
4262
4263        // And the second clears it.
4264        legacy.announced_write_finished(&addr);
4265        assert!(!store.has_pending_writes());
4266
4267        // Retiring one that was never announced changes nothing, which is what makes the
4268        // delete path's unconditional clear safe.
4269        legacy.announced_write_finished(&addr);
4270        assert!(!store.has_pending_writes());
4271    }
4272
4273    /// A write in flight is a note to self, not a claim to hold the chunk.
4274    ///
4275    /// The note exists because a write into the environment outlives the future waiting
4276    /// for it, so a cancelled one could leave a chunk nothing had recorded. But until both
4277    /// halves have returned the node does not hold it, and saying it does puts the key in
4278    /// signed commitments and in the count a quote is priced from.
4279    #[tokio::test]
4280    async fn a_write_in_flight_is_not_claimed_but_does_stop_retirement() {
4281        let dir = TempDir::new().expect("temp dir");
4282        seed_legacy(&dir, &["settled"]).await;
4283        let store = open(&dir).await;
4284        let legacy = store.legacy().expect("legacy");
4285        let (addr, _) = addressed("in-flight");
4286
4287        // Stand in for a write that announced itself and never came back.
4288        legacy.announce(&addr);
4289
4290        assert!(
4291            !store.exists(&addr).expect("exists"),
4292            "a write in flight must not be reported as held"
4293        );
4294        assert!(!store.all_keys().await.expect("keys").contains(&addr));
4295        assert!(!store.legacy_only_keys().contains(&addr));
4296        assert!(store.has_pending_writes());
4297
4298        // The distinction is the point: the same key in the key set IS claimed. If a
4299        // write announced itself there instead, every one of the assertions above would
4300        // be the opposite for as long as the write took.
4301        legacy.only.write().insert(addr);
4302        assert!(store.exists(&addr).expect("exists"));
4303        assert!(store.all_keys().await.expect("keys").contains(&addr));
4304        legacy.only.write().remove(&addr);
4305
4306        // But it does stop the environment going, because what it holds is unsettled.
4307        store.commit_to_files().expect("commit");
4308        store.note_commitment_rebuilt();
4309        store.note_commitment_rebuilt();
4310        store.force_migration_state(|s| {
4311            s.committed_at_unix =
4312                Some(now_unix().saturating_sub(MIN_RETIRE_DELAY_HOURS * 3600 + 60));
4313        });
4314        let proof = store
4315            .verify_before_retire(0, &never_cancelled())
4316            .await
4317            .expect("verify");
4318        let err = store
4319            .retire_legacy(&proof, &|_: &XorName| false, &approved_shed(&store))
4320            .await
4321            .expect_err("an unsettled write must stop the removal");
4322        assert!(format!("{err}").contains("not reported back"), "{err}");
4323
4324        // And the note is resolved against what is actually there: nothing, so it goes.
4325        store.reconcile_pending_writes().await;
4326        assert!(!store.has_pending_writes());
4327        assert!(!store.legacy_only_keys().contains(&addr));
4328    }
4329
4330    /// A delete outlasts a write for the same key that nobody waited for.
4331    ///
4332    /// A write has an environment half and a file half, and either can still be running
4333    /// when its caller is dropped: the blocking work is not cancelled with the future.
4334    /// A delete that did not wait for both would be undone by whichever half landed
4335    /// afterwards, putting back a chunk the node had decided to prune.
4336    #[tokio::test]
4337    async fn a_delete_outlasts_a_write_nobody_waited_for() {
4338        let dir = TempDir::new().expect("temp dir");
4339        seed_legacy(&dir, &["neighbour"]).await;
4340        let store = Arc::new(open(&dir).await);
4341        let (addr, content) = addressed("written-then-pruned");
4342
4343        // The gate is held from its own thread, so nothing holds a blocking guard across
4344        // an await, and it is released through a channel when the test is ready.
4345        let gate = store.files.test_put_gate();
4346        let (held_tx, held_rx) = std::sync::mpsc::channel::<()>();
4347        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
4348        let holder = std::thread::spawn(move || {
4349            let _parked = gate.write();
4350            held_tx.send(()).ok();
4351            release_rx.recv().ok();
4352        });
4353        held_rx.recv().expect("the gate is held");
4354
4355        // The state under test, built directly rather than by racing a real put: a write
4356        // that announced itself, whose file half is parked mid-publish, and whose caller
4357        // is gone. Driving it through `put` and aborting would be a race about which half
4358        // had started, and a test that sometimes sets up a different state than it claims
4359        // is worse than no test.
4360        let legacy = store.legacy().expect("legacy");
4361        legacy.announce(&addr);
4362        let publishing = {
4363            let files = Arc::clone(&store.files);
4364            let content = content.clone();
4365            tokio::spawn(async move { files.put(&addr, &content).await })
4366        };
4367        // Until the publish is genuinely in flight and parked at the gate.
4368        while store.files.tasks_in_flight() == 0 {
4369            tokio::time::sleep(Duration::from_millis(5)).await;
4370        }
4371        publishing.abort();
4372        let _ = publishing.await;
4373
4374        // The delete has to wait the parked half out rather than racing it.
4375        let deleting = {
4376            let store = Arc::clone(&store);
4377            tokio::spawn(async move { store.delete(&addr).await })
4378        };
4379        tokio::time::sleep(Duration::from_millis(100)).await;
4380        assert!(
4381            !deleting.is_finished(),
4382            "the delete must wait for the write it would otherwise race"
4383        );
4384
4385        release_tx.send(()).ok();
4386        holder.join().ok();
4387        deleting.await.expect("join").expect("delete");
4388
4389        // Whichever half landed, the key is gone and stays gone.
4390        store.files.wait_idle().await;
4391        assert!(
4392            !store.exists(&addr).unwrap_or(true),
4393            "a write that landed after the delete would resurrect a pruned chunk"
4394        );
4395        assert!(!store.legacy_only_keys().contains(&addr));
4396    }
4397
4398    /// A delete outlasts a file write that no journal knows about.
4399    ///
4400    /// The journal is kept by writes that touch both stores. The copier and the repair
4401    /// path write only the file, so a delete that consulted the journal to decide whether
4402    /// to wait would not wait for either of them, and whichever landed afterwards would
4403    /// put back a chunk the node had decided to prune. What is writing a key is the file
4404    /// store's own question to answer.
4405    #[tokio::test]
4406    async fn a_delete_outlasts_a_file_write_with_no_journal_entry() {
4407        let dir = TempDir::new().expect("temp dir");
4408        seed_legacy(&dir, &["neighbour"]).await;
4409        let store = Arc::new(open(&dir).await);
4410        let (addr, content) = addressed("copied-then-pruned");
4411
4412        let gate = store.files.test_put_gate();
4413        let (held_tx, held_rx) = std::sync::mpsc::channel::<()>();
4414        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
4415        let holder = std::thread::spawn(move || {
4416            let _parked = gate.write();
4417            held_tx.send(()).ok();
4418            release_rx.recv().ok();
4419        });
4420        held_rx.recv().expect("the gate is held");
4421
4422        // Deliberately no journal entry: this is the copier's shape, not a dual write.
4423        let publishing = {
4424            let files = Arc::clone(&store.files);
4425            let content = content.clone();
4426            tokio::spawn(async move { files.put(&addr, &content).await })
4427        };
4428        while store.files.tasks_in_flight() == 0 {
4429            tokio::time::sleep(Duration::from_millis(5)).await;
4430        }
4431        publishing.abort();
4432        let _ = publishing.await;
4433        assert!(
4434            !store
4435                .legacy()
4436                .is_some_and(|l| l.pending.read().contains_key(&addr)),
4437            "this is the case the journal does not cover, so it must be empty"
4438        );
4439
4440        let deleting = {
4441            let store = Arc::clone(&store);
4442            tokio::spawn(async move { store.delete(&addr).await })
4443        };
4444        tokio::time::sleep(Duration::from_millis(100)).await;
4445        assert!(
4446            !deleting.is_finished(),
4447            "the delete must wait for a write the journal never knew about"
4448        );
4449
4450        release_tx.send(()).ok();
4451        holder.join().ok();
4452        deleting.await.expect("join").expect("delete");
4453
4454        store.files.wait_idle().await;
4455        assert!(
4456            !store.exists(&addr).unwrap_or(true),
4457            "a write that landed after the delete would resurrect a pruned chunk"
4458        );
4459    }
4460
4461    /// A single node can still be told to keep both stores.
4462    #[tokio::test]
4463    async fn retirement_is_refused_when_the_switch_is_turned_off() {
4464        let dir = TempDir::new().expect("temp dir");
4465        seed_legacy(&dir, &["off"]).await;
4466        let mut config = test_config(&dir);
4467        config.migration.retire_legacy = false;
4468        let store = ChunkStore::new(config).await.expect("open store");
4469        store.commit_to_files().expect("commit");
4470        assert!(store
4471            .retirement_blocker(|_| false)
4472            .expect("blocked")
4473            .contains("retirement is disabled"));
4474    }
4475
4476    #[tokio::test]
4477    async fn retiring_removes_the_legacy_environment_and_frees_its_space() {
4478        let dir = TempDir::new().expect("temp dir");
4479        let keys = seed_legacy(&dir, &["f1", "f2", "f3"]).await;
4480        let mut config = test_config(&dir);
4481        config.migration.retire_legacy = true;
4482        let store = ChunkStore::new(config).await.expect("open");
4483
4484        store
4485            .copy_batch(&keys, 0, 0, &never_cancelled())
4486            .await
4487            .expect("copy");
4488        open_the_retirement_gate(&store);
4489
4490        let proof = store
4491            .verify_before_retire(0, &never_cancelled())
4492            .await
4493            .expect("verify");
4494        assert!(proof.is_clean());
4495        assert_eq!(proof.checked, 3);
4496
4497        let freed = store
4498            .retire_legacy(&proof, &|_: &XorName| false, &approved_shed(&store))
4499            .await
4500            .expect("retire");
4501        assert!(freed > 0, "retirement must report the space it returned");
4502        assert!(
4503            !dir.path().join(LEGACY_ENV_DIR).exists(),
4504            "the legacy environment must actually be removed"
4505        );
4506        assert!(!store.has_legacy());
4507        assert_eq!(store.migration_phase(), MigrationPhase::FilesOnly);
4508
4509        // Everything is still readable, from files alone.
4510        assert_eq!(store.current_chunks().expect("count"), 3);
4511        for key in &keys {
4512            assert!(store.get(key).await.expect("get").is_some());
4513        }
4514    }
4515
4516    #[tokio::test]
4517    async fn a_reader_holding_the_legacy_handle_defers_retirement_without_hiding_chunks() {
4518        let dir = TempDir::new().expect("temp dir");
4519        let keys = seed_legacy(&dir, &["busy"]).await;
4520        let mut config = test_config(&dir);
4521        config.migration.retire_legacy = true;
4522        let store = Arc::new(ChunkStore::new(config).await.expect("open"));
4523        store
4524            .copy_batch(&keys, 0, 0, &never_cancelled())
4525            .await
4526            .expect("copy");
4527        open_the_retirement_gate(&store);
4528
4529        // Stand in for a read that is still holding the legacy handle. Retirement must
4530        // defer rather than unmap underneath it, and the chunk must stay readable
4531        // throughout: a retirement attempt that briefly hid the legacy store would make a
4532        // node answer "not found" for a chunk it holds.
4533        let squatter = store.legacy().expect("a legacy handle");
4534        let proof = store
4535            .verify_before_retire(0, &never_cancelled())
4536            .await
4537            .expect("verify");
4538        let err = store
4539            .retire_legacy(&proof, &|_: &XorName| false, &approved_shed(&store))
4540            .await
4541            .expect_err("must defer while the handle is held");
4542        assert!(format!("{err}").contains("deferred"), "{err}");
4543
4544        assert!(store.has_legacy(), "the store must keep its legacy handle");
4545        let key = keys.first().copied().expect("a key");
4546        assert!(
4547            store.get(&key).await.expect("get").is_some(),
4548            "the chunk must stay readable across a deferred retirement"
4549        );
4550
4551        // Once the reader lets go, the next attempt succeeds.
4552        drop(squatter);
4553        store
4554            .retire_legacy(&proof, &|_: &XorName| false, &approved_shed(&store))
4555            .await
4556            .expect("retire");
4557        assert!(!store.has_legacy());
4558    }
4559
4560    #[tokio::test]
4561    async fn retirement_needs_a_clean_verification_report() {
4562        let dir = TempDir::new().expect("temp dir");
4563        // Left uncopied on purpose, so this node is about to give the chunk up and the
4564        // answerability veto has something to fire on.
4565        seed_legacy(&dir, &["v1"]).await;
4566        let mut config = test_config(&dir);
4567        config.migration.retire_legacy = true;
4568        let store = ChunkStore::new(config).await.expect("open");
4569
4570        // A report cannot be fabricated: every field is private and the only source is
4571        // the verification pass. The one available here is the default, which never ran.
4572        let absent = VerifyReport::default();
4573        let err = store
4574            .retire_legacy(&absent, &|_: &XorName| false, &approved_shed(&store))
4575            .await
4576            .expect_err("must refuse a report that never ran");
4577        assert!(format!("{err}").contains("unrepairable"), "{err}");
4578        assert!(store.has_legacy(), "the legacy environment must survive");
4579
4580        // And a real, clean report is still refused while any gate is unmet, because
4581        // retirement rechecks them all itself rather than trusting its caller.
4582        open_the_retirement_gate(&store);
4583        let proof = store
4584            .verify_before_retire(0, &never_cancelled())
4585            .await
4586            .expect("verify");
4587        assert!(proof.is_clean());
4588        let err = store
4589            .retire_legacy(&proof, &|_: &XorName| true, &approved_shed(&store))
4590            .await
4591            .expect_err("must refuse while a chunk is still answerable");
4592        assert!(format!("{err}").contains("still answerable"), "{err}");
4593        assert!(store.has_legacy());
4594    }
4595
4596    #[tokio::test]
4597    async fn verification_repairs_a_file_that_rotted_before_retirement() {
4598        let dir = TempDir::new().expect("temp dir");
4599        let keys = seed_legacy(&dir, &["w1", "w2"]).await;
4600        let mut config = test_config(&dir);
4601        config.migration.retire_legacy = true;
4602        let store = ChunkStore::new(config).await.expect("open");
4603        store
4604            .copy_batch(&keys, 0, 0, &never_cancelled())
4605            .await
4606            .expect("copy");
4607
4608        // A filename is not proof the bytes behind it are good. Corrupt one, exactly as
4609        // a truncated write or a bad sector would, then prove retirement repairs it
4610        // rather than deleting the only intact copy.
4611        let victim = keys.first().copied().expect("a key");
4612        let path = dir
4613            .path()
4614            .join(crate::storage::file_store::CHUNKS_DIR_NAME)
4615            .join(format!("{:02x}", victim.last().copied().unwrap_or(0)))
4616            .join(hex::encode(victim));
4617        std::fs::write(&path, b"rotted").expect("corrupt the file");
4618        open_the_retirement_gate(&store);
4619
4620        let proof = store
4621            .verify_before_retire(0, &never_cancelled())
4622            .await
4623            .expect("verify");
4624        assert_eq!(proof.repaired(), 1);
4625        assert_eq!(proof.unrepairable(), 0);
4626        assert!(proof.is_clean());
4627
4628        store
4629            .retire_legacy(&proof, &|_: &XorName| false, &approved_shed(&store))
4630            .await
4631            .expect("retire");
4632        assert_eq!(
4633            store.get(&victim).await.expect("get").expect("present"),
4634            addressed("w1").1
4635        );
4636    }
4637
4638    #[tokio::test]
4639    async fn a_corrupt_file_is_served_from_the_legacy_copy_and_requeued() {
4640        let dir = TempDir::new().expect("temp dir");
4641        let keys = seed_legacy(&dir, &["s1"]).await;
4642        let store = open(&dir).await;
4643        store
4644            .copy_batch(&keys, 0, 0, &never_cancelled())
4645            .await
4646            .expect("copy");
4647        assert!(store.legacy_only_keys().is_empty());
4648
4649        let victim = keys.first().copied().expect("a key");
4650        let path = dir
4651            .path()
4652            .join(crate::storage::file_store::CHUNKS_DIR_NAME)
4653            .join(format!("{:02x}", victim.last().copied().unwrap_or(0)))
4654            .join(hex::encode(victim));
4655        std::fs::write(&path, b"rotted").expect("corrupt the file");
4656
4657        // The file store removes the bad file and stops advertising it; the facade must
4658        // still find the intact copy rather than reporting a failure.
4659        assert_eq!(
4660            store.get(&victim).await.expect("get").expect("present"),
4661            addressed("s1").1
4662        );
4663        assert!(
4664            store.legacy_only_keys().contains(&victim),
4665            "the key must go back on the copier's list"
4666        );
4667    }
4668
4669    #[tokio::test]
4670    async fn a_marker_claiming_more_than_the_file_store_holds_restarts_the_copy() {
4671        let dir = TempDir::new().expect("temp dir");
4672        let keys = seed_legacy(&dir, &["p1", "p2", "p3"]).await;
4673        let store = open(&dir).await;
4674        store
4675            .copy_batch(&keys, 0, 0, &never_cancelled())
4676            .await
4677            .expect("copy");
4678        store.commit_to_files().expect("commit");
4679        assert_eq!(store.migration_state().kept_key_count, 3);
4680        store.wait_idle().await;
4681        drop(store);
4682
4683        // Someone clears the chunk directory to reclaim space, keeping chunks.mdb.
4684        // Trusting the marker here would skip the copier, the shed rules and their rank
4685        // checks on the way to deleting the legacy environment.
4686        let chunks = dir.path().join(crate::storage::file_store::CHUNKS_DIR_NAME);
4687        for key in &keys {
4688            let path = chunks
4689                .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
4690                .join(hex::encode(key));
4691            std::fs::remove_file(path).expect("clear the file store");
4692        }
4693
4694        let store = open(&dir).await;
4695        assert_eq!(
4696            store.migration_phase(),
4697            MigrationPhase::Bridging,
4698            "the filesystem must win over the marker"
4699        );
4700        assert_eq!(store.legacy_only_keys().len(), 3);
4701    }
4702
4703    /// V2-1232. Once committed, the copier moves only the keys the rank check refuses to
4704    /// shed, so a chunk that is found in the legacy environment after the commitment,
4705    /// and that this node never agreed to give up, is never copied, never provable
4706    /// elsewhere, and keeps the environment from ever being retired. Free disk does not
4707    /// help and neither does a restart. Reopening has to notice and reopen the bridge.
4708    #[tokio::test]
4709    async fn a_node_that_committed_with_nothing_to_shed_resumes_the_copy_for_chunks_only_it_holds()
4710    {
4711        let dir = TempDir::new().expect("temp dir");
4712        let keys = seed_legacy(&dir, &["c1", "c2"]).await;
4713        let store = open(&dir).await;
4714        store
4715            .copy_batch(&keys, 0, 0, &never_cancelled())
4716            .await
4717            .expect("copy");
4718        store.commit_to_files().expect("commit");
4719        store.note_commitment_rebuilt();
4720        let state = store.migration_state();
4721        assert_eq!(state.shed_key_count, 0, "nothing had to be shed");
4722        assert!(state.committed_at_unix.is_some());
4723        assert_eq!(state.rebuilds_since_commit, 1);
4724        store.wait_idle().await;
4725        drop(store);
4726
4727        // A chunk in the legacy environment that the file store has no record of, found
4728        // after the node committed. The file store is untouched, so the kept-count rule
4729        // has nothing to say about this.
4730        let late = seed_legacy(&dir, &["c3"]).await;
4731
4732        let store = open(&dir).await;
4733        let state = store.migration_state();
4734        assert_eq!(
4735            state.phase,
4736            MigrationPhase::Bridging,
4737            "a chunk the node never agreed to shed must reopen the bridge"
4738        );
4739        assert!(
4740            state.committed_at_unix.is_none(),
4741            "the retirement clock must not carry over from the abandoned commitment"
4742        );
4743        assert_eq!(state.rebuilds_since_commit, 0);
4744        assert_eq!(store.legacy_only_keys(), late);
4745
4746        // And the copier, which the phase change lets run again, moves it.
4747        store
4748            .copy_batch(&late, 0, 0, &never_cancelled())
4749            .await
4750            .expect("copy");
4751        assert!(store.legacy_only_keys().is_empty());
4752        assert_eq!(
4753            store
4754                .get(late.first().expect("a key"))
4755                .await
4756                .expect("get")
4757                .expect("present"),
4758            addressed("c3").1
4759        );
4760    }
4761
4762    /// The counterpart of the test above, and it matters as much. A node that shed keeps
4763    /// exactly the keys it is giving up in the legacy environment until they stop being
4764    /// answerable, so a non-empty legacy-only set is its normal state. Sending it back
4765    /// to the bridge on every restart would reset its retention clock each time, and a
4766    /// node restarted regularly would never retire.
4767    #[tokio::test]
4768    async fn a_node_that_shed_stays_committed_across_a_restart() {
4769        let dir = TempDir::new().expect("temp dir");
4770        let keys = seed_legacy(&dir, &["k1", "k2"]).await;
4771        let store = open(&dir).await;
4772        store
4773            .copy_batch(&keys[..1], 0, 0, &never_cancelled())
4774            .await
4775            .expect("copy");
4776        store.commit_to_files().expect("commit");
4777        store.note_commitment_rebuilt();
4778        let before = store.migration_state();
4779        assert_eq!(before.shed_key_count, 1);
4780        assert_eq!(store.legacy_only_keys().len(), 1);
4781        store.wait_idle().await;
4782        drop(store);
4783
4784        let store = open(&dir).await;
4785        let after = store.migration_state();
4786        assert_eq!(
4787            after.phase,
4788            MigrationPhase::Committed,
4789            "the keys it is giving up are not a reason to reopen the bridge"
4790        );
4791        assert_eq!(after.committed_at_unix, before.committed_at_unix);
4792        assert_eq!(after.rebuilds_since_commit, before.rebuilds_since_commit);
4793        assert_eq!(store.legacy_only_keys().len(), 1);
4794    }
4795
4796    #[tokio::test]
4797    async fn a_file_that_vanished_mid_verification_is_requeued_not_republished() {
4798        let dir = TempDir::new().expect("temp dir");
4799        let keys = seed_legacy(&dir, &["gone"]).await;
4800        let mut config = test_config(&dir);
4801        config.migration.retire_legacy = true;
4802        let store = ChunkStore::new(config).await.expect("open");
4803        store
4804            .copy_batch(&keys, 0, 0, &never_cancelled())
4805            .await
4806            .expect("copy");
4807        assert!(store.legacy_only_keys().is_empty());
4808
4809        // Remove the file without telling the store, which is what the pruner's own
4810        // delete looks like if it lands mid-pass. Republishing from the legacy copy here
4811        // would resurrect a chunk the node had deliberately deleted, so the key goes back
4812        // on the copier's list instead and retirement is refused.
4813        let key = keys.first().copied().expect("a key");
4814        let path = dir
4815            .path()
4816            .join(crate::storage::file_store::CHUNKS_DIR_NAME)
4817            .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
4818            .join(hex::encode(key));
4819        std::fs::remove_file(&path).expect("remove behind the store's back");
4820
4821        let proof = store
4822            .verify_before_retire(0, &never_cancelled())
4823            .await
4824            .expect("verify");
4825        assert!(
4826            proof.unrepairable >= 1,
4827            "the vanished file must be counted against the proof"
4828        );
4829        assert!(!proof.is_clean());
4830        assert!(!path.exists(), "the pass must not republish it");
4831        assert!(store.legacy_only_keys().contains(&key));
4832        assert!(store
4833            .retire_legacy(&proof, &|_: &XorName| false, &approved_shed(&store))
4834            .await
4835            .is_err());
4836        assert!(store.has_legacy());
4837    }
4838
4839    #[tokio::test]
4840    async fn a_cancelled_shutdown_stops_the_copier_and_refuses_to_pass_verification() {
4841        let dir = TempDir::new().expect("temp dir");
4842        let keys = seed_legacy(&dir, &["s1", "s2", "s3"]).await;
4843        let store = open(&dir).await;
4844
4845        // Shutdown must not have to wait out a pass that can run for hours, and a pass
4846        // that stopped early is not evidence of anything.
4847        let cancelled = CancellationToken::new();
4848        cancelled.cancel();
4849
4850        let report = store
4851            .copy_batch(&keys, 0, 0, &cancelled)
4852            .await
4853            .expect("copy");
4854        assert_eq!(report.copied, 0, "the copier must stop immediately");
4855        assert_eq!(store.legacy_only_keys().len(), 3);
4856
4857        let proof = store
4858            .verify_before_retire(0, &cancelled)
4859            .await
4860            .expect("verify");
4861        assert!(
4862            !proof.is_clean(),
4863            "an interrupted verification must never read as a pass"
4864        );
4865    }
4866
4867    #[tokio::test]
4868    async fn the_migration_marker_survives_a_restart() {
4869        let dir = TempDir::new().expect("temp dir");
4870        let keys = seed_legacy(&dir, &["m1", "m2"]).await;
4871        let store = open(&dir).await;
4872        store
4873            .copy_batch(&keys[..1], 0, 0, &never_cancelled())
4874            .await
4875            .expect("copy");
4876        store.commit_to_files().expect("commit");
4877        store.note_commitment_rebuilt();
4878        let first_start = store.migration_state().first_start_unix;
4879        store.wait_idle().await;
4880        drop(store);
4881
4882        let store = open(&dir).await;
4883        let state = store.migration_state();
4884        assert_eq!(state.phase, MigrationPhase::Committed);
4885        assert_eq!(state.shed_key_count, 1);
4886        assert_eq!(
4887            state.first_start_unix, first_start,
4888            "a restart must not restart the shed hold"
4889        );
4890        assert!(
4891            state.committed_at_unix.is_some(),
4892            "nor the retirement clock"
4893        );
4894    }
4895
4896    #[tokio::test]
4897    async fn a_marker_that_disagrees_with_the_filesystem_loses() {
4898        let dir = TempDir::new().expect("temp dir");
4899        seed_legacy(&dir, &["x1"]).await;
4900        let store = open(&dir).await;
4901        store.force_migration_state(|s| s.phase = MigrationPhase::FilesOnly);
4902        store.migration_state().save(dir.path()).expect("save");
4903        store.wait_idle().await;
4904        drop(store);
4905
4906        // The marker claims the migration is done, but `chunks.mdb` is right there. The
4907        // filesystem is the authority.
4908        let store = open(&dir).await;
4909        assert_eq!(store.migration_phase(), MigrationPhase::Bridging);
4910        assert!(store.has_legacy());
4911    }
4912
4913    /// A legacy record whose bytes do not hash to its key is removed, not passed around.
4914    ///
4915    /// Leaving it in the environment while dropping it from the key set puts it in
4916    /// neither view, and the pre-retirement pass reads a key in neither view as one to
4917    /// protect and puts it straight back. The next copier pass drops it again. One rotted
4918    /// record would keep this node, and every node sharing its disk, from ever reclaiming
4919    /// space.
4920    #[tokio::test]
4921    async fn a_legacy_chunk_that_does_not_match_its_address_is_removed_not_recycled() {
4922        let dir = TempDir::new().expect("temp dir");
4923        let (addr, _) = addressed("bad");
4924        let other = addressed("other").1;
4925        {
4926            let lmdb = LmdbStorage::new(LmdbStorageConfig {
4927                root_dir: dir.path().to_path_buf(),
4928                verify_on_read: false,
4929                max_map_size: 0,
4930                disk_reserve: 0,
4931            })
4932            .await
4933            .expect("open legacy");
4934            // Under a key it does not hash to: what a record that rotted in place looks
4935            // like, and the one shape the ordinary path refuses to create.
4936            lmdb.put_unchecked(&addr, &other).await.expect("put");
4937            lmdb.wait_idle().await;
4938        }
4939        let store = open(&dir).await;
4940        let keys = store.legacy_only_keys();
4941        assert_eq!(keys, vec![addr]);
4942
4943        let report = store
4944            .copy_batch(&keys, 0, 0, &never_cancelled())
4945            .await
4946            .expect("copy");
4947        assert_eq!(report.copied, 0);
4948        assert_eq!(report.unusable, 1);
4949        assert!(store.legacy_only_keys().is_empty());
4950
4951        // And it is gone from the environment, so the pass below cannot find it and put
4952        // it back. That is the loop this is about.
4953        let proof = store
4954            .verify_before_retire(0, &never_cancelled())
4955            .await
4956            .expect("verify");
4957        assert!(
4958            store.legacy_only_keys().is_empty(),
4959            "a removed record must not come back on the copier's list"
4960        );
4961        assert!(
4962            proof.is_clean(),
4963            "and must not go on refusing the proof for ever"
4964        );
4965    }
4966
4967    #[test]
4968    fn the_release_switches_are_never_written_to_an_operator_config_file() {
4969        // A node writes its effective configuration back to disk. If these round-tripped,
4970        // R1's values would be baked into every operator's file and the next release
4971        // would change nothing.
4972        let mut config = MigrationConfig::default();
4973        config.retire_legacy = !config.retire_legacy;
4974        config.allow_shed = false;
4975        config.shed_hold_hours = 5;
4976
4977        let encoded = toml::to_string(&config).expect("encode");
4978        assert!(!encoded.contains("retire_legacy"), "{encoded}");
4979
4980        let decoded: MigrationConfig = toml::from_str(&encoded).expect("decode");
4981        let fresh = MigrationConfig::default();
4982        assert_eq!(decoded.retire_legacy, fresh.retire_legacy);
4983        // Genuine operator controls do survive.
4984        assert!(!decoded.allow_shed);
4985        assert_eq!(decoded.shed_hold_hours, 5);
4986    }
4987
4988    #[test]
4989    fn the_copy_order_is_closest_first() {
4990        let me = [0u8; XORNAME_LEN_LOCAL];
4991        let mut near = [0u8; XORNAME_LEN_LOCAL];
4992        if let Some(b) = near.last_mut() {
4993            *b = 1;
4994        }
4995        let mut far = [0u8; XORNAME_LEN_LOCAL];
4996        if let Some(b) = far.first_mut() {
4997            *b = 0xff;
4998        }
4999        let ordered = rank_closest_first(vec![far, near], Some(me));
5000        assert_eq!(ordered.first().copied(), Some(near));
5001        assert_eq!(ordered.last().copied(), Some(far));
5002
5003        // With no identity the order is still stable, which is all the copier needs.
5004        let ordered = rank_closest_first(vec![far, near], None);
5005        let mut expected = vec![far, near];
5006        expected.sort_unstable();
5007        assert_eq!(ordered, expected);
5008    }
5009
5010    /// Local alias so the test does not import from the protocol crate.
5011    const XORNAME_LEN_LOCAL: usize = 32;
5012
5013    #[test]
5014    fn the_retirement_delay_can_never_be_shortened_below_the_retention_window() {
5015        let config = MigrationConfig {
5016            retire_delay_hours: 0,
5017            ..MigrationConfig::default()
5018        };
5019        assert_eq!(
5020            config.effective_retire_delay_hours(),
5021            MIN_RETIRE_DELAY_HOURS
5022        );
5023    }
5024}