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