Skip to main content

ant_node/storage/
chunk_store.rs

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