Skip to main content

ant_node/storage/
file_store.rs

1//! One immutable file per chunk, content-addressed, with the filesystem as the
2//! only authority.
3//!
4//! ```text
5//! {root}/chunks/                     store root
6//! {root}/chunks/layout.json          versioned layout marker
7//! {root}/chunks/.lock                advisory single-process guard
8//! {root}/chunks/<xy>/<64-hex>        xy = the LAST two hex characters of the address
9//! {root}/chunks/<xy>/.tmp.<pid>.<n>  an in-flight write, in the destination directory
10//! ```
11//!
12//! # Why the *last* two hex characters
13//!
14//! A node holds keys for which it is among the [`CLOSE_GROUP_SIZE`] closest, so its
15//! holdings share roughly `log2(N / CLOSE_GROUP_SIZE)` leading bits with its own node
16//! ID, and that shared prefix grows as the network grows. Sharding on a prefix therefore
17//! does not degrade, it collapses: at ~800 nodes a two-hex prefix already resolves to
18//! about two distinct directories, and past a million nodes even a four-hex prefix
19//! resolves to one. Close-group membership constrains the leading bits and places no
20//! constraint at all on the trailing ones, and the address is a BLAKE3 output, so the
21//! last byte is uniform by construction at every network size.
22//!
23//! 256 shards keeps a 24 GiB node at ~23 files per directory and a 1 TiB node at ~977,
24//! for 1 MiB of directory inodes. The scheme and depth are recorded in `layout.json` at
25//! creation so a future layout can be detected rather than silently misread.
26//!
27//! # Why lowercase hex names
28//!
29//! NTFS and default APFS fold case. Under an encoding with both cases (base64url,
30//! base58) two distinct 32-byte keys can share one case-folded filename, which is a
31//! silent overwrite. Hex has one case-folded form per key, and no hex string can ever
32//! spell a reserved Windows device name (`CON`, `NUL`, `AUX`, `COM1`, ...) because none
33//! of those letters is in `0-9a-f`. The full 64-character key stays in the filename, so
34//! a `find` over the tree recovers the whole store even if the directory layer is lost.
35//!
36//! [`CLOSE_GROUP_SIZE`]: crate::ant_protocol::CLOSE_GROUP_SIZE
37
38use crate::ant_protocol::{XorName, MAX_CHUNK_SIZE, XORNAME_LEN};
39use crate::error::{Error, Result};
40use crate::logging::{debug, info, trace, warn};
41use crate::storage::StorageStats;
42use fs2::FileExt;
43use serde::{Deserialize, Serialize};
44use std::collections::{BTreeSet, HashMap, HashSet};
45use std::fs::{File, OpenOptions};
46use std::io::{ErrorKind, Read, Write};
47use std::path::{Path, PathBuf};
48use std::sync::atomic::{AtomicU64, Ordering};
49use std::sync::Arc;
50use std::time::{Duration, Instant};
51use tokio::task::spawn_blocking;
52use tokio_util::task::TaskTracker;
53
54/// Directory under the node root that holds the chunk files.
55pub const CHUNKS_DIR_NAME: &str = "chunks";
56
57/// Name of the layout marker written once at store creation.
58pub const LAYOUT_FILE_NAME: &str = "layout.json";
59
60/// Name of the advisory single-process lock file.
61const LOCK_FILE_NAME: &str = ".lock";
62
63/// Prefix that marks an in-flight write. Never a valid chunk name (chunk names are
64/// exactly [`CHUNK_NAME_LEN`] lowercase hex characters, and `.` is not hex).
65const TEMP_PREFIX: &str = ".tmp.";
66
67/// Number of shard directories. One level, `00` through `ff`.
68const SHARD_COUNT: usize = 256;
69
70/// Length of a chunk filename: the full address in lowercase hex.
71const CHUNK_NAME_LEN: usize = XORNAME_LEN * 2;
72
73/// How often to re-query available disk space, in seconds.
74///
75/// Matches the LMDB store's cadence so the capacity predicate behaves identically
76/// for callers that only ask "is there room at all".
77const DISK_CHECK_INTERVAL_SECS: u64 = 5;
78
79/// Allocation granularity assumed when charging a pending write against free space.
80///
81/// Every filesystem we support allocates in units of at least 4 KiB, so a write of
82/// `n` bytes consumes at least `ceil(n / 4096) * 4096`. One extra unit covers the
83/// directory entry and inode.
84const ALLOC_UNIT: u64 = 4096;
85
86/// How many times a publish retries a transient Windows sharing violation.
87const RENAME_RETRY_ATTEMPTS: u32 = 5;
88
89/// Base backoff between those retries; the wait grows linearly with the attempt.
90const RENAME_RETRY_BACKOFF: Duration = Duration::from_millis(20);
91
92/// Longest absolute path a chunk file may need, checked once at open.
93///
94/// Windows caps a non-verbatim path at `MAX_PATH` (260) including the terminating NUL.
95/// Rust's standard library transparently switches to the `\\?\` verbatim form for long
96/// absolute paths, so this is a warning rather than a hard failure, but an operator who
97/// buries the node root ten directories deep should hear about it before the first write
98/// fails rather than after.
99#[cfg(windows)]
100const WINDOWS_PATH_WARN_LEN: usize = 240;
101
102/// The on-disk layout marker.
103///
104/// Written once when the store directory is created and read on every subsequent open.
105/// Nothing in this survey of comparable stores (IPFS flatfs, Storj, borgbackup) shipped
106/// an in-place re-sharder, and all three paid for it. Recording the scheme costs one
107/// small file and is the difference between changing the default later and never being
108/// able to.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct StoreLayout {
111    /// Marker schema version. A store written by a newer schema is refused.
112    pub schema: u32,
113    /// How a chunk address maps to a shard directory.
114    pub scheme: String,
115    /// How many hex characters of the address name the shard directory.
116    pub shard_chars: u8,
117    /// How many directory levels of sharding.
118    pub depth: u8,
119    /// How a chunk address maps to a filename.
120    pub name_encoding: String,
121}
122
123/// Marker schema this build writes and understands.
124const LAYOUT_SCHEMA: u32 = 1;
125/// Shard scheme this build implements: the trailing hex characters of the address.
126const LAYOUT_SCHEME_SUFFIX_HEX: &str = "suffix-hex";
127/// Filename encoding this build implements.
128const LAYOUT_NAME_LOWER_HEX: &str = "lower-hex";
129
130impl Default for StoreLayout {
131    fn default() -> Self {
132        Self {
133            schema: LAYOUT_SCHEMA,
134            scheme: LAYOUT_SCHEME_SUFFIX_HEX.to_string(),
135            shard_chars: 2,
136            depth: 1,
137            name_encoding: LAYOUT_NAME_LOWER_HEX.to_string(),
138        }
139    }
140}
141
142impl StoreLayout {
143    /// Return an error unless this build can read a store written with this layout.
144    fn check_supported(&self) -> Result<()> {
145        if self.schema > LAYOUT_SCHEMA {
146            return Err(Error::Storage(format!(
147                "Chunk store layout schema {} is newer than this build understands ({LAYOUT_SCHEMA}). \
148                 Refusing to open rather than misread the store.",
149                self.schema
150            )));
151        }
152        if self.scheme != LAYOUT_SCHEME_SUFFIX_HEX {
153            return Err(Error::Storage(format!(
154                "Chunk store uses shard scheme '{}', this build implements '{LAYOUT_SCHEME_SUFFIX_HEX}'",
155                self.scheme
156            )));
157        }
158        if self.shard_chars != 2 || self.depth != 1 {
159            return Err(Error::Storage(format!(
160                "Chunk store uses {} shard characters at depth {}, this build implements 2 at depth 1",
161                self.shard_chars, self.depth
162            )));
163        }
164        if self.name_encoding != LAYOUT_NAME_LOWER_HEX {
165            return Err(Error::Storage(format!(
166                "Chunk store names files with '{}', this build implements '{LAYOUT_NAME_LOWER_HEX}'",
167                self.name_encoding
168            )));
169        }
170        Ok(())
171    }
172}
173
174/// Configuration for [`FileStore`].
175#[derive(Debug, Clone)]
176pub struct FileStoreConfig {
177    /// Node root directory. The store lives at `{root_dir}/chunks/`.
178    pub root_dir: PathBuf,
179    /// Verify `BLAKE3(content) == address` on read.
180    pub verify_on_read: bool,
181    /// Free bytes to keep on the storage partition. Writes are refused below this.
182    pub disk_reserve: u64,
183}
184
185/// Outcome of a single write attempt, used to keep the duplicate accounting honest.
186enum PutOutcome {
187    /// The chunk was newly published.
188    New,
189    /// The chunk was already on disk.
190    Duplicate,
191}
192
193/// Snapshot of free space, plus what has been written since it was taken.
194#[derive(Debug)]
195struct CapacitySnapshot {
196    /// When `available` was measured. `None` means never.
197    measured_at: Option<Instant>,
198    /// Free bytes reported by the filesystem at `measured_at`.
199    available: u64,
200    /// Bytes published since `measured_at`, charged against `available`.
201    ///
202    /// Cleared by a fresh measurement, which already accounts for them.
203    written_since: u64,
204    /// Bytes reserved by writes that have not landed yet.
205    ///
206    /// Deliberately **not** cleared by a measurement: a `statvfs` taken while writes are
207    /// in flight reports space those writes are about to consume, so forgetting their
208    /// reservations at that moment would hand the same bytes out twice. That is precisely
209    /// the over-admission the reservation exists to prevent.
210    in_flight: u64,
211}
212
213/// Size-aware free-space predicate with a short-lived cache.
214///
215/// Free bytes alone stopped being a sufficient answer the moment chunks became files:
216/// a caller wants to know whether *this* write fits, not whether the disk is non-empty.
217/// The cache keeps the common case at one `statvfs` per interval while staying correct
218/// under a burst, because bytes written since the measurement are charged against it.
219#[derive(Debug)]
220struct CapacityGuard {
221    /// Directory whose partition is measured.
222    dir: PathBuf,
223    /// Free bytes to keep unused.
224    reserve: u64,
225    /// The cached measurement.
226    snapshot: parking_lot::Mutex<CapacitySnapshot>,
227}
228
229impl CapacitySnapshot {
230    /// Free bytes, less everything written or promised since the measurement.
231    fn free_estimate(&self) -> u64 {
232        self.available
233            .saturating_sub(self.written_since)
234            .saturating_sub(self.in_flight)
235    }
236}
237
238impl CapacityGuard {
239    /// Create a guard over the partition hosting `dir`.
240    fn new(dir: PathBuf, reserve: u64) -> Self {
241        Self {
242            dir,
243            reserve,
244            snapshot: parking_lot::Mutex::new(CapacitySnapshot {
245                measured_at: None,
246                available: 0,
247                written_since: 0,
248                in_flight: 0,
249            }),
250        }
251    }
252
253    /// Bytes actually consumed on disk by a payload of `len` bytes.
254    fn charge(len: u64) -> u64 {
255        // Round the payload up to the allocation unit, then add one unit for the
256        // directory entry and inode.
257        len.div_ceil(ALLOC_UNIT)
258            .saturating_mul(ALLOC_UNIT)
259            .saturating_add(ALLOC_UNIT)
260    }
261
262    /// Free bytes right now, or `None` if the question could not be answered.
263    ///
264    /// Deliberately separate from [`Self::measure`], which folds a failure into an error
265    /// the caller cannot tell from "below the reserve".
266    fn measure_available(&self) -> Option<u64> {
267        let mut snapshot = self.snapshot.lock();
268        match self.measure(&mut snapshot) {
269            Ok(()) => Some(snapshot.free_estimate()),
270            Err(_) => None,
271        }
272    }
273
274    /// Query the filesystem and refresh the snapshot.
275    fn measure(&self, snapshot: &mut CapacitySnapshot) -> Result<()> {
276        let available = fs2::available_space(&self.dir)
277            .map_err(|e| Error::Storage(format!("Failed to query available disk space: {e}")))?;
278        snapshot.available = available;
279        // Reservations survive: their bytes are not on the platter yet, so the fresh
280        // measurement does not include them.
281        snapshot.written_since = 0;
282        snapshot.measured_at = Some(Instant::now());
283        Ok(())
284    }
285
286    /// Test `needed` against the snapshot, refreshing it if it is stale or short.
287    ///
288    /// Only *passing* results are cached, so a low-space condition is rechecked on every
289    /// call and freed space is noticed promptly.
290    fn admit(&self, snapshot: &mut CapacitySnapshot, needed: u64) -> Result<()> {
291        let want = self.reserve.saturating_add(Self::charge(needed));
292
293        let cache_fresh = snapshot
294            .measured_at
295            .is_some_and(|t| t.elapsed().as_secs() < DISK_CHECK_INTERVAL_SECS);
296        if cache_fresh && snapshot.free_estimate() >= want {
297            return Ok(());
298        }
299
300        self.measure(snapshot)?;
301        if snapshot.free_estimate() < want {
302            // Do not cache a failing result: `measured_at` is left set so the next call
303            // still re-measures, because the branch above only short-circuits a pass.
304            return Err(Error::Storage(format!(
305                "Insufficient disk space: {:.2} GiB available, {:.2} GiB reserve required. \
306                 Free disk space or increase the partition to continue storing chunks.",
307                bytes_to_gib(snapshot.free_estimate()),
308                bytes_to_gib(self.reserve),
309            )));
310        }
311        Ok(())
312    }
313
314    /// Drop the cached measurement so the next question hits the filesystem.
315    fn invalidate(&self) {
316        let mut snapshot = self.snapshot.lock();
317        snapshot.measured_at = None;
318        snapshot.written_since = 0;
319    }
320
321    /// Return `Ok(())` if a write of `needed` bytes would fit. Charges nothing.
322    fn check(&self, needed: u64) -> Result<()> {
323        let mut snapshot = self.snapshot.lock();
324        self.admit(&mut snapshot, needed)
325    }
326
327    /// Admit a write of `needed` bytes and charge it in the same critical section.
328    ///
329    /// Checking and charging separately is the bug this exists to prevent: dozens of
330    /// protocol handlers can each pass against the same cached measurement before any of
331    /// them has written a byte, and collectively cross the reserve.
332    ///
333    /// The returned [`Reservation`] settles itself when dropped, so a caller whose future
334    /// is dropped mid-write cannot strand it. Nothing else ever decrements the in-flight
335    /// count, so a stranded reservation would be permanent, and enough of them would make
336    /// an empty disk look full until the process restarted.
337    fn reserve(self: &Arc<Self>, needed: u64) -> Result<Reservation> {
338        {
339            let mut snapshot = self.snapshot.lock();
340            self.admit(&mut snapshot, needed)?;
341            snapshot.in_flight = snapshot.in_flight.saturating_add(Self::charge(needed));
342        }
343        Ok(Reservation {
344            capacity: Arc::clone(self),
345            bytes: needed,
346            settled: false,
347        })
348    }
349
350    /// The two accounting counters, for tests that need to prove a charge was
351    /// settled one way rather than the other.
352    #[cfg(test)]
353    fn counters(&self) -> (u64, u64) {
354        let snapshot = self.snapshot.lock();
355        (snapshot.written_since, snapshot.in_flight)
356    }
357
358    /// Give back a reservation whose write did not happen.
359    fn release(&self, needed: u64) {
360        let mut snapshot = self.snapshot.lock();
361        snapshot.in_flight = snapshot.in_flight.saturating_sub(Self::charge(needed));
362    }
363
364    /// Turn a reservation into bytes that are now on disk.
365    fn commit_reservation(&self, needed: u64) {
366        let charge = Self::charge(needed);
367        let mut snapshot = self.snapshot.lock();
368        snapshot.in_flight = snapshot.in_flight.saturating_sub(charge);
369        snapshot.written_since = snapshot.written_since.saturating_add(charge);
370    }
371
372    /// Credit a completed delete back to the cached measurement.
373    fn record_removed(&self, len: u64) {
374        let mut snapshot = self.snapshot.lock();
375        snapshot.written_since = snapshot.written_since.saturating_sub(Self::charge(len));
376    }
377}
378
379/// A charged, unsettled write.
380///
381/// Held by whatever is actually doing the write, so the charge is released even if the
382/// caller's future is dropped and only the blocking closure survives.
383pub(crate) struct Reservation {
384    /// The guard this was taken from.
385    capacity: Arc<CapacityGuard>,
386    /// Payload size, before rounding.
387    bytes: u64,
388    /// Whether it has already been accounted for.
389    settled: bool,
390}
391
392impl Reservation {
393    /// The write landed: move the charge from in-flight to written.
394    pub(crate) fn commit(mut self) {
395        self.capacity.commit_reservation(self.bytes);
396        self.settled = true;
397    }
398}
399
400impl Drop for Reservation {
401    fn drop(&mut self) {
402        if !self.settled {
403            self.capacity.release(self.bytes);
404        }
405    }
406}
407
408/// Environment variable naming a failpoint: stop after the temp file, before the rename.
409#[cfg(any(test, feature = "test-utils"))]
410pub const HALT_BEFORE_PUBLISH: &str = "ANT_HALT_BEFORE_PUBLISH";
411
412/// Environment variable naming a failpoint: stop once the legacy environment is renamed
413/// aside and marked retired, before any of it is deleted.
414///
415/// The most destructive window in the migration. What a start that finds a marked
416/// directory must do is finish the deletion, never reopen it, because the node has already
417/// told the network it holds those chunks from the file store.
418#[cfg(any(test, feature = "test-utils"))]
419pub const HALT_AFTER_RETIRE_MARK: &str = "ANT_HALT_AFTER_RETIRE_MARK";
420
421/// Park forever at a named failpoint, once a marker says the process has reached it.
422///
423/// For crash tests, which need a process to die *inside* an operation rather than at
424/// whatever point a sleep in another process happened to land. The variable holds a path:
425/// this writes it, so the parent knows the child is exactly here, and then waits to be
426/// killed.
427///
428/// Costs one environment read per write when the feature is compiled in, and the feature
429/// is not in a release build.
430#[cfg(any(test, feature = "test-utils"))]
431pub(crate) fn halt_here_if_asked(variable: &str, reached: &Path) {
432    let Ok(marker) = std::env::var(variable) else {
433        return;
434    };
435    // Let the first few through. A test that stops the very first write leaves a store
436    // with nothing successfully in it, and an assertion over what it holds then passes by
437    // iterating nothing. Letting some land first means the crash happens to a store that
438    // has real chunks in it, which is the situation worth checking.
439    let skip: u64 = std::env::var(HALT_AFTER)
440        .ok()
441        .and_then(|raw| raw.parse().ok())
442        .unwrap_or(0);
443    if HALTS_SEEN.fetch_add(1, std::sync::atomic::Ordering::AcqRel) < skip {
444        return;
445    }
446    if let Err(e) = std::fs::write(&marker, reached.as_os_str().as_encoded_bytes()) {
447        // The parent waits for this file. Saying so on the way past is the difference
448        // between a test that fails and one that hangs until the job times out.
449        eprintln!("failpoint could not write its marker {marker}: {e}");
450        return;
451    }
452    loop {
453        std::thread::sleep(Duration::from_hours(1));
454    }
455}
456
457/// How many writes to let through before the failpoint fires.
458#[cfg(any(test, feature = "test-utils"))]
459pub const HALT_AFTER: &str = "ANT_HALT_AFTER";
460
461/// How many times the failpoint has been reached in this process.
462#[cfg(any(test, feature = "test-utils"))]
463static HALTS_SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
464
465/// Clears a write's registration when the work finishes, however it finishes.
466///
467/// Held by the blocking closure rather than by the caller, so a dropped future cannot
468/// leave an entry behind, and a panic in the work cannot either.
469struct WriteInFlight {
470    writing: Arc<parking_lot::Mutex<HashMap<XorName, usize>>>,
471    finished: Arc<tokio::sync::Notify>,
472    address: XorName,
473}
474
475impl Drop for WriteInFlight {
476    fn drop(&mut self) {
477        let was_last = {
478            let mut writing = self.writing.lock();
479            match writing.get_mut(&self.address) {
480                Some(count) if *count > 1 => {
481                    *count -= 1;
482                    false
483                }
484                _ => {
485                    writing.remove(&self.address);
486                    true
487                }
488            }
489        };
490        // Only when this was the last one. Waking a waiter while another write for the
491        // same key is still queued is exactly what the count exists to prevent.
492        if was_last {
493            self.finished.notify_waiters();
494        }
495    }
496}
497
498/// What is behind a chunk's name on disk.
499///
500/// Four answers, not two, because "could not read it" must never be treated as "wrong":
501/// replacing a chunk is destructive, and off Unix it truncates the file in place, so a
502/// transient fault would turn a healthy sole copy into an empty one.
503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
504enum StoredBytes {
505    /// The bytes are there and hash to the name.
506    Good,
507    /// The bytes are there and do not.
508    Wrong,
509    /// There is nothing behind the name.
510    Absent,
511    /// The question could not be answered this time.
512    Unreadable,
513}
514
515/// Convert a byte count to GiB for human-readable log messages.
516#[allow(clippy::cast_precision_loss)] // display only — sub-byte precision is irrelevant
517fn bytes_to_gib(bytes: u64) -> f64 {
518    bytes as f64 / (1024.0 * 1024.0 * 1024.0)
519}
520
521/// Content-addressed store holding one immutable file per chunk.
522///
523/// The filesystem is the sole authority. The in-memory index is a cache of what the
524/// directory tree already contains, rebuilt from directory entries at every open, and
525/// every mutation of it mirrors a filesystem operation that has *already* completed.
526/// Bitcask's issue #114 is the cautionary tale for the opposite order: an index that is
527/// rebuilt at startup and then mutated in anticipation drifts, and the drift is silent.
528#[derive(Debug)]
529pub struct FileStore {
530    /// Store configuration.
531    config: FileStoreConfig,
532    /// `{root_dir}/chunks`.
533    chunks_dir: PathBuf,
534    /// Every address whose file is published, in ascending order.
535    ///
536    /// `BTreeSet` rather than a hash set because `all_keys()` must be sorted (the
537    /// commitment builder truncates with `take(cap)` *before* the Merkle tree sorts, so
538    /// an unstable order would make the node's published commitment depend on iteration
539    /// luck), and because it never spikes memory while growing.
540    index: Arc<parking_lot::RwLock<BTreeSet<XorName>>>,
541    /// One mutex per shard, serialising writers of the same address.
542    ///
543    /// LMDB gave exactly-once `put` semantics for free: the duplicate test happened
544    /// inside the write transaction. Two threads publishing the same address here would
545    /// otherwise both see an absent file, both rename, and both report "newly stored",
546    /// double-counting the chunk. The lane is indexed by the address's LAST byte for the
547    /// same reason the shard is: a node's keys share their leading bytes, so lanes keyed
548    /// on the first byte would all collapse into one.
549    write_lanes: Arc<Vec<parking_lot::Mutex<()>>>,
550    /// Operation counters, same shape as the LMDB store reported.
551    stats: parking_lot::RwLock<StorageStats>,
552    /// Which of the 256 shard directories are known to exist, so a steady-state write
553    /// does not pay a `create_dir_all` syscall.
554    shards_present: Arc<parking_lot::Mutex<[bool; SHARD_COUNT]>>,
555    /// Indexed chunks this store currently cannot read.
556    ///
557    /// Held back from everything the node says it has, while the files themselves are
558    /// left alone. See [`Self::mark_suspect`].
559    suspect: Arc<parking_lot::RwLock<HashSet<XorName>>>,
560    /// Indexed chunks a read has proven do not match their name.
561    ///
562    /// Separate from the above because they clear differently. Not being able to read a
563    /// file is a question a later read answers; bytes that are wrong stay wrong however
564    /// often they are read, and only a repair or a removal settles it. A raw read that
565    /// does not hash anything must not take a chunk out of this set.
566    known_wrong: Arc<parking_lot::RwLock<HashSet<XorName>>>,
567    /// Addresses this store is part-way through writing.
568    ///
569    /// Every mutation registers here before it spawns its blocking work and clears the
570    /// entry *inside* that work, so a caller whose future is dropped cannot skip the
571    /// clearing while the write itself goes on to land. That is the difference that
572    /// matters: the blocking half is not cancelled with the future, so anything the
573    /// future was going to do afterwards is not a record of what happened.
574    ///
575    /// It lets a delete queue behind the exact write it would otherwise race, rather than
576    /// behind every write this store has in flight.
577    ///
578    /// Counted, not a set. Cancellation can release the facade's key lane while the
579    /// blocking half survives, so a second write for the same key can start behind the
580    /// first. With one entry between them, whichever finished first would remove it and a
581    /// waiter would be told the key is free while the other was still queued.
582    writing: Arc<parking_lot::Mutex<HashMap<XorName, usize>>>,
583    /// Woken when [`Self::writing`] loses its last entry for a key.
584    write_finished: Arc<tokio::sync::Notify>,
585    /// Bumped whenever a chunk stops being servable.
586    ///
587    /// The pre-retirement pass reads every chunk, and its result is reused for a while
588    /// rather than re-read on every tick. This is how the caller can tell that the store
589    /// has not changed underneath that result: a proof carries the value it saw, and a
590    /// file that has since gone or stopped being readable makes it stale.
591    health: Arc<std::sync::atomic::AtomicU64>,
592    /// Size-aware free-space predicate.
593    capacity: Arc<CapacityGuard>,
594    /// Monotonic counter that makes temp filenames unique within this store.
595    temp_seq: AtomicU64,
596    /// Random per-instance discriminator for temp filenames.
597    nonce: u32,
598    /// Held for the store's lifetime. Startup fails without it.
599    ///
600    /// Shared rather than owned so the blocking work that depends on it can hold a lease
601    /// of its own: that work outlives the future that spawned it, and a cancelled caller
602    /// releasing the lock would leave it writing into a directory another process had
603    /// just been let into.
604    lock: Arc<File>,
605    /// Tracks every blocking task, so [`FileStore::wait_idle`] can wait for writes that
606    /// outlived their awaiting future.
607    blocking_tracker: TaskTracker,
608    /// Test-only gate read-acquired at the top of the put blocking closure.
609    ///
610    /// Tests hold the write half to park an in-flight write on the blocking pool, which
611    /// is the shape a `select!` losing to a shutdown token leaves behind.
612    #[cfg(any(test, feature = "test-utils"))]
613    test_put_gate: Arc<parking_lot::RwLock<()>>,
614}
615
616impl FileStore {
617    /// Open (or create) the store at `{root_dir}/chunks/`.
618    ///
619    /// Sweeps orphaned temp files, then rebuilds the index from directory entries.
620    /// The scan reads names only: it never `stat`s an entry and never reads a chunk.
621    ///
622    /// # Errors
623    ///
624    /// Returns [`Error::Storage`] if the directory cannot be created, the layout marker
625    /// is unreadable or describes a layout this build does not implement, or the scan
626    /// fails.
627    pub async fn new(config: FileStoreConfig) -> Result<Self> {
628        let chunks_dir = config.root_dir.join(CHUNKS_DIR_NAME);
629        std::fs::create_dir_all(&chunks_dir).map_err(|e| {
630            Error::Storage(format!(
631                "Failed to create chunk store directory {}: {e}",
632                chunks_dir.display()
633            ))
634        })?;
635
636        check_path_budget(&chunks_dir);
637
638        let layout = read_or_write_layout(&chunks_dir)?;
639        layout.check_supported()?;
640
641        // Startup fails without it, so from here this process is the only one using this
642        // directory and an interrupted write can only be its own.
643        let lock = acquire_store_lock(&chunks_dir)?;
644
645        let scan_dir = chunks_dir.clone();
646        // The scan holds the lease itself. It sweeps interrupted writes on the strength of
647        // being alone here, and it runs on a thread that outlives this future: a
648        // cancelled startup that released the lock would leave it sweeping a directory
649        // another process had just been let into.
650        let scan_lease = Arc::clone(&lock);
651        // The node root as well as the chunk tree. The scan sweeps interrupted writes
652        // under `chunks/`, which covers the layout marker's temporary because that lives
653        // there; the migration marker's lives in the root, where nothing looked.
654        let root = config.root_dir.clone();
655        let scan = spawn_blocking(move || {
656            let _lease = scan_lease;
657            sweep_marker_temps(&root);
658            scan_store(&scan_dir)
659        })
660        .await
661        .map_err(|e| Error::Storage(format!("Chunk store scan task failed: {e}")))??;
662
663        let ScanResult {
664            keys,
665            shards_present,
666            swept_temps,
667            skipped,
668        } = scan;
669
670        let key_count = keys.len();
671        // Build from a sorted vector: bulk-building packs every B-tree node to its
672        // capacity, where repeated `insert` converges on ~68% fill for the same keys.
673        let index: BTreeSet<XorName> = keys.into_iter().collect();
674
675        if swept_temps > 0 {
676            info!("Chunk store: removed {swept_temps} orphaned temporary file(s) from interrupted writes");
677        }
678        if skipped > 0 {
679            warn!("Chunk store: ignored {skipped} directory entr(ies) that are not chunk files");
680        }
681        info!(
682            "Chunk store open at {} ({key_count} chunks)",
683            chunks_dir.display()
684        );
685
686        let capacity = Arc::new(CapacityGuard::new(chunks_dir.clone(), config.disk_reserve));
687
688        Ok(Self {
689            config,
690            chunks_dir,
691            index: Arc::new(parking_lot::RwLock::new(index)),
692            write_lanes: Arc::new(
693                std::iter::repeat_with(|| parking_lot::Mutex::new(()))
694                    .take(SHARD_COUNT)
695                    .collect(),
696            ),
697            stats: parking_lot::RwLock::new(StorageStats::default()),
698            shards_present: Arc::new(parking_lot::Mutex::new(shards_present)),
699            suspect: Arc::new(parking_lot::RwLock::new(HashSet::new())),
700            known_wrong: Arc::new(parking_lot::RwLock::new(HashSet::new())),
701            writing: Arc::new(parking_lot::Mutex::new(HashMap::new())),
702            write_finished: Arc::new(tokio::sync::Notify::new()),
703            health: Arc::new(std::sync::atomic::AtomicU64::new(0)),
704            capacity,
705            temp_seq: AtomicU64::new(0),
706            nonce: rand::random(),
707            lock,
708            blocking_tracker: TaskTracker::new(),
709            #[cfg(any(test, feature = "test-utils"))]
710            test_put_gate: Arc::new(parking_lot::RwLock::new(())),
711        })
712    }
713
714    /// Store a chunk.
715    ///
716    /// On Unix, publishing is a rename within the destination directory, so the final name
717    /// can never appear on partial content: the name *is* the hash, and the content is
718    /// fully written and flushed before the name exists. Off Unix there is no rename, for
719    /// the reason `publish_in_place` gives (it is compiled only on those platforms, so this
720    /// is not a link), and a partial file can wear a real name; that
721    /// is why a duplicate is read and compared rather than trusted.
722    ///
723    /// # Returns
724    ///
725    /// `true` if the chunk was newly stored, `false` if it was already present.
726    ///
727    /// # Errors
728    ///
729    /// Returns [`Error::Storage`] if the content does not hash to `address`, the disk
730    /// is too full, or the write fails.
731    pub async fn put(&self, address: &XorName, content: &[u8]) -> Result<bool> {
732        let computed = crate::client::compute_address(content);
733        if computed != *address {
734            return Err(Error::Storage(format!(
735                "Content address mismatch: expected {}, computed {}",
736                hex::encode(address),
737                hex::encode(computed)
738            )));
739        }
740        // The read path refuses anything over the ceiling, so writing one would create a
741        // file the store could never read back and could never repair.
742        if content.len() > MAX_CHUNK_SIZE {
743            return Err(Error::Storage(format!(
744                "Chunk {} is {} bytes, over the {MAX_CHUNK_SIZE} byte maximum",
745                hex::encode(address),
746                content.len()
747            )));
748        }
749
750        // An indexed name is not proof of the bytes under it. The index is built from
751        // names, by the startup scan and by a completed publish, and a name can outlive
752        // what it points at: off Unix a chunk is created under its final name before its
753        // bytes are written, so a crash leaves a short file wearing a real name, and rot
754        // leaves a full-length one. Answering "already have it" to the copy that would fix
755        // either is how a node discards its own repair and is never offered another.
756        //
757        // So the bytes decide. Checked before the reservation below, so re-storing a chunk
758        // this node already holds stays a no-op on a full disk.
759        if self.index.read().contains(address) {
760            if let Some(answer) = self.settle_indexed_duplicate(address, content).await {
761                return answer;
762            }
763        }
764
765        let len = content.len() as u64;
766        // Reserved after the duplicate test so re-storing an existing chunk stays a
767        // harmless no-op on a full disk, matching the LMDB store's ordering.
768        let reservation = self.capacity.reserve(len)?;
769
770        let shard = self.chunks_dir.join(shard_name(address));
771        let final_path = shard.join(hex::encode(address));
772        let temp_path = shard.join(self.next_temp_name());
773        let payload = content.to_vec();
774        let lanes = Arc::clone(&self.write_lanes);
775        let index = Arc::clone(&self.index);
776        let shards_present = Arc::clone(&self.shards_present);
777        let chunks_dir = self.chunks_dir.clone();
778        let lane = shard_index(address);
779        let key = *address;
780        #[cfg(any(test, feature = "test-utils"))]
781        let test_put_gate = Arc::clone(&self.test_put_gate);
782        // Registered before the work is spawned and cleared by the work itself, so a
783        // caller that goes away cannot leave a delete free to race this publish.
784        let in_flight = self.begin_write(address);
785        // And the lease, for the same reason the scan holds it: this thread writes into a
786        // directory whose exclusivity the lock is what establishes, and it can outlive
787        // the last owner of the store.
788        let lease = Arc::clone(&self.lock);
789        let known_wrong = Arc::clone(&self.known_wrong);
790        let suspect = Arc::clone(&self.suspect);
791
792        let outcome = self
793            .blocking_tracker
794            .spawn_blocking(move || -> Result<PutOutcome> {
795                let _in_flight = in_flight;
796                let _lease = lease;
797                // Test-only: parks here while a test holds the write half.
798                #[cfg(any(test, feature = "test-utils"))]
799                let _test_put_gate = test_put_gate.read();
800                let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
801                // `mkdir` plus a directory flush are syscalls, so they belong here and
802                // not on a runtime worker.
803                ensure_shard_dir(&chunks_dir, &shard, lane, &shards_present)?;
804                let outcome = match publish(&temp_path, &final_path, &payload, &shard) {
805                    Ok(outcome) => outcome,
806                    Err(PublishFailed { error, left_behind }) => {
807                        // A publish that failed can still have left the bytes there: off
808                        // Unix the chunk is created under its final name, and if the write
809                        // or the flush then fails, the cleanup that removes it can fail
810                        // too. Releasing the reservation would hand back a charge for a
811                        // file that is on the disk.
812                        //
813                        // The publish says so rather than this deciding from a later
814                        // `is_file`. Asking the filesystem afterwards infers ownership from
815                        // a name being occupied, which is true under the store lock and the
816                        // shard lane and not true against anything out of band, and this
817                        // file spends a lot of its length arguing that a name is not
818                        // evidence. A bit set by the code that created the file is.
819                        if left_behind {
820                            reservation.commit();
821                        }
822                        return Err(error);
823                    }
824                };
825                // Placed, not yet durable. A failure from here on leaves the bytes on the
826                // disk: the chunk is rightly not reported as stored, because a copy that is
827                // not durable must not authorise deleting another, but the space is spent
828                // all the same. Dropping the reservation would hand that charge back and
829                // admit the next write against room that is already gone.
830                //
831                // Only for a chunk this call published. `Duplicate` means the file was
832                // already there and was charged by whoever wrote it, so charging it again
833                // here would count one file twice and shrink the store's idea of its own
834                // disk on every retry.
835                if let Err(e) = flush_publication(&final_path, &shard) {
836                    if matches!(outcome, PutOutcome::New) {
837                        reservation.commit();
838                    }
839                    return Err(e);
840                }
841                // Index inside the lane, and only after the rename has returned. A
842                // concurrent delete of the same address therefore cannot interleave
843                // between publishing the file and admitting the key.
844                //
845                // Only for a chunk this call actually published. `Duplicate` says a file
846                // already wears the name, and a name is not evidence about the bytes under
847                // it: the four-way answer that decides whether they are good, wrong, absent
848                // or unreadable runs after the await below, and a caller whose future is
849                // dropped never reaches it. Admitting the key here would leave the node
850                // claiming, advertising and committing to bytes nothing has read, with no
851                // suspect or known-wrong mark to hold it back, and the sharpest case is a
852                // name the startup scan deliberately refused because what wears it is a
853                // fifo, a socket or a directory. The duplicate arm admits the key itself,
854                // once a read has proven the bytes.
855                if matches!(outcome, PutOutcome::New) {
856                    index.write().insert(key);
857                    // With the marks that would otherwise hold the key back. These bytes
858                    // were hashed against their own name on the way in, so an older
859                    // instance proven wrong or merely unreadable has just been replaced by
860                    // a good one. Cleared here rather than after the await for the same
861                    // reason the insert is here: a cancelled caller would leave the key
862                    // indexed and suppressed at once, so a chunk this node really does hold
863                    // would stay hidden from `exists` and `all_keys` until some later read
864                    // happened to settle it.
865                    known_wrong.write().remove(&key);
866                    suspect.write().remove(&key);
867                    // Settled here, inside the work, so a dropped awaiter cannot strand it.
868                    reservation.commit();
869                }
870                Ok(outcome)
871            })
872            .await
873            .map_err(|e| Error::Storage(format!("Chunk store put task failed: {e}")))??;
874
875        match outcome {
876            PutOutcome::Duplicate => self.settle_duplicate(address, content).await,
877            PutOutcome::New => {
878                // Freshly published bytes that were checked against their own name on the
879                // way in. The marks were already cleared inside the work, where a dropped
880                // caller cannot skip them; what is left here is only what a caller who is
881                // still waiting should see.
882                let mut stats = self.stats.write();
883                stats.chunks_stored = stats.chunks_stored.saturating_add(1);
884                stats.bytes_stored = stats.bytes_stored.saturating_add(len);
885                drop(stats);
886                debug!("Stored chunk {} ({len} bytes)", hex::encode(address));
887                Ok(true)
888            }
889        }
890    }
891
892    /// Decide what a name that was already taken actually means.
893    ///
894    /// Split out of [`Self::put`] because it is a different question. `put` puts bytes on
895    /// a disk; this reads bytes back to find out whether the ones already there are the
896    /// ones the caller is offering, which is the only thing that makes a duplicate safe to
897    /// report as stored.
898    ///
899    /// # Errors
900    ///
901    /// Returns [`Error::Storage`] when the existing file is absent or could not be read,
902    /// both of which mean this node must not report the chunk as held.
903    async fn settle_duplicate(&self, address: &XorName, content: &[u8]) -> Result<bool> {
904        // The file was already on disk, and its name is not evidence its contents
905        // are right. The startup scan indexes by name without reading anything,
906        // and on Windows a crash mid-write leaves a partial file under a real
907        // chunk name. Trusting the name here would acknowledge a chunk that was
908        // never stored, and then discard the good copy arriving to repair it.
909        // Every answer handled, because three of the four must not report the
910        // chunk as stored. A caller that hears success acts on it: a client drops
911        // its own copy, replication marks the key held, and the copier takes it
912        // out of the legacy-only set.
913        match self.stored_bytes_match(address).await {
914            StoredBytes::Good => {
915                // Admitted here, which is the first moment the bytes behind the
916                // name have been read and shown to hash to it. Idempotent: the
917                // ordinary case is a key the startup scan already indexed.
918                self.index.write().insert(*address);
919                {
920                    let mut stats = self.stats.write();
921                    stats.duplicates = stats.duplicates.saturating_add(1);
922                }
923                Ok(false)
924            }
925            StoredBytes::Wrong => {
926                warn!(
927                    "Chunk {} was already on disk but its contents are wrong; \
928                     replacing it with the copy just offered",
929                    hex::encode(address)
930                );
931                self.repair(address, content).await.map(|()| true)
932            }
933            // The name was taken a moment ago and is not now, or was never a
934            // readable chunk file. Either way nothing holds these bytes, so say so
935            // rather than reporting a chunk that is not there.
936            StoredBytes::Absent => Err(Error::Storage(format!(
937                "Chunk {} was reported already on disk but nothing is there. Not \
938                 reporting it as stored.",
939                hex::encode(address)
940            ))),
941            // Replacing on an unanswered question would destroy a healthy copy,
942            // and reporting success would discard the offered one. The index entry
943            // stays: the file is still there, and dropping the entry would leave
944            // the chunk in neither this store's view nor the legacy one, which is
945            // what retirement destroys. Removing an entry is the quarantine path's
946            // job, and it removes the file with it, after a read that succeeded
947            // and proved the bytes wrong.
948            StoredBytes::Unreadable => Err(Error::Storage(format!(
949                "Chunk {} is on disk but could not be read to check it. Not \
950                 replacing it, and not reporting it as stored.",
951                hex::encode(address)
952            ))),
953        }
954    }
955
956    /// Flush every directory a chunk can live in, so the names in them are durable.
957    ///
958    /// Byte integrity is not the whole of what the pre-retirement proof has to establish.
959    /// A chunk whose contents are on the platter but whose *name* is not is still lost to
960    /// a power loss, and a publish whose rename landed and whose directory flush failed
961    /// leaves exactly that: the next attempt sees the name, the next verification reads
962    /// the right bytes, and nothing goes back to retry the flush. So the proof flushes
963    /// them itself rather than trusting that each publish did.
964    ///
965    /// Cheap: at most 257 directory flushes for a store of any size, and nothing off Unix,
966    /// where directories cannot be flushed and the retirement marker covers the same
967    /// ground instead.
968    ///
969    /// # Errors
970    ///
971    /// Returns [`Error::Storage`] on the first directory that cannot be flushed. The
972    /// caller must treat that as a proof it did not get.
973    pub fn flush_namespace(&self) -> Result<()> {
974        fsync_dir(&self.chunks_dir).map_err(|e| {
975            Error::Storage(format!(
976                "Could not flush {}: {e}",
977                self.chunks_dir.display()
978            ))
979        })?;
980        let present = *self.shards_present.lock();
981        for (shard, _) in present.iter().enumerate().filter(|(_, here)| **here) {
982            let dir = self.chunks_dir.join(format!("{shard:02x}"));
983            fsync_dir(&dir)
984                .map_err(|e| Error::Storage(format!("Could not flush {}: {e}", dir.display())))?;
985        }
986        Ok(())
987    }
988
989    /// Decide what to do about a write of a chunk the index already names.
990    ///
991    /// `None` means the index was wrong and there is nothing on disk, so the caller
992    /// publishes it as new. Everything else is the answer.
993    async fn settle_indexed_duplicate(
994        &self,
995        address: &XorName,
996        content: &[u8],
997    ) -> Option<Result<bool>> {
998        match self.stored_bytes_match(address).await {
999            StoredBytes::Good => {
1000                trace!("Chunk {} already exists", hex::encode(address));
1001                {
1002                    let mut stats = self.stats.write();
1003                    stats.duplicates = stats.duplicates.saturating_add(1);
1004                }
1005                Some(Ok(false))
1006            }
1007            StoredBytes::Wrong => {
1008                warn!(
1009                    "Chunk {} is indexed but its bytes are wrong; replacing it with the \
1010                     copy just offered",
1011                    hex::encode(address)
1012                );
1013                Some(self.repair(address, content).await.map(|()| true))
1014            }
1015            // Indexed but gone: publish it fresh rather than replacing something that is
1016            // not there.
1017            StoredBytes::Absent => None,
1018            // Unanswerable this time. Do not touch what is there, and do not tell the
1019            // caller the chunk is safely stored either: a client would take that as an
1020            // acknowledgement and drop the only other copy. The index entry stays, for
1021            // the reason given on the same case after publication.
1022            StoredBytes::Unreadable => Some(Err(Error::Storage(format!(
1023                "Chunk {} is indexed but could not be read to check it. Not replacing it, \
1024                 and not reporting it as stored.",
1025                hex::encode(address)
1026            )))),
1027        }
1028    }
1029
1030    /// Drop an address from the index without touching the file. Tests only.
1031    ///
1032    /// Stands in for whatever leaves a key indexed nowhere: a quarantine, a publish that
1033    /// failed after the file went, an operator with a shell.
1034    #[cfg(test)]
1035    pub(crate) fn forget_for_test(&self, address: &XorName) {
1036        self.index.write().remove(address);
1037    }
1038
1039    /// The size of the file behind `address`, if there is one.
1040    ///
1041    /// One `metadata` call, no read. Used where an indexed name has to be checked against
1042    /// what a caller is offering before that offer is turned away.
1043    #[must_use]
1044    pub fn stored_len(&self, address: &XorName) -> Option<usize> {
1045        std::fs::metadata(self.chunk_path(address))
1046            .ok()
1047            .filter(std::fs::Metadata::is_file)
1048            .and_then(|m| usize::try_from(m.len()).ok())
1049    }
1050
1051    /// Whether the file already stored under `address` really hashes to it.
1052    async fn stored_bytes_match(&self, address: &XorName) -> StoredBytes {
1053        match self.get_raw(address).await {
1054            Ok(Some(bytes)) if crate::client::compute_address(&bytes) == *address => {
1055                // A read that hashed. It settles both questions.
1056                self.clear_suspect(address);
1057                self.clear_known_wrong(address);
1058                StoredBytes::Good
1059            }
1060            Ok(Some(_)) => {
1061                self.mark_known_wrong(address);
1062                StoredBytes::Wrong
1063            }
1064            Ok(None) => StoredBytes::Absent,
1065            // NOT the same as wrong. A file that could not be read this once may be
1066            // perfectly good, and off Unix replacing it means opening it with `truncate`,
1067            // which would destroy a healthy sole copy on the strength of a transient
1068            // fault. Say so and let the caller leave it alone.
1069            Err(e) => {
1070                debug!("Could not read {} to check it: {e}", hex::encode(address));
1071                self.mark_suspect(address);
1072                StoredBytes::Unreadable
1073            }
1074        }
1075    }
1076
1077    /// Replace the file behind an address with known-good bytes, atomically.
1078    ///
1079    /// Unlike [`Self::put`], this deliberately publishes **over** an existing name. It
1080    /// exists for one caller: repairing a file whose bytes no longer hash to their own
1081    /// name, from a copy held elsewhere, before that copy is destroyed. Doing it as
1082    /// delete-then-put would leave a window where the only remaining copy is the one
1083    /// about to be deleted, and any failure in that window is unrecoverable.
1084    ///
1085    /// # Errors
1086    ///
1087    /// Returns [`Error::Storage`] if `content` does not hash to `address`, or the write
1088    /// fails. The old file is left untouched on every error path.
1089    pub async fn repair(&self, address: &XorName, content: &[u8]) -> Result<()> {
1090        // The same ceiling `put` enforces. Without it a repair can install bytes the read
1091        // path will refuse for ever, which is a chunk that verifies as present and can
1092        // never be served.
1093        if content.len() > MAX_CHUNK_SIZE {
1094            return Err(Error::Storage(format!(
1095                "Refusing to repair {} with {} bytes, over the {MAX_CHUNK_SIZE} byte \
1096                 maximum",
1097                hex::encode(address),
1098                content.len()
1099            )));
1100        }
1101        let computed = crate::client::compute_address(content);
1102        if computed != *address {
1103            return Err(Error::Storage(format!(
1104                "Refusing to repair {} with content that hashes to {}",
1105                hex::encode(address),
1106                hex::encode(computed)
1107            )));
1108        }
1109        // The replacement exists alongside the original until the rename, so the room for
1110        // it has to be there first. Reserved rather than merely checked: a plain check
1111        // passes against a cached measurement, so concurrent repairs and PUTs can each be
1112        // admitted against the same headroom and cross the reserve together.
1113        // Moved into the work below, so it is released when the write finishes rather
1114        // than when its caller stops waiting. A caller that goes away otherwise frees
1115        // room that the detached write is still about to consume.
1116        let reservation = self.capacity.reserve(content.len() as u64)?;
1117
1118        let shard = self.chunks_dir.join(shard_name(address));
1119        let final_path = shard.join(hex::encode(address));
1120        let temp_path = shard.join(self.next_temp_name());
1121        let payload = content.to_vec();
1122        let lanes = Arc::clone(&self.write_lanes);
1123        let index = Arc::clone(&self.index);
1124        let shards_present = Arc::clone(&self.shards_present);
1125        let chunks_dir = self.chunks_dir.clone();
1126        let lane = shard_index(address);
1127        let key = *address;
1128        let in_flight = self.begin_write(address);
1129        let lease = Arc::clone(&self.lock);
1130        let capacity = Arc::clone(&self.capacity);
1131        let suspect = Arc::clone(&self.suspect);
1132        let known_wrong = Arc::clone(&self.known_wrong);
1133
1134        self.blocking_tracker
1135            .spawn_blocking(move || -> Result<()> {
1136                let _in_flight = in_flight;
1137                let _lease = lease;
1138                let _reservation = reservation;
1139                let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
1140                ensure_shard_dir(&chunks_dir, &shard, lane, &shards_present)?;
1141                write_and_replace(&temp_path, &final_path, &payload, &shard)?;
1142                index.write().insert(key);
1143                // Settled here rather than after the await. The replacement has landed
1144                // and hashes to its own name, so nothing is wrong with this chunk any
1145                // more; a caller that stopped waiting would otherwise leave a healthy
1146                // file excluded from everything the node claims to hold, and the
1147                // measurement believing the store is a chunk smaller than it is.
1148                suspect.write().remove(&key);
1149                known_wrong.write().remove(&key);
1150                capacity.invalidate();
1151                Ok(())
1152            })
1153            .await
1154            .map_err(|e| Error::Storage(format!("Chunk store repair task failed: {e}")))??;
1155
1156        // Everything the success means was recorded by the work that succeeded: the
1157        // reservation released, the marks cleared, the measurement thrown away. Released
1158        // rather than committed because a repair is not a new chunk, and the measurement
1159        // discarded rather than adjusted because the file it replaced may have been
1160        // shorter, which is exactly the case a repair fixes.
1161        debug!("Repaired chunk {}", hex::encode(address));
1162        Ok(())
1163    }
1164
1165    /// Retrieve a chunk, verifying it against its address when configured to.
1166    ///
1167    /// # Errors
1168    ///
1169    /// Returns [`Error::Storage`] on an I/O failure, or when verification fails. A
1170    /// chunk whose bytes do not hash to its name is removed and dropped from the index
1171    /// before the error is returned, so it leaves `all_keys()` and ordinary replication
1172    /// repairs it.
1173    pub async fn get(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
1174        let Some(content) = self.read_file(address).await? else {
1175            trace!("Chunk {} not found", hex::encode(address));
1176            return Ok(None);
1177        };
1178
1179        if self.config.verify_on_read {
1180            let computed = crate::client::compute_address(&content);
1181            if computed != *address {
1182                {
1183                    let mut stats = self.stats.write();
1184                    stats.verification_failures = stats.verification_failures.saturating_add(1);
1185                }
1186                warn!(
1187                    "Chunk verification failed: expected {}, computed {}",
1188                    hex::encode(address),
1189                    hex::encode(computed)
1190                );
1191                // Said before it is acted on. Removing the file can fail or be cancelled,
1192                // and a chunk proven wrong that goes on looking healthy is one the node
1193                // keeps committing to and, worse, one a cached pre-retirement pass still
1194                // covers: the legacy copy that would repair it gets deleted.
1195                self.mark_known_wrong(address);
1196                self.quarantine_corrupt(address).await;
1197                return Err(Error::Storage(format!(
1198                    "Chunk verification failed for {}",
1199                    hex::encode(address)
1200                )));
1201            }
1202        }
1203
1204        if self.config.verify_on_read {
1205            // The bytes hashed to their name. Whatever this store thought was wrong with
1206            // them is not wrong with them, and a mark that outlives the fault it
1207            // describes means the node can serve a chunk it will not claim, commit or
1208            // offer.
1209            self.clear_known_wrong(address);
1210        }
1211
1212        let len = content.len() as u64;
1213        {
1214            let mut stats = self.stats.write();
1215            stats.chunks_retrieved = stats.chunks_retrieved.saturating_add(1);
1216            stats.bytes_retrieved = stats.bytes_retrieved.saturating_add(len);
1217        }
1218        debug!("Retrieved chunk {} ({len} bytes)", hex::encode(address));
1219        Ok(Some(content))
1220    }
1221
1222    /// Retrieve raw chunk bytes without content-address verification.
1223    ///
1224    /// # Errors
1225    ///
1226    /// Returns [`Error::Storage`] on an I/O failure.
1227    pub async fn get_raw(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
1228        self.read_file(address).await
1229    }
1230
1231    /// Check whether a chunk is stored.
1232    ///
1233    /// An in-memory lookup: no syscall, no I/O.
1234    ///
1235    /// # Errors
1236    ///
1237    /// Never fails. The signature keeps the shape the LMDB store had, because callers
1238    /// treat the error as "assume absent".
1239    pub fn exists(&self, address: &XorName) -> Result<bool> {
1240        if self.is_unservable(address) {
1241            return Ok(false);
1242        }
1243        Ok(self.is_indexed(address))
1244    }
1245
1246    /// Is this chunk one the node must not answer for?
1247    #[must_use]
1248    fn is_unservable(&self, address: &XorName) -> bool {
1249        self.suspect.read().contains(address) || self.known_wrong.read().contains(address)
1250    }
1251
1252    /// Is this chunk in the index, whether or not it can currently be read?
1253    ///
1254    /// The physical question, as against [`Self::exists`]'s question about what the node
1255    /// is willing to claim. The migration must ask this one: a suspect chunk is still a
1256    /// file this store has, and treating it as absent would put the key in the legacy-only
1257    /// set, from where the union view advertises it again — a key the node claims through
1258    /// one view and cannot serve through either.
1259    #[must_use]
1260    pub fn is_indexed(&self, address: &XorName) -> bool {
1261        self.index.read().contains(address)
1262    }
1263
1264    /// Delete a chunk, returning whether it was present.
1265    ///
1266    /// `unlink` returns the blocks to the filesystem immediately. That is the whole
1267    /// point of this store: no free list, no compaction, no free space required to
1268    /// reclaim space.
1269    ///
1270    /// # Errors
1271    ///
1272    /// Returns [`Error::Storage`] if the file exists but cannot be removed. The index
1273    /// keeps the key in that case, because the bytes are still on disk.
1274    pub async fn delete(&self, address: &XorName) -> Result<bool> {
1275        let path = self.chunk_path(address);
1276        let lanes = Arc::clone(&self.write_lanes);
1277        let index = Arc::clone(&self.index);
1278        let lane = shard_index(address);
1279        let key = *address;
1280        // Carried into the closure for the reason `put`, `repair` and the startup scan
1281        // carry it: this work outlives the future that started it, so a cancelled caller
1282        // that drops the last `FileStore` would otherwise release the directory to another
1283        // process while an unlink is still queued against it. Deleting is the operation
1284        // where that matters most.
1285        let lease = Arc::clone(&self.lock);
1286
1287        let (existed, freed) = self
1288            .blocking_tracker
1289            .spawn_blocking(move || -> Result<(bool, u64)> {
1290                let _lease = lease;
1291                let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
1292                let len = std::fs::metadata(&path).map_or(0, |m| m.len());
1293                let removed = match std::fs::remove_file(&path) {
1294                    Ok(()) => {
1295                        // Without this a crash can resurrect the entry on ext4, XFS,
1296                        // btrfs and APFS: the unlink is in the page cache, the directory
1297                        // is not.
1298                        if let Some(shard) = path.parent() {
1299                            fsync_dir_best_effort(shard);
1300                        }
1301                        true
1302                    }
1303                    // Already gone: the index was stale. Still a successful delete as
1304                    // far as the caller is concerned.
1305                    Err(e) if e.kind() == ErrorKind::NotFound => false,
1306                    Err(e) => {
1307                        return Err(Error::Storage(format!(
1308                            "Failed to delete chunk file {}: {e}",
1309                            path.display()
1310                        )))
1311                    }
1312                };
1313                // Index only after the filesystem operation has succeeded. On the error
1314                // path above the entry stays, because the bytes are still on disk.
1315                let was_indexed = index.write().remove(&key);
1316                Ok((removed || was_indexed, if removed { len } else { 0 }))
1317            })
1318            .await
1319            .map_err(|e| Error::Storage(format!("Chunk store delete task failed: {e}")))??;
1320
1321        if freed > 0 {
1322            self.capacity.record_removed(freed);
1323            debug!("Deleted chunk {}", hex::encode(address));
1324        }
1325        Ok(existed)
1326    }
1327
1328    /// Return every stored key, in ascending order.
1329    ///
1330    /// The order is a correctness requirement, not a convenience: the commitment
1331    /// builder truncates the responsible subset with `take(cap)` before the Merkle tree
1332    /// sorts it, so an unstable order would make the node's published commitment depend
1333    /// on iteration luck.
1334    ///
1335    /// # Errors
1336    ///
1337    /// Never fails. The signature matches the LMDB store's.
1338    // Async without awaiting anything, deliberately: the whole point of this store is
1339    // that the key set is already in memory. Callers are spread across the replication
1340    // engine and cannot all be de-async'd in this change.
1341    //
1342    // Two lint names because they were renamed between toolchains, and `unknown_lints`
1343    // so whichever one the compiler in use has never heard of stays quiet.
1344    #[allow(unknown_lints)]
1345    #[allow(clippy::unused_async, clippy::unused_async_trait_impl)]
1346    pub async fn all_keys(&self) -> Result<Vec<XorName>> {
1347        // Copied out first so neither lock is held while the other is taken, and so the
1348        // usual case, where nothing is suspect, costs one clone of an empty set.
1349        let mut unservable: HashSet<XorName> = self.suspect.read().clone();
1350        unservable.extend(self.known_wrong.read().iter().copied());
1351        let keys = self.index.read().clone();
1352        if unservable.is_empty() {
1353            return Ok(keys.into_iter().collect());
1354        }
1355        Ok(keys
1356            .into_iter()
1357            .filter(|key| !unservable.contains(key))
1358            .collect())
1359    }
1360
1361    /// Stop answering for a chunk this store could not read.
1362    ///
1363    /// The file stays. It may be perfectly good and unreadable only for the moment, and
1364    /// deleting it, or dropping it from the index, is how a chunk ends up in neither this
1365    /// store's view nor the legacy one, which is what retirement destroys.
1366    ///
1367    /// What does change is what the node says about it. A chunk it cannot read is one it
1368    /// cannot serve, and claiming it anyway puts the key in signed commitments, answers
1369    /// presence probes with a yes, suppresses the replication that would repair it, and
1370    /// earns a penalty at the next commitment-bound audit. Those penalties are not
1371    /// suspended.
1372    fn mark_suspect(&self, address: &XorName) {
1373        if self.suspect.write().insert(*address) {
1374            self.note_health_changed();
1375            warn!(
1376                "Chunk {} is on disk but could not be read; this node stops answering for \
1377                 it until a read succeeds",
1378                hex::encode(address)
1379            );
1380        }
1381    }
1382
1383    /// What the store's health looked like at this moment.
1384    ///
1385    /// Compare a value taken before a long-running check with one taken after, or after
1386    /// taking a lock: different means a chunk stopped being servable in between and any
1387    /// conclusion drawn from that check is out of date.
1388    #[must_use]
1389    pub fn health_generation(&self) -> u64 {
1390        self.health.load(std::sync::atomic::Ordering::Acquire)
1391    }
1392
1393    /// Record that a chunk stopped being servable.
1394    fn note_health_changed(&self) {
1395        self.health
1396            .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1397    }
1398
1399    /// Stop answering for a chunk a read has proven wrong.
1400    ///
1401    /// Unlike a chunk that merely could not be read, a later read does not clear this.
1402    /// The bytes are wrong, and reading them again says the same thing; only replacing
1403    /// them or removing them settles it. Bumping health matters as much as the suppression: a chunk that
1404    /// has become unservable since the last pre-retirement pass must invalidate that pass,
1405    /// or a repair that fails leaves the node deleting the copy it would have repaired
1406    /// from.
1407    ///
1408    /// For callers outside this module that have proven it themselves.
1409    pub fn note_known_wrong(&self, address: &XorName) {
1410        self.mark_known_wrong(address);
1411    }
1412
1413    /// Stop answering for a chunk a read has proven wrong.
1414    fn mark_known_wrong(&self, address: &XorName) {
1415        if self.known_wrong.write().insert(*address) {
1416            self.note_health_changed();
1417            warn!(
1418                "Chunk {} does not match its name; this node stops answering for it until \
1419                 it is repaired or removed",
1420                hex::encode(address)
1421            );
1422        }
1423    }
1424
1425    /// A caller outside this module has proven the stored bytes are right.
1426    pub fn note_bytes_proven_good(&self, address: &XorName) {
1427        self.clear_known_wrong(address);
1428        self.clear_suspect(address);
1429    }
1430
1431    /// Answer for a chunk again, after it has been replaced or removed.
1432    fn clear_known_wrong(&self, address: &XorName) {
1433        self.known_wrong.write().remove(address);
1434    }
1435
1436    /// Answer for a chunk again, after a read that worked.
1437    fn clear_suspect(&self, address: &XorName) {
1438        if !self.suspect.read().contains(address) {
1439            return;
1440        }
1441        if self.suspect.write().remove(address) {
1442            info!(
1443                "Chunk {} could be read again; this node answers for it once more",
1444                hex::encode(address)
1445            );
1446        }
1447    }
1448
1449    /// Number of chunks currently stored.
1450    ///
1451    /// The physical count: every name in the index, including chunks the node has stopped
1452    /// answering for because a read found them wrong or could not read them at all. It is
1453    /// deliberately not the same number as `all_keys().len()`, which is what the node is
1454    /// willing to claim and so leaves those out.
1455    ///
1456    /// Anything asking "how much is on this disk" wants this one, and that is what its
1457    /// callers ask: the migration's progress, the storage stats, and the size an audit is
1458    /// built for. Anything asking "what will this node answer for" wants `all_keys`.
1459    /// Quietly filtering this one would move all three of those without saying so, which
1460    /// is why the difference is written down here rather than removed.
1461    ///
1462    /// # Errors
1463    ///
1464    /// Never fails. The signature matches the LMDB store's.
1465    pub fn current_chunks(&self) -> Result<u64> {
1466        Ok(self.index.read().len() as u64)
1467    }
1468
1469    /// Operation statistics, with the live chunk count filled in.
1470    #[must_use]
1471    pub fn stats(&self) -> StorageStats {
1472        let mut stats = self.stats.read().clone();
1473        stats.current_chunks = self.index.read().len() as u64;
1474        stats
1475    }
1476
1477    /// The node root directory this store was configured with.
1478    #[must_use]
1479    pub fn root_dir(&self) -> &Path {
1480        &self.config.root_dir
1481    }
1482
1483    /// The directory holding the shard tree.
1484    #[must_use]
1485    pub fn chunks_dir(&self) -> &Path {
1486        &self.chunks_dir
1487    }
1488
1489    /// Reject work early when the disk cannot take another chunk at all.
1490    ///
1491    /// # Errors
1492    ///
1493    /// Returns [`Error::Storage`] when free space is below the configured reserve.
1494    pub fn check_capacity(&self) -> Result<()> {
1495        self.capacity.check(0)
1496    }
1497
1498    /// Three-way answer to "can this store take a write right now".
1499    ///
1500    /// Kept distinct from [`Self::check_capacity`] because a failed free-space query and a
1501    /// genuinely full disk are not the same thing, and the replication verification cycle
1502    /// depends on the difference: a full disk is a standing condition worth minutes of
1503    /// backoff, while a `statvfs` that failed says nothing about available space and may
1504    /// well succeed on the next pass.
1505    #[must_use]
1506    pub fn capacity_verdict(&self) -> crate::storage::CapacityVerdict {
1507        match self.capacity.measure_available() {
1508            Some(available) if available < self.capacity.reserve => {
1509                crate::storage::CapacityVerdict::Full
1510            }
1511            Some(_) => crate::storage::CapacityVerdict::Writable,
1512            None => crate::storage::CapacityVerdict::Unknown,
1513        }
1514    }
1515
1516    /// Credit `len` bytes that were deleted outside this store back to the
1517    /// cached measurement. The pointer store keeps its own files on this disk.
1518    pub(crate) fn release_bytes(&self, len: u64) {
1519        self.capacity.record_removed(len);
1520    }
1521
1522    /// Reject work early when the disk cannot take `bytes` more.
1523    ///
1524    /// # Errors
1525    ///
1526    /// Returns [`Error::Storage`] when the write would not fit above the reserve.
1527    pub fn check_capacity_for(&self, bytes: u64) -> Result<()> {
1528        self.capacity.check(bytes)
1529    }
1530
1531    /// Charge `bytes` against the disk before writing them, releasing the charge if the
1532    /// write does not happen.
1533    ///
1534    /// For stores that share this disk but keep their own files — the pointer store does.
1535    /// They must not check and then write: that is the race [`CapacityGuard::reserve`]
1536    /// exists to close.
1537    pub(crate) fn reserve_bytes(&self, bytes: u64) -> Result<Reservation> {
1538        self.capacity.reserve(bytes)
1539    }
1540
1541    /// `(written_since, in_flight)` from the capacity guard. Tests only: it is
1542    /// how a released charge is told apart from a stranded one.
1543    #[cfg(test)]
1544    pub(crate) fn capacity_counters(&self) -> (u64, u64) {
1545        self.capacity.counters()
1546    }
1547
1548    /// What a payload of `bytes` actually costs the disk, rounded to the
1549    /// allocation unit. Tests only, so they can assert exact counter deltas
1550    /// rather than "it went up" — which a charge of one allocation unit would
1551    /// satisfy for several payloads at once.
1552    #[cfg(test)]
1553    pub(crate) fn capacity_charge_for(bytes: u64) -> u64 {
1554        CapacityGuard::charge(bytes)
1555    }
1556
1557    /// Force the next capacity question to re-measure the filesystem.
1558    ///
1559    /// Called after the legacy environment is removed, because that is a step change in
1560    /// free space that the short-lived cache would otherwise hide for a few seconds.
1561    pub fn invalidate_capacity_cache(&self) {
1562        self.capacity.invalidate();
1563    }
1564
1565    /// Test-only handle to the put gate.
1566    ///
1567    /// Hold the write half to park the next write inside its blocking closure, for
1568    /// example to prove that shutdown waits for a write whose awaiter was dropped.
1569    #[cfg(any(test, feature = "test-utils"))]
1570    #[must_use]
1571    pub fn test_put_gate(&self) -> Arc<parking_lot::RwLock<()>> {
1572        Arc::clone(&self.test_put_gate)
1573    }
1574
1575    /// Test-only handle to the write lanes, and the index of the one `address` is
1576    /// written, repaired and quarantined under.
1577    ///
1578    /// Holding that lane stalls every write, repair and quarantine in the shard the way a
1579    /// hung disk would. [`Self::test_put_gate`] cannot stand in for it: a put parks there
1580    /// before it takes its lane.
1581    #[cfg(test)]
1582    pub(crate) fn test_write_lane(
1583        &self,
1584        address: &XorName,
1585    ) -> (Arc<Vec<parking_lot::Mutex<()>>>, usize) {
1586        (Arc::clone(&self.write_lanes), shard_index(address))
1587    }
1588
1589    /// Register a write of `address` and hand back the token that clears it.
1590    ///
1591    /// The token must be moved into the blocking closure that does the work, so the entry
1592    /// is cleared by the thread that finishes rather than by a caller that may be gone.
1593    fn begin_write(&self, address: &XorName) -> WriteInFlight {
1594        *self.writing.lock().entry(*address).or_insert(0) += 1;
1595        WriteInFlight {
1596            writing: Arc::clone(&self.writing),
1597            finished: Arc::clone(&self.write_finished),
1598            address: *address,
1599        }
1600    }
1601
1602    /// Wait until nothing is part-way through writing `address`.
1603    ///
1604    /// For callers that must be last: a delete whose key still has a write in flight
1605    /// would be undone by that write landing afterwards.
1606    pub async fn wait_for_write(&self, address: &XorName) {
1607        loop {
1608            // Registered before the check, so a clear between the two is not missed.
1609            let waiting = self.write_finished.notified();
1610            if !self.writing.lock().contains_key(address) {
1611                return;
1612            }
1613            waiting.await;
1614        }
1615    }
1616
1617    /// How many blocking tasks this store currently has in flight. Tests only.
1618    ///
1619    /// Lets a test wait for work to have actually started rather than guessing at a
1620    /// delay, which is the difference between a test that proves something and one that
1621    /// passes because the machine was quick.
1622    #[cfg(any(test, feature = "test-utils"))]
1623    #[must_use]
1624    pub(crate) fn tasks_in_flight(&self) -> usize {
1625        self.blocking_tracker.len()
1626    }
1627
1628    /// Wait until every blocking task this store spawned has finished.
1629    ///
1630    /// Dropping the awaiting future does not cancel a `spawn_blocking` closure, so
1631    /// shutdown has to wait for the closure itself.
1632    pub async fn wait_idle(&self) {
1633        self.blocking_tracker.close();
1634        self.blocking_tracker.wait().await;
1635        self.blocking_tracker.reopen();
1636    }
1637
1638    /// Absolute path of a chunk file.
1639    pub(crate) fn chunk_path(&self, address: &XorName) -> PathBuf {
1640        self.chunks_dir
1641            .join(shard_name(address))
1642            .join(hex::encode(address))
1643    }
1644
1645    /// A temp name unique to this store instance, and distinguishable from a chunk name.
1646    ///
1647    /// The nonce matters: two `FileStore`s on one root in one process share a PID, and a
1648    /// recycled PID collides with an age-gated leftover. Either way `create_new` would
1649    /// fail and surface as a spurious write error.
1650    fn next_temp_name(&self) -> String {
1651        let seq = self.temp_seq.fetch_add(1, Ordering::Relaxed);
1652        format!(
1653            "{TEMP_PREFIX}{}.{:08x}.{seq}",
1654            std::process::id(),
1655            self.nonce
1656        )
1657    }
1658
1659    /// Read a chunk file, dropping the index entry if the file has vanished.
1660    async fn read_file(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
1661        let path = self.chunk_path(address);
1662        let read = self
1663            .blocking_tracker
1664            .spawn_blocking(move || -> Result<Option<Vec<u8>>> {
1665                match open_regular(&path) {
1666                    Ok(Some(f)) => read_bounded(f, &path).map(Some),
1667                    Ok(None) => Ok(None),
1668                    Err(e) => Err(e),
1669                }
1670            })
1671            .await
1672            .map_err(|e| Error::Storage(format!("Chunk store read task failed: {e}")))?;
1673
1674        // Every read decides the question, not only the ones that were checking. A read
1675        // that failed means this chunk cannot be served, whoever asked; a read that
1676        // worked means it can be, whoever asked. Doing this anywhere else leaves a key
1677        // stuck unadvertised after the fault has cleared, or advertised after it has not.
1678        let read = match read {
1679            Ok(read) => {
1680                self.clear_suspect(address);
1681                read
1682            }
1683            Err(e) => {
1684                self.mark_suspect(address);
1685                return Err(e);
1686            }
1687        };
1688
1689        if read.is_none() && self.forget_if_absent(address).await {
1690            // The file went away underneath us. Stop advertising the key so the close
1691            // group notices the shortfall and replication puts it back.
1692            warn!(
1693                "Chunk {} is indexed but its file is missing; dropped from the index so \
1694                 replication can repair it",
1695                hex::encode(address)
1696            );
1697        }
1698        Ok(read)
1699    }
1700
1701    /// Drop an index entry whose file is genuinely gone.
1702    ///
1703    /// Re-checks under the address's write lane, so a chunk republished between the
1704    /// failing read and this call keeps its entry.
1705    async fn forget_if_absent(&self, address: &XorName) -> bool {
1706        // Not suspect any more: it is not unreadable, it is not there.
1707        self.clear_suspect(address);
1708        let path = self.chunk_path(address);
1709        let lanes = Arc::clone(&self.write_lanes);
1710        let index = Arc::clone(&self.index);
1711        let lane = shard_index(address);
1712        let key = *address;
1713        // The bump happens inside the closure, with the mutation it describes. The
1714        // closure runs to completion on its own thread whether or not anyone is still
1715        // awaiting it, so bumping after the await is skipped entirely when a shutdown
1716        // drops the caller — and the index change it was meant to announce still lands.
1717        // A cached pre-retirement proof would then stay valid over a store that had
1718        // quietly lost a chunk.
1719        let health = Arc::clone(&self.health);
1720        self.blocking_tracker
1721            .spawn_blocking(move || {
1722                let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
1723                if path.exists() {
1724                    return false;
1725                }
1726                let forgotten = index.write().remove(&key);
1727                if forgotten {
1728                    health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1729                }
1730                forgotten
1731            })
1732            .await
1733            .unwrap_or(false)
1734    }
1735
1736    /// Remove a chunk whose bytes do not match its name, and stop advertising it.
1737    ///
1738    /// Re-reads and re-verifies under the address's write lane first. A read that failed
1739    /// verification is rare enough that paying for one extra read is worth never
1740    /// discarding a chunk that a concurrent write had already repaired.
1741    async fn quarantine_corrupt(&self, address: &XorName) {
1742        let path = self.chunk_path(address);
1743        let lanes = Arc::clone(&self.write_lanes);
1744        let index = Arc::clone(&self.index);
1745        let lane = shard_index(address);
1746        let key = *address;
1747        // For the reason given on `forget_if_absent`: this closure outlives its awaiter,
1748        // and the change it makes has to be announced by the same thread that makes it.
1749        let health = Arc::clone(&self.health);
1750        // And the store-lock lease, for the reason `put`, `repair`, `delete` and the
1751        // startup scan carry it: this closure outlives its awaiter, so without it a
1752        // cancelled verification whose caller dropped the last `FileStore` would unlink
1753        // inside a directory a second process had already been handed.
1754        let lease = Arc::clone(&self.lock);
1755        let outcome =
1756            self.blocking_tracker
1757                .spawn_blocking(move || -> std::io::Result<bool> {
1758                    let _lease = lease;
1759                    let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
1760                    // Nothing is thrown away without proof. A re-read that fails says the
1761                    // question could not be answered this time, not that the bytes are wrong,
1762                    // and a repair may have published a good copy since the read that brought
1763                    // us here. Treating either as corruption deletes a chunk this node has.
1764                    let buf = match open_regular(&path) {
1765                        Ok(Some(f)) => read_bounded(f, &path)
1766                            .map_err(|e| std::io::Error::other(e.to_string()))?,
1767                        Ok(None) => {
1768                            index.write().remove(&key);
1769                            health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1770                            return Ok(true);
1771                        }
1772                        Err(e) => return Err(std::io::Error::other(e.to_string())),
1773                    };
1774                    if crate::client::compute_address(&buf) == key {
1775                        // Repaired between the failing read and now. Leave it alone.
1776                        return Ok(false);
1777                    }
1778                    std::fs::remove_file(&path)?;
1779                    // The same flush the ordinary delete does, for the same reason: an
1780                    // unlink that has not reached the directory can be undone by a power
1781                    // loss, and here the entry that comes back is one this node has proven
1782                    // wrong. The startup scan would re-index it by name, and the
1783                    // known-wrong mark that would otherwise hold it back lives only in
1784                    // memory and does not survive the restart, so the node would go back to
1785                    // claiming and committing to a chunk it already knows is bad.
1786                    if let Some(shard) = path.parent() {
1787                        fsync_dir_best_effort(shard);
1788                    }
1789                    index.write().remove(&key);
1790                    health.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1791                    Ok(true)
1792                })
1793                .await;
1794        match outcome {
1795            Ok(Ok(true)) => {
1796                self.clear_known_wrong(address);
1797                self.clear_suspect(address);
1798                warn!(
1799                    "Removed corrupt chunk file {}; replication will repair it",
1800                    hex::encode(address)
1801                );
1802            }
1803            Ok(Ok(false)) => {
1804                // The re-read hashed and matched: a repair landed between the failing
1805                // read and this one.
1806                self.clear_known_wrong(address);
1807                self.clear_suspect(address);
1808                debug!(
1809                    "Chunk {} verified on re-read; leaving it in place",
1810                    hex::encode(address)
1811                );
1812            }
1813            // Still indexed, so it must not still be claimed: the read that brought us
1814            // here proved the bytes wrong, and the node would otherwise go on committing
1815            // to a chunk it knows it cannot serve.
1816            Ok(Err(e)) => {
1817                self.mark_suspect(address);
1818                warn!(
1819                    "Corrupt chunk {} could not be removed: {e}. It stays on disk, and \
1820                     this node stops answering for it.",
1821                    hex::encode(address)
1822                );
1823            }
1824            Err(e) => {
1825                self.mark_suspect(address);
1826                warn!("Corrupt-chunk removal task failed: {e}");
1827            }
1828        }
1829    }
1830}
1831
1832// ────────────────────────────────────────────────────────────────────────────
1833// Free functions
1834// ────────────────────────────────────────────────────────────────────────────
1835
1836/// Create the destination shard directory if this store has not seen it yet.
1837///
1838/// A newly created directory entry is only durable once its parent is flushed; without
1839/// that a crash could take the directory and the chunk inside it together.
1840fn ensure_shard_dir(
1841    chunks_dir: &Path,
1842    dir: &Path,
1843    shard: usize,
1844    present: &parking_lot::Mutex<[bool; SHARD_COUNT]>,
1845) -> Result<()> {
1846    if present.lock().get(shard).copied().unwrap_or(false) {
1847        return Ok(());
1848    }
1849    std::fs::create_dir_all(dir).map_err(|e| {
1850        Error::Storage(format!(
1851            "Failed to create shard directory {}: {e}",
1852            dir.display()
1853        ))
1854    })?;
1855    // Load-bearing, like the flush that publishes a chunk into this directory. Until the
1856    // parent is flushed the shard's own entry can be lost, and losing it loses every chunk
1857    // inside it. Reporting the shard present anyway would let the very first chunk written
1858    // into it count as durably stored.
1859    fsync_dir(chunks_dir).map_err(|e| {
1860        Error::Storage(format!(
1861            "Created shard directory {} but could not flush {}: {e}. Not marking the shard \
1862             usable, because a directory that is not durable cannot hold a chunk that is.",
1863            dir.display(),
1864            chunks_dir.display()
1865        ))
1866    })?;
1867    if let Some(slot) = present.lock().get_mut(shard) {
1868        *slot = true;
1869    }
1870    Ok(())
1871}
1872
1873/// Shard directory index for an address: its last byte.
1874fn shard_index(address: &XorName) -> usize {
1875    address.last().copied().unwrap_or(0) as usize
1876}
1877
1878/// Shard directory name for an address: the last two characters of its hex form.
1879fn shard_name(address: &XorName) -> String {
1880    format!("{:02x}", shard_index(address))
1881}
1882
1883/// True for a string of hex digits in either case.
1884fn is_hex_any_case(s: &str) -> bool {
1885    !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit())
1886}
1887
1888/// Move an entry aside under a name that can never be read as a chunk.
1889fn quarantine_entry(path: &Path) {
1890    let aside = path.with_extension("not-a-chunk");
1891    match std::fs::rename(path, &aside) {
1892        Ok(()) => warn!(
1893            "Chunk store: moved {} aside to {}; a name that differs from a chunk name only \
1894             by case collides with it on Windows and macOS",
1895            path.display(),
1896            aside.display()
1897        ),
1898        Err(e) => warn!(
1899            "Chunk store: {} collides with a chunk name by case folding and could not be \
1900             moved aside: {e}. Rename or delete it.",
1901            path.display()
1902        ),
1903    }
1904}
1905
1906/// True for a string of lowercase hex digits only.
1907fn is_lower_hex(s: &str) -> bool {
1908    !s.is_empty() && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
1909}
1910
1911/// Decode a filename back into the address it names, or `None` if it is not one.
1912///
1913/// Rejects uppercase deliberately. On a case-folding filesystem (NTFS, default APFS)
1914/// accepting both cases would let one file answer to two index entries.
1915fn decode_chunk_name(name: &str) -> Option<XorName> {
1916    if name.len() != CHUNK_NAME_LEN || !is_lower_hex(name) {
1917        return None;
1918    }
1919    let bytes = hex::decode(name).ok()?;
1920    XorName::try_from(bytes.as_slice()).ok()
1921}
1922
1923/// Flush a directory and report whether it worked, for callers outside this module.
1924///
1925/// For the one caller whose next step is destructive: retirement moves the legacy
1926/// environment aside and then deletes it under its new name, so if the rename has not
1927/// reached the disk when the delete lands, a power loss brings the environment back under
1928/// its old name with its contents gone.
1929///
1930/// # Errors
1931///
1932/// Returns the underlying I/O error. Off Unix there is no way to flush a directory through
1933/// the standard library, so this reports success without being able to promise anything.
1934pub fn fsync_path(path: &Path) -> std::io::Result<()> {
1935    fsync_dir(path)
1936}
1937
1938/// Flush a directory so a rename or creation inside it survives power loss.
1939///
1940/// Best effort by design. Linux and XFS require it, macOS accepts it with undocumented
1941/// effect, and Windows offers no way to do it at all through the standard library. The
1942/// content is content-addressed and re-replicable, so a lost directory entry costs a
1943/// refetch rather than data. Pretending otherwise in the code would be dishonest.
1944#[cfg(unix)]
1945fn fsync_dir_best_effort(path: &Path) {
1946    if let Err(e) = fsync_dir(path) {
1947        debug!("Directory flush of {} failed: {e}", path.display());
1948    }
1949}
1950
1951/// Flush a directory, reporting whether it worked.
1952///
1953/// Used where the answer is load-bearing: a chunk copied out of the legacy store is only
1954/// durable once its directory entry is, and that copy is what permits the legacy store to
1955/// be deleted.
1956#[cfg(unix)]
1957fn fsync_dir(path: &Path) -> std::io::Result<()> {
1958    File::open(path)?.sync_all()
1959}
1960
1961/// Off Unix there is no way to flush a directory through the standard library, so this
1962/// reports success without being able to promise anything.
1963///
1964/// That is why the publish path off Unix does not use a rename at all: it creates the
1965/// chunk under its final name and flushes the file, which Microsoft documents as flushing
1966/// the creation metadata with it. Directory creation has no equivalent, so the guarantee
1967/// there rests on the pre-retirement pass, which re-reads every chunk before the legacy
1968/// store is deleted, and on the operator gate that keeps retirement off a platform until
1969/// forced power loss has been shown to hold old-or-new on it.
1970///
1971/// Returns a `Result` so the callers that must handle a flush failure on Unix read the
1972/// same on every platform.
1973#[cfg(not(unix))]
1974#[allow(clippy::unnecessary_wraps)]
1975fn fsync_dir(_path: &Path) -> std::io::Result<()> {
1976    Ok(())
1977}
1978
1979/// No-op on platforms with no way to flush a directory handle.
1980#[cfg(not(unix))]
1981fn fsync_dir_best_effort(_path: &Path) {}
1982
1983/// Warn if the deepest chunk path this store can produce is close to `MAX_PATH`.
1984#[cfg(windows)]
1985fn check_path_budget(chunks_dir: &Path) {
1986    // Measured absolute, because that is what the filesystem sees. A relative root is the
1987    // case that still fails hard at MAX_PATH, since the standard library's long-path
1988    // handling only applies to paths it resolves as absolute.
1989    let absolute = if chunks_dir.is_absolute() {
1990        chunks_dir.to_path_buf()
1991    } else {
1992        std::env::current_dir()
1993            .map_or_else(|_| chunks_dir.to_path_buf(), |cwd| cwd.join(chunks_dir))
1994    };
1995    // `{chunks_dir}\{xy}\{64 hex}` — two separators, two shard characters, 64 name
1996    // characters.
1997    let deepest = absolute.as_os_str().len() + 1 + 2 + 1 + CHUNK_NAME_LEN;
1998    if deepest > WINDOWS_PATH_WARN_LEN {
1999        warn!(
2000            "Chunk file paths will be {deepest} characters, close to the {} character \
2001             Windows limit. Move the node root closer to the drive letter if writes start \
2002             failing.",
2003            WINDOWS_PATH_WARN_LEN
2004        );
2005    }
2006}
2007
2008/// No-op where path length is not a practical constraint.
2009#[cfg(not(windows))]
2010fn check_path_budget(_chunks_dir: &Path) {}
2011
2012/// Write `bytes` to `path` durably, for small metadata files outside the shard tree.
2013///
2014/// # Errors
2015///
2016/// Returns [`Error::Storage`] if the file cannot be written or published.
2017pub fn write_file_durably(path: &Path, bytes: &[u8]) -> Result<()> {
2018    write_file_atomic(path, bytes)
2019}
2020
2021/// Write `bytes` to `path` so a reader sees either the old content or the new.
2022/// Is this the exact name [`write_file_atomic`] gives its temporaries?
2023///
2024/// `.tmp.<pid>.<8 hex>.marker`, with both middle parts checked. Matching on the prefix and
2025/// suffix alone would also take `.tmp.operator-notes.marker`, and this runs over a
2026/// directory holding a node's data, so what it removes is not a place to be approximate.
2027fn is_marker_temp_name(name: &str) -> bool {
2028    let Some(rest) = name.strip_prefix(TEMP_PREFIX) else {
2029        return false;
2030    };
2031    let Some(rest) = rest.strip_suffix(".marker") else {
2032        return false;
2033    };
2034    let mut parts = rest.split('.');
2035    let (Some(pid), Some(nonce), None) = (parts.next(), parts.next(), parts.next()) else {
2036        return false;
2037    };
2038    !pid.is_empty()
2039        && pid.bytes().all(|b| b.is_ascii_digit())
2040        && nonce.len() == 8
2041        && nonce.bytes().all(|b| b.is_ascii_hexdigit())
2042}
2043
2044/// Remove marker temporaries a previous run left beside `path`.
2045///
2046/// [`write_file_atomic`] writes its temporary next to its target. For the layout marker
2047/// that is inside `chunks/`, which the startup scan sweeps; for the migration marker it is
2048/// the node root, which nothing sweeps, so a crash between the write and the rename leaves
2049/// one there for the life of the node. Each is a few hundred bytes, so this is inodes
2050/// rather than capacity, but nothing else was ever going to remove them.
2051///
2052/// Only the exact shape this module writes, and only files: a name has to carry the temp
2053/// prefix and the marker suffix. Anything broader would be this function deciding what
2054/// else in a node's root directory is rubbish, which is not its business.
2055///
2056/// Best effort throughout. Failing to tidy up is not a reason to refuse to start, and the
2057/// caller takes the store lock before this runs, so there is no other process whose live
2058/// temporary this could take.
2059pub(crate) fn sweep_marker_temps(dir: &Path) {
2060    let Ok(entries) = std::fs::read_dir(dir) else {
2061        return;
2062    };
2063    for entry in entries.flatten() {
2064        let name = entry.file_name();
2065        let Some(name) = name.to_str() else {
2066            continue;
2067        };
2068        if !is_marker_temp_name(name) {
2069            continue;
2070        }
2071        if !entry.file_type().is_ok_and(|kind| kind.is_file()) {
2072            continue;
2073        }
2074        match std::fs::remove_file(entry.path()) {
2075            Ok(()) => debug!(
2076                "Swept a leftover marker temporary {}",
2077                entry.path().display()
2078            ),
2079            Err(e) => debug!("Could not sweep {}: {e}", entry.path().display()),
2080        }
2081    }
2082}
2083
2084fn write_file_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
2085    let Some(dir) = path.parent() else {
2086        return Err(Error::Storage(format!(
2087            "Refusing to write {} — it has no parent directory",
2088            path.display()
2089        )));
2090    };
2091    let temp = dir.join(format!(
2092        "{TEMP_PREFIX}{}.{:08x}.marker",
2093        std::process::id(),
2094        rand::random::<u32>()
2095    ));
2096    write_temp(&temp, bytes)?;
2097    // Through the retry, because these small files (the layout marker, the migration
2098    // state) are rewritten while the node runs, and on Windows a scanner holding a handle
2099    // for a few milliseconds turns an ordinary rewrite into a hard failure.
2100    rename_with_retry(&temp, path).map_err(|e| {
2101        let _ = std::fs::remove_file(&temp);
2102        Error::Storage(format!("Failed to publish {}: {e}", path.display()))
2103    })?;
2104    fsync_dir_best_effort(dir);
2105    Ok(())
2106}
2107
2108/// Read the layout marker, writing the current one if the store is new.
2109fn read_or_write_layout(chunks_dir: &Path) -> Result<StoreLayout> {
2110    let path = chunks_dir.join(LAYOUT_FILE_NAME);
2111    match read_small_file(&path) {
2112        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| {
2113            Error::Storage(format!(
2114                "Chunk store layout marker {} is unreadable: {e}. Refusing to open rather \
2115                 than guess the layout.",
2116                path.display()
2117            ))
2118        }),
2119        Err(e) if e.kind() == ErrorKind::NotFound => {
2120            if store_has_entries(chunks_dir) {
2121                warn!(
2122                    "Chunk store at {} has data but no layout marker. Adopting it under \
2123                     the current scheme, which is the only one this build implements. If \
2124                     it was written by a build with a different layout its chunks will \
2125                     appear to be missing.",
2126                    chunks_dir.display()
2127                );
2128            }
2129            let layout = StoreLayout::default();
2130            let bytes = serde_json::to_vec_pretty(&layout)
2131                .map_err(|e| Error::Storage(format!("Failed to encode chunk store layout: {e}")))?;
2132            write_file_atomic(&path, &bytes)?;
2133            debug!("Wrote chunk store layout marker to {}", path.display());
2134            Ok(layout)
2135        }
2136        Err(e) => Err(Error::Storage(format!(
2137            "Failed to read chunk store layout marker {}: {e}",
2138            path.display()
2139        ))),
2140    }
2141}
2142
2143/// Whether the store directory already holds at least one shard.
2144fn store_has_entries(chunks_dir: &Path) -> bool {
2145    let Ok(entries) = std::fs::read_dir(chunks_dir) else {
2146        return false;
2147    };
2148    entries.filter_map(std::result::Result::ok).any(|e| {
2149        e.file_name()
2150            .to_str()
2151            .is_some_and(|n| n.len() == 2 && is_lower_hex(n))
2152    })
2153}
2154
2155/// Largest a metadata marker may be before it is treated as corrupt.
2156const MAX_MARKER_BYTES: u64 = 64 * 1024;
2157
2158/// Read a small metadata file, refusing an implausibly large one.
2159///
2160/// The chunk path is bounded for exactly this reason; the markers live in the same data
2161/// directory and deserve the same ceiling.
2162///
2163/// # Errors
2164///
2165/// Returns an I/O error, including `NotFound`, so callers can distinguish "no marker yet".
2166pub fn read_small_file(path: &Path) -> std::io::Result<Vec<u8>> {
2167    let file = File::open(path)?;
2168    let mut bytes = Vec::new();
2169    let read = file.take(MAX_MARKER_BYTES + 1).read_to_end(&mut bytes)?;
2170    if read as u64 > MAX_MARKER_BYTES {
2171        return Err(std::io::Error::other(format!(
2172            "{} is larger than the {MAX_MARKER_BYTES} byte limit for a marker file",
2173            path.display()
2174        )));
2175    }
2176    Ok(bytes)
2177}
2178
2179/// Take the store lock, or refuse to open the store.
2180///
2181/// Both failures are refusals, deliberately. Unlike LMDB, which was genuinely
2182/// multi-process safe, two of these stores on one directory keep independent in-memory
2183/// indices, independent views of what is in flight, and independent opinions about
2184/// whether the legacy environment may be deleted: both would report the same write as
2185/// new and each would keep serving keys the other had deleted. A node that cannot create
2186/// the lock file has no way to know it is alone, and this is the one migration where
2187/// being wrong about that destroys data.
2188///
2189/// The lock is an [`Arc`] so the work that relies on it can hold a lease. The startup
2190/// scan sweeps interrupted writes on the strength of being alone in the directory, and it
2191/// runs on a thread that outlives the future that started it.
2192///
2193/// # Errors
2194///
2195/// Returns [`Error::Storage`] when another process owns the directory, or when the lock
2196/// file cannot be created.
2197fn acquire_store_lock(chunks_dir: &Path) -> Result<Arc<File>> {
2198    let path = chunks_dir.join(LOCK_FILE_NAME);
2199    let file = match OpenOptions::new()
2200        .write(true)
2201        .create(true)
2202        .truncate(false)
2203        .open(&path)
2204    {
2205        Ok(f) => f,
2206        // Not a warning and carry on. Without this lock two processes can open the same
2207        // directory, each with its own index, its own view of what is in flight, and its
2208        // own opinion about whether the legacy environment may be deleted. A node that
2209        // cannot take it has no way to know it is alone, and this is the one migration
2210        // where being wrong about that destroys data.
2211        Err(e) => {
2212            return Err(Error::Storage(format!(
2213                "Could not create the chunk store lock {}: {e}. Refusing to start: \
2214                 without it this node cannot tell whether another is using the same data \
2215                 directory. Fix the permissions on that path, or remove a stale lock file \
2216                 left by a different user.",
2217                path.display()
2218            )))
2219        }
2220    };
2221    match file.try_lock_exclusive() {
2222        Ok(()) => Ok(Arc::new(file)),
2223        Err(e) => Err(Error::Storage(format!(
2224            "Another process already has the chunk store at {} open ({e}). Two nodes \
2225             cannot share one data directory: each keeps its own index and they would \
2226             disagree about what is stored. Stop the other node first.",
2227            chunks_dir.display()
2228        ))),
2229    }
2230}
2231
2232/// What a startup scan found.
2233struct ScanResult {
2234    /// Every published address, ascending.
2235    keys: Vec<XorName>,
2236    /// Which shard directories already exist.
2237    shards_present: [bool; SHARD_COUNT],
2238    /// Orphaned temp files removed.
2239    swept_temps: usize,
2240    /// Entries that were neither a chunk nor one of ours.
2241    skipped: usize,
2242}
2243
2244/// Rebuild the key set from directory entries.
2245///
2246/// Reads names only. A `stat` per entry costs about ten times the enumeration on Linux
2247/// and macOS and fifty to sixty times on Windows, and buys nothing: the filename is the
2248/// key, and the content is verified on read.
2249fn scan_store(chunks_dir: &Path) -> Result<ScanResult> {
2250    let mut result = ScanResult {
2251        keys: Vec::new(),
2252        shards_present: [false; SHARD_COUNT],
2253        swept_temps: 0,
2254        skipped: 0,
2255    };
2256
2257    let top = std::fs::read_dir(chunks_dir).map_err(|e| {
2258        Error::Storage(format!(
2259            "Failed to enumerate chunk store {}: {e}",
2260            chunks_dir.display()
2261        ))
2262    })?;
2263
2264    for entry in top {
2265        let entry = entry.map_err(|e| {
2266            Error::Storage(format!(
2267                "Failed to read an entry of {}: {e}",
2268                chunks_dir.display()
2269            ))
2270        })?;
2271        let name = entry.file_name();
2272        let Some(name) = name.to_str() else {
2273            result.skipped = result.skipped.saturating_add(1);
2274            continue;
2275        };
2276        if name == LAYOUT_FILE_NAME || name == LOCK_FILE_NAME {
2277            continue;
2278        }
2279        if name.starts_with(TEMP_PREFIX) {
2280            if sweep_temp(&entry.path()) {
2281                result.swept_temps = result.swept_temps.saturating_add(1);
2282            }
2283            continue;
2284        }
2285        if name.len() != 2 || !is_lower_hex(name) {
2286            warn!(
2287                "Chunk store: ignoring unexpected entry {name} in {}",
2288                chunks_dir.display()
2289            );
2290            result.skipped = result.skipped.saturating_add(1);
2291            continue;
2292        }
2293        let Ok(shard) = u8::from_str_radix(name, 16) else {
2294            result.skipped = result.skipped.saturating_add(1);
2295            continue;
2296        };
2297        // `shards_present` is set inside `scan_shard`, on success only. Setting it from
2298        // the name alone would make a stray regular file called `ab` look like a shard
2299        // that already exists, and every write to that shard would then fail with a
2300        // misleading error until the node was restarted.
2301        scan_shard(&entry.path(), shard, &mut result)?;
2302    }
2303
2304    result.keys.sort_unstable();
2305    result.keys.dedup();
2306    Ok(result)
2307}
2308
2309/// Scan one shard directory into `result`.
2310fn scan_shard(dir: &Path, shard: u8, result: &mut ScanResult) -> Result<()> {
2311    let entries = match std::fs::read_dir(dir) {
2312        Ok(e) => e,
2313        // A stray file named like a shard, or a directory removed between the two reads.
2314        // Neither is fatal, and neither marks the shard as present.
2315        Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => {
2316            warn!(
2317                "Chunk store: {} is not a shard directory ({e}); ignoring it",
2318                dir.display()
2319            );
2320            result.skipped = result.skipped.saturating_add(1);
2321            return Ok(());
2322        }
2323        // Anything else is a real fault: a permission problem, exhausted descriptors, or
2324        // failing hardware. Opening with a shard's worth of keys silently missing would
2325        // make the node under-claim in its published commitment and stop serving chunks
2326        // it still holds and is answerable for, so refuse to open at all.
2327        Err(e) => {
2328            return Err(Error::Storage(format!(
2329                "Failed to enumerate shard {}: {e}. Refusing to open with an incomplete \
2330                 key set.",
2331                dir.display()
2332            )))
2333        }
2334    };
2335    if let Some(slot) = result.shards_present.get_mut(shard as usize) {
2336        *slot = true;
2337    }
2338
2339    for entry in entries {
2340        let entry =
2341            entry.map_err(|e| Error::Storage(format!("Failed to read {}: {e}", dir.display())))?;
2342        let name = entry.file_name();
2343        let Some(name) = name.to_str() else {
2344            result.skipped = result.skipped.saturating_add(1);
2345            continue;
2346        };
2347        if name.starts_with(TEMP_PREFIX) {
2348            if sweep_temp(&entry.path()) {
2349                result.swept_temps = result.swept_temps.saturating_add(1);
2350            }
2351            continue;
2352        }
2353        let Some(key) = decode_chunk_name(name) else {
2354            if name.len() == CHUNK_NAME_LEN && is_hex_any_case(name) {
2355                // A case-folded twin of a real chunk name. On NTFS and default APFS the
2356                // existence check in the write path folds onto it, so a paid write would
2357                // be answered "already stored" and its bytes dropped. Move it aside.
2358                quarantine_entry(&entry.path());
2359            } else {
2360                warn!(
2361                    "Chunk store: ignoring non-chunk entry {name} in {}",
2362                    dir.display()
2363                );
2364            }
2365            result.skipped = result.skipped.saturating_add(1);
2366            continue;
2367        };
2368        // `file_type` comes from the directory entry itself on Linux and macOS and from
2369        // the enumeration on Windows, so this is not the per-entry `stat` the scan
2370        // deliberately avoids. A pipe, socket, device or directory wearing a chunk name
2371        // must never enter the index: nothing downstream can read it, and it would sit in
2372        // the published commitment forever.
2373        match entry.file_type() {
2374            Ok(kind) if kind.is_file() => {}
2375            Ok(_) => {
2376                warn!(
2377                    "Chunk store: {name} in {} is not a regular file; ignoring it",
2378                    dir.display()
2379                );
2380                result.skipped = result.skipped.saturating_add(1);
2381                continue;
2382            }
2383            // Not the same as knowing it is not a file. Treating an unanswered question
2384            // as a no would drop a real chunk from the index and from the commitment
2385            // while its bytes sit on disk, and the node would not serve it again until
2386            // some later restart happened to succeed. Fail the scan instead: an index
2387            // that is missing keys must never be published as this node's key set.
2388            Err(e) => {
2389                return Err(Error::Storage(format!(
2390                    "Could not tell what {name} in {} is: {e}. Refusing to publish an \
2391                     index that may be missing chunks.",
2392                    dir.display()
2393                )));
2394            }
2395        }
2396        // A file in the wrong shard is unreachable through `chunk_path`, so indexing it
2397        // would make the index claim a key the read path cannot find.
2398        if shard_index(&key) != shard as usize {
2399            warn!(
2400                "Chunk store: {name} is filed under shard {shard:02x} but belongs in {:02x}; \
2401                 ignoring it. Move it or delete it.",
2402                shard_index(&key)
2403            );
2404            result.skipped = result.skipped.saturating_add(1);
2405            continue;
2406        }
2407        result.keys.push(key);
2408    }
2409    Ok(())
2410}
2411
2412/// Remove one orphaned temp file. Returns whether it went.
2413///
2414/// Always removed. The scan that calls this runs only after the store lock has been taken,
2415/// so by then any temp file is an interrupted write of a previous run and there is no other
2416/// process that could be writing it. This used to describe a second, gentler mode for the
2417/// unlocked case; there was never any such branch and there is no caller that would need
2418/// one.
2419fn sweep_temp(path: &Path) -> bool {
2420    match std::fs::remove_file(path) {
2421        Ok(()) => {
2422            debug!("Removed orphaned temporary file {}", path.display());
2423            true
2424        }
2425        Err(e) => {
2426            debug!("Could not remove {}: {e}", path.display());
2427            false
2428        }
2429    }
2430}
2431
2432/// Open a chunk file, refusing anything that is not a regular file.
2433///
2434/// `Ok(None)` means the file is not there. A named pipe wearing a valid chunk name would
2435/// otherwise block the opening thread forever: `open` on a FIFO with no writer does not
2436/// return, and enough of them would exhaust the blocking pool and stall every file and
2437/// database operation in the process. `O_NOFOLLOW` refuses a symlink for the same reason,
2438/// and both are checked on the handle rather than the path, so nothing can be swapped
2439/// underneath between the check and the open.
2440fn open_regular(path: &Path) -> Result<Option<File>> {
2441    #[cfg(unix)]
2442    let opened = {
2443        use std::os::unix::fs::OpenOptionsExt;
2444        OpenOptions::new()
2445            .read(true)
2446            .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW)
2447            .open(path)
2448    };
2449    #[cfg(not(unix))]
2450    let opened = OpenOptions::new().read(true).open(path);
2451
2452    let file = match opened {
2453        Ok(f) => f,
2454        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
2455        Err(e) => {
2456            return Err(Error::Storage(format!(
2457                "Failed to open chunk file {}: {e}",
2458                path.display()
2459            )))
2460        }
2461    };
2462    let is_regular = file.metadata().is_ok_and(|m| m.file_type().is_file());
2463    if !is_regular {
2464        return Err(Error::Storage(format!(
2465            "{} is not a regular file; refusing to read it as a chunk",
2466            path.display()
2467        )));
2468    }
2469    Ok(Some(file))
2470}
2471
2472/// Read a chunk file, refusing anything larger than a chunk can legitimately be.
2473///
2474/// A corrupt, sparse, or locally planted file wearing a valid 64-hex name would
2475/// otherwise be read straight into memory, so a single bad entry could exhaust the node
2476/// during an ordinary GET or an audit response.
2477fn read_bounded(file: File, path: &Path) -> Result<Vec<u8>> {
2478    let ceiling = MAX_CHUNK_SIZE as u64;
2479    // Sized from the file, so a chunk lands in an exactly-sized buffer: grown from
2480    // empty, a full chunk ended in twice its size, held for as long as the bytes are
2481    // served or offered. Capped at the ceiling, so a planted oversized file still
2482    // cannot make this allocate more than a chunk up front.
2483    let expected = file.metadata().map_or(0, |m| m.len()).min(ceiling);
2484    let mut buf = Vec::with_capacity(usize::try_from(expected).unwrap_or(0));
2485    let read = file.take(ceiling + 1).read_to_end(&mut buf).map_err(|e| {
2486        Error::Storage(format!("Failed to read chunk file {}: {e}", path.display()))
2487    })?;
2488    if read as u64 > ceiling {
2489        return Err(Error::Storage(format!(
2490            "Chunk file {} is larger than the {ceiling} byte maximum; refusing to read it",
2491            path.display()
2492        )));
2493    }
2494    Ok(buf)
2495}
2496
2497/// Whether a Windows error is one a scanner or indexer holding a handle would produce.
2498///
2499/// `ERROR_ACCESS_DENIED`, `ERROR_SHARING_VIOLATION`, `ERROR_LOCK_VIOLATION`. Every other
2500/// failure is deterministic and retrying it only burns a blocking thread.
2501fn is_windows_sharing_violation(e: &std::io::Error) -> bool {
2502    matches!(e.raw_os_error(), Some(5 | 32 | 33))
2503}
2504
2505/// Publish `temp_path` as `final_path`, retrying a transient sharing violation.
2506///
2507/// On Windows an antivirus scanner or the search indexer can hold a handle to either
2508/// file for a few milliseconds after it is created, and `MoveFileEx` fails outright
2509/// rather than queueing. Retrying a bounded number of times turns that from a failed
2510/// write into a short pause. Every other error returns immediately.
2511pub(crate) fn rename_with_retry(temp_path: &Path, final_path: &Path) -> std::io::Result<()> {
2512    let mut last = match std::fs::rename(temp_path, final_path) {
2513        Ok(()) => return Ok(()),
2514        Err(e) => e,
2515    };
2516    if !cfg!(windows) || !is_windows_sharing_violation(&last) {
2517        return Err(last);
2518    }
2519    for attempt in 1..=RENAME_RETRY_ATTEMPTS {
2520        std::thread::sleep(RENAME_RETRY_BACKOFF * attempt);
2521        match std::fs::rename(temp_path, final_path) {
2522            Ok(()) => return Ok(()),
2523            Err(e) => last = e,
2524        }
2525    }
2526    Err(last)
2527}
2528
2529/// Write `payload` and publish it as `final_path`, replacing whatever is there.
2530///
2531/// Success here means the bytes are durable, not merely written. The repair path this
2532/// serves runs during the pre-retirement pass, where a chunk that fails to match its
2533/// address is rewritten from the legacy store and the legacy store is then deleted. A
2534/// replacement that a power loss can undo would leave that chunk with the wrong bytes and
2535/// no other copy.
2536fn write_and_replace(
2537    temp_path: &Path,
2538    final_path: &Path,
2539    payload: &[u8],
2540    shard: &Path,
2541) -> Result<()> {
2542    // Unix: an intra-directory rename is atomic, so a reader sees the old content or the
2543    // new one and never an absence, and the directory flush is what makes it durable.
2544    #[cfg(unix)]
2545    {
2546        write_temp(temp_path, payload)?;
2547        if let Err(e) = rename_with_retry(temp_path, final_path) {
2548            let _ = std::fs::remove_file(temp_path);
2549            return Err(Error::Storage(format!(
2550                "Failed to replace chunk {}: {e}",
2551                final_path.display()
2552            )));
2553        }
2554        fsync_dir(shard).map_err(|e| {
2555            Error::Storage(format!(
2556                "Replaced {} but could not flush {}: {e}. Not reporting the repair as \
2557                 done, because a rewrite that is not durable must not authorise deleting \
2558                 the copy it was rewritten from.",
2559                final_path.display(),
2560                shard.display()
2561            ))
2562        })?;
2563        Ok(())
2564    }
2565    // Everywhere else, Windows included: there is no way to flush a directory through the
2566    // standard library, so a rename cannot be shown to be durable at return. Overwriting
2567    // the existing file changes no directory entry at all, and `sync_all` (FlushFileBuffers
2568    // on Windows) is documented to flush the file's data, so a successful return is
2569    // durable under a documented contract.
2570    //
2571    // The cost is that this is not atomic: a crash part-way leaves the file holding a mix
2572    // of old and new bytes. That is safe here and only here, because the only caller that
2573    // matters runs before the legacy store is deleted, and a crash means no report was
2574    // produced and nothing was deleted. The next start re-reads the file, sees it does not
2575    // match its address, and repairs it again from the store that is still there.
2576    #[cfg(not(unix))]
2577    {
2578        let _ = temp_path;
2579        let _ = shard;
2580        let mut file = OpenOptions::new()
2581            .write(true)
2582            .truncate(true)
2583            .open(final_path)
2584            .map_err(|e| {
2585                Error::Storage(format!(
2586                    "Failed to open {} for replacement: {e}",
2587                    final_path.display()
2588                ))
2589            })?;
2590        file.write_all(payload).map_err(|e| {
2591            Error::Storage(format!("Failed to rewrite {}: {e}", final_path.display()))
2592        })?;
2593        file.sync_all().map_err(|e| {
2594            Error::Storage(format!(
2595                "Rewrote {} but could not flush it: {e}. Not reporting the repair as \
2596                 done, because a rewrite that is not durable must not authorise deleting \
2597                 the copy it was rewritten from.",
2598                final_path.display()
2599            ))
2600        })?;
2601        Ok(())
2602    }
2603}
2604
2605/// Create `temp_path`, write `payload` into it, and flush it.
2606///
2607/// Flushed before any rename. On ext4 `auto_da_alloc` only orders the data before the
2608/// rename's own commit; it does not make the data durable, and btrfs has been observed
2609/// reordering. A name must never become visible on bytes that are not on the platter.
2610fn write_temp(temp_path: &Path, payload: &[u8]) -> Result<()> {
2611    let mut f = OpenOptions::new()
2612        .write(true)
2613        .create_new(true)
2614        .open(temp_path)
2615        .map_err(|e| {
2616            Error::Storage(format!(
2617                "Failed to create temporary file {}: {e}",
2618                temp_path.display()
2619            ))
2620        })?;
2621    if let Err(e) = f.write_all(payload) {
2622        let _ = std::fs::remove_file(temp_path);
2623        return Err(Error::Storage(format!(
2624            "Failed to write {}: {e}",
2625            temp_path.display()
2626        )));
2627    }
2628    if let Err(e) = f.sync_all() {
2629        let _ = std::fs::remove_file(temp_path);
2630        return Err(Error::Storage(format!(
2631            "Failed to flush {}: {e}",
2632            temp_path.display()
2633        )));
2634    }
2635    Ok(())
2636}
2637
2638/// Write `payload` and publish it under `final_path`.
2639///
2640/// The temp lives in the destination directory, so the publish is an intra-directory
2641/// rename: atomic on every filesystem we support, and needing only that one directory
2642/// Put `payload` on disk as `final_path`, durably.
2643///
2644/// Returns [`PutOutcome::Duplicate`] when the name is already taken. The name is a hash
2645/// of the content, so that is not treated as proof the bytes are right: the caller
2646/// re-reads and verifies them.
2647#[cfg(unix)]
2648fn publish(
2649    temp_path: &Path,
2650    final_path: &Path,
2651    payload: &[u8],
2652    shard: &Path,
2653) -> std::result::Result<PutOutcome, PublishFailed> {
2654    // On Unix nothing is ever created under the final name by a failing path: the bytes go
2655    // to a temporary and only a successful rename gives them the real name. So every
2656    // failure here leaves the name as it found it.
2657    publish_via_rename(temp_path, final_path, payload, shard)
2658        .map_err(PublishFailed::nothing_written)
2659}
2660
2661/// Put `payload` on disk as `final_path`, durably. See [`publish_in_place`] for why this
2662/// takes a different route off Unix.
2663#[cfg(not(unix))]
2664fn publish(
2665    temp_path: &Path,
2666    final_path: &Path,
2667    payload: &[u8],
2668    shard: &Path,
2669) -> std::result::Result<PutOutcome, PublishFailed> {
2670    let _ = temp_path;
2671    let _ = shard;
2672    publish_in_place(final_path, payload)
2673}
2674
2675/// Create the chunk under its final name and flush it. Everywhere but Unix.
2676///
2677/// There is no way to flush a directory through the standard library, and Microsoft does
2678/// not document `MoveFileEx` as durable at return unless it is called with
2679/// `MOVEFILE_WRITE_THROUGH`, which std does not use. So off Unix a rename cannot be
2680/// relied on to have reached the disk before the legacy store is deleted.
2681///
2682/// Creating the file under its final name sidesteps the rename entirely. Microsoft
2683/// documents that creation metadata is cached and that `FlushFileBuffers`, which
2684/// `sync_all` calls on Windows, is the way to flush it. So a successful create, write and
2685/// flush is a durable publication under a documented contract, with no directory flush
2686/// and no rename involved.
2687///
2688/// The cost is that a crash mid-write leaves a partial file wearing a real chunk name.
2689/// That is why a duplicate re-reads and verifies rather than trusting the name, and why
2690/// the pre-retirement pass re-hashes everything before anything is deleted.
2691#[cfg(not(unix))]
2692fn publish_in_place(
2693    final_path: &Path,
2694    payload: &[u8],
2695) -> std::result::Result<PutOutcome, PublishFailed> {
2696    // Test-only, and here rather than after the write so that it means the same thing on
2697    // both platforms: the file half of a dual write has not happened yet. On Unix the
2698    // equivalent point is the temporary file written and the rename not yet made, which is
2699    // also before the chunk's name exists on disk. Stopping after the write instead would
2700    // put the file under its real name already, so a crash there is not between the two
2701    // halves at all, and it could not demonstrate anything about the missing flush either:
2702    // killing a process does not empty the page cache, so the bytes are still there to be
2703    // read. Only losing power loses them, which no test that kills a process can stage.
2704    #[cfg(any(test, feature = "test-utils"))]
2705    halt_here_if_asked(HALT_BEFORE_PUBLISH, final_path);
2706    let mut file = match OpenOptions::new()
2707        .write(true)
2708        .create_new(true)
2709        .open(final_path)
2710    {
2711        Ok(f) => f,
2712        // Someone got there first. Immutable content under a content-addressed name, so
2713        // the caller verifies what is already there rather than assuming it is right.
2714        Err(e) if e.kind() == ErrorKind::AlreadyExists => return Ok(PutOutcome::Duplicate),
2715        Err(e) => {
2716            // Nothing was created, so nothing was spent.
2717            return Err(PublishFailed::nothing_written(Error::Storage(format!(
2718                "Failed to create chunk {}: {e}",
2719                final_path.display()
2720            ))));
2721        }
2722    };
2723    if let Err(e) = file.write_all(payload) {
2724        drop(file);
2725        // Taken back if it can be. Whether it could is what the caller needs: the file
2726        // was created by this call, so if it is still there the space is spent.
2727        let left_behind = std::fs::remove_file(final_path).is_err();
2728        return Err(PublishFailed {
2729            error: Error::Storage(format!("Failed to write {}: {e}", final_path.display())),
2730            left_behind,
2731        });
2732    }
2733    if let Err(e) = file.sync_all() {
2734        drop(file);
2735        // Taken back if it can be. Whether it could is what the caller needs: the file
2736        // was created by this call, so if it is still there the space is spent.
2737        let left_behind = std::fs::remove_file(final_path).is_err();
2738        return Err(PublishFailed {
2739            error: Error::Storage(format!("Failed to flush {}: {e}", final_path.display())),
2740            left_behind,
2741        });
2742    }
2743    Ok(PutOutcome::New)
2744}
2745
2746/// Write a temp beside the target and rename it into place. Unix only.
2747///
2748/// Places the bytes and nothing more. Making the name durable is
2749/// [`flush_publication`]'s job, kept separate so a caller can tell a publish that spent no
2750/// space from one that spent it and could not be reported.
2751#[cfg(unix)]
2752fn publish_via_rename(
2753    temp_path: &Path,
2754    final_path: &Path,
2755    payload: &[u8],
2756    _shard: &Path,
2757) -> Result<PutOutcome> {
2758    // Content is immutable and the name is its hash, so an existing file already holds
2759    // exactly these bytes. Skipping the write is both cheaper and safer than replacing
2760    // it: on Windows a rename over a file another thread has open fails outright.
2761    //
2762    // The caller flushes either way. A name that is already there is not proof it is
2763    // durable:
2764    // the write that put it there may have been this store's own previous attempt, whose
2765    // rename landed and whose directory flush then failed. That attempt returned an
2766    // error, so nothing was retired on the strength of it, but if this call reported a
2767    // durable duplicate without flushing, the retry would silently launder an unflushed
2768    // rename into a copy that authorises deleting the last other one.
2769    let outcome = if final_path.exists() {
2770        PutOutcome::Duplicate
2771    } else {
2772        write_temp(temp_path, payload)?;
2773        // Test-only: the one moment a complete chunk exists on disk under a name nothing
2774        // looks for. A crash test needs to die at a named point rather than wherever a
2775        // sleep in another process happened to land.
2776        #[cfg(any(test, feature = "test-utils"))]
2777        halt_here_if_asked(HALT_BEFORE_PUBLISH, temp_path);
2778        match rename_with_retry(temp_path, final_path) {
2779            Ok(()) => PutOutcome::New,
2780            Err(e) => {
2781                let _ = std::fs::remove_file(temp_path);
2782                // Another writer of the same address won the race, or the destination was
2783                // open. Either way the bytes are already published.
2784                if !final_path.exists() {
2785                    return Err(Error::Storage(format!(
2786                        "Failed to publish chunk {}: {e}",
2787                        final_path.display()
2788                    )));
2789                }
2790                PutOutcome::Duplicate
2791            }
2792        }
2793    };
2794
2795    Ok(outcome)
2796}
2797
2798/// A publish that failed, and whether it left its bytes on the disk.
2799///
2800/// The second half is the point. A failure before anything was created has spent nothing;
2801/// one that created the file and then could not remove it again has spent the space, and
2802/// whoever is accounting for free space has to know which happened. Only the code that did
2803/// the creating can say.
2804struct PublishFailed {
2805    error: Error,
2806    left_behind: bool,
2807}
2808
2809impl PublishFailed {
2810    /// A failure that created nothing.
2811    fn nothing_written(error: Error) -> Self {
2812        Self {
2813            error,
2814            left_behind: false,
2815        }
2816    }
2817}
2818
2819/// Make a publication durable by flushing the directory its name lives in.
2820///
2821/// Separate from placing the bytes, because the caller has to tell the two failures apart.
2822/// A publish that fails before the bytes land has spent nothing; one that fails here has
2823/// spent the space and must not be reported as stored, so whoever is accounting for free
2824/// space has to charge it while whoever is accounting for chunks must not count it.
2825///
2826/// NOT best effort. The directory flush is what makes the rename durable, and a copy
2827/// reported successful is what authorises deleting the only other copy. Swallowing the
2828/// failure would let a power loss discard the directory entry after the legacy store had
2829/// already been removed.
2830///
2831/// # Errors
2832///
2833/// Returns [`Error::Storage`] if the directory cannot be flushed.
2834#[cfg(unix)]
2835fn flush_publication(final_path: &Path, shard: &Path) -> Result<()> {
2836    fsync_dir(shard).map_err(|e| {
2837        Error::Storage(format!(
2838            "Published {} but could not flush {}: {e}. Not reporting this chunk as stored, \
2839             because a copy that is not durable must not authorise deleting another.",
2840            final_path.display(),
2841            shard.display()
2842        ))
2843    })
2844}
2845
2846/// Nothing to do off Unix, where the chunk is created under its final name and flushed
2847/// with `sync_all`, which is documented to carry its creation metadata with it, and where
2848/// there is no way to flush a directory at all.
2849#[cfg(not(unix))]
2850fn flush_publication(_final_path: &Path, _shard: &Path) -> Result<()> {
2851    Ok(())
2852}
2853
2854#[cfg(test)]
2855#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2856mod tests {
2857    use super::*;
2858    use std::collections::HashSet;
2859
2860    /// A directory flush that fails must say so.
2861    ///
2862    /// The quiet version of this function is only used where the answer does not change
2863    /// what happens next. On the publish path it does.
2864    #[cfg(unix)]
2865    #[test]
2866    fn flushing_a_directory_that_is_not_there_reports_the_failure() {
2867        let dir = TempDir::new().expect("temp dir");
2868        assert!(fsync_dir(dir.path()).is_ok());
2869        assert!(fsync_dir(&dir.path().join("no-such-shard")).is_err());
2870    }
2871
2872    /// A chunk whose directory entry was never flushed is not reported as stored.
2873    ///
2874    /// This is the whole safety argument for retirement: the legacy store is deleted
2875    /// because every chunk was copied durably. A published file whose directory flush
2876    /// failed can vanish on power loss, so counting it as copied would lose data. The
2877    /// file staying on disk afterwards is fine, the next pass republishes it.
2878    #[cfg(unix)]
2879    #[test]
2880    fn a_publish_whose_directory_flush_fails_is_not_reported_as_stored() {
2881        let dir = TempDir::new().expect("temp dir");
2882        let temp_path = dir.path().join("chunk.tmp");
2883        let final_path = dir.path().join("chunk");
2884        let unflushable = dir.path().join("shard-that-does-not-exist");
2885
2886        // Asserted in two steps, not chained. Chaining them means a regression in placing
2887        // the bytes also produces an error, and the test passes without the flush ever
2888        // being reached: it would be checking that something went wrong rather than that
2889        // this went wrong.
2890        let placed = publish_via_rename(&temp_path, &final_path, b"payload", &unflushable);
2891        assert!(
2892            placed.is_ok(),
2893            "the bytes must be placed before this can be about the flush: {:?}",
2894            placed.err()
2895        );
2896        let outcome = flush_publication(&final_path, &unflushable);
2897
2898        assert!(
2899            outcome.is_err(),
2900            "an unflushed publication must not be reported as stored"
2901        );
2902        assert!(
2903            !temp_path.exists(),
2904            "the temp file must not be left behind either way"
2905        );
2906    }
2907
2908    use tempfile::TempDir;
2909
2910    /// Open a store on a fresh temp directory with the disk reserve disabled.
2911    async fn test_store() -> (FileStore, TempDir) {
2912        let dir = TempDir::new().expect("temp dir");
2913        let store = FileStore::new(FileStoreConfig {
2914            root_dir: dir.path().to_path_buf(),
2915            verify_on_read: true,
2916            disk_reserve: 0,
2917        })
2918        .await
2919        .expect("open store");
2920        (store, dir)
2921    }
2922
2923    /// Open a store on an existing directory, as a restart would.
2924    async fn reopen(dir: &TempDir) -> FileStore {
2925        FileStore::new(FileStoreConfig {
2926            root_dir: dir.path().to_path_buf(),
2927            verify_on_read: true,
2928            disk_reserve: 0,
2929        })
2930        .await
2931        .expect("reopen store")
2932    }
2933
2934    /// An ordinary read settles whether the node answers for a chunk.
2935    ///
2936    /// Not only the reads that were checking something. A read that failed means the
2937    /// chunk cannot be served, whoever asked; a read that worked means it can be. Deciding
2938    /// this anywhere else leaves a key stuck unadvertised after the fault has cleared, or
2939    /// advertised after it has not.
2940    #[cfg(unix)]
2941    #[tokio::test]
2942    async fn an_ordinary_read_decides_whether_the_node_answers_for_a_chunk() {
2943        use std::os::unix::fs::PermissionsExt;
2944
2945        let (store, dir) = test_store().await;
2946        let (addr, content) = addressed("read-decides");
2947        store.put(&addr, &content).await.expect("put");
2948        let path = store.chunk_path(&addr);
2949
2950        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
2951        perms.set_mode(0o000);
2952        std::fs::set_permissions(&path, perms).expect("chmod");
2953
2954        assert!(store.get(&addr).await.is_err(), "the read must fail");
2955        assert!(
2956            !store.exists(&addr).expect("exists"),
2957            "and a plain read that failed must stop the node answering for it"
2958        );
2959
2960        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
2961        perms.set_mode(0o600);
2962        std::fs::set_permissions(&path, perms).expect("chmod back");
2963
2964        assert_eq!(
2965            store.get(&addr).await.expect("get").expect("present"),
2966            content
2967        );
2968        assert!(
2969            store.exists(&addr).expect("exists"),
2970            "and a plain read that worked must start it answering again"
2971        );
2972        drop(dir);
2973    }
2974
2975    /// Two writes for one key: waiting means waiting for both.
2976    ///
2977    /// Cancellation releases the caller's lane while the blocking half survives, so a
2978    /// second write for the same key can start behind the first. If the registry only
2979    /// recorded that *something* was writing, whichever finished first would clear it and
2980    /// a delete would be told the key was free while the other was still queued, then be
2981    /// undone by it.
2982    #[tokio::test]
2983    async fn waiting_for_a_key_waits_for_every_write_of_it() {
2984        let (store, dir) = test_store().await;
2985        let store = Arc::new(store);
2986        let (addr, content) = addressed("two-writers");
2987
2988        // Two registrations, as two overlapping writes would make.
2989        let first = store.begin_write(&addr);
2990        let second = store.begin_write(&addr);
2991
2992        let waiting = {
2993            let store = Arc::clone(&store);
2994            tokio::spawn(async move { store.wait_for_write(&addr).await })
2995        };
2996        tokio::time::sleep(Duration::from_millis(50)).await;
2997        assert!(!waiting.is_finished());
2998
2999        // One finishes. The other has not, so the wait must continue.
3000        drop(first);
3001        tokio::time::sleep(Duration::from_millis(50)).await;
3002        assert!(
3003            !waiting.is_finished(),
3004            "one write finishing does not mean the key is free"
3005        );
3006
3007        drop(second);
3008        waiting
3009            .await
3010            .expect("the wait ends once both have finished");
3011
3012        // And the store is still usable afterwards.
3013        store.put(&addr, &content).await.expect("put");
3014        assert!(store.exists(&addr).expect("exists"));
3015        drop(dir);
3016    }
3017
3018    /// A chunk this store cannot read is kept but not claimed.
3019    ///
3020    /// Both halves matter. Deleting it, or dropping it from the index, is how a chunk ends
3021    /// up in neither this store's view nor the legacy one, which is what retirement
3022    /// destroys. Claiming it anyway puts the key in signed commitments and answers
3023    /// presence probes with a yes for a chunk the node cannot serve, and the audit that
3024    /// catches that still penalises.
3025    #[cfg(unix)]
3026    #[tokio::test]
3027    async fn a_chunk_that_cannot_be_read_is_kept_but_not_claimed() {
3028        use std::os::unix::fs::PermissionsExt;
3029
3030        let (store, dir) = test_store().await;
3031        let (addr, content) = addressed("unreadable-for-now");
3032        store.put(&addr, &content).await.expect("put");
3033        assert!(store.exists(&addr).expect("exists"));
3034
3035        let path = store.chunk_path(&addr);
3036        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
3037        perms.set_mode(0o000);
3038        std::fs::set_permissions(&path, perms).expect("chmod");
3039
3040        // Offering the same bytes again must not be acknowledged, and must not replace
3041        // what is there on the strength of a read that did not happen.
3042        assert!(
3043            store.put(&addr, &content).await.is_err(),
3044            "an unreadable chunk must not be reported as stored"
3045        );
3046        assert!(path.exists(), "and the file must be left alone");
3047        assert!(
3048            !store.exists(&addr).expect("exists"),
3049            "but the node must stop claiming it"
3050        );
3051        assert!(!store.all_keys().await.expect("keys").contains(&addr));
3052
3053        // Readable again: the node answers for it once more.
3054        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
3055        perms.set_mode(0o600);
3056        std::fs::set_permissions(&path, perms).expect("chmod back");
3057        assert!(!store.put(&addr, &content).await.expect("put again"));
3058        assert!(store.exists(&addr).expect("exists"));
3059        assert!(store.all_keys().await.expect("keys").contains(&addr));
3060        drop(dir);
3061    }
3062
3063    /// Content plus the address it hashes to.
3064    fn addressed(seed: &str) -> (XorName, Vec<u8>) {
3065        let content = format!("chunk-content-{seed}").into_bytes();
3066        (crate::client::compute_address(&content), content)
3067    }
3068
3069    #[tokio::test]
3070    async fn put_then_get_returns_the_same_bytes() {
3071        let (store, _dir) = test_store().await;
3072        let (addr, content) = addressed("a");
3073
3074        assert!(store.put(&addr, &content).await.expect("put"));
3075        let got = store.get(&addr).await.expect("get").expect("present");
3076        assert_eq!(got, content);
3077    }
3078
3079    #[tokio::test]
3080    async fn a_second_put_of_the_same_chunk_reports_not_new() {
3081        let (store, _dir) = test_store().await;
3082        let (addr, content) = addressed("b");
3083
3084        assert!(store.put(&addr, &content).await.expect("first put"));
3085        assert!(!store.put(&addr, &content).await.expect("second put"));
3086        assert_eq!(store.current_chunks().expect("count"), 1);
3087        assert_eq!(store.stats().duplicates, 1);
3088    }
3089
3090    #[tokio::test]
3091    async fn get_of_an_unknown_address_is_none() {
3092        let (store, _dir) = test_store().await;
3093        let (addr, _) = addressed("missing");
3094        assert!(store.get(&addr).await.expect("get").is_none());
3095    }
3096
3097    #[tokio::test]
3098    async fn exists_tracks_the_store() {
3099        let (store, _dir) = test_store().await;
3100        let (addr, content) = addressed("c");
3101
3102        assert!(!store.exists(&addr).expect("exists"));
3103        store.put(&addr, &content).await.expect("put");
3104        assert!(store.exists(&addr).expect("exists"));
3105        store.delete(&addr).await.expect("delete");
3106        assert!(!store.exists(&addr).expect("exists"));
3107    }
3108
3109    #[tokio::test]
3110    async fn delete_unlinks_the_file_and_returns_the_space() {
3111        let (store, _dir) = test_store().await;
3112        let (addr, content) = addressed("d");
3113        store.put(&addr, &content).await.expect("put");
3114
3115        let path = store.chunk_path(&addr);
3116        assert!(path.exists(), "the chunk file should be on disk");
3117
3118        assert!(store.delete(&addr).await.expect("delete"));
3119        assert!(!path.exists(), "delete must actually unlink the file");
3120        assert_eq!(store.current_chunks().expect("count"), 0);
3121
3122        // Deleting again is a no-op that reports nothing was there.
3123        assert!(!store.delete(&addr).await.expect("second delete"));
3124    }
3125
3126    #[tokio::test]
3127    async fn content_that_does_not_hash_to_its_address_is_rejected() {
3128        let (store, _dir) = test_store().await;
3129        let (addr, _) = addressed("e");
3130        let err = store
3131            .put(&addr, b"different content")
3132            .await
3133            .expect_err("must reject");
3134        assert!(
3135            format!("{err}").contains("Content address mismatch"),
3136            "unexpected error: {err}"
3137        );
3138        assert_eq!(store.current_chunks().expect("count"), 0);
3139    }
3140
3141    #[tokio::test]
3142    async fn a_chunk_is_filed_under_the_last_two_hex_characters_of_its_address() {
3143        let (store, dir) = test_store().await;
3144        let (addr, content) = addressed("f");
3145        store.put(&addr, &content).await.expect("put");
3146
3147        let name = hex::encode(addr);
3148        let expected_shard = name
3149            .get(name.len() - 2..)
3150            .expect("64-character name")
3151            .to_string();
3152        let path = dir
3153            .path()
3154            .join(CHUNKS_DIR_NAME)
3155            .join(&expected_shard)
3156            .join(&name);
3157        assert!(path.exists(), "expected the chunk at {}", path.display());
3158    }
3159
3160    #[tokio::test]
3161    async fn the_index_is_rebuilt_from_the_filesystem_on_restart() {
3162        let (store, dir) = test_store().await;
3163        let mut written = Vec::new();
3164        for i in 0..64 {
3165            let (addr, content) = addressed(&format!("restart-{i}"));
3166            store.put(&addr, &content).await.expect("put");
3167            written.push(addr);
3168        }
3169        drop(store);
3170
3171        let reopened = reopen(&dir).await;
3172        assert_eq!(reopened.current_chunks().expect("count"), 64);
3173        for addr in &written {
3174            assert!(reopened.exists(addr).expect("exists"), "lost a key");
3175        }
3176    }
3177
3178    #[tokio::test]
3179    async fn all_keys_is_sorted_ascending() {
3180        let (store, dir) = test_store().await;
3181        for i in 0..128 {
3182            let (addr, content) = addressed(&format!("sorted-{i}"));
3183            store.put(&addr, &content).await.expect("put");
3184        }
3185
3186        let keys = store.all_keys().await.expect("all_keys");
3187        let mut sorted = keys.clone();
3188        sorted.sort_unstable();
3189        assert_eq!(keys, sorted, "all_keys() must be ordered");
3190
3191        // And the order has to survive a restart, because the commitment builder
3192        // truncates the responsible subset before the Merkle tree sorts it.
3193        drop(store);
3194        let reopened = reopen(&dir).await;
3195        assert_eq!(reopened.all_keys().await.expect("all_keys"), keys);
3196    }
3197
3198    #[tokio::test]
3199    async fn get_raw_skips_verification() {
3200        let (store, _dir) = test_store().await;
3201        let (addr, content) = addressed("raw");
3202        store.put(&addr, &content).await.expect("put");
3203
3204        // Corrupt the file behind the store's back.
3205        std::fs::write(store.chunk_path(&addr), b"tampered").expect("tamper");
3206
3207        let raw = store.get_raw(&addr).await.expect("get_raw").expect("bytes");
3208        assert_eq!(raw, b"tampered");
3209    }
3210
3211    /// A full-size chunk reads into an exactly-sized buffer, verified or raw.
3212    #[tokio::test]
3213    async fn reads_allocate_exactly_the_chunk() {
3214        let (store, _dir) = test_store().await;
3215        let content: Vec<u8> = (0..=u8::MAX).cycle().take(MAX_CHUNK_SIZE).collect();
3216        let addr = crate::client::compute_address(&content);
3217        store.put(&addr, &content).await.expect("put");
3218
3219        let verified = store.get(&addr).await.expect("get").expect("bytes");
3220        assert_eq!(verified, content);
3221        assert_eq!(verified.capacity(), MAX_CHUNK_SIZE);
3222        let raw = store.get_raw(&addr).await.expect("get_raw").expect("bytes");
3223        assert_eq!(raw.capacity(), MAX_CHUNK_SIZE);
3224    }
3225
3226    /// A put whose caller goes away does not admit a key on bytes nothing has read.
3227    ///
3228    /// The blocking half of a put outlives the future that started it, deliberately, so
3229    /// the work is never left half done. That makes anything it writes to memory a claim
3230    /// the node keeps whether or not the caller is still there to finish checking it.
3231    ///
3232    /// For a chunk this call published the claim is earned: the bytes were hashed against
3233    /// their own name on the way in. For a name that was already taken it is not. The
3234    /// check that decides whether those bytes are good runs after the await, and a dropped
3235    /// future skips it, so admitting the key in the closure claims a chunk nobody read.
3236    ///
3237    /// Staged with a fifo, which is the sharpest case and a real one: the startup scan
3238    /// refuses non-regular entries by design, so this is a key the store has already
3239    /// decided it must not claim, walked in through the back door.
3240    #[cfg(unix)]
3241    #[tokio::test]
3242    // The gate is held across an await deliberately: holding it is what parks the put
3243    // inside its closure, which is the state under test. Dropping it before awaiting would
3244    // let the put finish and there would be nothing to cancel.
3245    #[allow(clippy::await_holding_lock)]
3246    async fn a_cancelled_put_does_not_admit_a_key_whose_bytes_were_never_read() {
3247        let dir = TempDir::new().expect("temp dir");
3248        let store = Arc::new(reopen(&dir).await);
3249
3250        // A name a real chunk would use, wearing something that is not a chunk.
3251        let content = b"the bytes that belong under this name".to_vec();
3252        let addr = crate::client::compute_address(&content);
3253        let shard = dir
3254            .path()
3255            .join(CHUNKS_DIR_NAME)
3256            .join(format!("{:02x}", addr[31]));
3257        std::fs::create_dir_all(&shard).expect("mkdir");
3258        let path = shard.join(hex::encode(addr));
3259        let name = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
3260            .expect("a path with no interior nul");
3261        // SAFETY: `name` is a valid NUL-terminated C string that outlives the call, and the
3262        // mode is a constant. `mkfifo` reads the pointer and returns; nothing is retained.
3263        #[allow(clippy::undocumented_unsafe_blocks, unsafe_code)]
3264        let made = unsafe { libc::mkfifo(name.as_ptr(), 0o644) };
3265        assert_eq!(made, 0, "could not make the fifo this test needs");
3266
3267        // Hold the gate so the put parks inside the closure, then drop the future while it
3268        // is parked. That is a caller going away mid-put, which is what a cancelled
3269        // request, a client disconnect or a shutdown all look like from in here.
3270        let gate = store.test_put_gate();
3271        let held = gate.write();
3272        let put = {
3273            let store = Arc::clone(&store);
3274            let content = content.clone();
3275            tokio::spawn(async move { store.put(&addr, &content).await })
3276        };
3277        // Waited for rather than slept at. A sleep proves nothing: if the put had not
3278        // reached the gated closure yet, aborting would cancel it before it ever got
3279        // there and the test would pass having staged nothing.
3280        let deadline = std::time::Instant::now() + Duration::from_secs(30);
3281        while store.tasks_in_flight() == 0 {
3282            assert!(
3283                std::time::Instant::now() < deadline,
3284                "the put never reached the closure, so there was nothing to cancel"
3285            );
3286            tokio::time::sleep(Duration::from_millis(5)).await;
3287        }
3288        put.abort();
3289        let _ = put.await;
3290        drop(held);
3291        store.wait_idle().await;
3292
3293        assert!(
3294            !store.is_indexed(&addr),
3295            "a cancelled put admitted {} on bytes nothing read; the fifo under that name \
3296             would then be advertised, committed to, and audited against",
3297            hex::encode(addr)
3298        );
3299        assert!(
3300            !store.exists(&addr).unwrap_or(true),
3301            "and the node must not claim it either"
3302        );
3303    }
3304
3305    /// A marker temporary left in the node root is swept, and nothing else is.
3306    ///
3307    /// The migration marker is written next to itself in the root, which no sweep looked
3308    /// at, so a crash between its write and its rename left one there for the life of the
3309    /// node. Small, but nothing was ever going to remove it.
3310    ///
3311    /// The second half is the point: this runs over a directory holding a node's data, so
3312    /// it has to take only the exact shape this module writes and leave everything else
3313    /// where it is.
3314    #[tokio::test]
3315    async fn a_leftover_marker_temporary_is_swept_and_its_neighbours_are_not() {
3316        let dir = TempDir::new().expect("temp dir");
3317        let root = dir.path();
3318        let leftover = root.join(format!("{TEMP_PREFIX}1234.abcdef01.marker"));
3319        std::fs::write(&leftover, b"an interrupted marker write").expect("plant");
3320
3321        // Things that must survive: the marker itself, a chunk-shaped temp that belongs to
3322        // the chunk tree's own sweep, and anything an operator put there.
3323        let keep = [
3324            root.join("migration-state.json"),
3325            root.join(format!("{TEMP_PREFIX}1234.abcdef01.chunk")),
3326            root.join("notes.txt"),
3327            // Prefix and suffix alone would take these. The pid and the nonce are checked
3328            // because this runs over a directory holding a node's data.
3329            root.join(format!("{TEMP_PREFIX}operator-notes.marker")),
3330            root.join(format!("{TEMP_PREFIX}1234.nothex01.marker")),
3331            root.join(format!("{TEMP_PREFIX}1234.abcdef0.marker")),
3332            root.join(format!("{TEMP_PREFIX}1234.abcdef01.extra.marker")),
3333        ];
3334        for path in &keep {
3335            std::fs::write(path, b"keep me").expect("plant");
3336        }
3337
3338        let store = reopen(&dir).await;
3339        drop(store);
3340
3341        assert!(
3342            !leftover.exists(),
3343            "the leftover marker temporary is still in the node root"
3344        );
3345        for path in &keep {
3346            assert!(
3347                path.exists(),
3348                "{} was swept and should not have been",
3349                path.display()
3350            );
3351        }
3352    }
3353
3354    #[tokio::test]
3355    async fn a_corrupt_chunk_is_removed_so_replication_can_repair_it() {
3356        let (store, _dir) = test_store().await;
3357        let (addr, content) = addressed("corrupt");
3358        store.put(&addr, &content).await.expect("put");
3359        std::fs::write(store.chunk_path(&addr), b"tampered").expect("tamper");
3360
3361        let err = store.get(&addr).await.expect_err("verification must fail");
3362        assert!(format!("{err}").contains("verification failed"), "{err}");
3363
3364        assert!(!store.chunk_path(&addr).exists(), "corrupt file must go");
3365        assert!(!store.exists(&addr).expect("exists"));
3366        assert!(
3367            !store.all_keys().await.expect("all_keys").contains(&addr),
3368            "a corrupt chunk must stop being advertised"
3369        );
3370        assert_eq!(store.stats().verification_failures, 1);
3371    }
3372
3373    #[tokio::test]
3374    async fn a_file_removed_underneath_the_store_drops_out_of_the_index() {
3375        let (store, _dir) = test_store().await;
3376        let (addr, content) = addressed("vanished");
3377        store.put(&addr, &content).await.expect("put");
3378
3379        std::fs::remove_file(store.chunk_path(&addr)).expect("remove behind our back");
3380
3381        assert!(store.get(&addr).await.expect("get").is_none());
3382        assert!(!store.exists(&addr).expect("exists"));
3383        assert_eq!(store.current_chunks().expect("count"), 0);
3384    }
3385
3386    #[tokio::test]
3387    async fn interrupted_writes_are_swept_at_startup() {
3388        let (store, dir) = test_store().await;
3389        let (addr, content) = addressed("sweep");
3390        store.put(&addr, &content).await.expect("put");
3391        let shard = store
3392            .chunk_path(&addr)
3393            .parent()
3394            .expect("shard")
3395            .to_path_buf();
3396        drop(store);
3397
3398        let orphan = shard.join(format!("{TEMP_PREFIX}999.7"));
3399        std::fs::write(&orphan, b"half a chunk").expect("write orphan");
3400        let stray_root = dir
3401            .path()
3402            .join(CHUNKS_DIR_NAME)
3403            .join(format!("{TEMP_PREFIX}999.8"));
3404        std::fs::write(&stray_root, b"half a marker").expect("write stray");
3405
3406        let reopened = reopen(&dir).await;
3407        assert!(!orphan.exists(), "an interrupted write must not survive");
3408        assert!(!stray_root.exists(), "nor one at the store root");
3409        assert_eq!(reopened.current_chunks().expect("count"), 1);
3410    }
3411
3412    #[tokio::test]
3413    async fn concurrent_writers_of_one_address_store_it_exactly_once() {
3414        let (store, _dir) = test_store().await;
3415        let store = Arc::new(store);
3416        let (addr, content) = addressed("racing");
3417
3418        let mut tasks = Vec::new();
3419        for _ in 0..16 {
3420            let store = Arc::clone(&store);
3421            let content = content.clone();
3422            tasks.push(tokio::spawn(
3423                async move { store.put(&addr, &content).await },
3424            ));
3425        }
3426
3427        let mut new_count = 0;
3428        for task in tasks {
3429            if task.await.expect("join").expect("put") {
3430                new_count += 1;
3431            }
3432        }
3433        assert_eq!(new_count, 1, "exactly one writer may report a new chunk");
3434        assert_eq!(store.current_chunks().expect("count"), 1);
3435        assert_eq!(
3436            store.get(&addr).await.expect("get").expect("present"),
3437            content
3438        );
3439    }
3440
3441    #[tokio::test]
3442    async fn names_that_are_not_lowercase_hex_are_ignored_by_the_scan() {
3443        let (store, dir) = test_store().await;
3444        let (addr, content) = addressed("scan");
3445        store.put(&addr, &content).await.expect("put");
3446        let shard = store
3447            .chunk_path(&addr)
3448            .parent()
3449            .expect("shard")
3450            .to_path_buf();
3451        drop(store);
3452
3453        // Uppercase is deliberately rejected: on a case-folding filesystem accepting it
3454        // would let one file answer to two index entries.
3455        let upper = shard.join(hex::encode_upper(addressed("upper").0));
3456        std::fs::write(&upper, b"x").expect("write upper");
3457        std::fs::write(shard.join("not-a-chunk"), b"x").expect("write junk");
3458        std::fs::write(shard.join("deadbeef"), b"x").expect("write short");
3459
3460        let reopened = reopen(&dir).await;
3461        assert_eq!(reopened.current_chunks().expect("count"), 1);
3462    }
3463
3464    #[tokio::test]
3465    async fn a_chunk_filed_in_the_wrong_shard_is_not_indexed() {
3466        let (store, dir) = test_store().await;
3467        let (addr, content) = addressed("misfiled");
3468        store.put(&addr, &content).await.expect("put");
3469        drop(store);
3470
3471        // Move it one shard over: the read path would never find it there, so indexing
3472        // it would make the store advertise a key it cannot serve.
3473        let correct = dir
3474            .path()
3475            .join(CHUNKS_DIR_NAME)
3476            .join(shard_name(&addr))
3477            .join(hex::encode(addr));
3478        let wrong_shard_index = (shard_index(&addr) + 1) % SHARD_COUNT;
3479        let wrong_dir = dir
3480            .path()
3481            .join(CHUNKS_DIR_NAME)
3482            .join(format!("{wrong_shard_index:02x}"));
3483        std::fs::create_dir_all(&wrong_dir).expect("mkdir");
3484        std::fs::rename(&correct, wrong_dir.join(hex::encode(addr))).expect("misfile");
3485
3486        let reopened = reopen(&dir).await;
3487        assert_eq!(reopened.current_chunks().expect("count"), 0);
3488        assert!(!reopened.exists(&addr).expect("exists"));
3489    }
3490
3491    #[tokio::test]
3492    async fn the_layout_marker_is_written_once_and_checked_on_reopen() {
3493        let (store, dir) = test_store().await;
3494        drop(store);
3495
3496        let marker = dir.path().join(CHUNKS_DIR_NAME).join(LAYOUT_FILE_NAME);
3497        let layout: StoreLayout =
3498            serde_json::from_slice(&std::fs::read(&marker).expect("read marker"))
3499                .expect("parse marker");
3500        assert_eq!(layout, StoreLayout::default());
3501
3502        // A store written by a future build must be refused, not misread.
3503        let future = StoreLayout {
3504            schema: LAYOUT_SCHEMA + 1,
3505            ..StoreLayout::default()
3506        };
3507        std::fs::write(&marker, serde_json::to_vec(&future).expect("encode")).expect("write");
3508        let err = FileStore::new(FileStoreConfig {
3509            root_dir: dir.path().to_path_buf(),
3510            verify_on_read: true,
3511            disk_reserve: 0,
3512        })
3513        .await
3514        .expect_err("must refuse a newer layout");
3515        assert!(format!("{err}").contains("newer than this build"), "{err}");
3516    }
3517
3518    #[tokio::test]
3519    async fn an_unknown_shard_scheme_is_refused() {
3520        let (store, dir) = test_store().await;
3521        drop(store);
3522        let marker = dir.path().join(CHUNKS_DIR_NAME).join(LAYOUT_FILE_NAME);
3523        let other = StoreLayout {
3524            scheme: "prefix-hex".to_string(),
3525            ..StoreLayout::default()
3526        };
3527        std::fs::write(&marker, serde_json::to_vec(&other).expect("encode")).expect("write");
3528        let err = FileStore::new(FileStoreConfig {
3529            root_dir: dir.path().to_path_buf(),
3530            verify_on_read: true,
3531            disk_reserve: 0,
3532        })
3533        .await
3534        .expect_err("must refuse an unknown scheme");
3535        assert!(format!("{err}").contains("shard scheme"), "{err}");
3536    }
3537
3538    #[tokio::test]
3539    async fn writes_are_refused_when_the_disk_reserve_cannot_be_met() {
3540        let dir = TempDir::new().expect("temp dir");
3541        let store = FileStore::new(FileStoreConfig {
3542            root_dir: dir.path().to_path_buf(),
3543            verify_on_read: true,
3544            disk_reserve: u64::MAX / 2,
3545        })
3546        .await
3547        .expect("open store");
3548
3549        let (addr, content) = addressed("full");
3550        let err = store.put(&addr, &content).await.expect_err("must refuse");
3551        assert!(
3552            format!("{err}").contains("Insufficient disk space"),
3553            "{err}"
3554        );
3555        assert!(store.check_capacity().is_err());
3556    }
3557
3558    #[tokio::test]
3559    async fn capacity_is_size_aware() {
3560        // Wide enough that a test running alongside this one cannot move the answer.
3561        const MARGIN: u64 = 512 * 1024 * 1024;
3562
3563        let dir = TempDir::new().expect("temp dir");
3564        let available = fs2::available_space(dir.path()).expect("free space");
3565        // A reserve that leaves room for a small write but not a huge one. This is the
3566        // whole reason the predicate takes a size: free bytes alone stopped being a
3567        // sufficient answer once chunks became files.
3568        let store = FileStore::new(FileStoreConfig {
3569            root_dir: dir.path().to_path_buf(),
3570            verify_on_read: true,
3571            disk_reserve: available.saturating_sub(MARGIN),
3572        })
3573        .await
3574        .expect("open store");
3575
3576        assert!(store.check_capacity_for(1024).is_ok());
3577        assert!(store.check_capacity_for(4 * MARGIN).is_err());
3578    }
3579
3580    #[test]
3581    fn suffix_shards_stay_uniform_for_a_close_group_of_keys() {
3582        // The real distribution: a node holds keys it is closest to, so they share a
3583        // long leading prefix with its own ID. Sharding on that prefix collapses to one
3584        // directory. The trailing byte is untouched by close-group membership.
3585        let mut prefix_dirs = HashSet::new();
3586        let mut suffix_dirs = HashSet::new();
3587        for i in 0u32..4096 {
3588            let mut key = [0u8; XORNAME_LEN];
3589            // 20 shared leading bits, as a ~1M-node network would impose.
3590            let tail = crate::client::compute_address(&i.to_le_bytes());
3591            key.copy_from_slice(&tail);
3592            if let Some(b) = key.first_mut() {
3593                *b = 0xab;
3594            }
3595            if let Some(b) = key.get_mut(1) {
3596                *b = 0xcd;
3597            }
3598            if let Some(b) = key.get_mut(2) {
3599                *b &= 0x0f;
3600            }
3601            prefix_dirs.insert(key.first().copied().unwrap_or(0));
3602            suffix_dirs.insert(shard_index(&key));
3603        }
3604        assert_eq!(
3605            prefix_dirs.len(),
3606            1,
3607            "prefix sharding collapses for a node's own holdings"
3608        );
3609        assert!(
3610            suffix_dirs.len() > 250,
3611            "suffix sharding must stay uniform, got {} of 256 directories",
3612            suffix_dirs.len()
3613        );
3614    }
3615
3616    #[test]
3617    fn no_chunk_filename_can_spell_a_reserved_windows_device_name() {
3618        // Hex has no `n`, `u`, `x`, `p`, `r`, `l`, `t`, `o` or `s`, so `CON`, `NUL`,
3619        // `AUX`, `PRN`, `COM1` and `LPT1` are all unspellable at any length. This is why
3620        // the encoding is hex and not base32 or base64url.
3621        for reserved in ["con", "prn", "aux", "nul", "com1", "com9", "lpt1", "lpt9"] {
3622            assert!(
3623                !is_lower_hex(reserved),
3624                "{reserved} must not be a valid chunk or shard name"
3625            );
3626        }
3627    }
3628
3629    #[test]
3630    fn only_full_length_lowercase_hex_decodes_to_an_address() {
3631        // 0xab so the hex form actually contains letters, which is where case matters.
3632        assert!(decode_chunk_name(&hex::encode([0xabu8; XORNAME_LEN])).is_some());
3633        assert!(decode_chunk_name(&hex::encode_upper([0xabu8; XORNAME_LEN])).is_none());
3634        assert!(decode_chunk_name("deadbeef").is_none());
3635        assert!(decode_chunk_name("").is_none());
3636        assert!(decode_chunk_name(&"g".repeat(CHUNK_NAME_LEN)).is_none());
3637    }
3638
3639    #[tokio::test]
3640    async fn repair_replaces_bad_bytes_without_the_file_ever_being_absent() {
3641        let (store, _dir) = test_store().await;
3642        let (addr, content) = addressed("repairable");
3643        store.put(&addr, &content).await.expect("put");
3644        let path = store.chunk_path(&addr);
3645
3646        std::fs::write(&path, b"rotted").expect("corrupt");
3647        store.repair(&addr, &content).await.expect("repair");
3648
3649        assert_eq!(
3650            store.get(&addr).await.expect("get").expect("present"),
3651            content
3652        );
3653        assert!(store.exists(&addr).expect("exists"));
3654    }
3655
3656    #[tokio::test]
3657    async fn a_repair_with_the_wrong_bytes_is_refused_and_changes_nothing() {
3658        let (store, _dir) = test_store().await;
3659        let (addr, content) = addressed("guarded");
3660        store.put(&addr, &content).await.expect("put");
3661        let path = store.chunk_path(&addr);
3662
3663        // The whole point of repairing in place is that a failure must leave the old file
3664        // where it was. Deleting first and writing after would open a window whose only
3665        // surviving copy is the one the caller is about to destroy.
3666        let err = store
3667            .repair(&addr, b"not this chunk")
3668            .await
3669            .expect_err("must refuse");
3670        assert!(format!("{err}").contains("Refusing to repair"), "{err}");
3671        assert!(
3672            path.exists(),
3673            "the existing file must survive a refused repair"
3674        );
3675        assert_eq!(
3676            store.get(&addr).await.expect("get").expect("present"),
3677            content
3678        );
3679    }
3680
3681    #[tokio::test]
3682    async fn a_chunk_can_be_deleted_and_stored_again() {
3683        let (store, _dir) = test_store().await;
3684        let (addr, content) = addressed("cycle");
3685
3686        assert!(store.put(&addr, &content).await.expect("put"));
3687        assert!(store.delete(&addr).await.expect("delete"));
3688        assert!(
3689            store.put(&addr, &content).await.expect("re-put"),
3690            "a re-stored chunk is new again"
3691        );
3692        assert_eq!(
3693            store.get(&addr).await.expect("get").expect("present"),
3694            content
3695        );
3696    }
3697
3698    /// Write a chunk file straight into its shard, the way an existing store already
3699    /// contains thousands of them. Bypasses the write path deliberately: this exercises
3700    /// the startup scan, not `put`.
3701    fn plant(chunks_dir: &Path, key: &XorName) {
3702        let dir = chunks_dir.join(shard_name(key));
3703        std::fs::create_dir_all(&dir).expect("mkdir");
3704        std::fs::write(dir.join(hex::encode(key)), key).expect("plant");
3705    }
3706
3707    #[tokio::test]
3708    async fn a_populated_and_churned_store_scans_correctly_at_scale() {
3709        // Every shard populated, then aged the way a long-lived node ages: some keys
3710        // deleted, others added in their place, so the directories carry holes rather
3711        // than being freshly written. APFS enumeration is known to degrade with churn
3712        // rather than with size, so a fresh corpus is not a realistic one.
3713        const PLANTED: u32 = 20_000;
3714        const CHURN: u32 = 1_000;
3715
3716        let dir = TempDir::new().expect("temp dir");
3717        let chunks_dir = dir.path().join(CHUNKS_DIR_NAME);
3718        std::fs::create_dir_all(&chunks_dir).expect("mkdir");
3719
3720        let mut expected: Vec<XorName> = Vec::new();
3721        for i in 0..PLANTED {
3722            let key = crate::client::compute_address(&i.to_le_bytes());
3723            plant(&chunks_dir, &key);
3724            expected.push(key);
3725        }
3726        for i in 0..CHURN {
3727            let key = crate::client::compute_address(&i.to_le_bytes());
3728            std::fs::remove_file(chunks_dir.join(shard_name(&key)).join(hex::encode(key)))
3729                .expect("churn out");
3730            let replacement = crate::client::compute_address(&(PLANTED + i).to_le_bytes());
3731            plant(&chunks_dir, &replacement);
3732        }
3733        expected.retain(|k| chunks_dir.join(shard_name(k)).join(hex::encode(k)).exists());
3734        for i in 0..CHURN {
3735            expected.push(crate::client::compute_address(&(PLANTED + i).to_le_bytes()));
3736        }
3737        expected.sort_unstable();
3738        expected.dedup();
3739
3740        let started = std::time::Instant::now();
3741        let store = reopen(&dir).await;
3742        let scan = started.elapsed();
3743
3744        assert_eq!(
3745            store.current_chunks().expect("count"),
3746            expected.len() as u64
3747        );
3748        assert_eq!(store.all_keys().await.expect("all_keys"), expected);
3749
3750        // Every shard should be in use at this size: 20,000 keys over 256 directories is
3751        // about 78 each, and the last byte of a BLAKE3 output is uniform.
3752        let occupied = std::fs::read_dir(&chunks_dir)
3753            .expect("read store root")
3754            .filter_map(std::result::Result::ok)
3755            .filter(|e| e.file_name().to_str().is_some_and(|n| n.len() == 2))
3756            .count();
3757        assert_eq!(occupied, SHARD_COUNT, "the suffix must reach every shard");
3758
3759        println!(
3760            "scan of {} keys across {SHARD_COUNT} shards took {scan:?}",
3761            expected.len()
3762        );
3763    }
3764
3765    #[tokio::test]
3766    async fn wait_idle_returns_once_writes_have_drained() {
3767        let (store, _dir) = test_store().await;
3768        let store = Arc::new(store);
3769        for i in 0..32 {
3770            let store = Arc::clone(&store);
3771            let (addr, content) = addressed(&format!("drain-{i}"));
3772            tokio::spawn(async move { store.put(&addr, &content).await });
3773        }
3774        // Not a synchronisation point for tasks that have not been spawned yet, but it
3775        // must not hang and it must leave the store usable.
3776        store.wait_idle().await;
3777        let (addr, content) = addressed("after-drain");
3778        assert!(store.put(&addr, &content).await.expect("put after drain"));
3779    }
3780}