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