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