Skip to main content

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